Bug Summary

File:llvm/lib/Target/ARM/ARMISelLowering.cpp
Warning:line 2635, 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-store=region -analyzer-opt-analyze-nested-blocks -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 -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-14~++20211110111138+cffbfd01e37b/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.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-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM -I include -I /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/include -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-14/lib/clang/14.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 -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/build-llvm -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -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-2021-11-10-160236-22541-1 -x c++ /build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/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
277 // No native support for these.
278 setOperationAction(ISD::UDIV, VT, Expand);
279 setOperationAction(ISD::SDIV, VT, Expand);
280 setOperationAction(ISD::UREM, VT, Expand);
281 setOperationAction(ISD::SREM, VT, Expand);
282 setOperationAction(ISD::UDIVREM, VT, Expand);
283 setOperationAction(ISD::SDIVREM, VT, Expand);
284 setOperationAction(ISD::CTPOP, VT, Expand);
285 setOperationAction(ISD::SELECT, VT, Expand);
286 setOperationAction(ISD::SELECT_CC, VT, Expand);
287
288 // Vector reductions
289 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
290 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
291 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
292 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
293 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
294 setOperationAction(ISD::VECREDUCE_MUL, VT, Custom);
295 setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
296 setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
297 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
298
299 if (!HasMVEFP) {
300 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
301 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
302 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
303 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
304 } else {
305 setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
306 setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
307 }
308
309 // Pre and Post inc are supported on loads and stores
310 for (unsigned im = (unsigned)ISD::PRE_INC;
311 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
312 setIndexedLoadAction(im, VT, Legal);
313 setIndexedStoreAction(im, VT, Legal);
314 setIndexedMaskedLoadAction(im, VT, Legal);
315 setIndexedMaskedStoreAction(im, VT, Legal);
316 }
317 }
318
319 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
320 for (auto VT : FloatTypes) {
321 addRegisterClass(VT, &ARM::MQPRRegClass);
322 if (!HasMVEFP)
323 setAllExpand(VT);
324
325 // These are legal or custom whether we have MVE.fp or not
326 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
327 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
328 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
329 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
330 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
331 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
332 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
333 setOperationAction(ISD::SETCC, VT, Custom);
334 setOperationAction(ISD::MLOAD, VT, Custom);
335 setOperationAction(ISD::MSTORE, VT, Legal);
336 setOperationAction(ISD::SELECT, VT, Expand);
337 setOperationAction(ISD::SELECT_CC, VT, Expand);
338
339 // Pre and Post inc are supported on loads and stores
340 for (unsigned im = (unsigned)ISD::PRE_INC;
341 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
342 setIndexedLoadAction(im, VT, Legal);
343 setIndexedStoreAction(im, VT, Legal);
344 setIndexedMaskedLoadAction(im, VT, Legal);
345 setIndexedMaskedStoreAction(im, VT, Legal);
346 }
347
348 if (HasMVEFP) {
349 setOperationAction(ISD::FMINNUM, VT, Legal);
350 setOperationAction(ISD::FMAXNUM, VT, Legal);
351 setOperationAction(ISD::FROUND, VT, Legal);
352 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
353 setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom);
354 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
355 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
356
357 // No native support for these.
358 setOperationAction(ISD::FDIV, VT, Expand);
359 setOperationAction(ISD::FREM, VT, Expand);
360 setOperationAction(ISD::FSQRT, VT, Expand);
361 setOperationAction(ISD::FSIN, VT, Expand);
362 setOperationAction(ISD::FCOS, VT, Expand);
363 setOperationAction(ISD::FPOW, VT, Expand);
364 setOperationAction(ISD::FLOG, VT, Expand);
365 setOperationAction(ISD::FLOG2, VT, Expand);
366 setOperationAction(ISD::FLOG10, VT, Expand);
367 setOperationAction(ISD::FEXP, VT, Expand);
368 setOperationAction(ISD::FEXP2, VT, Expand);
369 setOperationAction(ISD::FNEARBYINT, VT, Expand);
370 }
371 }
372
373 // Custom Expand smaller than legal vector reductions to prevent false zero
374 // items being added.
375 setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom);
376 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom);
377 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom);
378 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom);
379 setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom);
380 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom);
381 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom);
382 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom);
383
384 // We 'support' these types up to bitcast/load/store level, regardless of
385 // MVE integer-only / float support. Only doing FP data processing on the FP
386 // vector types is inhibited at integer-only level.
387 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
388 for (auto VT : LongTypes) {
389 addRegisterClass(VT, &ARM::MQPRRegClass);
390 setAllExpand(VT);
391 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
393 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
394 }
395 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
396
397 // We can do bitwise operations on v2i64 vectors
398 setOperationAction(ISD::AND, MVT::v2i64, Legal);
399 setOperationAction(ISD::OR, MVT::v2i64, Legal);
400 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
401
402 // It is legal to extload from v4i8 to v4i16 or v4i32.
403 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
404 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
405 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
406
407 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
408 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal);
409 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
410 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
411 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8, Legal);
412 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal);
413
414 // Some truncating stores are legal too.
415 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
416 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
417 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
418
419 // Pre and Post inc on these are legal, given the correct extends
420 for (unsigned im = (unsigned)ISD::PRE_INC;
421 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
422 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
423 setIndexedLoadAction(im, VT, Legal);
424 setIndexedStoreAction(im, VT, Legal);
425 setIndexedMaskedLoadAction(im, VT, Legal);
426 setIndexedMaskedStoreAction(im, VT, Legal);
427 }
428 }
429
430 // Predicate types
431 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
432 for (auto VT : pTypes) {
433 addRegisterClass(VT, &ARM::VCCRRegClass);
434 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
435 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
436 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
437 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
438 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
439 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
440 setOperationAction(ISD::SETCC, VT, Custom);
441 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
442 setOperationAction(ISD::LOAD, VT, Custom);
443 setOperationAction(ISD::STORE, VT, Custom);
444 setOperationAction(ISD::TRUNCATE, VT, Custom);
445 setOperationAction(ISD::VSELECT, VT, Expand);
446 setOperationAction(ISD::SELECT, VT, Expand);
447 }
448 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
449 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
450 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
451 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
452 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
453 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
454 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
455 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
456}
457
458ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
459 const ARMSubtarget &STI)
460 : TargetLowering(TM), Subtarget(&STI) {
461 RegInfo = Subtarget->getRegisterInfo();
462 Itins = Subtarget->getInstrItineraryData();
463
464 setBooleanContents(ZeroOrOneBooleanContent);
465 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
466
467 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
468 !Subtarget->isTargetWatchOS()) {
469 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
470 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
471 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
472 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
473 : CallingConv::ARM_AAPCS);
474 }
475
476 if (Subtarget->isTargetMachO()) {
477 // Uses VFP for Thumb libfuncs if available.
478 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
479 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
480 static const struct {
481 const RTLIB::Libcall Op;
482 const char * const Name;
483 const ISD::CondCode Cond;
484 } LibraryCalls[] = {
485 // Single-precision floating-point arithmetic.
486 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
487 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
488 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
489 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
490
491 // Double-precision floating-point arithmetic.
492 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
493 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
494 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
495 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
496
497 // Single-precision comparisons.
498 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
499 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
500 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
501 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
502 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
503 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
504 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
505
506 // Double-precision comparisons.
507 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
508 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
509 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
510 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
511 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
512 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
513 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
514
515 // Floating-point to integer conversions.
516 // i64 conversions are done via library routines even when generating VFP
517 // instructions, so use the same ones.
518 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
519 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
520 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
521 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
522
523 // Conversions between floating types.
524 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
525 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
526
527 // Integer to floating-point conversions.
528 // i64 conversions are done via library routines even when generating VFP
529 // instructions, so use the same ones.
530 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
531 // e.g., __floatunsidf vs. __floatunssidfvfp.
532 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
533 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
534 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
535 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
536 };
537
538 for (const auto &LC : LibraryCalls) {
539 setLibcallName(LC.Op, LC.Name);
540 if (LC.Cond != ISD::SETCC_INVALID)
541 setCmpLibcallCC(LC.Op, LC.Cond);
542 }
543 }
544 }
545
546 // These libcalls are not available in 32-bit.
547 setLibcallName(RTLIB::SHL_I128, nullptr);
548 setLibcallName(RTLIB::SRL_I128, nullptr);
549 setLibcallName(RTLIB::SRA_I128, nullptr);
550 setLibcallName(RTLIB::MUL_I128, nullptr);
551 setLibcallName(RTLIB::MULO_I64, nullptr);
552 setLibcallName(RTLIB::MULO_I128, nullptr);
553
554 // RTLIB
555 if (Subtarget->isAAPCS_ABI() &&
556 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
557 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
558 static const struct {
559 const RTLIB::Libcall Op;
560 const char * const Name;
561 const CallingConv::ID CC;
562 const ISD::CondCode Cond;
563 } LibraryCalls[] = {
564 // Double-precision floating-point arithmetic helper functions
565 // RTABI chapter 4.1.2, Table 2
566 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
567 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
568 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
569 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
570
571 // Double-precision floating-point comparison helper functions
572 // RTABI chapter 4.1.2, Table 3
573 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
574 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
575 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
576 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
577 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
578 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
579 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
580
581 // Single-precision floating-point arithmetic helper functions
582 // RTABI chapter 4.1.2, Table 4
583 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
584 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
585 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
586 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
587
588 // Single-precision floating-point comparison helper functions
589 // RTABI chapter 4.1.2, Table 5
590 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
591 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
592 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
593 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
594 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
595 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
596 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
597
598 // Floating-point to integer conversions.
599 // RTABI chapter 4.1.2, Table 6
600 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
601 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
602 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
603 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
604 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
605 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
606 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
607 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
608
609 // Conversions between floating types.
610 // RTABI chapter 4.1.2, Table 7
611 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
612 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
613 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
614
615 // Integer to floating-point conversions.
616 // RTABI chapter 4.1.2, Table 8
617 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
618 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
619 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
620 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
621 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
622 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
623 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
624 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
625
626 // Long long helper functions
627 // RTABI chapter 4.2, Table 9
628 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
629 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
630 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
631 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
632
633 // Integer division functions
634 // RTABI chapter 4.3.1
635 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
636 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
637 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
638 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
639 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
640 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
641 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
642 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
643 };
644
645 for (const auto &LC : LibraryCalls) {
646 setLibcallName(LC.Op, LC.Name);
647 setLibcallCallingConv(LC.Op, LC.CC);
648 if (LC.Cond != ISD::SETCC_INVALID)
649 setCmpLibcallCC(LC.Op, LC.Cond);
650 }
651
652 // EABI dependent RTLIB
653 if (TM.Options.EABIVersion == EABI::EABI4 ||
654 TM.Options.EABIVersion == EABI::EABI5) {
655 static const struct {
656 const RTLIB::Libcall Op;
657 const char *const Name;
658 const CallingConv::ID CC;
659 const ISD::CondCode Cond;
660 } MemOpsLibraryCalls[] = {
661 // Memory operations
662 // RTABI chapter 4.3.4
663 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
664 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
665 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
666 };
667
668 for (const auto &LC : MemOpsLibraryCalls) {
669 setLibcallName(LC.Op, LC.Name);
670 setLibcallCallingConv(LC.Op, LC.CC);
671 if (LC.Cond != ISD::SETCC_INVALID)
672 setCmpLibcallCC(LC.Op, LC.Cond);
673 }
674 }
675 }
676
677 if (Subtarget->isTargetWindows()) {
678 static const struct {
679 const RTLIB::Libcall Op;
680 const char * const Name;
681 const CallingConv::ID CC;
682 } LibraryCalls[] = {
683 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
684 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
685 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
686 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
687 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
688 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
689 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
690 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
691 };
692
693 for (const auto &LC : LibraryCalls) {
694 setLibcallName(LC.Op, LC.Name);
695 setLibcallCallingConv(LC.Op, LC.CC);
696 }
697 }
698
699 // Use divmod compiler-rt calls for iOS 5.0 and later.
700 if (Subtarget->isTargetMachO() &&
701 !(Subtarget->isTargetIOS() &&
702 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
703 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
704 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
705 }
706
707 // The half <-> float conversion functions are always soft-float on
708 // non-watchos platforms, but are needed for some targets which use a
709 // hard-float calling convention by default.
710 if (!Subtarget->isTargetWatchABI()) {
711 if (Subtarget->isAAPCS_ABI()) {
712 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
713 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
714 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
715 } else {
716 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
717 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
718 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
719 }
720 }
721
722 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
723 // a __gnu_ prefix (which is the default).
724 if (Subtarget->isTargetAEABI()) {
725 static const struct {
726 const RTLIB::Libcall Op;
727 const char * const Name;
728 const CallingConv::ID CC;
729 } LibraryCalls[] = {
730 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
731 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
732 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
733 };
734
735 for (const auto &LC : LibraryCalls) {
736 setLibcallName(LC.Op, LC.Name);
737 setLibcallCallingConv(LC.Op, LC.CC);
738 }
739 }
740
741 if (Subtarget->isThumb1Only())
742 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
743 else
744 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
745
746 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
747 Subtarget->hasFPRegs()) {
748 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
749 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
750
751 setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i32, Custom);
752 setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i32, Custom);
753 setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
754 setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
755
756 if (!Subtarget->hasVFP2Base())
757 setAllExpand(MVT::f32);
758 if (!Subtarget->hasFP64())
759 setAllExpand(MVT::f64);
760 }
761
762 if (Subtarget->hasFullFP16()) {
763 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
764 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
765 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
766
767 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
768 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
769 }
770
771 if (Subtarget->hasBF16()) {
772 addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
773 setAllExpand(MVT::bf16);
774 if (!Subtarget->hasFullFP16())
775 setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
776 }
777
778 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
779 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
780 setTruncStoreAction(VT, InnerVT, Expand);
781 addAllExtLoads(VT, InnerVT, Expand);
782 }
783
784 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
785 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
786
787 setOperationAction(ISD::BSWAP, VT, Expand);
788 }
789
790 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
791 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
792
793 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
794 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
795
796 if (Subtarget->hasMVEIntegerOps())
797 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
798
799 // Combine low-overhead loop intrinsics so that we can lower i1 types.
800 if (Subtarget->hasLOB()) {
801 setTargetDAGCombine(ISD::BRCOND);
802 setTargetDAGCombine(ISD::BR_CC);
803 }
804
805 if (Subtarget->hasNEON()) {
806 addDRTypeForNEON(MVT::v2f32);
807 addDRTypeForNEON(MVT::v8i8);
808 addDRTypeForNEON(MVT::v4i16);
809 addDRTypeForNEON(MVT::v2i32);
810 addDRTypeForNEON(MVT::v1i64);
811
812 addQRTypeForNEON(MVT::v4f32);
813 addQRTypeForNEON(MVT::v2f64);
814 addQRTypeForNEON(MVT::v16i8);
815 addQRTypeForNEON(MVT::v8i16);
816 addQRTypeForNEON(MVT::v4i32);
817 addQRTypeForNEON(MVT::v2i64);
818
819 if (Subtarget->hasFullFP16()) {
820 addQRTypeForNEON(MVT::v8f16);
821 addDRTypeForNEON(MVT::v4f16);
822 }
823
824 if (Subtarget->hasBF16()) {
825 addQRTypeForNEON(MVT::v8bf16);
826 addDRTypeForNEON(MVT::v4bf16);
827 }
828 }
829
830 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
831 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
832 // none of Neon, MVE or VFP supports any arithmetic operations on it.
833 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
834 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
835 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
836 // FIXME: Code duplication: FDIV and FREM are expanded always, see
837 // ARMTargetLowering::addTypeForNEON method for details.
838 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
839 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
840 // FIXME: Create unittest.
841 // In another words, find a way when "copysign" appears in DAG with vector
842 // operands.
843 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
844 // FIXME: Code duplication: SETCC has custom operation action, see
845 // ARMTargetLowering::addTypeForNEON method for details.
846 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
847 // FIXME: Create unittest for FNEG and for FABS.
848 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
849 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
850 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
851 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
852 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
853 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
854 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
855 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
856 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
857 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
858 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
859 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
860 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
861 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
862 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
863 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
864 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
865 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
866 }
867
868 if (Subtarget->hasNEON()) {
869 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
870 // supported for v4f32.
871 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
872 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
873 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
874 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
875 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
876 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
877 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
878 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
879 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
880 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
881 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
882 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
883 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
884 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
885
886 // Mark v2f32 intrinsics.
887 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
888 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
889 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
890 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
891 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
892 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
893 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
894 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
895 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
896 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
897 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
898 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
899 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
900 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
901
902 // Neon does not support some operations on v1i64 and v2i64 types.
903 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
904 // Custom handling for some quad-vector types to detect VMULL.
905 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
906 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
907 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
908 // Custom handling for some vector types to avoid expensive expansions
909 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
910 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
911 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
912 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
913 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
914 // a destination type that is wider than the source, and nor does
915 // it have a FP_TO_[SU]INT instruction with a narrower destination than
916 // source.
917 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
918 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
919 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
920 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
921 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
922 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
923 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
924 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
925
926 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
927 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
928
929 // NEON does not have single instruction CTPOP for vectors with element
930 // types wider than 8-bits. However, custom lowering can leverage the
931 // v8i8/v16i8 vcnt instruction.
932 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
933 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
934 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
935 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
936 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
937 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
938
939 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
940 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
941
942 // NEON does not have single instruction CTTZ for vectors.
943 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
944 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
945 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
946 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
947
948 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
949 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
950 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
951 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
952
953 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
954 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
955 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
956 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
957
958 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
959 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
960 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
961 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
962
963 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
964 setOperationAction(ISD::MULHS, VT, Expand);
965 setOperationAction(ISD::MULHU, VT, Expand);
966 }
967
968 // NEON only has FMA instructions as of VFP4.
969 if (!Subtarget->hasVFP4Base()) {
970 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
971 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
972 }
973
974 setTargetDAGCombine(ISD::SHL);
975 setTargetDAGCombine(ISD::SRL);
976 setTargetDAGCombine(ISD::SRA);
977 setTargetDAGCombine(ISD::FP_TO_SINT);
978 setTargetDAGCombine(ISD::FP_TO_UINT);
979 setTargetDAGCombine(ISD::FDIV);
980 setTargetDAGCombine(ISD::LOAD);
981
982 // It is legal to extload from v4i8 to v4i16 or v4i32.
983 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
984 MVT::v2i32}) {
985 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
986 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
987 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
988 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
989 }
990 }
991 }
992
993 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
994 setTargetDAGCombine(ISD::BUILD_VECTOR);
995 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
996 setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
997 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
998 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
999 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1000 setTargetDAGCombine(ISD::STORE);
1001 setTargetDAGCombine(ISD::SIGN_EXTEND);
1002 setTargetDAGCombine(ISD::ZERO_EXTEND);
1003 setTargetDAGCombine(ISD::ANY_EXTEND);
1004 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1005 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1006 setTargetDAGCombine(ISD::INTRINSIC_VOID);
1007 setTargetDAGCombine(ISD::VECREDUCE_ADD);
1008 setTargetDAGCombine(ISD::ADD);
1009 setTargetDAGCombine(ISD::BITCAST);
1010 }
1011 if (Subtarget->hasMVEIntegerOps()) {
1012 setTargetDAGCombine(ISD::SMIN);
1013 setTargetDAGCombine(ISD::UMIN);
1014 setTargetDAGCombine(ISD::SMAX);
1015 setTargetDAGCombine(ISD::UMAX);
1016 setTargetDAGCombine(ISD::FP_EXTEND);
1017 setTargetDAGCombine(ISD::SELECT);
1018 setTargetDAGCombine(ISD::SELECT_CC);
1019 }
1020
1021 if (!Subtarget->hasFP64()) {
1022 // When targeting a floating-point unit with only single-precision
1023 // operations, f64 is legal for the few double-precision instructions which
1024 // are present However, no double-precision operations other than moves,
1025 // loads and stores are provided by the hardware.
1026 setOperationAction(ISD::FADD, MVT::f64, Expand);
1027 setOperationAction(ISD::FSUB, MVT::f64, Expand);
1028 setOperationAction(ISD::FMUL, MVT::f64, Expand);
1029 setOperationAction(ISD::FMA, MVT::f64, Expand);
1030 setOperationAction(ISD::FDIV, MVT::f64, Expand);
1031 setOperationAction(ISD::FREM, MVT::f64, Expand);
1032 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1033 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
1034 setOperationAction(ISD::FNEG, MVT::f64, Expand);
1035 setOperationAction(ISD::FABS, MVT::f64, Expand);
1036 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
1037 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1038 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1039 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1040 setOperationAction(ISD::FLOG, MVT::f64, Expand);
1041 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
1042 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
1043 setOperationAction(ISD::FEXP, MVT::f64, Expand);
1044 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
1045 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
1046 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
1047 setOperationAction(ISD::FRINT, MVT::f64, Expand);
1048 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
1049 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
1050 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1051 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1052 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1053 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1054 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
1055 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
1056 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
1057 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
1058 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
1059 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
1060 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
1061 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
1062 }
1063
1064 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
1065 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
1066 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
1067 if (Subtarget->hasFullFP16()) {
1068 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
1069 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
1070 }
1071 }
1072
1073 if (!Subtarget->hasFP16()) {
1074 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
1075 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1076 }
1077
1078 computeRegisterProperties(Subtarget->getRegisterInfo());
1079
1080 // ARM does not have floating-point extending loads.
1081 for (MVT VT : MVT::fp_valuetypes()) {
1082 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1083 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1084 }
1085
1086 // ... or truncating stores
1087 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1088 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1089 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1090
1091 // ARM does not have i1 sign extending load.
1092 for (MVT VT : MVT::integer_valuetypes())
1093 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1094
1095 // ARM supports all 4 flavors of integer indexed load / store.
1096 if (!Subtarget->isThumb1Only()) {
1097 for (unsigned im = (unsigned)ISD::PRE_INC;
1098 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1099 setIndexedLoadAction(im, MVT::i1, Legal);
1100 setIndexedLoadAction(im, MVT::i8, Legal);
1101 setIndexedLoadAction(im, MVT::i16, Legal);
1102 setIndexedLoadAction(im, MVT::i32, Legal);
1103 setIndexedStoreAction(im, MVT::i1, Legal);
1104 setIndexedStoreAction(im, MVT::i8, Legal);
1105 setIndexedStoreAction(im, MVT::i16, Legal);
1106 setIndexedStoreAction(im, MVT::i32, Legal);
1107 }
1108 } else {
1109 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1110 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
1111 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1112 }
1113
1114 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1115 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1116 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1117 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1118
1119 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1120 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1121 if (Subtarget->hasDSP()) {
1122 setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1123 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1124 setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1125 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1126 setOperationAction(ISD::UADDSAT, MVT::i8, Custom);
1127 setOperationAction(ISD::USUBSAT, MVT::i8, Custom);
1128 setOperationAction(ISD::UADDSAT, MVT::i16, Custom);
1129 setOperationAction(ISD::USUBSAT, MVT::i16, Custom);
1130 }
1131 if (Subtarget->hasBaseDSP()) {
1132 setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1133 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1134 }
1135
1136 // i64 operation support.
1137 setOperationAction(ISD::MUL, MVT::i64, Expand);
1138 setOperationAction(ISD::MULHU, MVT::i32, Expand);
1139 if (Subtarget->isThumb1Only()) {
1140 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1141 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1142 }
1143 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1144 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1145 setOperationAction(ISD::MULHS, MVT::i32, Expand);
1146
1147 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1148 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1149 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1150 setOperationAction(ISD::SRL, MVT::i64, Custom);
1151 setOperationAction(ISD::SRA, MVT::i64, Custom);
1152 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1153 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1154 setOperationAction(ISD::LOAD, MVT::i64, Custom);
1155 setOperationAction(ISD::STORE, MVT::i64, Custom);
1156
1157 // MVE lowers 64 bit shifts to lsll and lsrl
1158 // assuming that ISD::SRL and SRA of i64 are already marked custom
1159 if (Subtarget->hasMVEIntegerOps())
1160 setOperationAction(ISD::SHL, MVT::i64, Custom);
1161
1162 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1163 if (Subtarget->isThumb1Only()) {
1164 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1165 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1166 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1167 }
1168
1169 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1170 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1171
1172 // ARM does not have ROTL.
1173 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1174 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1175 setOperationAction(ISD::ROTL, VT, Expand);
1176 setOperationAction(ISD::ROTR, VT, Expand);
1177 }
1178 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1179 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1180 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1181 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1182 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1183 }
1184
1185 // @llvm.readcyclecounter requires the Performance Monitors extension.
1186 // Default to the 0 expansion on unsupported platforms.
1187 // FIXME: Technically there are older ARM CPUs that have
1188 // implementation-specific ways of obtaining this information.
1189 if (Subtarget->hasPerfMon())
1190 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1191
1192 // Only ARMv6 has BSWAP.
1193 if (!Subtarget->hasV6Ops())
1194 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1195
1196 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1197 : Subtarget->hasDivideInARMMode();
1198 if (!hasDivide) {
1199 // These are expanded into libcalls if the cpu doesn't have HW divider.
1200 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1201 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1202 }
1203
1204 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1205 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1206 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1207
1208 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1209 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1210 }
1211
1212 setOperationAction(ISD::SREM, MVT::i32, Expand);
1213 setOperationAction(ISD::UREM, MVT::i32, Expand);
1214
1215 // Register based DivRem for AEABI (RTABI 4.2)
1216 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1217 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1218 Subtarget->isTargetWindows()) {
1219 setOperationAction(ISD::SREM, MVT::i64, Custom);
1220 setOperationAction(ISD::UREM, MVT::i64, Custom);
1221 HasStandaloneRem = false;
1222
1223 if (Subtarget->isTargetWindows()) {
1224 const struct {
1225 const RTLIB::Libcall Op;
1226 const char * const Name;
1227 const CallingConv::ID CC;
1228 } LibraryCalls[] = {
1229 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1230 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1231 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1232 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1233
1234 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1235 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1236 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1237 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1238 };
1239
1240 for (const auto &LC : LibraryCalls) {
1241 setLibcallName(LC.Op, LC.Name);
1242 setLibcallCallingConv(LC.Op, LC.CC);
1243 }
1244 } else {
1245 const struct {
1246 const RTLIB::Libcall Op;
1247 const char * const Name;
1248 const CallingConv::ID CC;
1249 } LibraryCalls[] = {
1250 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1251 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1252 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1253 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1254
1255 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1256 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1257 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1258 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1259 };
1260
1261 for (const auto &LC : LibraryCalls) {
1262 setLibcallName(LC.Op, LC.Name);
1263 setLibcallCallingConv(LC.Op, LC.CC);
1264 }
1265 }
1266
1267 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1268 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1269 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1270 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1271 } else {
1272 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1273 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1274 }
1275
1276 if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1277 // MSVCRT doesn't have powi; fall back to pow
1278 setLibcallName(RTLIB::POWI_F32, nullptr);
1279 setLibcallName(RTLIB::POWI_F64, nullptr);
1280 }
1281
1282 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1283 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1284 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1285 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1286
1287 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1288 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1289
1290 // Use the default implementation.
1291 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1292 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1293 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1294 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1295 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1296 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1297
1298 if (Subtarget->isTargetWindows())
1299 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1300 else
1301 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1302
1303 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1304 // the default expansion.
1305 InsertFencesForAtomic = false;
1306 if (Subtarget->hasAnyDataBarrier() &&
1307 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1308 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1309 // to ldrex/strex loops already.
1310 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1311 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1312 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1313
1314 // On v8, we have particularly efficient implementations of atomic fences
1315 // if they can be combined with nearby atomic loads and stores.
1316 if (!Subtarget->hasAcquireRelease() ||
1317 getTargetMachine().getOptLevel() == 0) {
1318 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1319 InsertFencesForAtomic = true;
1320 }
1321 } else {
1322 // If there's anything we can use as a barrier, go through custom lowering
1323 // for ATOMIC_FENCE.
1324 // If target has DMB in thumb, Fences can be inserted.
1325 if (Subtarget->hasDataBarrier())
1326 InsertFencesForAtomic = true;
1327
1328 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1329 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1330
1331 // Set them all for expansion, which will force libcalls.
1332 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1333 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1334 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1335 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1336 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1337 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1338 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1339 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1340 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1341 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1342 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1343 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1344 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1345 // Unordered/Monotonic case.
1346 if (!InsertFencesForAtomic) {
1347 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1348 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1349 }
1350 }
1351
1352 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1353
1354 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1355 if (!Subtarget->hasV6Ops()) {
1356 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1357 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1358 }
1359 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1360
1361 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1362 !Subtarget->isThumb1Only()) {
1363 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1364 // iff target supports vfp2.
1365 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1366 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1367 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
1368 }
1369
1370 // We want to custom lower some of our intrinsics.
1371 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1372 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1373 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1374 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1375 if (Subtarget->useSjLjEH())
1376 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1377
1378 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1379 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1380 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1381 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1382 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1383 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1384 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1385 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1386 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1387 if (Subtarget->hasFullFP16()) {
1388 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1389 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1390 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1391 }
1392
1393 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1394
1395 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1396 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1397 if (Subtarget->hasFullFP16())
1398 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1399 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1400 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1401 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1402
1403 // We don't support sin/cos/fmod/copysign/pow
1404 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1405 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1406 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1407 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1408 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1409 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1410 setOperationAction(ISD::FREM, MVT::f64, Expand);
1411 setOperationAction(ISD::FREM, MVT::f32, Expand);
1412 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1413 !Subtarget->isThumb1Only()) {
1414 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1415 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1416 }
1417 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1418 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1419
1420 if (!Subtarget->hasVFP4Base()) {
1421 setOperationAction(ISD::FMA, MVT::f64, Expand);
1422 setOperationAction(ISD::FMA, MVT::f32, Expand);
1423 }
1424
1425 // Various VFP goodness
1426 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1427 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1428 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1429 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1430 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1431 }
1432
1433 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1434 if (!Subtarget->hasFP16()) {
1435 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1436 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1437 }
1438
1439 // Strict floating-point comparisons need custom lowering.
1440 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
1441 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1442 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
1443 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1444 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
1445 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1446 }
1447
1448 // Use __sincos_stret if available.
1449 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1450 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1451 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1452 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1453 }
1454
1455 // FP-ARMv8 implements a lot of rounding-like FP operations.
1456 if (Subtarget->hasFPARMv8Base()) {
1457 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1458 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1459 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1460 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1461 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1462 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1463 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1464 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1465 if (Subtarget->hasNEON()) {
1466 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1467 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1468 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1469 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1470 }
1471
1472 if (Subtarget->hasFP64()) {
1473 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1474 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1475 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1476 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1477 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1478 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1479 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1480 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1481 }
1482 }
1483
1484 // FP16 often need to be promoted to call lib functions
1485 if (Subtarget->hasFullFP16()) {
1486 setOperationAction(ISD::FREM, MVT::f16, Promote);
1487 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1488 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1489 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1490 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1491 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1492 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1493 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1494 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1495 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1496 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1497 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1498
1499 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1500 }
1501
1502 if (Subtarget->hasNEON()) {
1503 // vmin and vmax aren't available in a scalar form, so we can use
1504 // a NEON instruction with an undef lane instead. This has a performance
1505 // penalty on some cores, so we don't do this unless we have been
1506 // asked to by the core tuning model.
1507 if (Subtarget->useNEONForSinglePrecisionFP()) {
1508 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1509 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1510 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1511 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1512 }
1513 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1514 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1515 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1516 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1517
1518 if (Subtarget->hasFullFP16()) {
1519 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1520 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1521 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1522 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1523
1524 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1525 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1526 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1527 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1528 }
1529 }
1530
1531 // We have target-specific dag combine patterns for the following nodes:
1532 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1533 setTargetDAGCombine(ISD::ADD);
1534 setTargetDAGCombine(ISD::SUB);
1535 setTargetDAGCombine(ISD::MUL);
1536 setTargetDAGCombine(ISD::AND);
1537 setTargetDAGCombine(ISD::OR);
1538 setTargetDAGCombine(ISD::XOR);
1539
1540 if (Subtarget->hasMVEIntegerOps())
1541 setTargetDAGCombine(ISD::VSELECT);
1542
1543 if (Subtarget->hasV6Ops())
1544 setTargetDAGCombine(ISD::SRL);
1545 if (Subtarget->isThumb1Only())
1546 setTargetDAGCombine(ISD::SHL);
1547
1548 setStackPointerRegisterToSaveRestore(ARM::SP);
1549
1550 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1551 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1552 setSchedulingPreference(Sched::RegPressure);
1553 else
1554 setSchedulingPreference(Sched::Hybrid);
1555
1556 //// temporary - rewrite interface to use type
1557 MaxStoresPerMemset = 8;
1558 MaxStoresPerMemsetOptSize = 4;
1559 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1560 MaxStoresPerMemcpyOptSize = 2;
1561 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1562 MaxStoresPerMemmoveOptSize = 2;
1563
1564 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1565 // are at least 4 bytes aligned.
1566 setMinStackArgumentAlignment(Align(4));
1567
1568 // Prefer likely predicted branches to selects on out-of-order cores.
1569 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1570
1571 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1572
1573 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1574
1575 if (Subtarget->isThumb() || Subtarget->isThumb2())
1576 setTargetDAGCombine(ISD::ABS);
1577}
1578
1579bool ARMTargetLowering::useSoftFloat() const {
1580 return Subtarget->useSoftFloat();
1581}
1582
1583// FIXME: It might make sense to define the representative register class as the
1584// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1585// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1586// SPR's representative would be DPR_VFP2. This should work well if register
1587// pressure tracking were modified such that a register use would increment the
1588// pressure of the register class's representative and all of it's super
1589// classes' representatives transitively. We have not implemented this because
1590// of the difficulty prior to coalescing of modeling operand register classes
1591// due to the common occurrence of cross class copies and subregister insertions
1592// and extractions.
1593std::pair<const TargetRegisterClass *, uint8_t>
1594ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1595 MVT VT) const {
1596 const TargetRegisterClass *RRC = nullptr;
1597 uint8_t Cost = 1;
1598 switch (VT.SimpleTy) {
1599 default:
1600 return TargetLowering::findRepresentativeClass(TRI, VT);
1601 // Use DPR as representative register class for all floating point
1602 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1603 // the cost is 1 for both f32 and f64.
1604 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1605 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1606 RRC = &ARM::DPRRegClass;
1607 // When NEON is used for SP, only half of the register file is available
1608 // because operations that define both SP and DP results will be constrained
1609 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1610 // coalescing by double-counting the SP regs. See the FIXME above.
1611 if (Subtarget->useNEONForSinglePrecisionFP())
1612 Cost = 2;
1613 break;
1614 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1615 case MVT::v4f32: case MVT::v2f64:
1616 RRC = &ARM::DPRRegClass;
1617 Cost = 2;
1618 break;
1619 case MVT::v4i64:
1620 RRC = &ARM::DPRRegClass;
1621 Cost = 4;
1622 break;
1623 case MVT::v8i64:
1624 RRC = &ARM::DPRRegClass;
1625 Cost = 8;
1626 break;
1627 }
1628 return std::make_pair(RRC, Cost);
1629}
1630
1631const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1632#define MAKE_CASE(V) \
1633 case V: \
1634 return #V;
1635 switch ((ARMISD::NodeType)Opcode) {
1636 case ARMISD::FIRST_NUMBER:
1637 break;
1638 MAKE_CASE(ARMISD::Wrapper)
1639 MAKE_CASE(ARMISD::WrapperPIC)
1640 MAKE_CASE(ARMISD::WrapperJT)
1641 MAKE_CASE(ARMISD::COPY_STRUCT_BYVAL)
1642 MAKE_CASE(ARMISD::CALL)
1643 MAKE_CASE(ARMISD::CALL_PRED)
1644 MAKE_CASE(ARMISD::CALL_NOLINK)
1645 MAKE_CASE(ARMISD::tSECALL)
1646 MAKE_CASE(ARMISD::BRCOND)
1647 MAKE_CASE(ARMISD::BR_JT)
1648 MAKE_CASE(ARMISD::BR2_JT)
1649 MAKE_CASE(ARMISD::RET_FLAG)
1650 MAKE_CASE(ARMISD::SERET_FLAG)
1651 MAKE_CASE(ARMISD::INTRET_FLAG)
1652 MAKE_CASE(ARMISD::PIC_ADD)
1653 MAKE_CASE(ARMISD::CMP)
1654 MAKE_CASE(ARMISD::CMN)
1655 MAKE_CASE(ARMISD::CMPZ)
1656 MAKE_CASE(ARMISD::CMPFP)
1657 MAKE_CASE(ARMISD::CMPFPE)
1658 MAKE_CASE(ARMISD::CMPFPw0)
1659 MAKE_CASE(ARMISD::CMPFPEw0)
1660 MAKE_CASE(ARMISD::BCC_i64)
1661 MAKE_CASE(ARMISD::FMSTAT)
1662 MAKE_CASE(ARMISD::CMOV)
1663 MAKE_CASE(ARMISD::SUBS)
1664 MAKE_CASE(ARMISD::SSAT)
1665 MAKE_CASE(ARMISD::USAT)
1666 MAKE_CASE(ARMISD::ASRL)
1667 MAKE_CASE(ARMISD::LSRL)
1668 MAKE_CASE(ARMISD::LSLL)
1669 MAKE_CASE(ARMISD::SRL_FLAG)
1670 MAKE_CASE(ARMISD::SRA_FLAG)
1671 MAKE_CASE(ARMISD::RRX)
1672 MAKE_CASE(ARMISD::ADDC)
1673 MAKE_CASE(ARMISD::ADDE)
1674 MAKE_CASE(ARMISD::SUBC)
1675 MAKE_CASE(ARMISD::SUBE)
1676 MAKE_CASE(ARMISD::LSLS)
1677 MAKE_CASE(ARMISD::VMOVRRD)
1678 MAKE_CASE(ARMISD::VMOVDRR)
1679 MAKE_CASE(ARMISD::VMOVhr)
1680 MAKE_CASE(ARMISD::VMOVrh)
1681 MAKE_CASE(ARMISD::VMOVSR)
1682 MAKE_CASE(ARMISD::EH_SJLJ_SETJMP)
1683 MAKE_CASE(ARMISD::EH_SJLJ_LONGJMP)
1684 MAKE_CASE(ARMISD::EH_SJLJ_SETUP_DISPATCH)
1685 MAKE_CASE(ARMISD::TC_RETURN)
1686 MAKE_CASE(ARMISD::THREAD_POINTER)
1687 MAKE_CASE(ARMISD::DYN_ALLOC)
1688 MAKE_CASE(ARMISD::MEMBARRIER_MCR)
1689 MAKE_CASE(ARMISD::PRELOAD)
1690 MAKE_CASE(ARMISD::LDRD)
1691 MAKE_CASE(ARMISD::STRD)
1692 MAKE_CASE(ARMISD::WIN__CHKSTK)
1693 MAKE_CASE(ARMISD::WIN__DBZCHK)
1694 MAKE_CASE(ARMISD::PREDICATE_CAST)
1695 MAKE_CASE(ARMISD::VECTOR_REG_CAST)
1696 MAKE_CASE(ARMISD::MVESEXT)
1697 MAKE_CASE(ARMISD::MVEZEXT)
1698 MAKE_CASE(ARMISD::MVETRUNC)
1699 MAKE_CASE(ARMISD::VCMP)
1700 MAKE_CASE(ARMISD::VCMPZ)
1701 MAKE_CASE(ARMISD::VTST)
1702 MAKE_CASE(ARMISD::VSHLs)
1703 MAKE_CASE(ARMISD::VSHLu)
1704 MAKE_CASE(ARMISD::VSHLIMM)
1705 MAKE_CASE(ARMISD::VSHRsIMM)
1706 MAKE_CASE(ARMISD::VSHRuIMM)
1707 MAKE_CASE(ARMISD::VRSHRsIMM)
1708 MAKE_CASE(ARMISD::VRSHRuIMM)
1709 MAKE_CASE(ARMISD::VRSHRNIMM)
1710 MAKE_CASE(ARMISD::VQSHLsIMM)
1711 MAKE_CASE(ARMISD::VQSHLuIMM)
1712 MAKE_CASE(ARMISD::VQSHLsuIMM)
1713 MAKE_CASE(ARMISD::VQSHRNsIMM)
1714 MAKE_CASE(ARMISD::VQSHRNuIMM)
1715 MAKE_CASE(ARMISD::VQSHRNsuIMM)
1716 MAKE_CASE(ARMISD::VQRSHRNsIMM)
1717 MAKE_CASE(ARMISD::VQRSHRNuIMM)
1718 MAKE_CASE(ARMISD::VQRSHRNsuIMM)
1719 MAKE_CASE(ARMISD::VSLIIMM)
1720 MAKE_CASE(ARMISD::VSRIIMM)
1721 MAKE_CASE(ARMISD::VGETLANEu)
1722 MAKE_CASE(ARMISD::VGETLANEs)
1723 MAKE_CASE(ARMISD::VMOVIMM)
1724 MAKE_CASE(ARMISD::VMVNIMM)
1725 MAKE_CASE(ARMISD::VMOVFPIMM)
1726 MAKE_CASE(ARMISD::VDUP)
1727 MAKE_CASE(ARMISD::VDUPLANE)
1728 MAKE_CASE(ARMISD::VEXT)
1729 MAKE_CASE(ARMISD::VREV64)
1730 MAKE_CASE(ARMISD::VREV32)
1731 MAKE_CASE(ARMISD::VREV16)
1732 MAKE_CASE(ARMISD::VZIP)
1733 MAKE_CASE(ARMISD::VUZP)
1734 MAKE_CASE(ARMISD::VTRN)
1735 MAKE_CASE(ARMISD::VTBL1)
1736 MAKE_CASE(ARMISD::VTBL2)
1737 MAKE_CASE(ARMISD::VMOVN)
1738 MAKE_CASE(ARMISD::VQMOVNs)
1739 MAKE_CASE(ARMISD::VQMOVNu)
1740 MAKE_CASE(ARMISD::VCVTN)
1741 MAKE_CASE(ARMISD::VCVTL)
1742 MAKE_CASE(ARMISD::VIDUP)
1743 MAKE_CASE(ARMISD::VMULLs)
1744 MAKE_CASE(ARMISD::VMULLu)
1745 MAKE_CASE(ARMISD::VQDMULH)
1746 MAKE_CASE(ARMISD::VADDVs)
1747 MAKE_CASE(ARMISD::VADDVu)
1748 MAKE_CASE(ARMISD::VADDVps)
1749 MAKE_CASE(ARMISD::VADDVpu)
1750 MAKE_CASE(ARMISD::VADDLVs)
1751 MAKE_CASE(ARMISD::VADDLVu)
1752 MAKE_CASE(ARMISD::VADDLVAs)
1753 MAKE_CASE(ARMISD::VADDLVAu)
1754 MAKE_CASE(ARMISD::VADDLVps)
1755 MAKE_CASE(ARMISD::VADDLVpu)
1756 MAKE_CASE(ARMISD::VADDLVAps)
1757 MAKE_CASE(ARMISD::VADDLVApu)
1758 MAKE_CASE(ARMISD::VMLAVs)
1759 MAKE_CASE(ARMISD::VMLAVu)
1760 MAKE_CASE(ARMISD::VMLAVps)
1761 MAKE_CASE(ARMISD::VMLAVpu)
1762 MAKE_CASE(ARMISD::VMLALVs)
1763 MAKE_CASE(ARMISD::VMLALVu)
1764 MAKE_CASE(ARMISD::VMLALVps)
1765 MAKE_CASE(ARMISD::VMLALVpu)
1766 MAKE_CASE(ARMISD::VMLALVAs)
1767 MAKE_CASE(ARMISD::VMLALVAu)
1768 MAKE_CASE(ARMISD::VMLALVAps)
1769 MAKE_CASE(ARMISD::VMLALVApu)
1770 MAKE_CASE(ARMISD::VMINVu)
1771 MAKE_CASE(ARMISD::VMINVs)
1772 MAKE_CASE(ARMISD::VMAXVu)
1773 MAKE_CASE(ARMISD::VMAXVs)
1774 MAKE_CASE(ARMISD::UMAAL)
1775 MAKE_CASE(ARMISD::UMLAL)
1776 MAKE_CASE(ARMISD::SMLAL)
1777 MAKE_CASE(ARMISD::SMLALBB)
1778 MAKE_CASE(ARMISD::SMLALBT)
1779 MAKE_CASE(ARMISD::SMLALTB)
1780 MAKE_CASE(ARMISD::SMLALTT)
1781 MAKE_CASE(ARMISD::SMULWB)
1782 MAKE_CASE(ARMISD::SMULWT)
1783 MAKE_CASE(ARMISD::SMLALD)
1784 MAKE_CASE(ARMISD::SMLALDX)
1785 MAKE_CASE(ARMISD::SMLSLD)
1786 MAKE_CASE(ARMISD::SMLSLDX)
1787 MAKE_CASE(ARMISD::SMMLAR)
1788 MAKE_CASE(ARMISD::SMMLSR)
1789 MAKE_CASE(ARMISD::QADD16b)
1790 MAKE_CASE(ARMISD::QSUB16b)
1791 MAKE_CASE(ARMISD::QADD8b)
1792 MAKE_CASE(ARMISD::QSUB8b)
1793 MAKE_CASE(ARMISD::UQADD16b)
1794 MAKE_CASE(ARMISD::UQSUB16b)
1795 MAKE_CASE(ARMISD::UQADD8b)
1796 MAKE_CASE(ARMISD::UQSUB8b)
1797 MAKE_CASE(ARMISD::BUILD_VECTOR)
1798 MAKE_CASE(ARMISD::BFI)
1799 MAKE_CASE(ARMISD::VORRIMM)
1800 MAKE_CASE(ARMISD::VBICIMM)
1801 MAKE_CASE(ARMISD::VBSP)
1802 MAKE_CASE(ARMISD::MEMCPY)
1803 MAKE_CASE(ARMISD::VLD1DUP)
1804 MAKE_CASE(ARMISD::VLD2DUP)
1805 MAKE_CASE(ARMISD::VLD3DUP)
1806 MAKE_CASE(ARMISD::VLD4DUP)
1807 MAKE_CASE(ARMISD::VLD1_UPD)
1808 MAKE_CASE(ARMISD::VLD2_UPD)
1809 MAKE_CASE(ARMISD::VLD3_UPD)
1810 MAKE_CASE(ARMISD::VLD4_UPD)
1811 MAKE_CASE(ARMISD::VLD1x2_UPD)
1812 MAKE_CASE(ARMISD::VLD1x3_UPD)
1813 MAKE_CASE(ARMISD::VLD1x4_UPD)
1814 MAKE_CASE(ARMISD::VLD2LN_UPD)
1815 MAKE_CASE(ARMISD::VLD3LN_UPD)
1816 MAKE_CASE(ARMISD::VLD4LN_UPD)
1817 MAKE_CASE(ARMISD::VLD1DUP_UPD)
1818 MAKE_CASE(ARMISD::VLD2DUP_UPD)
1819 MAKE_CASE(ARMISD::VLD3DUP_UPD)
1820 MAKE_CASE(ARMISD::VLD4DUP_UPD)
1821 MAKE_CASE(ARMISD::VST1_UPD)
1822 MAKE_CASE(ARMISD::VST2_UPD)
1823 MAKE_CASE(ARMISD::VST3_UPD)
1824 MAKE_CASE(ARMISD::VST4_UPD)
1825 MAKE_CASE(ARMISD::VST1x2_UPD)
1826 MAKE_CASE(ARMISD::VST1x3_UPD)
1827 MAKE_CASE(ARMISD::VST1x4_UPD)
1828 MAKE_CASE(ARMISD::VST2LN_UPD)
1829 MAKE_CASE(ARMISD::VST3LN_UPD)
1830 MAKE_CASE(ARMISD::VST4LN_UPD)
1831 MAKE_CASE(ARMISD::WLS)
1832 MAKE_CASE(ARMISD::WLSSETUP)
1833 MAKE_CASE(ARMISD::LE)
1834 MAKE_CASE(ARMISD::LOOP_DEC)
1835 MAKE_CASE(ARMISD::CSINV)
1836 MAKE_CASE(ARMISD::CSNEG)
1837 MAKE_CASE(ARMISD::CSINC)
1838 MAKE_CASE(ARMISD::MEMCPYLOOP)
1839 MAKE_CASE(ARMISD::MEMSETLOOP)
1840#undef MAKE_CASE
1841 }
1842 return nullptr;
1843}
1844
1845EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1846 EVT VT) const {
1847 if (!VT.isVector())
1848 return getPointerTy(DL);
1849
1850 // MVE has a predicate register.
1851 if ((Subtarget->hasMVEIntegerOps() &&
1852 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) ||
1853 (Subtarget->hasMVEFloatOps() && (VT == MVT::v4f32 || VT == MVT::v8f16)))
1854 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1855 return VT.changeVectorElementTypeToInteger();
1856}
1857
1858/// getRegClassFor - Return the register class that should be used for the
1859/// specified value type.
1860const TargetRegisterClass *
1861ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1862 (void)isDivergent;
1863 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1864 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1865 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1866 // MVE Q registers.
1867 if (Subtarget->hasNEON()) {
1868 if (VT == MVT::v4i64)
1869 return &ARM::QQPRRegClass;
1870 if (VT == MVT::v8i64)
1871 return &ARM::QQQQPRRegClass;
1872 }
1873 if (Subtarget->hasMVEIntegerOps()) {
1874 if (VT == MVT::v4i64)
1875 return &ARM::MQQPRRegClass;
1876 if (VT == MVT::v8i64)
1877 return &ARM::MQQQQPRRegClass;
1878 }
1879 return TargetLowering::getRegClassFor(VT);
1880}
1881
1882// memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1883// source/dest is aligned and the copy size is large enough. We therefore want
1884// to align such objects passed to memory intrinsics.
1885bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1886 unsigned &PrefAlign) const {
1887 if (!isa<MemIntrinsic>(CI))
1888 return false;
1889 MinSize = 8;
1890 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1891 // cycle faster than 4-byte aligned LDM.
1892 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1893 return true;
1894}
1895
1896// Create a fast isel object.
1897FastISel *
1898ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1899 const TargetLibraryInfo *libInfo) const {
1900 return ARM::createFastISel(funcInfo, libInfo);
1901}
1902
1903Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1904 unsigned NumVals = N->getNumValues();
1905 if (!NumVals)
1906 return Sched::RegPressure;
1907
1908 for (unsigned i = 0; i != NumVals; ++i) {
1909 EVT VT = N->getValueType(i);
1910 if (VT == MVT::Glue || VT == MVT::Other)
1911 continue;
1912 if (VT.isFloatingPoint() || VT.isVector())
1913 return Sched::ILP;
1914 }
1915
1916 if (!N->isMachineOpcode())
1917 return Sched::RegPressure;
1918
1919 // Load are scheduled for latency even if there instruction itinerary
1920 // is not available.
1921 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1922 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1923
1924 if (MCID.getNumDefs() == 0)
1925 return Sched::RegPressure;
1926 if (!Itins->isEmpty() &&
1927 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1928 return Sched::ILP;
1929
1930 return Sched::RegPressure;
1931}
1932
1933//===----------------------------------------------------------------------===//
1934// Lowering Code
1935//===----------------------------------------------------------------------===//
1936
1937static bool isSRL16(const SDValue &Op) {
1938 if (Op.getOpcode() != ISD::SRL)
1939 return false;
1940 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1941 return Const->getZExtValue() == 16;
1942 return false;
1943}
1944
1945static bool isSRA16(const SDValue &Op) {
1946 if (Op.getOpcode() != ISD::SRA)
1947 return false;
1948 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1949 return Const->getZExtValue() == 16;
1950 return false;
1951}
1952
1953static bool isSHL16(const SDValue &Op) {
1954 if (Op.getOpcode() != ISD::SHL)
1955 return false;
1956 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1957 return Const->getZExtValue() == 16;
1958 return false;
1959}
1960
1961// Check for a signed 16-bit value. We special case SRA because it makes it
1962// more simple when also looking for SRAs that aren't sign extending a
1963// smaller value. Without the check, we'd need to take extra care with
1964// checking order for some operations.
1965static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1966 if (isSRA16(Op))
1967 return isSHL16(Op.getOperand(0));
1968 return DAG.ComputeNumSignBits(Op) == 17;
1969}
1970
1971/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1972static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1973 switch (CC) {
1974 default: llvm_unreachable("Unknown condition code!")::llvm::llvm_unreachable_internal("Unknown condition code!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 1974)
;
1975 case ISD::SETNE: return ARMCC::NE;
1976 case ISD::SETEQ: return ARMCC::EQ;
1977 case ISD::SETGT: return ARMCC::GT;
1978 case ISD::SETGE: return ARMCC::GE;
1979 case ISD::SETLT: return ARMCC::LT;
1980 case ISD::SETLE: return ARMCC::LE;
1981 case ISD::SETUGT: return ARMCC::HI;
1982 case ISD::SETUGE: return ARMCC::HS;
1983 case ISD::SETULT: return ARMCC::LO;
1984 case ISD::SETULE: return ARMCC::LS;
1985 }
1986}
1987
1988/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1989static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1990 ARMCC::CondCodes &CondCode2) {
1991 CondCode2 = ARMCC::AL;
1992 switch (CC) {
1993 default: llvm_unreachable("Unknown FP condition!")::llvm::llvm_unreachable_internal("Unknown FP condition!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 1993)
;
1994 case ISD::SETEQ:
1995 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1996 case ISD::SETGT:
1997 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1998 case ISD::SETGE:
1999 case ISD::SETOGE: CondCode = ARMCC::GE; break;
2000 case ISD::SETOLT: CondCode = ARMCC::MI; break;
2001 case ISD::SETOLE: CondCode = ARMCC::LS; break;
2002 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
2003 case ISD::SETO: CondCode = ARMCC::VC; break;
2004 case ISD::SETUO: CondCode = ARMCC::VS; break;
2005 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
2006 case ISD::SETUGT: CondCode = ARMCC::HI; break;
2007 case ISD::SETUGE: CondCode = ARMCC::PL; break;
2008 case ISD::SETLT:
2009 case ISD::SETULT: CondCode = ARMCC::LT; break;
2010 case ISD::SETLE:
2011 case ISD::SETULE: CondCode = ARMCC::LE; break;
2012 case ISD::SETNE:
2013 case ISD::SETUNE: CondCode = ARMCC::NE; break;
2014 }
2015}
2016
2017//===----------------------------------------------------------------------===//
2018// Calling Convention Implementation
2019//===----------------------------------------------------------------------===//
2020
2021/// getEffectiveCallingConv - Get the effective calling convention, taking into
2022/// account presence of floating point hardware and calling convention
2023/// limitations, such as support for variadic functions.
2024CallingConv::ID
2025ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
2026 bool isVarArg) const {
2027 switch (CC) {
2028 default:
2029 report_fatal_error("Unsupported calling convention");
2030 case CallingConv::ARM_AAPCS:
2031 case CallingConv::ARM_APCS:
2032 case CallingConv::GHC:
2033 case CallingConv::CFGuard_Check:
2034 return CC;
2035 case CallingConv::PreserveMost:
2036 return CallingConv::PreserveMost;
2037 case CallingConv::ARM_AAPCS_VFP:
2038 case CallingConv::Swift:
2039 case CallingConv::SwiftTail:
2040 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
2041 case CallingConv::C:
2042 case CallingConv::Tail:
2043 if (!Subtarget->isAAPCS_ABI())
2044 return CallingConv::ARM_APCS;
2045 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
2046 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
2047 !isVarArg)
2048 return CallingConv::ARM_AAPCS_VFP;
2049 else
2050 return CallingConv::ARM_AAPCS;
2051 case CallingConv::Fast:
2052 case CallingConv::CXX_FAST_TLS:
2053 if (!Subtarget->isAAPCS_ABI()) {
2054 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
2055 return CallingConv::Fast;
2056 return CallingConv::ARM_APCS;
2057 } else if (Subtarget->hasVFP2Base() &&
2058 !Subtarget->isThumb1Only() && !isVarArg)
2059 return CallingConv::ARM_AAPCS_VFP;
2060 else
2061 return CallingConv::ARM_AAPCS;
2062 }
2063}
2064
2065CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2066 bool isVarArg) const {
2067 return CCAssignFnForNode(CC, false, isVarArg);
2068}
2069
2070CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
2071 bool isVarArg) const {
2072 return CCAssignFnForNode(CC, true, isVarArg);
2073}
2074
2075/// CCAssignFnForNode - Selects the correct CCAssignFn for the given
2076/// CallingConvention.
2077CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
2078 bool Return,
2079 bool isVarArg) const {
2080 switch (getEffectiveCallingConv(CC, isVarArg)) {
2081 default:
2082 report_fatal_error("Unsupported calling convention");
2083 case CallingConv::ARM_APCS:
2084 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
2085 case CallingConv::ARM_AAPCS:
2086 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2087 case CallingConv::ARM_AAPCS_VFP:
2088 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
2089 case CallingConv::Fast:
2090 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
2091 case CallingConv::GHC:
2092 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
2093 case CallingConv::PreserveMost:
2094 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2095 case CallingConv::CFGuard_Check:
2096 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
2097 }
2098}
2099
2100SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
2101 MVT LocVT, MVT ValVT, SDValue Val) const {
2102 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
2103 Val);
2104 if (Subtarget->hasFullFP16()) {
2105 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
2106 } else {
2107 Val = DAG.getNode(ISD::TRUNCATE, dl,
2108 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2109 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
2110 }
2111 return Val;
2112}
2113
2114SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
2115 MVT LocVT, MVT ValVT,
2116 SDValue Val) const {
2117 if (Subtarget->hasFullFP16()) {
2118 Val = DAG.getNode(ARMISD::VMOVrh, dl,
2119 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2120 } else {
2121 Val = DAG.getNode(ISD::BITCAST, dl,
2122 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2123 Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
2124 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2125 }
2126 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
2127}
2128
2129/// LowerCallResult - Lower the result values of a call into the
2130/// appropriate copies out of appropriate physical registers.
2131SDValue ARMTargetLowering::LowerCallResult(
2132 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2133 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2134 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2135 SDValue ThisVal) const {
2136 // Assign locations to each value returned by this call.
2137 SmallVector<CCValAssign, 16> RVLocs;
2138 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2139 *DAG.getContext());
2140 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
2141
2142 // Copy all of the result registers out of their specified physreg.
2143 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2144 CCValAssign VA = RVLocs[i];
2145
2146 // Pass 'this' value directly from the argument to return value, to avoid
2147 // reg unit interference
2148 if (i == 0 && isThisReturn) {
2149 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2150, __extension__ __PRETTY_FUNCTION__))
2150 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2150, __extension__ __PRETTY_FUNCTION__))
;
2151 InVals.push_back(ThisVal);
2152 continue;
2153 }
2154
2155 SDValue Val;
2156 if (VA.needsCustom() &&
2157 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
2158 // Handle f64 or half of a v2f64.
2159 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2160 InFlag);
2161 Chain = Lo.getValue(1);
2162 InFlag = Lo.getValue(2);
2163 VA = RVLocs[++i]; // skip ahead to next loc
2164 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2165 InFlag);
2166 Chain = Hi.getValue(1);
2167 InFlag = Hi.getValue(2);
2168 if (!Subtarget->isLittle())
2169 std::swap (Lo, Hi);
2170 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2171
2172 if (VA.getLocVT() == MVT::v2f64) {
2173 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2174 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2175 DAG.getConstant(0, dl, MVT::i32));
2176
2177 VA = RVLocs[++i]; // skip ahead to next loc
2178 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2179 Chain = Lo.getValue(1);
2180 InFlag = Lo.getValue(2);
2181 VA = RVLocs[++i]; // skip ahead to next loc
2182 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2183 Chain = Hi.getValue(1);
2184 InFlag = Hi.getValue(2);
2185 if (!Subtarget->isLittle())
2186 std::swap (Lo, Hi);
2187 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2188 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2189 DAG.getConstant(1, dl, MVT::i32));
2190 }
2191 } else {
2192 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2193 InFlag);
2194 Chain = Val.getValue(1);
2195 InFlag = Val.getValue(2);
2196 }
2197
2198 switch (VA.getLocInfo()) {
2199 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2199)
;
2200 case CCValAssign::Full: break;
2201 case CCValAssign::BCvt:
2202 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2203 break;
2204 }
2205
2206 // f16 arguments have their size extended to 4 bytes and passed as if they
2207 // had been copied to the LSBs of a 32-bit register.
2208 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2209 if (VA.needsCustom() &&
2210 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
2211 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
2212
2213 InVals.push_back(Val);
2214 }
2215
2216 return Chain;
2217}
2218
2219std::pair<SDValue, MachinePointerInfo> ARMTargetLowering::computeAddrForCallArg(
2220 const SDLoc &dl, SelectionDAG &DAG, const CCValAssign &VA, SDValue StackPtr,
2221 bool IsTailCall, int SPDiff) const {
2222 SDValue DstAddr;
2223 MachinePointerInfo DstInfo;
2224 int32_t Offset = VA.getLocMemOffset();
2225 MachineFunction &MF = DAG.getMachineFunction();
2226
2227 if (IsTailCall) {
2228 Offset += SPDiff;
2229 auto PtrVT = getPointerTy(DAG.getDataLayout());
2230 int Size = VA.getLocVT().getFixedSizeInBits() / 8;
2231 int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
2232 DstAddr = DAG.getFrameIndex(FI, PtrVT);
2233 DstInfo =
2234 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
2235 } else {
2236 SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
2237 DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2238 StackPtr, PtrOff);
2239 DstInfo =
2240 MachinePointerInfo::getStack(DAG.getMachineFunction(), Offset);
2241 }
2242
2243 return std::make_pair(DstAddr, DstInfo);
2244}
2245
2246void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2247 SDValue Chain, SDValue &Arg,
2248 RegsToPassVector &RegsToPass,
2249 CCValAssign &VA, CCValAssign &NextVA,
2250 SDValue &StackPtr,
2251 SmallVectorImpl<SDValue> &MemOpChains,
2252 bool IsTailCall,
2253 int SPDiff) const {
2254 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2255 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2256 unsigned id = Subtarget->isLittle() ? 0 : 1;
2257 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2258
2259 if (NextVA.isRegLoc())
2260 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2261 else {
2262 assert(NextVA.isMemLoc())(static_cast <bool> (NextVA.isMemLoc()) ? void (0) : __assert_fail
("NextVA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2262, __extension__ __PRETTY_FUNCTION__))
;
2263 if (!StackPtr.getNode())
2264 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2265 getPointerTy(DAG.getDataLayout()));
2266
2267 SDValue DstAddr;
2268 MachinePointerInfo DstInfo;
2269 std::tie(DstAddr, DstInfo) =
2270 computeAddrForCallArg(dl, DAG, NextVA, StackPtr, IsTailCall, SPDiff);
2271 MemOpChains.push_back(
2272 DAG.getStore(Chain, dl, fmrrd.getValue(1 - id), DstAddr, DstInfo));
2273 }
2274}
2275
2276static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
2277 return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
2278 CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
2279}
2280
2281/// LowerCall - Lowering a call into a callseq_start <-
2282/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2283/// nodes.
2284SDValue
2285ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2286 SmallVectorImpl<SDValue> &InVals) const {
2287 SelectionDAG &DAG = CLI.DAG;
2288 SDLoc &dl = CLI.DL;
2289 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2290 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2291 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2292 SDValue Chain = CLI.Chain;
2293 SDValue Callee = CLI.Callee;
2294 bool &isTailCall = CLI.IsTailCall;
2295 CallingConv::ID CallConv = CLI.CallConv;
2296 bool doesNotRet = CLI.DoesNotReturn;
2297 bool isVarArg = CLI.IsVarArg;
2298
2299 MachineFunction &MF = DAG.getMachineFunction();
2300 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2301 MachineFunction::CallSiteInfo CSInfo;
2302 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1
'?' condition is false
2303 bool isThisReturn = false;
2304 bool isCmseNSCall = false;
2305 bool isSibCall = false;
2306 bool PreferIndirect = false;
2307
2308 // Determine whether this is a non-secure function call.
2309 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr("cmse_nonsecure_call"))
2
Assuming field 'CB' is null
3
Taking false branch
2310 isCmseNSCall = true;
2311
2312 // Disable tail calls if they're not supported.
2313 if (!Subtarget->supportsTailCall())
4
Assuming the condition is false
2314 isTailCall = false;
2315
2316 // For both the non-secure calls and the returns from a CMSE entry function,
2317 // the function needs to do some extra work afte r the call, or before the
2318 // return, respectively, thus it cannot end with atail call
2319 if (isCmseNSCall
4.1
'isCmseNSCall' is false
|| AFI->isCmseNSEntryFunction())
5
Assuming the condition is false
6
Taking false branch
2320 isTailCall = false;
2321
2322 if (isa<GlobalAddressSDNode>(Callee)) {
7
Assuming 'Callee' is not a 'GlobalAddressSDNode'
8
Taking false branch
2323 // If we're optimizing for minimum size and the function is called three or
2324 // more times in this block, we can improve codesize by calling indirectly
2325 // as BLXr has a 16-bit encoding.
2326 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2327 if (CLI.CB) {
2328 auto *BB = CLI.CB->getParent();
2329 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2330 count_if(GV->users(), [&BB](const User *U) {
2331 return isa<Instruction>(U) &&
2332 cast<Instruction>(U)->getParent() == BB;
2333 }) > 2;
2334 }
2335 }
2336 if (isTailCall) {
9
Assuming 'isTailCall' is false
2337 // Check if it's really possible to do a tail call.
2338 isTailCall = IsEligibleForTailCallOptimization(
2339 Callee, CallConv, isVarArg, isStructRet,
2340 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2341 PreferIndirect);
2342
2343 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt &&
2344 CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
2345 isSibCall = true;
2346
2347 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2348 // detected sibcalls.
2349 if (isTailCall)
2350 ++NumTailCalls;
2351 }
2352
2353 if (!isTailCall
9.1
'isTailCall' is false
&& CLI.CB
9.2
Field 'CB' is null
&& CLI.CB->isMustTailCall())
2354 report_fatal_error("failed to perform tail call elimination on a call "
2355 "site marked musttail");
2356 // Analyze operands of the call, assigning locations to each operand.
2357 SmallVector<CCValAssign, 16> ArgLocs;
2358 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2359 *DAG.getContext());
2360 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2361
2362 // Get a count of how many bytes are to be pushed on the stack.
2363 unsigned NumBytes = CCInfo.getNextStackOffset();
2364
2365 // SPDiff is the byte offset of the call's argument area from the callee's.
2366 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2367 // by this amount for a tail call. In a sibling call it must be 0 because the
2368 // caller will deallocate the entire stack and the callee still expects its
2369 // arguments to begin at SP+0. Completely unused for non-tail calls.
2370 int SPDiff = 0;
2371
2372 if (isTailCall && !isSibCall) {
10
Assuming 'isTailCall' is false
2373 auto FuncInfo = MF.getInfo<ARMFunctionInfo>();
2374 unsigned NumReusableBytes = FuncInfo->getArgumentStackSize();
2375
2376 // Since callee will pop argument stack as a tail call, we must keep the
2377 // popped size 16-byte aligned.
2378 Align StackAlign = DAG.getDataLayout().getStackAlignment();
2379 NumBytes = alignTo(NumBytes, StackAlign);
2380
2381 // SPDiff will be negative if this tail call requires more space than we
2382 // would automatically have in our incoming argument space. Positive if we
2383 // can actually shrink the stack.
2384 SPDiff = NumReusableBytes - NumBytes;
2385
2386 // If this call requires more stack than we have available from
2387 // LowerFormalArguments, tell FrameLowering to reserve space for it.
2388 if (SPDiff < 0 && AFI->getArgRegsSaveSize() < (unsigned)-SPDiff)
2389 AFI->setArgRegsSaveSize(-SPDiff);
2390 }
2391
2392 if (isSibCall
10.1
'isSibCall' is false
) {
11
Taking false branch
2393 // For sibling tail calls, memory operands are available in our caller's stack.
2394 NumBytes = 0;
2395 } else {
2396 // Adjust the stack pointer for the new arguments...
2397 // These operations are automatically eliminated by the prolog/epilog pass
2398 Chain = DAG.getCALLSEQ_START(Chain, isTailCall
11.1
'isTailCall' is false
? 0 : NumBytes, 0, dl);
12
'?' condition is false
2399 }
2400
2401 SDValue StackPtr =
2402 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2403
2404 RegsToPassVector RegsToPass;
2405 SmallVector<SDValue, 8> MemOpChains;
2406
2407 // During a tail call, stores to the argument area must happen after all of
2408 // the function's incoming arguments have been loaded because they may alias.
2409 // This is done by folding in a TokenFactor from LowerFormalArguments, but
2410 // there's no point in doing so repeatedly so this tracks whether that's
2411 // happened yet.
2412 bool AfterFormalArgLoads = false;
2413
2414 // Walk the register/memloc assignments, inserting copies/loads. In the case
2415 // of tail call optimization, arguments are handled later.
2416 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
14
Loop condition is false. Execution continues on line 2570
2417 i != e;
13
Assuming 'i' is equal to 'e'
2418 ++i, ++realArgIdx) {
2419 CCValAssign &VA = ArgLocs[i];
2420 SDValue Arg = OutVals[realArgIdx];
2421 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2422 bool isByVal = Flags.isByVal();
2423
2424 // Promote the value if needed.
2425 switch (VA.getLocInfo()) {
2426 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2426)
;
2427 case CCValAssign::Full: break;
2428 case CCValAssign::SExt:
2429 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2430 break;
2431 case CCValAssign::ZExt:
2432 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2433 break;
2434 case CCValAssign::AExt:
2435 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2436 break;
2437 case CCValAssign::BCvt:
2438 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2439 break;
2440 }
2441
2442 if (isTailCall && VA.isMemLoc() && !AfterFormalArgLoads) {
2443 Chain = DAG.getStackArgumentTokenFactor(Chain);
2444 AfterFormalArgLoads = true;
2445 }
2446
2447 // f16 arguments have their size extended to 4 bytes and passed as if they
2448 // had been copied to the LSBs of a 32-bit register.
2449 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2450 if (VA.needsCustom() &&
2451 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2452 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2453 } else {
2454 // f16 arguments could have been extended prior to argument lowering.
2455 // Mask them arguments if this is a CMSE nonsecure call.
2456 auto ArgVT = Outs[realArgIdx].ArgVT;
2457 if (isCmseNSCall && (ArgVT == MVT::f16)) {
2458 auto LocBits = VA.getLocVT().getSizeInBits();
2459 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2460 SDValue Mask =
2461 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2462 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2463 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2464 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2465 }
2466 }
2467
2468 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2469 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2470 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2471 DAG.getConstant(0, dl, MVT::i32));
2472 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2473 DAG.getConstant(1, dl, MVT::i32));
2474
2475 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2476 StackPtr, MemOpChains, isTailCall, SPDiff);
2477
2478 VA = ArgLocs[++i]; // skip ahead to next loc
2479 if (VA.isRegLoc()) {
2480 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2481 StackPtr, MemOpChains, isTailCall, SPDiff);
2482 } else {
2483 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2483, __extension__ __PRETTY_FUNCTION__))
;
2484 SDValue DstAddr;
2485 MachinePointerInfo DstInfo;
2486 std::tie(DstAddr, DstInfo) =
2487 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2488 MemOpChains.push_back(DAG.getStore(Chain, dl, Op1, DstAddr, DstInfo));
2489 }
2490 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2491 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2492 StackPtr, MemOpChains, isTailCall, SPDiff);
2493 } else if (VA.isRegLoc()) {
2494 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2495 Outs[0].VT == MVT::i32) {
2496 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2497, __extension__ __PRETTY_FUNCTION__))
2497 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2497, __extension__ __PRETTY_FUNCTION__))
;
2498 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'\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2499, __extension__ __PRETTY_FUNCTION__))
2499 "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'\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2499, __extension__ __PRETTY_FUNCTION__))
;
2500 isThisReturn = true;
2501 }
2502 const TargetOptions &Options = DAG.getTarget().Options;
2503 if (Options.EmitCallSiteInfo)
2504 CSInfo.emplace_back(VA.getLocReg(), i);
2505 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2506 } else if (isByVal) {
2507 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2507, __extension__ __PRETTY_FUNCTION__))
;
2508 unsigned offset = 0;
2509
2510 // True if this byval aggregate will be split between registers
2511 // and memory.
2512 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2513 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2514
2515 if (CurByValIdx < ByValArgsCount) {
2516
2517 unsigned RegBegin, RegEnd;
2518 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2519
2520 EVT PtrVT =
2521 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2522 unsigned int i, j;
2523 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2524 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2525 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2526 SDValue Load =
2527 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2528 DAG.InferPtrAlign(AddArg));
2529 MemOpChains.push_back(Load.getValue(1));
2530 RegsToPass.push_back(std::make_pair(j, Load));
2531 }
2532
2533 // If parameter size outsides register area, "offset" value
2534 // helps us to calculate stack slot for remained part properly.
2535 offset = RegEnd - RegBegin;
2536
2537 CCInfo.nextInRegsParam();
2538 }
2539
2540 if (Flags.getByValSize() > 4*offset) {
2541 auto PtrVT = getPointerTy(DAG.getDataLayout());
2542 SDValue Dst;
2543 MachinePointerInfo DstInfo;
2544 std::tie(Dst, DstInfo) =
2545 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2546 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2547 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2548 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2549 MVT::i32);
2550 SDValue AlignNode =
2551 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2552
2553 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2554 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2555 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2556 Ops));
2557 }
2558 } else {
2559 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2559, __extension__ __PRETTY_FUNCTION__))
;
2560 SDValue DstAddr;
2561 MachinePointerInfo DstInfo;
2562 std::tie(DstAddr, DstInfo) =
2563 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2564
2565 SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo);
2566 MemOpChains.push_back(Store);
2567 }
2568 }
2569
2570 if (!MemOpChains.empty())
15
Taking false branch
2571 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2572
2573 // Build a sequence of copy-to-reg nodes chained together with token chain
2574 // and flag operands which copy the outgoing args into the appropriate regs.
2575 SDValue InFlag;
2576 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 2585
2577 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2578 RegsToPass[i].second, InFlag);
2579 InFlag = Chain.getValue(1);
2580 }
2581
2582 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2583 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2584 // node so that legalize doesn't hack it.
2585 bool isDirect = false;
2586
2587 const TargetMachine &TM = getTargetMachine();
2588 const Module *Mod = MF.getFunction().getParent();
2589 const GlobalValue *GV = nullptr;
18
'GV' initialized to a null pointer value
2590 if (GlobalAddressSDNode *G
18.1
'G' is null
= dyn_cast<GlobalAddressSDNode>(Callee))
2591 GV = G->getGlobal();
2592 bool isStub =
2593 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
19
Assuming the condition is false
2594
2595 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
20
Assuming the condition is true
2596 bool isLocalARMFunc = false;
2597 auto PtrVt = getPointerTy(DAG.getDataLayout());
2598
2599 if (Subtarget->genLongCalls()) {
21
Assuming the condition is false
22
Taking false branch
2600 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2601, __extension__ __PRETTY_FUNCTION__))
2601 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2601, __extension__ __PRETTY_FUNCTION__))
;
2602 // Handle a global address or an external symbol. If it's not one of
2603 // those, the target's already in a register, so we don't need to do
2604 // anything extra.
2605 if (isa<GlobalAddressSDNode>(Callee)) {
2606 // Create a constant pool entry for the callee address
2607 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2608 ARMConstantPoolValue *CPV =
2609 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2610
2611 // Get the address of the callee into a register
2612 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2613 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2614 Callee = DAG.getLoad(
2615 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2616 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2617 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2618 const char *Sym = S->getSymbol();
2619
2620 // Create a constant pool entry for the callee address
2621 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2622 ARMConstantPoolValue *CPV =
2623 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2624 ARMPCLabelIndex, 0);
2625 // Get the address of the callee into a register
2626 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2627 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2628 Callee = DAG.getLoad(
2629 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2630 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2631 }
2632 } else if (isa<GlobalAddressSDNode>(Callee)) {
23
Assuming 'Callee' is a 'GlobalAddressSDNode'
24
Taking true branch
2633 if (!PreferIndirect
24.1
'PreferIndirect' is false
) {
25
Taking true branch
2634 isDirect = true;
2635 bool isDef = GV->isStrongDefinitionForLinker();
26
Called C++ object pointer is null
2636
2637 // ARM call to a local ARM function is predicable.
2638 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2639 // tBX takes a register source operand.
2640 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2641 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?\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2641, __extension__ __PRETTY_FUNCTION__))
;
2642 Callee = DAG.getNode(
2643 ARMISD::WrapperPIC, dl, PtrVt,
2644 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2645 Callee = DAG.getLoad(
2646 PtrVt, dl, DAG.getEntryNode(), Callee,
2647 MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(),
2648 MachineMemOperand::MODereferenceable |
2649 MachineMemOperand::MOInvariant);
2650 } else if (Subtarget->isTargetCOFF()) {
2651 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2652, __extension__ __PRETTY_FUNCTION__))
2652 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2652, __extension__ __PRETTY_FUNCTION__))
;
2653 unsigned TargetFlags = ARMII::MO_NO_FLAG;
2654 if (GV->hasDLLImportStorageClass())
2655 TargetFlags = ARMII::MO_DLLIMPORT;
2656 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
2657 TargetFlags = ARMII::MO_COFFSTUB;
2658 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2659 TargetFlags);
2660 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2661 Callee =
2662 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2663 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2664 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2665 } else {
2666 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2667 }
2668 }
2669 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2670 isDirect = true;
2671 // tBX takes a register source operand.
2672 const char *Sym = S->getSymbol();
2673 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2674 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2675 ARMConstantPoolValue *CPV =
2676 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2677 ARMPCLabelIndex, 4);
2678 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2679 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2680 Callee = DAG.getLoad(
2681 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2682 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2683 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2684 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2685 } else {
2686 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2687 }
2688 }
2689
2690 if (isCmseNSCall) {
2691 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2692, __extension__ __PRETTY_FUNCTION__))
2692 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2692, __extension__ __PRETTY_FUNCTION__))
;
2693 if (NumBytes > 0) {
2694 DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(),
2695 "call to non-secure function would "
2696 "require passing arguments on stack",
2697 dl.getDebugLoc());
2698 DAG.getContext()->diagnose(Diag);
2699 }
2700 if (isStructRet) {
2701 DiagnosticInfoUnsupported Diag(
2702 DAG.getMachineFunction().getFunction(),
2703 "call to non-secure function would return value through pointer",
2704 dl.getDebugLoc());
2705 DAG.getContext()->diagnose(Diag);
2706 }
2707 }
2708
2709 // FIXME: handle tail calls differently.
2710 unsigned CallOpc;
2711 if (Subtarget->isThumb()) {
2712 if (isCmseNSCall)
2713 CallOpc = ARMISD::tSECALL;
2714 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2715 CallOpc = ARMISD::CALL_NOLINK;
2716 else
2717 CallOpc = ARMISD::CALL;
2718 } else {
2719 if (!isDirect && !Subtarget->hasV5TOps())
2720 CallOpc = ARMISD::CALL_NOLINK;
2721 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2722 // Emit regular call when code size is the priority
2723 !Subtarget->hasMinSize())
2724 // "mov lr, pc; b _foo" to avoid confusing the RSP
2725 CallOpc = ARMISD::CALL_NOLINK;
2726 else
2727 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2728 }
2729
2730 // We don't usually want to end the call-sequence here because we would tidy
2731 // the frame up *after* the call, however in the ABI-changing tail-call case
2732 // we've carefully laid out the parameters so that when sp is reset they'll be
2733 // in the correct location.
2734 if (isTailCall && !isSibCall) {
2735 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
2736 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2737 InFlag = Chain.getValue(1);
2738 }
2739
2740 std::vector<SDValue> Ops;
2741 Ops.push_back(Chain);
2742 Ops.push_back(Callee);
2743
2744 if (isTailCall) {
2745 Ops.push_back(DAG.getTargetConstant(SPDiff, dl, MVT::i32));
2746 }
2747
2748 // Add argument registers to the end of the list so that they are known live
2749 // into the call.
2750 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2751 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2752 RegsToPass[i].second.getValueType()));
2753
2754 // Add a register mask operand representing the call-preserved registers.
2755 if (!isTailCall) {
2756 const uint32_t *Mask;
2757 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2758 if (isThisReturn) {
2759 // For 'this' returns, use the R0-preserving mask if applicable
2760 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2761 if (!Mask) {
2762 // Set isThisReturn to false if the calling convention is not one that
2763 // allows 'returned' to be modeled in this way, so LowerCallResult does
2764 // not try to pass 'this' straight through
2765 isThisReturn = false;
2766 Mask = ARI->getCallPreservedMask(MF, CallConv);
2767 }
2768 } else
2769 Mask = ARI->getCallPreservedMask(MF, CallConv);
2770
2771 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2771, __extension__ __PRETTY_FUNCTION__))
;
2772 Ops.push_back(DAG.getRegisterMask(Mask));
2773 }
2774
2775 if (InFlag.getNode())
2776 Ops.push_back(InFlag);
2777
2778 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2779 if (isTailCall) {
2780 MF.getFrameInfo().setHasTailCall();
2781 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2782 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2783 return Ret;
2784 }
2785
2786 // Returns a chain and a flag for retval copy to use.
2787 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2788 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2789 InFlag = Chain.getValue(1);
2790 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2791
2792 // If we're guaranteeing tail-calls will be honoured, the callee must
2793 // pop its own argument stack on return. But this call is *not* a tail call so
2794 // we need to undo that after it returns to restore the status-quo.
2795 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
2796 uint64_t CalleePopBytes =
2797 canGuaranteeTCO(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : -1ULL;
2798
2799 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2800 DAG.getIntPtrConstant(CalleePopBytes, dl, true),
2801 InFlag, dl);
2802 if (!Ins.empty())
2803 InFlag = Chain.getValue(1);
2804
2805 // Handle result values, copying them out of physregs into vregs that we
2806 // return.
2807 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2808 InVals, isThisReturn,
2809 isThisReturn ? OutVals[0] : SDValue());
2810}
2811
2812/// HandleByVal - Every parameter *after* a byval parameter is passed
2813/// on the stack. Remember the next parameter register to allocate,
2814/// and then confiscate the rest of the parameter registers to insure
2815/// this.
2816void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2817 Align Alignment) const {
2818 // Byval (as with any stack) slots are always at least 4 byte aligned.
2819 Alignment = std::max(Alignment, Align(4));
2820
2821 unsigned Reg = State->AllocateReg(GPRArgRegs);
2822 if (!Reg)
2823 return;
2824
2825 unsigned AlignInRegs = Alignment.value() / 4;
2826 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2827 for (unsigned i = 0; i < Waste; ++i)
2828 Reg = State->AllocateReg(GPRArgRegs);
2829
2830 if (!Reg)
2831 return;
2832
2833 unsigned Excess = 4 * (ARM::R4 - Reg);
2834
2835 // Special case when NSAA != SP and parameter size greater than size of
2836 // all remained GPR regs. In that case we can't split parameter, we must
2837 // send it to stack. We also must set NCRN to R4, so waste all
2838 // remained registers.
2839 const unsigned NSAAOffset = State->getNextStackOffset();
2840 if (NSAAOffset != 0 && Size > Excess) {
2841 while (State->AllocateReg(GPRArgRegs))
2842 ;
2843 return;
2844 }
2845
2846 // First register for byval parameter is the first register that wasn't
2847 // allocated before this method call, so it would be "reg".
2848 // If parameter is small enough to be saved in range [reg, r4), then
2849 // the end (first after last) register would be reg + param-size-in-regs,
2850 // else parameter would be splitted between registers and stack,
2851 // end register would be r4 in this case.
2852 unsigned ByValRegBegin = Reg;
2853 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2854 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2855 // Note, first register is allocated in the beginning of function already,
2856 // allocate remained amount of registers we need.
2857 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2858 State->AllocateReg(GPRArgRegs);
2859 // A byval parameter that is split between registers and memory needs its
2860 // size truncated here.
2861 // In the case where the entire structure fits in registers, we set the
2862 // size in memory to zero.
2863 Size = std::max<int>(Size - Excess, 0);
2864}
2865
2866/// MatchingStackOffset - Return true if the given stack call argument is
2867/// already available in the same position (relatively) of the caller's
2868/// incoming argument stack.
2869static
2870bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2871 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2872 const TargetInstrInfo *TII) {
2873 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2874 int FI = std::numeric_limits<int>::max();
2875 if (Arg.getOpcode() == ISD::CopyFromReg) {
2876 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2877 if (!Register::isVirtualRegister(VR))
2878 return false;
2879 MachineInstr *Def = MRI->getVRegDef(VR);
2880 if (!Def)
2881 return false;
2882 if (!Flags.isByVal()) {
2883 if (!TII->isLoadFromStackSlot(*Def, FI))
2884 return false;
2885 } else {
2886 return false;
2887 }
2888 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2889 if (Flags.isByVal())
2890 // ByVal argument is passed in as a pointer but it's now being
2891 // dereferenced. e.g.
2892 // define @foo(%struct.X* %A) {
2893 // tail call @bar(%struct.X* byval %A)
2894 // }
2895 return false;
2896 SDValue Ptr = Ld->getBasePtr();
2897 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2898 if (!FINode)
2899 return false;
2900 FI = FINode->getIndex();
2901 } else
2902 return false;
2903
2904 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()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2904, __extension__ __PRETTY_FUNCTION__))
;
2905 if (!MFI.isFixedObjectIndex(FI))
2906 return false;
2907 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2908}
2909
2910/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2911/// for tail call optimization. Targets which want to do tail call
2912/// optimization should implement this function.
2913bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2914 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2915 bool isCalleeStructRet, bool isCallerStructRet,
2916 const SmallVectorImpl<ISD::OutputArg> &Outs,
2917 const SmallVectorImpl<SDValue> &OutVals,
2918 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2919 const bool isIndirect) const {
2920 MachineFunction &MF = DAG.getMachineFunction();
2921 const Function &CallerF = MF.getFunction();
2922 CallingConv::ID CallerCC = CallerF.getCallingConv();
2923
2924 assert(Subtarget->supportsTailCall())(static_cast <bool> (Subtarget->supportsTailCall()) ?
void (0) : __assert_fail ("Subtarget->supportsTailCall()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2924, __extension__ __PRETTY_FUNCTION__))
;
2925
2926 // Indirect tail calls cannot be optimized for Thumb1 if the args
2927 // to the call take up r0-r3. The reason is that there are no legal registers
2928 // left to hold the pointer to the function to be called.
2929 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2930 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2931 return false;
2932
2933 // Look for obvious safe cases to perform tail call optimization that do not
2934 // require ABI changes. This is what gcc calls sibcall.
2935
2936 // Exception-handling functions need a special set of instructions to indicate
2937 // a return to the hardware. Tail-calling another function would probably
2938 // break this.
2939 if (CallerF.hasFnAttribute("interrupt"))
2940 return false;
2941
2942 if (canGuaranteeTCO(CalleeCC, getTargetMachine().Options.GuaranteedTailCallOpt))
2943 return CalleeCC == CallerCC;
2944
2945 // Also avoid sibcall optimization if either caller or callee uses struct
2946 // return semantics.
2947 if (isCalleeStructRet || isCallerStructRet)
2948 return false;
2949
2950 // Externally-defined functions with weak linkage should not be
2951 // tail-called on ARM when the OS does not support dynamic
2952 // pre-emption of symbols, as the AAELF spec requires normal calls
2953 // to undefined weak functions to be replaced with a NOP or jump to the
2954 // next instruction. The behaviour of branch instructions in this
2955 // situation (as used for tail calls) is implementation-defined, so we
2956 // cannot rely on the linker replacing the tail call with a return.
2957 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2958 const GlobalValue *GV = G->getGlobal();
2959 const Triple &TT = getTargetMachine().getTargetTriple();
2960 if (GV->hasExternalWeakLinkage() &&
2961 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2962 return false;
2963 }
2964
2965 // Check that the call results are passed in the same way.
2966 LLVMContext &C = *DAG.getContext();
2967 if (!CCState::resultsCompatible(
2968 getEffectiveCallingConv(CalleeCC, isVarArg),
2969 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2970 CCAssignFnForReturn(CalleeCC, isVarArg),
2971 CCAssignFnForReturn(CallerCC, CallerF.isVarArg())))
2972 return false;
2973 // The callee has to preserve all registers the caller needs to preserve.
2974 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2975 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2976 if (CalleeCC != CallerCC) {
2977 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2978 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2979 return false;
2980 }
2981
2982 // If Caller's vararg or byval argument has been split between registers and
2983 // stack, do not perform tail call, since part of the argument is in caller's
2984 // local frame.
2985 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2986 if (AFI_Caller->getArgRegsSaveSize())
2987 return false;
2988
2989 // If the callee takes no arguments then go on to check the results of the
2990 // call.
2991 if (!Outs.empty()) {
2992 // Check if stack adjustment is needed. For now, do not do this if any
2993 // argument is passed on the stack.
2994 SmallVector<CCValAssign, 16> ArgLocs;
2995 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2996 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2997 if (CCInfo.getNextStackOffset()) {
2998 // Check if the arguments are already laid out in the right way as
2999 // the caller's fixed stack objects.
3000 MachineFrameInfo &MFI = MF.getFrameInfo();
3001 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3002 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
3003 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
3004 i != e;
3005 ++i, ++realArgIdx) {
3006 CCValAssign &VA = ArgLocs[i];
3007 EVT RegVT = VA.getLocVT();
3008 SDValue Arg = OutVals[realArgIdx];
3009 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3010 if (VA.getLocInfo() == CCValAssign::Indirect)
3011 return false;
3012 if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) {
3013 // f64 and vector types are split into multiple registers or
3014 // register/stack-slot combinations. The types will not match
3015 // the registers; give up on memory f64 refs until we figure
3016 // out what to do about this.
3017 if (!VA.isRegLoc())
3018 return false;
3019 if (!ArgLocs[++i].isRegLoc())
3020 return false;
3021 if (RegVT == MVT::v2f64) {
3022 if (!ArgLocs[++i].isRegLoc())
3023 return false;
3024 if (!ArgLocs[++i].isRegLoc())
3025 return false;
3026 }
3027 } else if (!VA.isRegLoc()) {
3028 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3029 MFI, MRI, TII))
3030 return false;
3031 }
3032 }
3033 }
3034
3035 const MachineRegisterInfo &MRI = MF.getRegInfo();
3036 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3037 return false;
3038 }
3039
3040 return true;
3041}
3042
3043bool
3044ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3045 MachineFunction &MF, bool isVarArg,
3046 const SmallVectorImpl<ISD::OutputArg> &Outs,
3047 LLVMContext &Context) const {
3048 SmallVector<CCValAssign, 16> RVLocs;
3049 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3050 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3051}
3052
3053static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3054 const SDLoc &DL, SelectionDAG &DAG) {
3055 const MachineFunction &MF = DAG.getMachineFunction();
3056 const Function &F = MF.getFunction();
3057
3058 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
3059
3060 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
3061 // version of the "preferred return address". These offsets affect the return
3062 // instruction if this is a return from PL1 without hypervisor extensions.
3063 // IRQ/FIQ: +4 "subs pc, lr, #4"
3064 // SWI: 0 "subs pc, lr, #0"
3065 // ABORT: +4 "subs pc, lr, #4"
3066 // UNDEF: +4/+2 "subs pc, lr, #0"
3067 // UNDEF varies depending on where the exception came from ARM or Thumb
3068 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
3069
3070 int64_t LROffset;
3071 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
3072 IntKind == "ABORT")
3073 LROffset = 4;
3074 else if (IntKind == "SWI" || IntKind == "UNDEF")
3075 LROffset = 0;
3076 else
3077 report_fatal_error("Unsupported interrupt attribute. If present, value "
3078 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
3079
3080 RetOps.insert(RetOps.begin() + 1,
3081 DAG.getConstant(LROffset, DL, MVT::i32, false));
3082
3083 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
3084}
3085
3086SDValue
3087ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3088 bool isVarArg,
3089 const SmallVectorImpl<ISD::OutputArg> &Outs,
3090 const SmallVectorImpl<SDValue> &OutVals,
3091 const SDLoc &dl, SelectionDAG &DAG) const {
3092 // CCValAssign - represent the assignment of the return value to a location.
3093 SmallVector<CCValAssign, 16> RVLocs;
3094
3095 // CCState - Info about the registers and stack slots.
3096 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3097 *DAG.getContext());
3098
3099 // Analyze outgoing return values.
3100 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3101
3102 SDValue Flag;
3103 SmallVector<SDValue, 4> RetOps;
3104 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3105 bool isLittleEndian = Subtarget->isLittle();
3106
3107 MachineFunction &MF = DAG.getMachineFunction();
3108 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3109 AFI->setReturnRegsCount(RVLocs.size());
3110
3111 // Report error if cmse entry function returns structure through first ptr arg.
3112 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
3113 // Note: using an empty SDLoc(), as the first line of the function is a
3114 // better place to report than the last line.
3115 DiagnosticInfoUnsupported Diag(
3116 DAG.getMachineFunction().getFunction(),
3117 "secure entry function would return value through pointer",
3118 SDLoc().getDebugLoc());
3119 DAG.getContext()->diagnose(Diag);
3120 }
3121
3122 // Copy the result values into the output registers.
3123 for (unsigned i = 0, realRVLocIdx = 0;
3124 i != RVLocs.size();
3125 ++i, ++realRVLocIdx) {
3126 CCValAssign &VA = RVLocs[i];
3127 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3127, __extension__ __PRETTY_FUNCTION__))
;
3128
3129 SDValue Arg = OutVals[realRVLocIdx];
3130 bool ReturnF16 = false;
3131
3132 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
3133 // Half-precision return values can be returned like this:
3134 //
3135 // t11 f16 = fadd ...
3136 // t12: i16 = bitcast t11
3137 // t13: i32 = zero_extend t12
3138 // t14: f32 = bitcast t13 <~~~~~~~ Arg
3139 //
3140 // to avoid code generation for bitcasts, we simply set Arg to the node
3141 // that produces the f16 value, t11 in this case.
3142 //
3143 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
3144 SDValue ZE = Arg.getOperand(0);
3145 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
3146 SDValue BC = ZE.getOperand(0);
3147 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
3148 Arg = BC.getOperand(0);
3149 ReturnF16 = true;
3150 }
3151 }
3152 }
3153 }
3154
3155 switch (VA.getLocInfo()) {
3156 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3156)
;
3157 case CCValAssign::Full: break;
3158 case CCValAssign::BCvt:
3159 if (!ReturnF16)
3160 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3161 break;
3162 }
3163
3164 // Mask f16 arguments if this is a CMSE nonsecure entry.
3165 auto RetVT = Outs[realRVLocIdx].ArgVT;
3166 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3167 if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3168 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3169 } else {
3170 auto LocBits = VA.getLocVT().getSizeInBits();
3171 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3172 SDValue Mask =
3173 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3174 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3175 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3176 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3177 }
3178 }
3179
3180 if (VA.needsCustom() &&
3181 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3182 if (VA.getLocVT() == MVT::v2f64) {
3183 // Extract the first half and return it in two registers.
3184 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3185 DAG.getConstant(0, dl, MVT::i32));
3186 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3187 DAG.getVTList(MVT::i32, MVT::i32), Half);
3188
3189 Chain =
3190 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3191 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag);
3192 Flag = Chain.getValue(1);
3193 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3194 VA = RVLocs[++i]; // skip ahead to next loc
3195 Chain =
3196 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3197 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Flag);
3198 Flag = Chain.getValue(1);
3199 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3200 VA = RVLocs[++i]; // skip ahead to next loc
3201
3202 // Extract the 2nd half and fall through to handle it as an f64 value.
3203 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3204 DAG.getConstant(1, dl, MVT::i32));
3205 }
3206 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
3207 // available.
3208 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3209 DAG.getVTList(MVT::i32, MVT::i32), Arg);
3210 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3211 fmrrd.getValue(isLittleEndian ? 0 : 1), Flag);
3212 Flag = Chain.getValue(1);
3213 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3214 VA = RVLocs[++i]; // skip ahead to next loc
3215 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3216 fmrrd.getValue(isLittleEndian ? 1 : 0), Flag);
3217 } else
3218 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
3219
3220 // Guarantee that all emitted copies are
3221 // stuck together, avoiding something bad.
3222 Flag = Chain.getValue(1);
3223 RetOps.push_back(DAG.getRegister(
3224 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3225 }
3226 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3227 const MCPhysReg *I =
3228 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3229 if (I) {
3230 for (; *I; ++I) {
3231 if (ARM::GPRRegClass.contains(*I))
3232 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3233 else if (ARM::DPRRegClass.contains(*I))
3234 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3235 else
3236 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3236)
;
3237 }
3238 }
3239
3240 // Update chain and glue.
3241 RetOps[0] = Chain;
3242 if (Flag.getNode())
3243 RetOps.push_back(Flag);
3244
3245 // CPUs which aren't M-class use a special sequence to return from
3246 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3247 // though we use "subs pc, lr, #N").
3248 //
3249 // M-class CPUs actually use a normal return sequence with a special
3250 // (hardware-provided) value in LR, so the normal code path works.
3251 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3252 !Subtarget->isMClass()) {
3253 if (Subtarget->isThumb1Only())
3254 report_fatal_error("interrupt attribute is not supported in Thumb1");
3255 return LowerInterruptReturn(RetOps, dl, DAG);
3256 }
3257
3258 ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG :
3259 ARMISD::RET_FLAG;
3260 return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3261}
3262
3263bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3264 if (N->getNumValues() != 1)
3265 return false;
3266 if (!N->hasNUsesOfValue(1, 0))
3267 return false;
3268
3269 SDValue TCChain = Chain;
3270 SDNode *Copy = *N->use_begin();
3271 if (Copy->getOpcode() == ISD::CopyToReg) {
3272 // If the copy has a glue operand, we conservatively assume it isn't safe to
3273 // perform a tail call.
3274 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3275 return false;
3276 TCChain = Copy->getOperand(0);
3277 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3278 SDNode *VMov = Copy;
3279 // f64 returned in a pair of GPRs.
3280 SmallPtrSet<SDNode*, 2> Copies;
3281 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3282 UI != UE; ++UI) {
3283 if (UI->getOpcode() != ISD::CopyToReg)
3284 return false;
3285 Copies.insert(*UI);
3286 }
3287 if (Copies.size() > 2)
3288 return false;
3289
3290 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3291 UI != UE; ++UI) {
3292 SDValue UseChain = UI->getOperand(0);
3293 if (Copies.count(UseChain.getNode()))
3294 // Second CopyToReg
3295 Copy = *UI;
3296 else {
3297 // We are at the top of this chain.
3298 // If the copy has a glue operand, we conservatively assume it
3299 // isn't safe to perform a tail call.
3300 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
3301 return false;
3302 // First CopyToReg
3303 TCChain = UseChain;
3304 }
3305 }
3306 } else if (Copy->getOpcode() == ISD::BITCAST) {
3307 // f32 returned in a single GPR.
3308 if (!Copy->hasOneUse())
3309 return false;
3310 Copy = *Copy->use_begin();
3311 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3312 return false;
3313 // If the copy has a glue operand, we conservatively assume it isn't safe to
3314 // perform a tail call.
3315 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3316 return false;
3317 TCChain = Copy->getOperand(0);
3318 } else {
3319 return false;
3320 }
3321
3322 bool HasRet = false;
3323 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
3324 UI != UE; ++UI) {
3325 if (UI->getOpcode() != ARMISD::RET_FLAG &&
3326 UI->getOpcode() != ARMISD::INTRET_FLAG)
3327 return false;
3328 HasRet = true;
3329 }
3330
3331 if (!HasRet)
3332 return false;
3333
3334 Chain = TCChain;
3335 return true;
3336}
3337
3338bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3339 if (!Subtarget->supportsTailCall())
3340 return false;
3341
3342 if (!CI->isTailCall())
3343 return false;
3344
3345 return true;
3346}
3347
3348// Trying to write a 64 bit value so need to split into two 32 bit values first,
3349// and pass the lower and high parts through.
3350static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3351 SDLoc DL(Op);
3352 SDValue WriteValue = Op->getOperand(2);
3353
3354 // This function is only supposed to be called for i64 type argument.
3355 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.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3356, __extension__ __PRETTY_FUNCTION__))
3356 && "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.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3356, __extension__ __PRETTY_FUNCTION__))
;
3357
3358 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3359 DAG.getConstant(0, DL, MVT::i32));
3360 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3361 DAG.getConstant(1, DL, MVT::i32));
3362 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3363 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3364}
3365
3366// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3367// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3368// one of the above mentioned nodes. It has to be wrapped because otherwise
3369// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3370// be used to form addressing mode. These wrapped nodes will be selected
3371// into MOVi.
3372SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3373 SelectionDAG &DAG) const {
3374 EVT PtrVT = Op.getValueType();
3375 // FIXME there is no actual debug info here
3376 SDLoc dl(Op);
3377 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3378 SDValue Res;
3379
3380 // When generating execute-only code Constant Pools must be promoted to the
3381 // global data section. It's a bit ugly that we can't share them across basic
3382 // blocks, but this way we guarantee that execute-only behaves correct with
3383 // position-independent addressing modes.
3384 if (Subtarget->genExecuteOnly()) {
3385 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3386 auto T = const_cast<Type*>(CP->getType());
3387 auto C = const_cast<Constant*>(CP->getConstVal());
3388 auto M = const_cast<Module*>(DAG.getMachineFunction().
3389 getFunction().getParent());
3390 auto GV = new GlobalVariable(
3391 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3392 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3393 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3394 Twine(AFI->createPICLabelUId())
3395 );
3396 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3397 dl, PtrVT);
3398 return LowerGlobalAddress(GA, DAG);
3399 }
3400
3401 if (CP->isMachineConstantPoolEntry())
3402 Res =
3403 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
3404 else
3405 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign());
3406 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3407}
3408
3409unsigned ARMTargetLowering::getJumpTableEncoding() const {
3410 return MachineJumpTableInfo::EK_Inline;
3411}
3412
3413SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3414 SelectionDAG &DAG) const {
3415 MachineFunction &MF = DAG.getMachineFunction();
3416 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3417 unsigned ARMPCLabelIndex = 0;
3418 SDLoc DL(Op);
3419 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3420 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3421 SDValue CPAddr;
3422 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3423 if (!IsPositionIndependent) {
3424 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3425 } else {
3426 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3427 ARMPCLabelIndex = AFI->createPICLabelUId();
3428 ARMConstantPoolValue *CPV =
3429 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3430 ARMCP::CPBlockAddress, PCAdj);
3431 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3432 }
3433 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3434 SDValue Result = DAG.getLoad(
3435 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3436 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3437 if (!IsPositionIndependent)
3438 return Result;
3439 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3440 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3441}
3442
3443/// Convert a TLS address reference into the correct sequence of loads
3444/// and calls to compute the variable's address for Darwin, and return an
3445/// SDValue containing the final node.
3446
3447/// Darwin only has one TLS scheme which must be capable of dealing with the
3448/// fully general situation, in the worst case. This means:
3449/// + "extern __thread" declaration.
3450/// + Defined in a possibly unknown dynamic library.
3451///
3452/// The general system is that each __thread variable has a [3 x i32] descriptor
3453/// which contains information used by the runtime to calculate the address. The
3454/// only part of this the compiler needs to know about is the first word, which
3455/// contains a function pointer that must be called with the address of the
3456/// entire descriptor in "r0".
3457///
3458/// Since this descriptor may be in a different unit, in general access must
3459/// proceed along the usual ARM rules. A common sequence to produce is:
3460///
3461/// movw rT1, :lower16:_var$non_lazy_ptr
3462/// movt rT1, :upper16:_var$non_lazy_ptr
3463/// ldr r0, [rT1]
3464/// ldr rT2, [r0]
3465/// blx rT2
3466/// [...address now in r0...]
3467SDValue
3468ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3469 SelectionDAG &DAG) const {
3470 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3471, __extension__ __PRETTY_FUNCTION__))
3471 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3471, __extension__ __PRETTY_FUNCTION__))
;
3472 SDLoc DL(Op);
3473
3474 // First step is to get the address of the actua global symbol. This is where
3475 // the TLS descriptor lives.
3476 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3477
3478 // The first entry in the descriptor is a function pointer that we must call
3479 // to obtain the address of the variable.
3480 SDValue Chain = DAG.getEntryNode();
3481 SDValue FuncTLVGet = DAG.getLoad(
3482 MVT::i32, DL, Chain, DescAddr,
3483 MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4),
3484 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3485 MachineMemOperand::MOInvariant);
3486 Chain = FuncTLVGet.getValue(1);
3487
3488 MachineFunction &F = DAG.getMachineFunction();
3489 MachineFrameInfo &MFI = F.getFrameInfo();
3490 MFI.setAdjustsStack(true);
3491
3492 // TLS calls preserve all registers except those that absolutely must be
3493 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3494 // silly).
3495 auto TRI =
3496 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3497 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3498 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3499
3500 // Finally, we can make the call. This is just a degenerate version of a
3501 // normal AArch64 call node: r0 takes the address of the descriptor, and
3502 // returns the address of the variable in this thread.
3503 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3504 Chain =
3505 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3506 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3507 DAG.getRegisterMask(Mask), Chain.getValue(1));
3508 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3509}
3510
3511SDValue
3512ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3513 SelectionDAG &DAG) const {
3514 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3514, __extension__ __PRETTY_FUNCTION__))
;
3515
3516 SDValue Chain = DAG.getEntryNode();
3517 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3518 SDLoc DL(Op);
3519
3520 // Load the current TEB (thread environment block)
3521 SDValue Ops[] = {Chain,
3522 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3523 DAG.getTargetConstant(15, DL, MVT::i32),
3524 DAG.getTargetConstant(0, DL, MVT::i32),
3525 DAG.getTargetConstant(13, DL, MVT::i32),
3526 DAG.getTargetConstant(0, DL, MVT::i32),
3527 DAG.getTargetConstant(2, DL, MVT::i32)};
3528 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3529 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3530
3531 SDValue TEB = CurrentTEB.getValue(0);
3532 Chain = CurrentTEB.getValue(1);
3533
3534 // Load the ThreadLocalStoragePointer from the TEB
3535 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3536 SDValue TLSArray =
3537 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3538 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3539
3540 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3541 // offset into the TLSArray.
3542
3543 // Load the TLS index from the C runtime
3544 SDValue TLSIndex =
3545 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3546 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3547 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3548
3549 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3550 DAG.getConstant(2, DL, MVT::i32));
3551 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3552 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3553 MachinePointerInfo());
3554
3555 // Get the offset of the start of the .tls section (section base)
3556 const auto *GA = cast<GlobalAddressSDNode>(Op);
3557 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3558 SDValue Offset = DAG.getLoad(
3559 PtrVT, DL, Chain,
3560 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3561 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3562 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3563
3564 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3565}
3566
3567// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3568SDValue
3569ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3570 SelectionDAG &DAG) const {
3571 SDLoc dl(GA);
3572 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3573 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3574 MachineFunction &MF = DAG.getMachineFunction();
3575 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3576 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3577 ARMConstantPoolValue *CPV =
3578 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3579 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3580 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3581 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3582 Argument = DAG.getLoad(
3583 PtrVT, dl, DAG.getEntryNode(), Argument,
3584 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3585 SDValue Chain = Argument.getValue(1);
3586
3587 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3588 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3589
3590 // call __tls_get_addr.
3591 ArgListTy Args;
3592 ArgListEntry Entry;
3593 Entry.Node = Argument;
3594 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3595 Args.push_back(Entry);
3596
3597 // FIXME: is there useful debug info available here?
3598 TargetLowering::CallLoweringInfo CLI(DAG);
3599 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3600 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3601 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3602
3603 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3604 return CallResult.first;
3605}
3606
3607// Lower ISD::GlobalTLSAddress using the "initial exec" or
3608// "local exec" model.
3609SDValue
3610ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3611 SelectionDAG &DAG,
3612 TLSModel::Model model) const {
3613 const GlobalValue *GV = GA->getGlobal();
3614 SDLoc dl(GA);
3615 SDValue Offset;
3616 SDValue Chain = DAG.getEntryNode();
3617 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3618 // Get the Thread Pointer
3619 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3620
3621 if (model == TLSModel::InitialExec) {
3622 MachineFunction &MF = DAG.getMachineFunction();
3623 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3624 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3625 // Initial exec model.
3626 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3627 ARMConstantPoolValue *CPV =
3628 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3629 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3630 true);
3631 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3632 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3633 Offset = DAG.getLoad(
3634 PtrVT, dl, Chain, Offset,
3635 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3636 Chain = Offset.getValue(1);
3637
3638 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3639 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3640
3641 Offset = DAG.getLoad(
3642 PtrVT, dl, Chain, Offset,
3643 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3644 } else {
3645 // local exec model
3646 assert(model == TLSModel::LocalExec)(static_cast <bool> (model == TLSModel::LocalExec) ? void
(0) : __assert_fail ("model == TLSModel::LocalExec", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3646, __extension__ __PRETTY_FUNCTION__))
;
3647 ARMConstantPoolValue *CPV =
3648 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3649 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3650 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3651 Offset = DAG.getLoad(
3652 PtrVT, dl, Chain, Offset,
3653 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3654 }
3655
3656 // The address of the thread local variable is the add of the thread
3657 // pointer with the offset of the variable.
3658 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3659}
3660
3661SDValue
3662ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3663 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3664 if (DAG.getTarget().useEmulatedTLS())
3665 return LowerToTLSEmulatedModel(GA, DAG);
3666
3667 if (Subtarget->isTargetDarwin())
3668 return LowerGlobalTLSAddressDarwin(Op, DAG);
3669
3670 if (Subtarget->isTargetWindows())
3671 return LowerGlobalTLSAddressWindows(Op, DAG);
3672
3673 // TODO: implement the "local dynamic" model
3674 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3674, __extension__ __PRETTY_FUNCTION__))
;
3675 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3676
3677 switch (model) {
3678 case TLSModel::GeneralDynamic:
3679 case TLSModel::LocalDynamic:
3680 return LowerToTLSGeneralDynamicModel(GA, DAG);
3681 case TLSModel::InitialExec:
3682 case TLSModel::LocalExec:
3683 return LowerToTLSExecModels(GA, DAG, model);
3684 }
3685 llvm_unreachable("bogus TLS model")::llvm::llvm_unreachable_internal("bogus TLS model", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3685)
;
3686}
3687
3688/// Return true if all users of V are within function F, looking through
3689/// ConstantExprs.
3690static bool allUsersAreInFunction(const Value *V, const Function *F) {
3691 SmallVector<const User*,4> Worklist(V->users());
3692 while (!Worklist.empty()) {
3693 auto *U = Worklist.pop_back_val();
3694 if (isa<ConstantExpr>(U)) {
3695 append_range(Worklist, U->users());
3696 continue;
3697 }
3698
3699 auto *I = dyn_cast<Instruction>(U);
3700 if (!I || I->getParent()->getParent() != F)
3701 return false;
3702 }
3703 return true;
3704}
3705
3706static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3707 const GlobalValue *GV, SelectionDAG &DAG,
3708 EVT PtrVT, const SDLoc &dl) {
3709 // If we're creating a pool entry for a constant global with unnamed address,
3710 // and the global is small enough, we can emit it inline into the constant pool
3711 // to save ourselves an indirection.
3712 //
3713 // This is a win if the constant is only used in one function (so it doesn't
3714 // need to be duplicated) or duplicating the constant wouldn't increase code
3715 // size (implying the constant is no larger than 4 bytes).
3716 const Function &F = DAG.getMachineFunction().getFunction();
3717
3718 // We rely on this decision to inline being idemopotent and unrelated to the
3719 // use-site. We know that if we inline a variable at one use site, we'll
3720 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3721 // doesn't know about this optimization, so bail out if it's enabled else
3722 // we could decide to inline here (and thus never emit the GV) but require
3723 // the GV from fast-isel generated code.
3724 if (!EnableConstpoolPromotion ||
3725 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3726 return SDValue();
3727
3728 auto *GVar = dyn_cast<GlobalVariable>(GV);
3729 if (!GVar || !GVar->hasInitializer() ||
3730 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3731 !GVar->hasLocalLinkage())
3732 return SDValue();
3733
3734 // If we inline a value that contains relocations, we move the relocations
3735 // from .data to .text. This is not allowed in position-independent code.
3736 auto *Init = GVar->getInitializer();
3737 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3738 Init->needsDynamicRelocation())
3739 return SDValue();
3740
3741 // The constant islands pass can only really deal with alignment requests
3742 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3743 // any type wanting greater alignment requirements than 4 bytes. We also
3744 // can only promote constants that are multiples of 4 bytes in size or
3745 // are paddable to a multiple of 4. Currently we only try and pad constants
3746 // that are strings for simplicity.
3747 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3748 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3749 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3750 unsigned RequiredPadding = 4 - (Size % 4);
3751 bool PaddingPossible =
3752 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3753 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3754 Size == 0)
3755 return SDValue();
3756
3757 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3758 MachineFunction &MF = DAG.getMachineFunction();
3759 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3760
3761 // We can't bloat the constant pool too much, else the ConstantIslands pass
3762 // may fail to converge. If we haven't promoted this global yet (it may have
3763 // multiple uses), and promoting it would increase the constant pool size (Sz
3764 // > 4), ensure we have space to do so up to MaxTotal.
3765 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3766 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3767 ConstpoolPromotionMaxTotal)
3768 return SDValue();
3769
3770 // This is only valid if all users are in a single function; we can't clone
3771 // the constant in general. The LLVM IR unnamed_addr allows merging
3772 // constants, but not cloning them.
3773 //
3774 // We could potentially allow cloning if we could prove all uses of the
3775 // constant in the current function don't care about the address, like
3776 // printf format strings. But that isn't implemented for now.
3777 if (!allUsersAreInFunction(GVar, &F))
3778 return SDValue();
3779
3780 // We're going to inline this global. Pad it out if needed.
3781 if (RequiredPadding != 4) {
3782 StringRef S = CDAInit->getAsString();
3783
3784 SmallVector<uint8_t,16> V(S.size());
3785 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3786 while (RequiredPadding--)
3787 V.push_back(0);
3788 Init = ConstantDataArray::get(*DAG.getContext(), V);
3789 }
3790
3791 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3792 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3793 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3794 AFI->markGlobalAsPromotedToConstantPool(GVar);
3795 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3796 PaddedSize - 4);
3797 }
3798 ++NumConstpoolPromoted;
3799 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3800}
3801
3802bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3803 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3804 if (!(GV = GA->getAliaseeObject()))
3805 return false;
3806 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3807 return V->isConstant();
3808 return isa<Function>(GV);
3809}
3810
3811SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3812 SelectionDAG &DAG) const {
3813 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3814 default: llvm_unreachable("unknown object format")::llvm::llvm_unreachable_internal("unknown object format", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3814)
;
3815 case Triple::COFF:
3816 return LowerGlobalAddressWindows(Op, DAG);
3817 case Triple::ELF:
3818 return LowerGlobalAddressELF(Op, DAG);
3819 case Triple::MachO:
3820 return LowerGlobalAddressDarwin(Op, DAG);
3821 }
3822}
3823
3824SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3825 SelectionDAG &DAG) const {
3826 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3827 SDLoc dl(Op);
3828 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3829 const TargetMachine &TM = getTargetMachine();
3830 bool IsRO = isReadOnly(GV);
3831
3832 // promoteToConstantPool only if not generating XO text section
3833 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3834 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3835 return V;
3836
3837 if (isPositionIndependent()) {
3838 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3839 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3840 UseGOT_PREL ? ARMII::MO_GOT : 0);
3841 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3842 if (UseGOT_PREL)
3843 Result =
3844 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3845 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3846 return Result;
3847 } else if (Subtarget->isROPI() && IsRO) {
3848 // PC-relative.
3849 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3850 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3851 return Result;
3852 } else if (Subtarget->isRWPI() && !IsRO) {
3853 // SB-relative.
3854 SDValue RelAddr;
3855 if (Subtarget->useMovt()) {
3856 ++NumMovwMovt;
3857 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3858 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3859 } else { // use literal pool for address constant
3860 ARMConstantPoolValue *CPV =
3861 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3862 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3863 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3864 RelAddr = DAG.getLoad(
3865 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3866 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3867 }
3868 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3869 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3870 return Result;
3871 }
3872
3873 // If we have T2 ops, we can materialize the address directly via movt/movw
3874 // pair. This is always cheaper.
3875 if (Subtarget->useMovt()) {
3876 ++NumMovwMovt;
3877 // FIXME: Once remat is capable of dealing with instructions with register
3878 // operands, expand this into two nodes.
3879 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3880 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3881 } else {
3882 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3883 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3884 return DAG.getLoad(
3885 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3886 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3887 }
3888}
3889
3890SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3891 SelectionDAG &DAG) const {
3892 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3893, __extension__ __PRETTY_FUNCTION__))
3893 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3893, __extension__ __PRETTY_FUNCTION__))
;
3894 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3895 SDLoc dl(Op);
3896 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3897
3898 if (Subtarget->useMovt())
3899 ++NumMovwMovt;
3900
3901 // FIXME: Once remat is capable of dealing with instructions with register
3902 // operands, expand this into multiple nodes
3903 unsigned Wrapper =
3904 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3905
3906 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3907 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3908
3909 if (Subtarget->isGVIndirectSymbol(GV))
3910 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3911 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3912 return Result;
3913}
3914
3915SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3916 SelectionDAG &DAG) const {
3917 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3917, __extension__ __PRETTY_FUNCTION__))
;
3918 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3919, __extension__ __PRETTY_FUNCTION__))
3919 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3919, __extension__ __PRETTY_FUNCTION__))
;
3920 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3921, __extension__ __PRETTY_FUNCTION__))
3921 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3921, __extension__ __PRETTY_FUNCTION__))
;
3922
3923 const TargetMachine &TM = getTargetMachine();
3924 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3925 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3926 if (GV->hasDLLImportStorageClass())
3927 TargetFlags = ARMII::MO_DLLIMPORT;
3928 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3929 TargetFlags = ARMII::MO_COFFSTUB;
3930 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3931 SDValue Result;
3932 SDLoc DL(Op);
3933
3934 ++NumMovwMovt;
3935
3936 // FIXME: Once remat is capable of dealing with instructions with register
3937 // operands, expand this into two nodes.
3938 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3939 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3940 TargetFlags));
3941 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3942 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3943 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3944 return Result;
3945}
3946
3947SDValue
3948ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3949 SDLoc dl(Op);
3950 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3951 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3952 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3953 Op.getOperand(1), Val);
3954}
3955
3956SDValue
3957ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3958 SDLoc dl(Op);
3959 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3960 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3961}
3962
3963SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3964 SelectionDAG &DAG) const {
3965 SDLoc dl(Op);
3966 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3967 Op.getOperand(0));
3968}
3969
3970SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3971 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3972 unsigned IntNo =
3973 cast<ConstantSDNode>(
3974 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3975 ->getZExtValue();
3976 switch (IntNo) {
3977 default:
3978 return SDValue(); // Don't custom lower most intrinsics.
3979 case Intrinsic::arm_gnu_eabi_mcount: {
3980 MachineFunction &MF = DAG.getMachineFunction();
3981 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3982 SDLoc dl(Op);
3983 SDValue Chain = Op.getOperand(0);
3984 // call "\01__gnu_mcount_nc"
3985 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3986 const uint32_t *Mask =
3987 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3988 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3988, __extension__ __PRETTY_FUNCTION__))
;
3989 // Mark LR an implicit live-in.
3990 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3991 SDValue ReturnAddress =
3992 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3993 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3994 SDValue Callee =
3995 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3996 SDValue RegisterMask = DAG.getRegisterMask(Mask);
3997 if (Subtarget->isThumb())
3998 return SDValue(
3999 DAG.getMachineNode(
4000 ARM::tBL_PUSHLR, dl, ResultTys,
4001 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
4002 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
4003 0);
4004 return SDValue(
4005 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
4006 {ReturnAddress, Callee, RegisterMask, Chain}),
4007 0);
4008 }
4009 }
4010}
4011
4012SDValue
4013ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
4014 const ARMSubtarget *Subtarget) const {
4015 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4016 SDLoc dl(Op);
4017 switch (IntNo) {
4018 default: return SDValue(); // Don't custom lower most intrinsics.
4019 case Intrinsic::thread_pointer: {
4020 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4021 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
4022 }
4023 case Intrinsic::arm_cls: {
4024 const SDValue &Operand = Op.getOperand(1);
4025 const EVT VTy = Op.getValueType();
4026 SDValue SRA =
4027 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
4028 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
4029 SDValue SHL =
4030 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
4031 SDValue OR =
4032 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
4033 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
4034 return Result;
4035 }
4036 case Intrinsic::arm_cls64: {
4037 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
4038 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
4039 const SDValue &Operand = Op.getOperand(1);
4040 const EVT VTy = Op.getValueType();
4041
4042 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
4043 DAG.getConstant(1, dl, VTy));
4044 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
4045 DAG.getConstant(0, dl, VTy));
4046 SDValue Constant0 = DAG.getConstant(0, dl, VTy);
4047 SDValue Constant1 = DAG.getConstant(1, dl, VTy);
4048 SDValue Constant31 = DAG.getConstant(31, dl, VTy);
4049 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
4050 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
4051 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
4052 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
4053 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
4054 SDValue CheckLo =
4055 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
4056 SDValue HiIsZero =
4057 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
4058 SDValue AdjustedLo =
4059 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
4060 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
4061 SDValue Result =
4062 DAG.getSelect(dl, VTy, CheckLo,
4063 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
4064 return Result;
4065 }
4066 case Intrinsic::eh_sjlj_lsda: {
4067 MachineFunction &MF = DAG.getMachineFunction();
4068 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4069 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
4070 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4071 SDValue CPAddr;
4072 bool IsPositionIndependent = isPositionIndependent();
4073 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
4074 ARMConstantPoolValue *CPV =
4075 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
4076 ARMCP::CPLSDA, PCAdj);
4077 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
4078 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
4079 SDValue Result = DAG.getLoad(
4080 PtrVT, dl, DAG.getEntryNode(), CPAddr,
4081 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
4082
4083 if (IsPositionIndependent) {
4084 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
4085 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
4086 }
4087 return Result;
4088 }
4089 case Intrinsic::arm_neon_vabs:
4090 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
4091 Op.getOperand(1));
4092 case Intrinsic::arm_neon_vmulls:
4093 case Intrinsic::arm_neon_vmullu: {
4094 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
4095 ? ARMISD::VMULLs : ARMISD::VMULLu;
4096 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4097 Op.getOperand(1), Op.getOperand(2));
4098 }
4099 case Intrinsic::arm_neon_vminnm:
4100 case Intrinsic::arm_neon_vmaxnm: {
4101 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
4102 ? ISD::FMINNUM : ISD::FMAXNUM;
4103 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4104 Op.getOperand(1), Op.getOperand(2));
4105 }
4106 case Intrinsic::arm_neon_vminu:
4107 case Intrinsic::arm_neon_vmaxu: {
4108 if (Op.getValueType().isFloatingPoint())
4109 return SDValue();
4110 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
4111 ? ISD::UMIN : ISD::UMAX;
4112 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4113 Op.getOperand(1), Op.getOperand(2));
4114 }
4115 case Intrinsic::arm_neon_vmins:
4116 case Intrinsic::arm_neon_vmaxs: {
4117 // v{min,max}s is overloaded between signed integers and floats.
4118 if (!Op.getValueType().isFloatingPoint()) {
4119 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4120 ? ISD::SMIN : ISD::SMAX;
4121 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4122 Op.getOperand(1), Op.getOperand(2));
4123 }
4124 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4125 ? ISD::FMINIMUM : ISD::FMAXIMUM;
4126 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4127 Op.getOperand(1), Op.getOperand(2));
4128 }
4129 case Intrinsic::arm_neon_vtbl1:
4130 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
4131 Op.getOperand(1), Op.getOperand(2));
4132 case Intrinsic::arm_neon_vtbl2:
4133 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
4134 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4135 case Intrinsic::arm_mve_pred_i2v:
4136 case Intrinsic::arm_mve_pred_v2i:
4137 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
4138 Op.getOperand(1));
4139 case Intrinsic::arm_mve_vreinterpretq:
4140 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
4141 Op.getOperand(1));
4142 case Intrinsic::arm_mve_lsll:
4143 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
4144 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4145 case Intrinsic::arm_mve_asrl:
4146 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
4147 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4148 }
4149}
4150
4151static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
4152 const ARMSubtarget *Subtarget) {
4153 SDLoc dl(Op);
4154 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
4155 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
4156 if (SSID == SyncScope::SingleThread)
4157 return Op;
4158
4159 if (!Subtarget->hasDataBarrier()) {
4160 // Some ARMv6 cpus can support data barriers with an mcr instruction.
4161 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4162 // here.
4163 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4164, __extension__ __PRETTY_FUNCTION__))
4164 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4164, __extension__ __PRETTY_FUNCTION__))
;
4165 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4166 DAG.getConstant(0, dl, MVT::i32));
4167 }
4168
4169 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
4170 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
4171 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
4172 if (Subtarget->isMClass()) {
4173 // Only a full system barrier exists in the M-class architectures.
4174 Domain = ARM_MB::SY;
4175 } else if (Subtarget->preferISHSTBarriers() &&
4176 Ord == AtomicOrdering::Release) {
4177 // Swift happens to implement ISHST barriers in a way that's compatible with
4178 // Release semantics but weaker than ISH so we'd be fools not to use
4179 // it. Beware: other processors probably don't!
4180 Domain = ARM_MB::ISHST;
4181 }
4182
4183 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4184 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4185 DAG.getConstant(Domain, dl, MVT::i32));
4186}
4187
4188static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
4189 const ARMSubtarget *Subtarget) {
4190 // ARM pre v5TE and Thumb1 does not have preload instructions.
4191 if (!(Subtarget->isThumb2() ||
4192 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4193 // Just preserve the chain.
4194 return Op.getOperand(0);
4195
4196 SDLoc dl(Op);
4197 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
4198 if (!isRead &&
4199 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4200 // ARMv7 with MP extension has PLDW.
4201 return Op.getOperand(0);
4202
4203 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
4204 if (Subtarget->isThumb()) {
4205 // Invert the bits.
4206 isRead = ~isRead & 1;
4207 isData = ~isData & 1;
4208 }
4209
4210 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4211 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4212 DAG.getConstant(isData, dl, MVT::i32));
4213}
4214
4215static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
4216 MachineFunction &MF = DAG.getMachineFunction();
4217 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4218
4219 // vastart just stores the address of the VarArgsFrameIndex slot into the
4220 // memory location argument.
4221 SDLoc dl(Op);
4222 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4223 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4224 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4225 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4226 MachinePointerInfo(SV));
4227}
4228
4229SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4230 CCValAssign &NextVA,
4231 SDValue &Root,
4232 SelectionDAG &DAG,
4233 const SDLoc &dl) const {
4234 MachineFunction &MF = DAG.getMachineFunction();
4235 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4236
4237 const TargetRegisterClass *RC;
4238 if (AFI->isThumb1OnlyFunction())
4239 RC = &ARM::tGPRRegClass;
4240 else
4241 RC = &ARM::GPRRegClass;
4242
4243 // Transform the arguments stored in physical registers into virtual ones.
4244 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4245 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4246
4247 SDValue ArgValue2;
4248 if (NextVA.isMemLoc()) {
4249 MachineFrameInfo &MFI = MF.getFrameInfo();
4250 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4251
4252 // Create load node to retrieve arguments from the stack.
4253 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4254 ArgValue2 = DAG.getLoad(
4255 MVT::i32, dl, Root, FIN,
4256 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4257 } else {
4258 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4259 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4260 }
4261 if (!Subtarget->isLittle())
4262 std::swap (ArgValue, ArgValue2);
4263 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4264}
4265
4266// The remaining GPRs hold either the beginning of variable-argument
4267// data, or the beginning of an aggregate passed by value (usually
4268// byval). Either way, we allocate stack slots adjacent to the data
4269// provided by our caller, and store the unallocated registers there.
4270// If this is a variadic function, the va_list pointer will begin with
4271// these values; otherwise, this reassembles a (byval) structure that
4272// was split between registers and memory.
4273// Return: The frame index registers were stored into.
4274int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4275 const SDLoc &dl, SDValue &Chain,
4276 const Value *OrigArg,
4277 unsigned InRegsParamRecordIdx,
4278 int ArgOffset, unsigned ArgSize) const {
4279 // Currently, two use-cases possible:
4280 // Case #1. Non-var-args function, and we meet first byval parameter.
4281 // Setup first unallocated register as first byval register;
4282 // eat all remained registers
4283 // (these two actions are performed by HandleByVal method).
4284 // Then, here, we initialize stack frame with
4285 // "store-reg" instructions.
4286 // Case #2. Var-args function, that doesn't contain byval parameters.
4287 // The same: eat all remained unallocated registers,
4288 // initialize stack frame.
4289
4290 MachineFunction &MF = DAG.getMachineFunction();
4291 MachineFrameInfo &MFI = MF.getFrameInfo();
4292 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4293 unsigned RBegin, REnd;
4294 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4295 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4296 } else {
4297 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4298 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4299 REnd = ARM::R4;
4300 }
4301
4302 if (REnd != RBegin)
4303 ArgOffset = -4 * (ARM::R4 - RBegin);
4304
4305 auto PtrVT = getPointerTy(DAG.getDataLayout());
4306 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4307 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4308
4309 SmallVector<SDValue, 4> MemOps;
4310 const TargetRegisterClass *RC =
4311 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4312
4313 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4314 unsigned VReg = MF.addLiveIn(Reg, RC);
4315 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4316 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4317 MachinePointerInfo(OrigArg, 4 * i));
4318 MemOps.push_back(Store);
4319 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4320 }
4321
4322 if (!MemOps.empty())
4323 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4324 return FrameIndex;
4325}
4326
4327// Setup stack frame, the va_list pointer will start from.
4328void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4329 const SDLoc &dl, SDValue &Chain,
4330 unsigned ArgOffset,
4331 unsigned TotalArgRegsSaveSize,
4332 bool ForceMutable) const {
4333 MachineFunction &MF = DAG.getMachineFunction();
4334 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4335
4336 // Try to store any remaining integer argument regs
4337 // to their spots on the stack so that they may be loaded by dereferencing
4338 // the result of va_next.
4339 // If there is no regs to be stored, just point address after last
4340 // argument passed via stack.
4341 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
4342 CCInfo.getInRegsParamsCount(),
4343 CCInfo.getNextStackOffset(),
4344 std::max(4U, TotalArgRegsSaveSize));
4345 AFI->setVarArgsFrameIndex(FrameIndex);
4346}
4347
4348bool ARMTargetLowering::splitValueIntoRegisterParts(
4349 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4350 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
4351 bool IsABIRegCopy = CC.hasValue();
4352 EVT ValueVT = Val.getValueType();
4353 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4354 PartVT == MVT::f32) {
4355 unsigned ValueBits = ValueVT.getSizeInBits();
4356 unsigned PartBits = PartVT.getSizeInBits();
4357 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4358 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4359 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4360 Parts[0] = Val;
4361 return true;
4362 }
4363 return false;
4364}
4365
4366SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4367 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4368 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
4369 bool IsABIRegCopy = CC.hasValue();
4370 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4371 PartVT == MVT::f32) {
4372 unsigned ValueBits = ValueVT.getSizeInBits();
4373 unsigned PartBits = PartVT.getSizeInBits();
4374 SDValue Val = Parts[0];
4375
4376 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4377 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4378 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4379 return Val;
4380 }
4381 return SDValue();
4382}
4383
4384SDValue ARMTargetLowering::LowerFormalArguments(
4385 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4386 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4387 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4388 MachineFunction &MF = DAG.getMachineFunction();
4389 MachineFrameInfo &MFI = MF.getFrameInfo();
4390
4391 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4392
4393 // Assign locations to all of the incoming arguments.
4394 SmallVector<CCValAssign, 16> ArgLocs;
4395 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4396 *DAG.getContext());
4397 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4398
4399 SmallVector<SDValue, 16> ArgValues;
4400 SDValue ArgValue;
4401 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4402 unsigned CurArgIdx = 0;
4403
4404 // Initially ArgRegsSaveSize is zero.
4405 // Then we increase this value each time we meet byval parameter.
4406 // We also increase this value in case of varargs function.
4407 AFI->setArgRegsSaveSize(0);
4408
4409 // Calculate the amount of stack space that we need to allocate to store
4410 // byval and variadic arguments that are passed in registers.
4411 // We need to know this before we allocate the first byval or variadic
4412 // argument, as they will be allocated a stack slot below the CFA (Canonical
4413 // Frame Address, the stack pointer at entry to the function).
4414 unsigned ArgRegBegin = ARM::R4;
4415 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4416 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4417 break;
4418
4419 CCValAssign &VA = ArgLocs[i];
4420 unsigned Index = VA.getValNo();
4421 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4422 if (!Flags.isByVal())
4423 continue;
4424
4425 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4425, __extension__ __PRETTY_FUNCTION__))
;
4426 unsigned RBegin, REnd;
4427 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4428 ArgRegBegin = std::min(ArgRegBegin, RBegin);
4429
4430 CCInfo.nextInRegsParam();
4431 }
4432 CCInfo.rewindByValRegsInfo();
4433
4434 int lastInsIndex = -1;
4435 if (isVarArg && MFI.hasVAStart()) {
4436 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4437 if (RegIdx != array_lengthof(GPRArgRegs))
4438 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4439 }
4440
4441 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4442 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4443 auto PtrVT = getPointerTy(DAG.getDataLayout());
4444
4445 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4446 CCValAssign &VA = ArgLocs[i];
4447 if (Ins[VA.getValNo()].isOrigArg()) {
4448 std::advance(CurOrigArg,
4449 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4450 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4451 }
4452 // Arguments stored in registers.
4453 if (VA.isRegLoc()) {
4454 EVT RegVT = VA.getLocVT();
4455
4456 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4457 // f64 and vector types are split up into multiple registers or
4458 // combinations of registers and stack slots.
4459 SDValue ArgValue1 =
4460 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4461 VA = ArgLocs[++i]; // skip ahead to next loc
4462 SDValue ArgValue2;
4463 if (VA.isMemLoc()) {
4464 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4465 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4466 ArgValue2 = DAG.getLoad(
4467 MVT::f64, dl, Chain, FIN,
4468 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4469 } else {
4470 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4471 }
4472 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4473 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4474 ArgValue1, DAG.getIntPtrConstant(0, dl));
4475 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4476 ArgValue2, DAG.getIntPtrConstant(1, dl));
4477 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4478 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4479 } else {
4480 const TargetRegisterClass *RC;
4481
4482 if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4483 RC = &ARM::HPRRegClass;
4484 else if (RegVT == MVT::f32)
4485 RC = &ARM::SPRRegClass;
4486 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4487 RegVT == MVT::v4bf16)
4488 RC = &ARM::DPRRegClass;
4489 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4490 RegVT == MVT::v8bf16)
4491 RC = &ARM::QPRRegClass;
4492 else if (RegVT == MVT::i32)
4493 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4494 : &ARM::GPRRegClass;
4495 else
4496 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering")::llvm::llvm_unreachable_internal("RegVT not supported by FORMAL_ARGUMENTS Lowering"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4496)
;
4497
4498 // Transform the arguments in physical registers into virtual ones.
4499 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4500 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4501
4502 // If this value is passed in r0 and has the returned attribute (e.g.
4503 // C++ 'structors), record this fact for later use.
4504 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4505 AFI->setPreservesR0();
4506 }
4507 }
4508
4509 // If this is an 8 or 16-bit value, it is really passed promoted
4510 // to 32 bits. Insert an assert[sz]ext to capture this, then
4511 // truncate to the right size.
4512 switch (VA.getLocInfo()) {
4513 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4513)
;
4514 case CCValAssign::Full: break;
4515 case CCValAssign::BCvt:
4516 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4517 break;
4518 case CCValAssign::SExt:
4519 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4520 DAG.getValueType(VA.getValVT()));
4521 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4522 break;
4523 case CCValAssign::ZExt:
4524 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4525 DAG.getValueType(VA.getValVT()));
4526 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4527 break;
4528 }
4529
4530 // f16 arguments have their size extended to 4 bytes and passed as if they
4531 // had been copied to the LSBs of a 32-bit register.
4532 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4533 if (VA.needsCustom() &&
4534 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4535 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4536
4537 InVals.push_back(ArgValue);
4538 } else { // VA.isRegLoc()
4539 // sanity check
4540 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4540, __extension__ __PRETTY_FUNCTION__))
;
4541 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4541, __extension__ __PRETTY_FUNCTION__))
;
4542
4543 int index = VA.getValNo();
4544
4545 // Some Ins[] entries become multiple ArgLoc[] entries.
4546 // Process them only once.
4547 if (index != lastInsIndex)
4548 {
4549 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4550 // FIXME: For now, all byval parameter objects are marked mutable.
4551 // This can be changed with more analysis.
4552 // In case of tail call optimization mark all arguments mutable.
4553 // Since they could be overwritten by lowering of arguments in case of
4554 // a tail call.
4555 if (Flags.isByVal()) {
4556 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4557, __extension__ __PRETTY_FUNCTION__))
4557 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4557, __extension__ __PRETTY_FUNCTION__))
;
4558 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4559
4560 int FrameIndex = StoreByValRegs(
4561 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4562 VA.getLocMemOffset(), Flags.getByValSize());
4563 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4564 CCInfo.nextInRegsParam();
4565 } else {
4566 unsigned FIOffset = VA.getLocMemOffset();
4567 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4568 FIOffset, true);
4569
4570 // Create load nodes to retrieve arguments from the stack.
4571 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4572 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4573 MachinePointerInfo::getFixedStack(
4574 DAG.getMachineFunction(), FI)));
4575 }
4576 lastInsIndex = index;
4577 }
4578 }
4579 }
4580
4581 // varargs
4582 if (isVarArg && MFI.hasVAStart()) {
4583 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset(),
4584 TotalArgRegsSaveSize);
4585 if (AFI->isCmseNSEntryFunction()) {
4586 DiagnosticInfoUnsupported Diag(
4587 DAG.getMachineFunction().getFunction(),
4588 "secure entry function must not be variadic", dl.getDebugLoc());
4589 DAG.getContext()->diagnose(Diag);
4590 }
4591 }
4592
4593 unsigned StackArgSize = CCInfo.getNextStackOffset();
4594 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4595 if (canGuaranteeTCO(CallConv, TailCallOpt)) {
4596 // The only way to guarantee a tail call is if the callee restores its
4597 // argument area, but it must also keep the stack aligned when doing so.
4598 const DataLayout &DL = DAG.getDataLayout();
4599 StackArgSize = alignTo(StackArgSize, DL.getStackAlignment());
4600
4601 AFI->setArgumentStackToRestore(StackArgSize);
4602 }
4603 AFI->setArgumentStackSize(StackArgSize);
4604
4605 if (CCInfo.getNextStackOffset() > 0 && AFI->isCmseNSEntryFunction()) {
4606 DiagnosticInfoUnsupported Diag(
4607 DAG.getMachineFunction().getFunction(),
4608 "secure entry function requires arguments on stack", dl.getDebugLoc());
4609 DAG.getContext()->diagnose(Diag);
4610 }
4611
4612 return Chain;
4613}
4614
4615/// isFloatingPointZero - Return true if this is +0.0.
4616static bool isFloatingPointZero(SDValue Op) {
4617 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4618 return CFP->getValueAPF().isPosZero();
4619 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4620 // Maybe this has already been legalized into the constant pool?
4621 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4622 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4623 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4624 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4625 return CFP->getValueAPF().isPosZero();
4626 }
4627 } else if (Op->getOpcode() == ISD::BITCAST &&
4628 Op->getValueType(0) == MVT::f64) {
4629 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4630 // created by LowerConstantFP().
4631 SDValue BitcastOp = Op->getOperand(0);
4632 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4633 isNullConstant(BitcastOp->getOperand(0)))
4634 return true;
4635 }
4636 return false;
4637}
4638
4639/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4640/// the given operands.
4641SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4642 SDValue &ARMcc, SelectionDAG &DAG,
4643 const SDLoc &dl) const {
4644 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4645 unsigned C = RHSC->getZExtValue();
4646 if (!isLegalICmpImmediate((int32_t)C)) {
4647 // Constant does not fit, try adjusting it by one.
4648 switch (CC) {
4649 default: break;
4650 case ISD::SETLT:
4651 case ISD::SETGE:
4652 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4653 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4654 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4655 }
4656 break;
4657 case ISD::SETULT:
4658 case ISD::SETUGE:
4659 if (C != 0 && isLegalICmpImmediate(C-1)) {
4660 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4661 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4662 }
4663 break;
4664 case ISD::SETLE:
4665 case ISD::SETGT:
4666 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4667 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4668 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4669 }
4670 break;
4671 case ISD::SETULE:
4672 case ISD::SETUGT:
4673 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4674 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4675 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4676 }
4677 break;
4678 }
4679 }
4680 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4681 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4682 // In ARM and Thumb-2, the compare instructions can shift their second
4683 // operand.
4684 CC = ISD::getSetCCSwappedOperands(CC);
4685 std::swap(LHS, RHS);
4686 }
4687
4688 // Thumb1 has very limited immediate modes, so turning an "and" into a
4689 // shift can save multiple instructions.
4690 //
4691 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4692 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4693 // own. If it's the operand to an unsigned comparison with an immediate,
4694 // we can eliminate one of the shifts: we transform
4695 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4696 //
4697 // We avoid transforming cases which aren't profitable due to encoding
4698 // details:
4699 //
4700 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4701 // would not; in that case, we're essentially trading one immediate load for
4702 // another.
4703 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4704 // 3. C2 is zero; we have other code for this special case.
4705 //
4706 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4707 // instruction, since the AND is always one instruction anyway, but we could
4708 // use narrow instructions in some cases.
4709 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4710 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4711 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4712 !isSignedIntSetCC(CC)) {
4713 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4714 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4715 uint64_t RHSV = RHSC->getZExtValue();
4716 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4717 unsigned ShiftBits = countLeadingZeros(Mask);
4718 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4719 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4720 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4721 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4722 }
4723 }
4724 }
4725
4726 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4727 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4728 // way a cmp would.
4729 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4730 // some tweaks to the heuristics for the previous and->shift transform.
4731 // FIXME: Optimize cases where the LHS isn't a shift.
4732 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4733 isa<ConstantSDNode>(RHS) &&
4734 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4735 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4736 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4737 unsigned ShiftAmt =
4738 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4739 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4740 DAG.getVTList(MVT::i32, MVT::i32),
4741 LHS.getOperand(0),
4742 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4743 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4744 Shift.getValue(1), SDValue());
4745 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4746 return Chain.getValue(1);
4747 }
4748
4749 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4750
4751 // If the RHS is a constant zero then the V (overflow) flag will never be
4752 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4753 // simpler for other passes (like the peephole optimiser) to deal with.
4754 if (isNullConstant(RHS)) {
4755 switch (CondCode) {
4756 default: break;
4757 case ARMCC::GE:
4758 CondCode = ARMCC::PL;
4759 break;
4760 case ARMCC::LT:
4761 CondCode = ARMCC::MI;
4762 break;
4763 }
4764 }
4765
4766 ARMISD::NodeType CompareType;
4767 switch (CondCode) {
4768 default:
4769 CompareType = ARMISD::CMP;
4770 break;
4771 case ARMCC::EQ:
4772 case ARMCC::NE:
4773 // Uses only Z Flag
4774 CompareType = ARMISD::CMPZ;
4775 break;
4776 }
4777 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4778 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4779}
4780
4781/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4782SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4783 SelectionDAG &DAG, const SDLoc &dl,
4784 bool Signaling) const {
4785 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"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4785, __extension__ __PRETTY_FUNCTION__))
;
4786 SDValue Cmp;
4787 if (!isFloatingPointZero(RHS))
4788 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP,
4789 dl, MVT::Glue, LHS, RHS);
4790 else
4791 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0,
4792 dl, MVT::Glue, LHS);
4793 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4794}
4795
4796/// duplicateCmp - Glue values can have only one use, so this function
4797/// duplicates a comparison node.
4798SDValue
4799ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4800 unsigned Opc = Cmp.getOpcode();
4801 SDLoc DL(Cmp);
4802 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4803 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4804
4805 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4805, __extension__ __PRETTY_FUNCTION__))
;
4806 Cmp = Cmp.getOperand(0);
4807 Opc = Cmp.getOpcode();
4808 if (Opc == ARMISD::CMPFP)
4809 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4810 else {
4811 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4811, __extension__ __PRETTY_FUNCTION__))
;
4812 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4813 }
4814 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4815}
4816
4817// This function returns three things: the arithmetic computation itself
4818// (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4819// comparison and the condition code define the case in which the arithmetic
4820// computation *does not* overflow.
4821std::pair<SDValue, SDValue>
4822ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4823 SDValue &ARMcc) const {
4824 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4824, __extension__ __PRETTY_FUNCTION__))
;
4825
4826 SDValue Value, OverflowCmp;
4827 SDValue LHS = Op.getOperand(0);
4828 SDValue RHS = Op.getOperand(1);
4829 SDLoc dl(Op);
4830
4831 // FIXME: We are currently always generating CMPs because we don't support
4832 // generating CMN through the backend. This is not as good as the natural
4833 // CMP case because it causes a register dependency and cannot be folded
4834 // later.
4835
4836 switch (Op.getOpcode()) {
4837 default:
4838 llvm_unreachable("Unknown overflow instruction!")::llvm::llvm_unreachable_internal("Unknown overflow instruction!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4838)
;
4839 case ISD::SADDO:
4840 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4841 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4842 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4843 break;
4844 case ISD::UADDO:
4845 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4846 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4847 // We do not use it in the USUBO case as Value may not be used.
4848 Value = DAG.getNode(ARMISD::ADDC, dl,
4849 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4850 .getValue(0);
4851 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4852 break;
4853 case ISD::SSUBO:
4854 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4855 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4856 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4857 break;
4858 case ISD::USUBO:
4859 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4860 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4861 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4862 break;
4863 case ISD::UMULO:
4864 // We generate a UMUL_LOHI and then check if the high word is 0.
4865 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4866 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4867 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4868 LHS, RHS);
4869 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4870 DAG.getConstant(0, dl, MVT::i32));
4871 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4872 break;
4873 case ISD::SMULO:
4874 // We generate a SMUL_LOHI and then check if all the bits of the high word
4875 // are the same as the sign bit of the low word.
4876 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4877 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4878 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4879 LHS, RHS);
4880 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4881 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4882 Value.getValue(0),
4883 DAG.getConstant(31, dl, MVT::i32)));
4884 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4885 break;
4886 } // switch (...)
4887
4888 return std::make_pair(Value, OverflowCmp);
4889}
4890
4891SDValue
4892ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4893 // Let legalize expand this if it isn't a legal type yet.
4894 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4895 return SDValue();
4896
4897 SDValue Value, OverflowCmp;
4898 SDValue ARMcc;
4899 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4900 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4901 SDLoc dl(Op);
4902 // We use 0 and 1 as false and true values.
4903 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4904 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4905 EVT VT = Op.getValueType();
4906
4907 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4908 ARMcc, CCR, OverflowCmp);
4909
4910 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4911 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4912}
4913
4914static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4915 SelectionDAG &DAG) {
4916 SDLoc DL(BoolCarry);
4917 EVT CarryVT = BoolCarry.getValueType();
4918
4919 // This converts the boolean value carry into the carry flag by doing
4920 // ARMISD::SUBC Carry, 1
4921 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4922 DAG.getVTList(CarryVT, MVT::i32),
4923 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4924 return Carry.getValue(1);
4925}
4926
4927static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4928 SelectionDAG &DAG) {
4929 SDLoc DL(Flags);
4930
4931 // Now convert the carry flag into a boolean carry. We do this
4932 // using ARMISD:ADDE 0, 0, Carry
4933 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4934 DAG.getConstant(0, DL, MVT::i32),
4935 DAG.getConstant(0, DL, MVT::i32), Flags);
4936}
4937
4938SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4939 SelectionDAG &DAG) const {
4940 // Let legalize expand this if it isn't a legal type yet.
4941 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4942 return SDValue();
4943
4944 SDValue LHS = Op.getOperand(0);
4945 SDValue RHS = Op.getOperand(1);
4946 SDLoc dl(Op);
4947
4948 EVT VT = Op.getValueType();
4949 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4950 SDValue Value;
4951 SDValue Overflow;
4952 switch (Op.getOpcode()) {
4953 default:
4954 llvm_unreachable("Unknown overflow instruction!")::llvm::llvm_unreachable_internal("Unknown overflow instruction!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4954)
;
4955 case ISD::UADDO:
4956 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4957 // Convert the carry flag into a boolean value.
4958 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4959 break;
4960 case ISD::USUBO: {
4961 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4962 // Convert the carry flag into a boolean value.
4963 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4964 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4965 // value. So compute 1 - C.
4966 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4967 DAG.getConstant(1, dl, MVT::i32), Overflow);
4968 break;
4969 }
4970 }
4971
4972 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4973}
4974
4975static SDValue LowerADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4976 const ARMSubtarget *Subtarget) {
4977 EVT VT = Op.getValueType();
4978 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
4979 return SDValue();
4980 if (!VT.isSimple())
4981 return SDValue();
4982
4983 unsigned NewOpcode;
4984 switch (VT.getSimpleVT().SimpleTy) {
4985 default:
4986 return SDValue();
4987 case MVT::i8:
4988 switch (Op->getOpcode()) {
4989 case ISD::UADDSAT:
4990 NewOpcode = ARMISD::UQADD8b;
4991 break;
4992 case ISD::SADDSAT:
4993 NewOpcode = ARMISD::QADD8b;
4994 break;
4995 case ISD::USUBSAT:
4996 NewOpcode = ARMISD::UQSUB8b;
4997 break;
4998 case ISD::SSUBSAT:
4999 NewOpcode = ARMISD::QSUB8b;
5000 break;
5001 }
5002 break;
5003 case MVT::i16:
5004 switch (Op->getOpcode()) {
5005 case ISD::UADDSAT:
5006 NewOpcode = ARMISD::UQADD16b;
5007 break;
5008 case ISD::SADDSAT:
5009 NewOpcode = ARMISD::QADD16b;
5010 break;
5011 case ISD::USUBSAT:
5012 NewOpcode = ARMISD::UQSUB16b;
5013 break;
5014 case ISD::SSUBSAT:
5015 NewOpcode = ARMISD::QSUB16b;
5016 break;
5017 }
5018 break;
5019 }
5020
5021 SDLoc dl(Op);
5022 SDValue Add =
5023 DAG.getNode(NewOpcode, dl, MVT::i32,
5024 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
5025 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
5026 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
5027}
5028
5029SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5030 SDValue Cond = Op.getOperand(0);
5031 SDValue SelectTrue = Op.getOperand(1);
5032 SDValue SelectFalse = Op.getOperand(2);
5033 SDLoc dl(Op);
5034 unsigned Opc = Cond.getOpcode();
5035
5036 if (Cond.getResNo() == 1 &&
5037 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5038 Opc == ISD::USUBO)) {
5039 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5040 return SDValue();
5041
5042 SDValue Value, OverflowCmp;
5043 SDValue ARMcc;
5044 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5045 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5046 EVT VT = Op.getValueType();
5047
5048 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
5049 OverflowCmp, DAG);
5050 }
5051
5052 // Convert:
5053 //
5054 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
5055 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
5056 //
5057 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
5058 const ConstantSDNode *CMOVTrue =
5059 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
5060 const ConstantSDNode *CMOVFalse =
5061 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
5062
5063 if (CMOVTrue && CMOVFalse) {
5064 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
5065 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
5066
5067 SDValue True;
5068 SDValue False;
5069 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
5070 True = SelectTrue;
5071 False = SelectFalse;
5072 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
5073 True = SelectFalse;
5074 False = SelectTrue;
5075 }
5076
5077 if (True.getNode() && False.getNode()) {
5078 EVT VT = Op.getValueType();
5079 SDValue ARMcc = Cond.getOperand(2);
5080 SDValue CCR = Cond.getOperand(3);
5081 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
5082 assert(True.getValueType() == VT)(static_cast <bool> (True.getValueType() == VT) ? void (
0) : __assert_fail ("True.getValueType() == VT", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5082, __extension__ __PRETTY_FUNCTION__))
;
5083 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
5084 }
5085 }
5086 }
5087
5088 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
5089 // undefined bits before doing a full-word comparison with zero.
5090 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
5091 DAG.getConstant(1, dl, Cond.getValueType()));
5092
5093 return DAG.getSelectCC(dl, Cond,
5094 DAG.getConstant(0, dl, Cond.getValueType()),
5095 SelectTrue, SelectFalse, ISD::SETNE);
5096}
5097
5098static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
5099 bool &swpCmpOps, bool &swpVselOps) {
5100 // Start by selecting the GE condition code for opcodes that return true for
5101 // 'equality'
5102 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
5103 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
5104 CondCode = ARMCC::GE;
5105
5106 // and GT for opcodes that return false for 'equality'.
5107 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
5108 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
5109 CondCode = ARMCC::GT;
5110
5111 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
5112 // to swap the compare operands.
5113 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
5114 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
5115 swpCmpOps = true;
5116
5117 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
5118 // If we have an unordered opcode, we need to swap the operands to the VSEL
5119 // instruction (effectively negating the condition).
5120 //
5121 // This also has the effect of swapping which one of 'less' or 'greater'
5122 // returns true, so we also swap the compare operands. It also switches
5123 // whether we return true for 'equality', so we compensate by picking the
5124 // opposite condition code to our original choice.
5125 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
5126 CC == ISD::SETUGT) {
5127 swpCmpOps = !swpCmpOps;
5128 swpVselOps = !swpVselOps;
5129 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
5130 }
5131
5132 // 'ordered' is 'anything but unordered', so use the VS condition code and
5133 // swap the VSEL operands.
5134 if (CC == ISD::SETO) {
5135 CondCode = ARMCC::VS;
5136 swpVselOps = true;
5137 }
5138
5139 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
5140 // code and swap the VSEL operands. Also do this if we don't care about the
5141 // unordered case.
5142 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
5143 CondCode = ARMCC::EQ;
5144 swpVselOps = true;
5145 }
5146}
5147
5148SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
5149 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
5150 SDValue Cmp, SelectionDAG &DAG) const {
5151 if (!Subtarget->hasFP64() && VT == MVT::f64) {
5152 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5153 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
5154 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5155 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
5156
5157 SDValue TrueLow = TrueVal.getValue(0);
5158 SDValue TrueHigh = TrueVal.getValue(1);
5159 SDValue FalseLow = FalseVal.getValue(0);
5160 SDValue FalseHigh = FalseVal.getValue(1);
5161
5162 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
5163 ARMcc, CCR, Cmp);
5164 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
5165 ARMcc, CCR, duplicateCmp(Cmp, DAG));
5166
5167 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
5168 } else {
5169 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
5170 Cmp);
5171 }
5172}
5173
5174static bool isGTorGE(ISD::CondCode CC) {
5175 return CC == ISD::SETGT || CC == ISD::SETGE;
5176}
5177
5178static bool isLTorLE(ISD::CondCode CC) {
5179 return CC == ISD::SETLT || CC == ISD::SETLE;
5180}
5181
5182// See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
5183// All of these conditions (and their <= and >= counterparts) will do:
5184// x < k ? k : x
5185// x > k ? x : k
5186// k < x ? x : k
5187// k > x ? k : x
5188static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5189 const SDValue TrueVal, const SDValue FalseVal,
5190 const ISD::CondCode CC, const SDValue K) {
5191 return (isGTorGE(CC) &&
5192 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5193 (isLTorLE(CC) &&
5194 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5195}
5196
5197// Check if two chained conditionals could be converted into SSAT or USAT.
5198//
5199// SSAT can replace a set of two conditional selectors that bound a number to an
5200// interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5201//
5202// x < -k ? -k : (x > k ? k : x)
5203// x < -k ? -k : (x < k ? x : k)
5204// x > -k ? (x > k ? k : x) : -k
5205// x < k ? (x < -k ? -k : x) : k
5206// etc.
5207//
5208// LLVM canonicalizes these to either a min(max()) or a max(min())
5209// pattern. This function tries to match one of these and will return a SSAT
5210// node if successful.
5211//
5212// USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1
5213// is a power of 2.
5214static SDValue LowerSaturatingConditional(SDValue Op, SelectionDAG &DAG) {
5215 EVT VT = Op.getValueType();
5216 SDValue V1 = Op.getOperand(0);
5217 SDValue K1 = Op.getOperand(1);
5218 SDValue TrueVal1 = Op.getOperand(2);
5219 SDValue FalseVal1 = Op.getOperand(3);
5220 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5221
5222 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5223 if (Op2.getOpcode() != ISD::SELECT_CC)
5224 return SDValue();
5225
5226 SDValue V2 = Op2.getOperand(0);
5227 SDValue K2 = Op2.getOperand(1);
5228 SDValue TrueVal2 = Op2.getOperand(2);
5229 SDValue FalseVal2 = Op2.getOperand(3);
5230 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
5231
5232 SDValue V1Tmp = V1;
5233 SDValue V2Tmp = V2;
5234
5235 // Check that the registers and the constants match a max(min()) or min(max())
5236 // pattern
5237 if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 ||
5238 K2 != FalseVal2 ||
5239 !((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2))))
5240 return SDValue();
5241
5242 // Check that the constant in the lower-bound check is
5243 // the opposite of the constant in the upper-bound check
5244 // in 1's complement.
5245 if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2))
5246 return SDValue();
5247
5248 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5249 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5250 int64_t PosVal = std::max(Val1, Val2);
5251 int64_t NegVal = std::min(Val1, Val2);
5252
5253 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5254 !isPowerOf2_64(PosVal + 1))
5255 return SDValue();
5256
5257 // Handle the difference between USAT (unsigned) and SSAT (signed)
5258 // saturation
5259 // At this point, PosVal is guaranteed to be positive
5260 uint64_t K = PosVal;
5261 SDLoc dl(Op);
5262 if (Val1 == ~Val2)
5263 return DAG.getNode(ARMISD::SSAT, dl, VT, V2Tmp,
5264 DAG.getConstant(countTrailingOnes(K), dl, VT));
5265 if (NegVal == 0)
5266 return DAG.getNode(ARMISD::USAT, dl, VT, V2Tmp,
5267 DAG.getConstant(countTrailingOnes(K), dl, VT));
5268
5269 return SDValue();
5270}
5271
5272// Check if a condition of the type x < k ? k : x can be converted into a
5273// bit operation instead of conditional moves.
5274// Currently this is allowed given:
5275// - The conditions and values match up
5276// - k is 0 or -1 (all ones)
5277// This function will not check the last condition, thats up to the caller
5278// It returns true if the transformation can be made, and in such case
5279// returns x in V, and k in SatK.
5280static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
5281 SDValue &SatK)
5282{
5283 SDValue LHS = Op.getOperand(0);
5284 SDValue RHS = Op.getOperand(1);
5285 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5286 SDValue TrueVal = Op.getOperand(2);
5287 SDValue FalseVal = Op.getOperand(3);
5288
5289 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
5290 ? &RHS
5291 : nullptr;
5292
5293 // No constant operation in comparison, early out
5294 if (!K)
5295 return false;
5296
5297 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5298 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5299 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5300
5301 // If the constant on left and right side, or variable on left and right,
5302 // does not match, early out
5303 if (*K != KTmp || V != VTmp)
5304 return false;
5305
5306 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5307 SatK = *K;
5308 return true;
5309 }
5310
5311 return false;
5312}
5313
5314bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5315 if (VT == MVT::f32)
5316 return !Subtarget->hasVFP2Base();
5317 if (VT == MVT::f64)
5318 return !Subtarget->hasFP64();
5319 if (VT == MVT::f16)
5320 return !Subtarget->hasFullFP16();
5321 return false;
5322}
5323
5324SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5325 EVT VT = Op.getValueType();
5326 SDLoc dl(Op);
5327
5328 // Try to convert two saturating conditional selects into a single SSAT
5329 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2())
5330 if (SDValue SatValue = LowerSaturatingConditional(Op, DAG))
5331 return SatValue;
5332
5333 // Try to convert expressions of the form x < k ? k : x (and similar forms)
5334 // into more efficient bit operations, which is possible when k is 0 or -1
5335 // On ARM and Thumb-2 which have flexible operand 2 this will result in
5336 // single instructions. On Thumb the shift and the bit operation will be two
5337 // instructions.
5338 // Only allow this transformation on full-width (32-bit) operations
5339 SDValue LowerSatConstant;
5340 SDValue SatValue;
5341 if (VT == MVT::i32 &&
5342 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5343 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5344 DAG.getConstant(31, dl, VT));
5345 if (isNullConstant(LowerSatConstant)) {
5346 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5347 DAG.getAllOnesConstant(dl, VT));
5348 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5349 } else if (isAllOnesConstant(LowerSatConstant))
5350 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5351 }
5352
5353 SDValue LHS = Op.getOperand(0);
5354 SDValue RHS = Op.getOperand(1);
5355 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5356 SDValue TrueVal = Op.getOperand(2);
5357 SDValue FalseVal = Op.getOperand(3);
5358 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5359 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5360
5361 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
5362 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5363 unsigned TVal = CTVal->getZExtValue();
5364 unsigned FVal = CFVal->getZExtValue();
5365 unsigned Opcode = 0;
5366
5367 if (TVal == ~FVal) {
5368 Opcode = ARMISD::CSINV;
5369 } else if (TVal == ~FVal + 1) {
5370 Opcode = ARMISD::CSNEG;
5371 } else if (TVal + 1 == FVal) {
5372 Opcode = ARMISD::CSINC;
5373 } else if (TVal == FVal + 1) {
5374 Opcode = ARMISD::CSINC;
5375 std::swap(TrueVal, FalseVal);
5376 std::swap(TVal, FVal);
5377 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5378 }
5379
5380 if (Opcode) {
5381 // If one of the constants is cheaper than another, materialise the
5382 // cheaper one and let the csel generate the other.
5383 if (Opcode != ARMISD::CSINC &&
5384 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5385 std::swap(TrueVal, FalseVal);
5386 std::swap(TVal, FVal);
5387 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5388 }
5389
5390 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5391 // to get there. CSINC not is invertable like the other two (~(~a) == a,
5392 // -(-a) == a, but (a+1)+1 != a).
5393 if (FVal == 0 && Opcode != ARMISD::CSINC) {
5394 std::swap(TrueVal, FalseVal);
5395 std::swap(TVal, FVal);
5396 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5397 }
5398
5399 // Drops F's value because we can get it by inverting/negating TVal.
5400 FalseVal = TrueVal;
5401
5402 SDValue ARMcc;
5403 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5404 EVT VT = TrueVal.getValueType();
5405 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5406 }
5407 }
5408
5409 if (isUnsupportedFloatingType(LHS.getValueType())) {
5410 DAG.getTargetLoweringInfo().softenSetCCOperands(
5411 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5412
5413 // If softenSetCCOperands only returned one value, we should compare it to
5414 // zero.
5415 if (!RHS.getNode()) {
5416 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5417 CC = ISD::SETNE;
5418 }
5419 }
5420
5421 if (LHS.getValueType() == MVT::i32) {
5422 // Try to generate VSEL on ARMv8.
5423 // The VSEL instruction can't use all the usual ARM condition
5424 // codes: it only has two bits to select the condition code, so it's
5425 // constrained to use only GE, GT, VS and EQ.
5426 //
5427 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5428 // swap the operands of the previous compare instruction (effectively
5429 // inverting the compare condition, swapping 'less' and 'greater') and
5430 // sometimes need to swap the operands to the VSEL (which inverts the
5431 // condition in the sense of firing whenever the previous condition didn't)
5432 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5433 TrueVal.getValueType() == MVT::f32 ||
5434 TrueVal.getValueType() == MVT::f64)) {
5435 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5436 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5437 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5438 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5439 std::swap(TrueVal, FalseVal);
5440 }
5441 }
5442
5443 SDValue ARMcc;
5444 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5445 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5446 // Choose GE over PL, which vsel does now support
5447 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
5448 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5449 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5450 }
5451
5452 ARMCC::CondCodes CondCode, CondCode2;
5453 FPCCToARMCC(CC, CondCode, CondCode2);
5454
5455 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5456 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5457 // must use VSEL (limited condition codes), due to not having conditional f16
5458 // moves.
5459 if (Subtarget->hasFPARMv8Base() &&
5460 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5461 (TrueVal.getValueType() == MVT::f16 ||
5462 TrueVal.getValueType() == MVT::f32 ||
5463 TrueVal.getValueType() == MVT::f64)) {
5464 bool swpCmpOps = false;
5465 bool swpVselOps = false;
5466 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5467
5468 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5469 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5470 if (swpCmpOps)
5471 std::swap(LHS, RHS);
5472 if (swpVselOps)
5473 std::swap(TrueVal, FalseVal);
5474 }
5475 }
5476
5477 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5478 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5479 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5480 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5481 if (CondCode2 != ARMCC::AL) {
5482 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5483 // FIXME: Needs another CMP because flag can have but one use.
5484 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5485 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5486 }
5487 return Result;
5488}
5489
5490/// canChangeToInt - Given the fp compare operand, return true if it is suitable
5491/// to morph to an integer compare sequence.
5492static bool canChangeToInt(SDValue Op, bool &SeenZero,
5493 const ARMSubtarget *Subtarget) {
5494 SDNode *N = Op.getNode();
5495 if (!N->hasOneUse())
5496 // Otherwise it requires moving the value from fp to integer registers.
5497 return false;
5498 if (!N->getNumValues())
5499 return false;
5500 EVT VT = Op.getValueType();
5501 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5502 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5503 // vmrs are very slow, e.g. cortex-a8.
5504 return false;
5505
5506 if (isFloatingPointZero(Op)) {
5507 SeenZero = true;
5508 return true;
5509 }
5510 return ISD::isNormalLoad(N);
5511}
5512
5513static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5514 if (isFloatingPointZero(Op))
5515 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5516
5517 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5518 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5519 Ld->getPointerInfo(), Ld->getAlignment(),
5520 Ld->getMemOperand()->getFlags());
5521
5522 llvm_unreachable("Unknown VFP cmp argument!")::llvm::llvm_unreachable_internal("Unknown VFP cmp argument!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5522)
;
5523}
5524
5525static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5526 SDValue &RetVal1, SDValue &RetVal2) {
5527 SDLoc dl(Op);
5528
5529 if (isFloatingPointZero(Op)) {
5530 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5531 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5532 return;
5533 }
5534
5535 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5536 SDValue Ptr = Ld->getBasePtr();
5537 RetVal1 =
5538 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5539 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5540
5541 EVT PtrType = Ptr.getValueType();
5542 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5543 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5544 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5545 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5546 Ld->getPointerInfo().getWithOffset(4), NewAlign,
5547 Ld->getMemOperand()->getFlags());
5548 return;
5549 }
5550
5551 llvm_unreachable("Unknown VFP cmp argument!")::llvm::llvm_unreachable_internal("Unknown VFP cmp argument!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5551)
;
5552}
5553
5554/// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5555/// f32 and even f64 comparisons to integer ones.
5556SDValue
5557ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5558 SDValue Chain = Op.getOperand(0);
5559 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5560 SDValue LHS = Op.getOperand(2);
5561 SDValue RHS = Op.getOperand(3);
5562 SDValue Dest = Op.getOperand(4);
5563 SDLoc dl(Op);
5564
5565 bool LHSSeenZero = false;
5566 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5567 bool RHSSeenZero = false;
5568 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5569 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5570 // If unsafe fp math optimization is enabled and there are no other uses of
5571 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5572 // to an integer comparison.
5573 if (CC == ISD::SETOEQ)
5574 CC = ISD::SETEQ;
5575 else if (CC == ISD::SETUNE)
5576 CC = ISD::SETNE;
5577
5578 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5579 SDValue ARMcc;
5580 if (LHS.getValueType() == MVT::f32) {
5581 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5582 bitcastf32Toi32(LHS, DAG), Mask);
5583 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5584 bitcastf32Toi32(RHS, DAG), Mask);
5585 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5586 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5587 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5588 Chain, Dest, ARMcc, CCR, Cmp);
5589 }
5590
5591 SDValue LHS1, LHS2;
5592 SDValue RHS1, RHS2;
5593 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5594 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5595 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5596 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5597 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5598 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5599 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5600 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5601 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5602 }
5603
5604 return SDValue();
5605}
5606
5607SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5608 SDValue Chain = Op.getOperand(0);
5609 SDValue Cond = Op.getOperand(1);
5610 SDValue Dest = Op.getOperand(2);
5611 SDLoc dl(Op);
5612
5613 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5614 // instruction.
5615 unsigned Opc = Cond.getOpcode();
5616 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5617 !Subtarget->isThumb1Only();
5618 if (Cond.getResNo() == 1 &&
5619 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5620 Opc == ISD::USUBO || OptimizeMul)) {
5621 // Only lower legal XALUO ops.
5622 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5623 return SDValue();
5624
5625 // The actual operation with overflow check.
5626 SDValue Value, OverflowCmp;
5627 SDValue ARMcc;
5628 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5629
5630 // Reverse the condition code.
5631 ARMCC::CondCodes CondCode =
5632 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5633 CondCode = ARMCC::getOppositeCondition(CondCode);
5634 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5635 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5636
5637 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5638 OverflowCmp);
5639 }
5640
5641 return SDValue();
5642}
5643
5644SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5645 SDValue Chain = Op.getOperand(0);
5646 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5647 SDValue LHS = Op.getOperand(2);
5648 SDValue RHS = Op.getOperand(3);
5649 SDValue Dest = Op.getOperand(4);
5650 SDLoc dl(Op);
5651
5652 if (isUnsupportedFloatingType(LHS.getValueType())) {
5653 DAG.getTargetLoweringInfo().softenSetCCOperands(
5654 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5655
5656 // If softenSetCCOperands only returned one value, we should compare it to
5657 // zero.
5658 if (!RHS.getNode()) {
5659 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5660 CC = ISD::SETNE;
5661 }
5662 }
5663
5664 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5665 // instruction.
5666 unsigned Opc = LHS.getOpcode();
5667 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5668 !Subtarget->isThumb1Only();
5669 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5670 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5671 Opc == ISD::USUBO || OptimizeMul) &&
5672 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5673 // Only lower legal XALUO ops.
5674 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5675 return SDValue();
5676
5677 // The actual operation with overflow check.
5678 SDValue Value, OverflowCmp;
5679 SDValue ARMcc;
5680 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5681
5682 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5683 // Reverse the condition code.
5684 ARMCC::CondCodes CondCode =
5685 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5686 CondCode = ARMCC::getOppositeCondition(CondCode);
5687 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5688 }
5689 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5690
5691 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5692 OverflowCmp);
5693 }
5694
5695 if (LHS.getValueType() == MVT::i32) {
5696 SDValue ARMcc;
5697 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5698 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5699 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5700 Chain, Dest, ARMcc, CCR, Cmp);
5701 }
5702
5703 if (getTargetMachine().Options.UnsafeFPMath &&
5704 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5705 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5706 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5707 return Result;
5708 }
5709
5710 ARMCC::CondCodes CondCode, CondCode2;
5711 FPCCToARMCC(CC, CondCode, CondCode2);
5712
5713 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5714 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5715 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5716 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5717 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5718 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5719 if (CondCode2 != ARMCC::AL) {
5720 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5721 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5722 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5723 }
5724 return Res;
5725}
5726
5727SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5728 SDValue Chain = Op.getOperand(0);
5729 SDValue Table = Op.getOperand(1);
5730 SDValue Index = Op.getOperand(2);
5731 SDLoc dl(Op);
5732
5733 EVT PTy = getPointerTy(DAG.getDataLayout());
5734 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5735 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5736 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5737 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5738 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5739 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5740 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5741 // which does another jump to the destination. This also makes it easier
5742 // to translate it to TBB / TBH later (Thumb2 only).
5743 // FIXME: This might not work if the function is extremely large.
5744 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5745 Addr, Op.getOperand(2), JTI);
5746 }
5747 if (isPositionIndependent() || Subtarget->isROPI()) {
5748 Addr =
5749 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5750 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5751 Chain = Addr.getValue(1);
5752 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5753 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5754 } else {
5755 Addr =
5756 DAG.getLoad(PTy, dl, Chain, Addr,
5757 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5758 Chain = Addr.getValue(1);
5759 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5760 }
5761}
5762
5763static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5764 EVT VT = Op.getValueType();
5765 SDLoc dl(Op);
5766
5767 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5768 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5769 return Op;
5770 return DAG.UnrollVectorOp(Op.getNode());
5771 }
5772
5773 const bool HasFullFP16 =
5774 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5775
5776 EVT NewTy;
5777 const EVT OpTy = Op.getOperand(0).getValueType();
5778 if (OpTy == MVT::v4f32)
5779 NewTy = MVT::v4i32;
5780 else if (OpTy == MVT::v4f16 && HasFullFP16)
5781 NewTy = MVT::v4i16;
5782 else if (OpTy == MVT::v8f16 && HasFullFP16)
5783 NewTy = MVT::v8i16;
5784 else
5785 llvm_unreachable("Invalid type for custom lowering!")::llvm::llvm_unreachable_internal("Invalid type for custom lowering!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5785)
;
5786
5787 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5788 return DAG.UnrollVectorOp(Op.getNode());
5789
5790 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5791 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5792}
5793
5794SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5795 EVT VT = Op.getValueType();
5796 if (VT.isVector())
5797 return LowerVectorFP_TO_INT(Op, DAG);
5798
5799 bool IsStrict = Op->isStrictFPOpcode();
5800 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5801
5802 if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5803 RTLIB::Libcall LC;
5804 if (Op.getOpcode() == ISD::FP_TO_SINT ||
5805 Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5806 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5807 Op.getValueType());
5808 else
5809 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5810 Op.getValueType());
5811 SDLoc Loc(Op);
5812 MakeLibCallOptions CallOptions;
5813 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5814 SDValue Result;
5815 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5816 CallOptions, Loc, Chain);
5817 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5818 }
5819
5820 // FIXME: Remove this when we have strict fp instruction selection patterns
5821 if (IsStrict) {
5822 SDLoc Loc(Op);
5823 SDValue Result =
5824 DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5825 : ISD::FP_TO_UINT,
5826 Loc, Op.getValueType(), SrcVal);
5827 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5828 }
5829
5830 return Op;
5831}
5832
5833static SDValue LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
5834 const ARMSubtarget *Subtarget) {
5835 EVT VT = Op.getValueType();
5836 EVT ToVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5837 EVT FromVT = Op.getOperand(0).getValueType();
5838
5839 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f32)
5840 return Op;
5841 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f64 &&
5842 Subtarget->hasFP64())
5843 return Op;
5844 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f16 &&
5845 Subtarget->hasFullFP16())
5846 return Op;
5847 if (VT == MVT::v4i32 && ToVT == MVT::i32 && FromVT == MVT::v4f32 &&
5848 Subtarget->hasMVEFloatOps())
5849 return Op;
5850 if (VT == MVT::v8i16 && ToVT == MVT::i16 && FromVT == MVT::v8f16 &&
5851 Subtarget->hasMVEFloatOps())
5852 return Op;
5853
5854 if (FromVT != MVT::v4f32 && FromVT != MVT::v8f16)
5855 return SDValue();
5856
5857 SDLoc DL(Op);
5858 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
5859 unsigned BW = ToVT.getScalarSizeInBits() - IsSigned;
5860 SDValue CVT = DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
5861 DAG.getValueType(VT.getScalarType()));
5862 SDValue Max = DAG.getNode(IsSigned ? ISD::SMIN : ISD::UMIN, DL, VT, CVT,
5863 DAG.getConstant((1 << BW) - 1, DL, VT));
5864 if (IsSigned)
5865 Max = DAG.getNode(ISD::SMAX, DL, VT, Max,
5866 DAG.getConstant(-(1 << BW), DL, VT));
5867 return Max;
5868}
5869
5870static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5871 EVT VT = Op.getValueType();
5872 SDLoc dl(Op);
5873
5874 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5875 if (VT.getVectorElementType() == MVT::f32)
5876 return Op;
5877 return DAG.UnrollVectorOp(Op.getNode());
5878 }
5879
5880 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5882, __extension__ __PRETTY_FUNCTION__))
5881 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5882, __extension__ __PRETTY_FUNCTION__))
5882 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5882, __extension__ __PRETTY_FUNCTION__))
;
5883
5884 const bool HasFullFP16 =
5885 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5886
5887 EVT DestVecType;
5888 if (VT == MVT::v4f32)
5889 DestVecType = MVT::v4i32;
5890 else if (VT == MVT::v4f16 && HasFullFP16)
5891 DestVecType = MVT::v4i16;
5892 else if (VT == MVT::v8f16 && HasFullFP16)
5893 DestVecType = MVT::v8i16;
5894 else
5895 return DAG.UnrollVectorOp(Op.getNode());
5896
5897 unsigned CastOpc;
5898 unsigned Opc;
5899 switch (Op.getOpcode()) {
5900 default: llvm_unreachable("Invalid opcode!")::llvm::llvm_unreachable_internal("Invalid opcode!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5900)
;
5901 case ISD::SINT_TO_FP:
5902 CastOpc = ISD::SIGN_EXTEND;
5903 Opc = ISD::SINT_TO_FP;
5904 break;
5905 case ISD::UINT_TO_FP:
5906 CastOpc = ISD::ZERO_EXTEND;
5907 Opc = ISD::UINT_TO_FP;
5908 break;
5909 }
5910
5911 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5912 return DAG.getNode(Opc, dl, VT, Op);
5913}
5914
5915SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5916 EVT VT = Op.getValueType();
5917 if (VT.isVector())
5918 return LowerVectorINT_TO_FP(Op, DAG);
5919 if (isUnsupportedFloatingType(VT)) {
5920 RTLIB::Libcall LC;
5921 if (Op.getOpcode() == ISD::SINT_TO_FP)
5922 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5923 Op.getValueType());
5924 else
5925 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5926 Op.getValueType());
5927 MakeLibCallOptions CallOptions;
5928 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5929 CallOptions, SDLoc(Op)).first;
5930 }
5931
5932 return Op;
5933}
5934
5935SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5936 // Implement fcopysign with a fabs and a conditional fneg.
5937 SDValue Tmp0 = Op.getOperand(0);
5938 SDValue Tmp1 = Op.getOperand(1);
5939 SDLoc dl(Op);
5940 EVT VT = Op.getValueType();
5941 EVT SrcVT = Tmp1.getValueType();
5942 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5943 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5944 bool UseNEON = !InGPR && Subtarget->hasNEON();
5945
5946 if (UseNEON) {
5947 // Use VBSL to copy the sign bit.
5948 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5949 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5950 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5951 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5952 if (VT == MVT::f64)
5953 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5954 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5955 DAG.getConstant(32, dl, MVT::i32));
5956 else /*if (VT == MVT::f32)*/
5957 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5958 if (SrcVT == MVT::f32) {
5959 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5960 if (VT == MVT::f64)
5961 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5962 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5963 DAG.getConstant(32, dl, MVT::i32));
5964 } else if (VT == MVT::f32)
5965 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5966 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5967 DAG.getConstant(32, dl, MVT::i32));
5968 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5969 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5970
5971 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5972 dl, MVT::i32);
5973 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5974 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5975 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5976
5977 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5978 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5979 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5980 if (VT == MVT::f32) {
5981 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5982 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5983 DAG.getConstant(0, dl, MVT::i32));
5984 } else {
5985 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5986 }
5987
5988 return Res;
5989 }
5990
5991 // Bitcast operand 1 to i32.
5992 if (SrcVT == MVT::f64)
5993 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5994 Tmp1).getValue(1);
5995 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5996
5997 // Or in the signbit with integer operations.
5998 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5999 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
6000 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
6001 if (VT == MVT::f32) {
6002 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
6003 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
6004 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
6005 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
6006 }
6007
6008 // f64: Or the high part with signbit and then combine two parts.
6009 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
6010 Tmp0);
6011 SDValue Lo = Tmp0.getValue(0);
6012 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
6013 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
6014 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
6015}
6016
6017SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
6018 MachineFunction &MF = DAG.getMachineFunction();
6019 MachineFrameInfo &MFI = MF.getFrameInfo();
6020 MFI.setReturnAddressIsTaken(true);
6021
6022 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
6023 return SDValue();
6024
6025 EVT VT = Op.getValueType();
6026 SDLoc dl(Op);
6027 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6028 if (Depth) {
6029 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6030 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
6031 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
6032 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
6033 MachinePointerInfo());
6034 }
6035
6036 // Return LR, which contains the return address. Mark it an implicit live-in.
6037 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
6038 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
6039}
6040
6041SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6042 const ARMBaseRegisterInfo &ARI =
6043 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
6044 MachineFunction &MF = DAG.getMachineFunction();
6045 MachineFrameInfo &MFI = MF.getFrameInfo();
6046 MFI.setFrameAddressIsTaken(true);
6047
6048 EVT VT = Op.getValueType();
6049 SDLoc dl(Op); // FIXME probably not meaningful
6050 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6051 Register FrameReg = ARI.getFrameRegister(MF);
6052 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6053 while (Depth--)
6054 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
6055 MachinePointerInfo());
6056 return FrameAddr;
6057}
6058
6059// FIXME? Maybe this could be a TableGen attribute on some registers and
6060// this table could be generated automatically from RegInfo.
6061Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
6062 const MachineFunction &MF) const {
6063 Register Reg = StringSwitch<unsigned>(RegName)
6064 .Case("sp", ARM::SP)
6065 .Default(0);
6066 if (Reg)
6067 return Reg;
6068 report_fatal_error(Twine("Invalid register name \""
6069 + StringRef(RegName) + "\"."));
6070}
6071
6072// Result is 64 bit value so split into two 32 bit values and return as a
6073// pair of values.
6074static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
6075 SelectionDAG &DAG) {
6076 SDLoc DL(N);
6077
6078 // This function is only supposed to be called for i64 type destination.
6079 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.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6080, __extension__ __PRETTY_FUNCTION__))
6080 && "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.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6080, __extension__ __PRETTY_FUNCTION__))
;
6081
6082 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
6083 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
6084 N->getOperand(0),
6085 N->getOperand(1));
6086
6087 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
6088 Read.getValue(1)));
6089 Results.push_back(Read.getOperand(0));
6090}
6091
6092/// \p BC is a bitcast that is about to be turned into a VMOVDRR.
6093/// When \p DstVT, the destination type of \p BC, is on the vector
6094/// register bank and the source of bitcast, \p Op, operates on the same bank,
6095/// it might be possible to combine them, such that everything stays on the
6096/// vector register bank.
6097/// \p return The node that would replace \p BT, if the combine
6098/// is possible.
6099static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
6100 SelectionDAG &DAG) {
6101 SDValue Op = BC->getOperand(0);
6102 EVT DstVT = BC->getValueType(0);
6103
6104 // The only vector instruction that can produce a scalar (remember,
6105 // since the bitcast was about to be turned into VMOVDRR, the source
6106 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
6107 // Moreover, we can do this combine only if there is one use.
6108 // Finally, if the destination type is not a vector, there is not
6109 // much point on forcing everything on the vector bank.
6110 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6111 !Op.hasOneUse())
6112 return SDValue();
6113
6114 // If the index is not constant, we will introduce an additional
6115 // multiply that will stick.
6116 // Give up in that case.
6117 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6118 if (!Index)
6119 return SDValue();
6120 unsigned DstNumElt = DstVT.getVectorNumElements();
6121
6122 // Compute the new index.
6123 const APInt &APIntIndex = Index->getAPIntValue();
6124 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
6125 NewIndex *= APIntIndex;
6126 // Check if the new constant index fits into i32.
6127 if (NewIndex.getBitWidth() > 32)
6128 return SDValue();
6129
6130 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
6131 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
6132 SDLoc dl(Op);
6133 SDValue ExtractSrc = Op.getOperand(0);
6134 EVT VecVT = EVT::getVectorVT(
6135 *DAG.getContext(), DstVT.getScalarType(),
6136 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
6137 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
6138 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
6139 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
6140}
6141
6142/// ExpandBITCAST - If the target supports VFP, this function is called to
6143/// expand a bit convert where either the source or destination type is i64 to
6144/// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
6145/// operand type is illegal (e.g., v2f32 for a target that doesn't support
6146/// vectors), since the legalizer won't know what to do with that.
6147SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
6148 const ARMSubtarget *Subtarget) const {
6149 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6150 SDLoc dl(N);
6151 SDValue Op = N->getOperand(0);
6152
6153 // This function is only supposed to be called for i16 and i64 types, either
6154 // as the source or destination of the bit convert.
6155 EVT SrcVT = Op.getValueType();
6156 EVT DstVT = N->getValueType(0);
6157
6158 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
6159 (DstVT == MVT::f16 || DstVT == MVT::bf16))
6160 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
6161 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
6162
6163 if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
6164 (SrcVT == MVT::f16 || SrcVT == MVT::bf16))
6165 return DAG.getNode(
6166 ISD::TRUNCATE, SDLoc(N), DstVT,
6167 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
6168
6169 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
6170 return SDValue();
6171
6172 // Turn i64->f64 into VMOVDRR.
6173 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
6174 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
6175 // if we can combine the bitcast with its source.
6176 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
6177 return Val;
6178
6179 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
6180 DAG.getConstant(0, dl, MVT::i32));
6181 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
6182 DAG.getConstant(1, dl, MVT::i32));
6183 return DAG.getNode(ISD::BITCAST, dl, DstVT,
6184 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
6185 }
6186
6187 // Turn f64->i64 into VMOVRRD.
6188 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
6189 SDValue Cvt;
6190 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6191 SrcVT.getVectorNumElements() > 1)
6192 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6193 DAG.getVTList(MVT::i32, MVT::i32),
6194 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6195 else
6196 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6197 DAG.getVTList(MVT::i32, MVT::i32), Op);
6198 // Merge the pieces into a single i64 value.
6199 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6200 }
6201
6202 return SDValue();
6203}
6204
6205/// getZeroVector - Returns a vector of specified type with all zero elements.
6206/// Zero vectors are used to represent vector negation and in those cases
6207/// will be implemented with the NEON VNEG instruction. However, VNEG does
6208/// not support i64 elements, so sometimes the zero vectors will need to be
6209/// explicitly constructed. Regardless, use a canonical VMOV to create the
6210/// zero vector.
6211static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6212 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6212, __extension__ __PRETTY_FUNCTION__))
;
6213 // The canonical modified immediate encoding of a zero vector is....0!
6214 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6215 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6216 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6217 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6218}
6219
6220/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6221/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6222SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6223 SelectionDAG &DAG) const {
6224 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6224, __extension__ __PRETTY_FUNCTION__))
;
6225 EVT VT = Op.getValueType();
6226 unsigned VTBits = VT.getSizeInBits();
6227 SDLoc dl(Op);
6228 SDValue ShOpLo = Op.getOperand(0);
6229 SDValue ShOpHi = Op.getOperand(1);
6230 SDValue ShAmt = Op.getOperand(2);
6231 SDValue ARMcc;
6232 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6233 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6234
6235 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"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6235, __extension__ __PRETTY_FUNCTION__))
;
6236
6237 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6238 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6239 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6240 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6241 DAG.getConstant(VTBits, dl, MVT::i32));
6242 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6243 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6244 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6245 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6246 ISD::SETGE, ARMcc, DAG, dl);
6247 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
6248 ARMcc, CCR, CmpLo);
6249
6250 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6251 SDValue HiBigShift = Opc == ISD::SRA
6252 ? DAG.getNode(Opc, dl, VT, ShOpHi,
6253 DAG.getConstant(VTBits - 1, dl, VT))
6254 : DAG.getConstant(0, dl, VT);
6255 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6256 ISD::SETGE, ARMcc, DAG, dl);
6257 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6258 ARMcc, CCR, CmpHi);
6259
6260 SDValue Ops[2] = { Lo, Hi };
6261 return DAG.getMergeValues(Ops, dl);
6262}
6263
6264/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6265/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6266SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6267 SelectionDAG &DAG) const {
6268 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6268, __extension__ __PRETTY_FUNCTION__))
;
6269 EVT VT = Op.getValueType();
6270 unsigned VTBits = VT.getSizeInBits();
6271 SDLoc dl(Op);
6272 SDValue ShOpLo = Op.getOperand(0);
6273 SDValue ShOpHi = Op.getOperand(1);
6274 SDValue ShAmt = Op.getOperand(2);
6275 SDValue ARMcc;
6276 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6277
6278 assert(Op.getOpcode() == ISD::SHL_PARTS)(static_cast <bool> (Op.getOpcode() == ISD::SHL_PARTS) ?
void (0) : __assert_fail ("Op.getOpcode() == ISD::SHL_PARTS"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6278, __extension__ __PRETTY_FUNCTION__))
;
6279 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6280 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6281 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6282 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6283 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6284
6285 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6286 DAG.getConstant(VTBits, dl, MVT::i32));
6287 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6288 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6289 ISD::SETGE, ARMcc, DAG, dl);
6290 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6291 ARMcc, CCR, CmpHi);
6292
6293 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6294 ISD::SETGE, ARMcc, DAG, dl);
6295 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6296 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6297 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
6298
6299 SDValue Ops[2] = { Lo, Hi };
6300 return DAG.getMergeValues(Ops, dl);
6301}
6302
6303SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6304 SelectionDAG &DAG) const {
6305 // The rounding mode is in bits 23:22 of the FPSCR.
6306 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6307 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6308 // so that the shift + and get folded into a bitfield extract.
6309 SDLoc dl(Op);
6310 SDValue Chain = Op.getOperand(0);
6311 SDValue Ops[] = {Chain,
6312 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6313
6314 SDValue FPSCR =
6315 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6316 Chain = FPSCR.getValue(1);
6317 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6318 DAG.getConstant(1U << 22, dl, MVT::i32));
6319 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6320 DAG.getConstant(22, dl, MVT::i32));
6321 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6322 DAG.getConstant(3, dl, MVT::i32));
6323 return DAG.getMergeValues({And, Chain}, dl);
6324}
6325
6326SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op,
6327 SelectionDAG &DAG) const {
6328 SDLoc DL(Op);
6329 SDValue Chain = Op->getOperand(0);
6330 SDValue RMValue = Op->getOperand(1);
6331
6332 // The rounding mode is in bits 23:22 of the FPSCR.
6333 // The llvm.set.rounding argument value to ARM rounding mode value mapping
6334 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
6335 // ((arg - 1) & 3) << 22).
6336 //
6337 // It is expected that the argument of llvm.set.rounding is within the
6338 // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is
6339 // responsibility of the code generated llvm.set.rounding to ensure this
6340 // condition.
6341
6342 // Calculate new value of FPSCR[23:22].
6343 RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
6344 DAG.getConstant(1, DL, MVT::i32));
6345 RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
6346 DAG.getConstant(0x3, DL, MVT::i32));
6347 RMValue = DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
6348 DAG.getConstant(ARM::RoundingBitsPos, DL, MVT::i32));
6349
6350 // Get current value of FPSCR.
6351 SDValue Ops[] = {Chain,
6352 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6353 SDValue FPSCR =
6354 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6355 Chain = FPSCR.getValue(1);
6356 FPSCR = FPSCR.getValue(0);
6357
6358 // Put new rounding mode into FPSCR[23:22].
6359 const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos);
6360 FPSCR = DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6361 DAG.getConstant(RMMask, DL, MVT::i32));
6362 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCR, RMValue);
6363 SDValue Ops2[] = {
6364 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6365 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6366}
6367
6368static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
6369 const ARMSubtarget *ST) {
6370 SDLoc dl(N);
6371 EVT VT = N->getValueType(0);
6372 if (VT.isVector() && ST->hasNEON()) {
6373
6374 // Compute the least significant set bit: LSB = X & -X
6375 SDValue X = N->getOperand(0);
6376 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6377 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6378
6379 EVT ElemTy = VT.getVectorElementType();
6380
6381 if (ElemTy == MVT::i8) {
6382 // Compute with: cttz(x) = ctpop(lsb - 1)
6383 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6384 DAG.getTargetConstant(1, dl, ElemTy));
6385 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6386 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6387 }
6388
6389 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6390 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6391 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6392 unsigned NumBits = ElemTy.getSizeInBits();
6393 SDValue WidthMinus1 =
6394 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6395 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6396 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6397 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6398 }
6399
6400 // Compute with: cttz(x) = ctpop(lsb - 1)
6401
6402 // Compute LSB - 1.
6403 SDValue Bits;
6404 if (ElemTy == MVT::i64) {
6405 // Load constant 0xffff'ffff'ffff'ffff to register.
6406 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6407 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6408 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6409 } else {
6410 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6411 DAG.getTargetConstant(1, dl, ElemTy));
6412 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6413 }
6414 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6415 }
6416
6417 if (!ST->hasV6T2Ops())
6418 return SDValue();
6419
6420 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6421 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6422}
6423
6424static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6425 const ARMSubtarget *ST) {
6426 EVT VT = N->getValueType(0);
6427 SDLoc DL(N);
6428
6429 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.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6429, __extension__ __PRETTY_FUNCTION__))
;
6430 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6432, __extension__ __PRETTY_FUNCTION__))
6431 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6432, __extension__ __PRETTY_FUNCTION__))
6432 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6432, __extension__ __PRETTY_FUNCTION__))
;
6433
6434 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6435 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6436 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6437 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6438
6439 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6440 unsigned EltSize = 8;
6441 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6442 while (EltSize != VT.getScalarSizeInBits()) {
6443 SmallVector<SDValue, 8> Ops;
6444 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6445 TLI.getPointerTy(DAG.getDataLayout())));
6446 Ops.push_back(Res);
6447
6448 EltSize *= 2;
6449 NumElts /= 2;
6450 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6451 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6452 }
6453
6454 return Res;
6455}
6456
6457/// Getvshiftimm - Check if this is a valid build_vector for the immediate
6458/// operand of a vector shift operation, where all the elements of the
6459/// build_vector must have the same constant integer value.
6460static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6461 // Ignore bit_converts.
6462 while (Op.getOpcode() == ISD::BITCAST)
6463 Op = Op.getOperand(0);
6464 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6465 APInt SplatBits, SplatUndef;
6466 unsigned SplatBitSize;
6467 bool HasAnyUndefs;
6468 if (!BVN ||
6469 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6470 ElementBits) ||
6471 SplatBitSize > ElementBits)
6472 return false;
6473 Cnt = SplatBits.getSExtValue();
6474 return true;
6475}
6476
6477/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6478/// operand of a vector shift left operation. That value must be in the range:
6479/// 0 <= Value < ElementBits for a left shift; or
6480/// 0 <= Value <= ElementBits for a long left shift.
6481static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6482 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6482, __extension__ __PRETTY_FUNCTION__))
;
6483 int64_t ElementBits = VT.getScalarSizeInBits();
6484 if (!getVShiftImm(Op, ElementBits, Cnt))
6485 return false;
6486 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6487}
6488
6489/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6490/// operand of a vector shift right operation. For a shift opcode, the value
6491/// is positive, but for an intrinsic the value count must be negative. The
6492/// absolute value must be in the range:
6493/// 1 <= |Value| <= ElementBits for a right shift; or
6494/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6495static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6496 int64_t &Cnt) {
6497 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6497, __extension__ __PRETTY_FUNCTION__))
;
6498 int64_t ElementBits = VT.getScalarSizeInBits();
6499 if (!getVShiftImm(Op, ElementBits, Cnt))
6500 return false;
6501 if (!isIntrinsic)
6502 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6503 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6504 Cnt = -Cnt;
6505 return true;
6506 }
6507 return false;
6508}
6509
6510static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6511 const ARMSubtarget *ST) {
6512 EVT VT = N->getValueType(0);
6513 SDLoc dl(N);
6514 int64_t Cnt;
6515
6516 if (!VT.isVector())
6517 return SDValue();
6518
6519 // We essentially have two forms here. Shift by an immediate and shift by a
6520 // vector register (there are also shift by a gpr, but that is just handled
6521 // with a tablegen pattern). We cannot easily match shift by an immediate in
6522 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6523 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6524 // signed or unsigned, and a negative shift indicates a shift right).
6525 if (N->getOpcode() == ISD::SHL) {
6526 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6527 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6528 DAG.getConstant(Cnt, dl, MVT::i32));
6529 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6530 N->getOperand(1));
6531 }
6532
6533 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6534, __extension__ __PRETTY_FUNCTION__))
6534 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6534, __extension__ __PRETTY_FUNCTION__))
;
6535
6536 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6537 unsigned VShiftOpc =
6538 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6539 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6540 DAG.getConstant(Cnt, dl, MVT::i32));
6541 }
6542
6543 // Other right shifts we don't have operations for (we use a shift left by a
6544 // negative number).
6545 EVT ShiftVT = N->getOperand(1).getValueType();
6546 SDValue NegatedCount = DAG.getNode(
6547 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6548 unsigned VShiftOpc =
6549 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6550 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6551}
6552
6553static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6554 const ARMSubtarget *ST) {
6555 EVT VT = N->getValueType(0);
6556 SDLoc dl(N);
6557
6558 // We can get here for a node like i32 = ISD::SHL i32, i64
6559 if (VT != MVT::i64)
6560 return SDValue();
6561
6562 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6564, __extension__ __PRETTY_FUNCTION__))
6563 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6564, __extension__ __PRETTY_FUNCTION__))
6564 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6564, __extension__ __PRETTY_FUNCTION__))
;
6565
6566 unsigned ShOpc = N->getOpcode();
6567 if (ST->hasMVEIntegerOps()) {
6568 SDValue ShAmt = N->getOperand(1);
6569 unsigned ShPartsOpc = ARMISD::LSLL;
6570 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6571
6572 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6573 // then do the default optimisation
6574 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6575 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6576 return SDValue();
6577
6578 // Extract the lower 32 bits of the shift amount if it's not an i32
6579 if (ShAmt->getValueType(0) != MVT::i32)
6580 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6581
6582 if (ShOpc == ISD::SRL) {
6583 if (!Con)
6584 // There is no t2LSRLr instruction so negate and perform an lsll if the
6585 // shift amount is in a register, emulating a right shift.
6586 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6587 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6588 else
6589 // Else generate an lsrl on the immediate shift amount
6590 ShPartsOpc = ARMISD::LSRL;
6591 } else if (ShOpc == ISD::SRA)
6592 ShPartsOpc = ARMISD::ASRL;
6593
6594 // Lower 32 bits of the destination/source
6595 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6596 DAG.getConstant(0, dl, MVT::i32));
6597 // Upper 32 bits of the destination/source
6598 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6599 DAG.getConstant(1, dl, MVT::i32));
6600
6601 // Generate the shift operation as computed above
6602 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6603 ShAmt);
6604 // The upper 32 bits come from the second return value of lsll
6605 Hi = SDValue(Lo.getNode(), 1);
6606 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6607 }
6608
6609 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6610 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6611 return SDValue();
6612
6613 // If we are in thumb mode, we don't have RRX.
6614 if (ST->isThumb1Only())
6615 return SDValue();
6616
6617 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6618 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6619 DAG.getConstant(0, dl, MVT::i32));
6620 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6621 DAG.getConstant(1, dl, MVT::i32));
6622
6623 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6624 // captures the result into a carry flag.
6625 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6626 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6627
6628 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6629 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6630
6631 // Merge the pieces into a single i64 value.
6632 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6633}
6634
6635static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6636 const ARMSubtarget *ST) {
6637 bool Invert = false;
6638 bool Swap = false;
6639 unsigned Opc = ARMCC::AL;
6640
6641 SDValue Op0 = Op.getOperand(0);
6642 SDValue Op1 = Op.getOperand(1);
6643 SDValue CC = Op.getOperand(2);
6644 EVT VT = Op.getValueType();
6645 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6646 SDLoc dl(Op);
6647
6648 EVT CmpVT;
6649 if (ST->hasNEON())
6650 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6651 else {
6652 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6653, __extension__ __PRETTY_FUNCTION__))
6653 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6653, __extension__ __PRETTY_FUNCTION__))
;
6654
6655 if (Op.getValueType().getVectorElementType() != MVT::i1)
6656 return SDValue();
6657
6658 // Make sure we expand floating point setcc to scalar if we do not have
6659 // mve.fp, so that we can handle them from there.
6660 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6661 return SDValue();
6662
6663 CmpVT = VT;
6664 }
6665
6666 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6667 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6668 // Special-case integer 64-bit equality comparisons. They aren't legal,
6669 // but they can be lowered with a few vector instructions.
6670 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6671 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6672 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6673 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6674 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6675 DAG.getCondCode(ISD::SETEQ));
6676 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6677 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6678 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6679 if (SetCCOpcode == ISD::SETNE)
6680 Merged = DAG.getNOT(dl, Merged, CmpVT);
6681 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6682 return Merged;
6683 }
6684
6685 if (CmpVT.getVectorElementType() == MVT::i64)
6686 // 64-bit comparisons are not legal in general.
6687 return SDValue();
6688
6689 if (Op1.getValueType().isFloatingPoint()) {
6690 switch (SetCCOpcode) {
6691 default: llvm_unreachable("Illegal FP comparison")::llvm::llvm_unreachable_internal("Illegal FP comparison", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6691)
;
6692 case ISD::SETUNE:
6693 case ISD::SETNE:
6694 if (ST->hasMVEFloatOps()) {
6695 Opc = ARMCC::NE; break;
6696 } else {
6697 Invert = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6698 }
6699 case ISD::SETOEQ:
6700 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6701 case ISD::SETOLT:
6702 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6703 case ISD::SETOGT:
6704 case ISD::SETGT: Opc = ARMCC::GT; break;
6705 case ISD::SETOLE:
6706 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6707 case ISD::SETOGE:
6708 case ISD::SETGE: Opc = ARMCC::GE; break;
6709 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6710 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6711 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6712 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6713 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6714 case ISD::SETONE: {
6715 // Expand this to (OLT | OGT).
6716 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6717 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6718 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6719 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6720 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6721 if (Invert)
6722 Result = DAG.getNOT(dl, Result, VT);
6723 return Result;
6724 }
6725 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6726 case ISD::SETO: {
6727 // Expand this to (OLT | OGE).
6728 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6729 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6730 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6731 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6732 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6733 if (Invert)
6734 Result = DAG.getNOT(dl, Result, VT);
6735 return Result;
6736 }
6737 }
6738 } else {
6739 // Integer comparisons.
6740 switch (SetCCOpcode) {
6741 default: llvm_unreachable("Illegal integer comparison")::llvm::llvm_unreachable_internal("Illegal integer comparison"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6741)
;
6742 case ISD::SETNE:
6743 if (ST->hasMVEIntegerOps()) {
6744 Opc = ARMCC::NE; break;
6745 } else {
6746 Invert = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6747 }
6748 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6749 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6750 case ISD::SETGT: Opc = ARMCC::GT; break;
6751 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6752 case ISD::SETGE: Opc = ARMCC::GE; break;
6753 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6754 case ISD::SETUGT: Opc = ARMCC::HI; break;
6755 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6756 case ISD::SETUGE: Opc = ARMCC::HS; break;
6757 }
6758
6759 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6760 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6761 SDValue AndOp;
6762 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6763 AndOp = Op0;
6764 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6765 AndOp = Op1;
6766
6767 // Ignore bitconvert.
6768 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6769 AndOp = AndOp.getOperand(0);
6770
6771 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6772 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6773 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6774 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6775 if (!Invert)
6776 Result = DAG.getNOT(dl, Result, VT);
6777 return Result;
6778 }
6779 }
6780 }
6781
6782 if (Swap)
6783 std::swap(Op0, Op1);
6784
6785 // If one of the operands is a constant vector zero, attempt to fold the
6786 // comparison to a specialized compare-against-zero form.
6787 SDValue SingleOp;
6788 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6789 SingleOp = Op0;
6790 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6791 if (Opc == ARMCC::GE)
6792 Opc = ARMCC::LE;
6793 else if (Opc == ARMCC::GT)
6794 Opc = ARMCC::LT;
6795 SingleOp = Op1;
6796 }
6797
6798 SDValue Result;
6799 if (SingleOp.getNode()) {
6800 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6801 DAG.getConstant(Opc, dl, MVT::i32));
6802 } else {
6803 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6804 DAG.getConstant(Opc, dl, MVT::i32));
6805 }
6806
6807 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6808
6809 if (Invert)
6810 Result = DAG.getNOT(dl, Result, VT);
6811
6812 return Result;
6813}
6814
6815static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6816 SDValue LHS = Op.getOperand(0);
6817 SDValue RHS = Op.getOperand(1);
6818 SDValue Carry = Op.getOperand(2);
6819 SDValue Cond = Op.getOperand(3);
6820 SDLoc DL(Op);
6821
6822 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.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6822, __extension__ __PRETTY_FUNCTION__))
;
6823
6824 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6825 // have to invert the carry first.
6826 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6827 DAG.getConstant(1, DL, MVT::i32), Carry);
6828 // This converts the boolean value carry into the carry flag.
6829 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6830
6831 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6832 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6833
6834 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6835 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6836 SDValue ARMcc = DAG.getConstant(
6837 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6838 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6839 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6840 Cmp.getValue(1), SDValue());
6841 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6842 CCR, Chain.getValue(1));
6843}
6844
6845/// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6846/// valid vector constant for a NEON or MVE instruction with a "modified
6847/// immediate" operand (e.g., VMOV). If so, return the encoded value.
6848static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6849 unsigned SplatBitSize, SelectionDAG &DAG,
6850 const SDLoc &dl, EVT &VT, EVT VectorVT,
6851 VMOVModImmType type) {
6852 unsigned OpCmode, Imm;
6853 bool is128Bits = VectorVT.is128BitVector();
6854
6855 // SplatBitSize is set to the smallest size that splats the vector, so a
6856 // zero vector will always have SplatBitSize == 8. However, NEON modified
6857 // immediate instructions others than VMOV do not support the 8-bit encoding
6858 // of a zero vector, and the default encoding of zero is supposed to be the
6859 // 32-bit version.
6860 if (SplatBits == 0)
6861 SplatBitSize = 32;
6862
6863 switch (SplatBitSize) {
6864 case 8:
6865 if (type != VMOVModImm)
6866 return SDValue();
6867 // Any 1-byte value is OK. Op=0, Cmode=1110.
6868 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6868, __extension__ __PRETTY_FUNCTION__))
;
6869 OpCmode = 0xe;
6870 Imm = SplatBits;
6871 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6872 break;
6873
6874 case 16:
6875 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6876 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6877 if ((SplatBits & ~0xff) == 0) {
6878 // Value = 0x00nn: Op=x, Cmode=100x.
6879 OpCmode = 0x8;
6880 Imm = SplatBits;
6881 break;
6882 }
6883 if ((SplatBits & ~0xff00) == 0) {
6884 // Value = 0xnn00: Op=x, Cmode=101x.
6885 OpCmode = 0xa;
6886 Imm = SplatBits >> 8;
6887 break;
6888 }
6889 return SDValue();
6890
6891 case 32:
6892 // NEON's 32-bit VMOV supports splat values where:
6893 // * only one byte is nonzero, or
6894 // * the least significant byte is 0xff and the second byte is nonzero, or
6895 // * the least significant 2 bytes are 0xff and the third is nonzero.
6896 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6897 if ((SplatBits & ~0xff) == 0) {
6898 // Value = 0x000000nn: Op=x, Cmode=000x.
6899 OpCmode = 0;
6900 Imm = SplatBits;
6901 break;
6902 }
6903 if ((SplatBits & ~0xff00) == 0) {
6904 // Value = 0x0000nn00: Op=x, Cmode=001x.
6905 OpCmode = 0x2;
6906 Imm = SplatBits >> 8;
6907 break;
6908 }
6909 if ((SplatBits & ~0xff0000) == 0) {
6910 // Value = 0x00nn0000: Op=x, Cmode=010x.
6911 OpCmode = 0x4;
6912 Imm = SplatBits >> 16;
6913 break;
6914 }
6915 if ((SplatBits & ~0xff000000) == 0) {
6916 // Value = 0xnn000000: Op=x, Cmode=011x.
6917 OpCmode = 0x6;
6918 Imm = SplatBits >> 24;
6919 break;
6920 }
6921
6922 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6923 if (type == OtherModImm) return SDValue();
6924
6925 if ((SplatBits & ~0xffff) == 0 &&
6926 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6927 // Value = 0x0000nnff: Op=x, Cmode=1100.
6928 OpCmode = 0xc;
6929 Imm = SplatBits >> 8;
6930 break;
6931 }
6932
6933 // cmode == 0b1101 is not supported for MVE VMVN
6934 if (type == MVEVMVNModImm)
6935 return SDValue();
6936
6937 if ((SplatBits & ~0xffffff) == 0 &&
6938 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6939 // Value = 0x00nnffff: Op=x, Cmode=1101.
6940 OpCmode = 0xd;
6941 Imm = SplatBits >> 16;
6942 break;
6943 }
6944
6945 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6946 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6947 // VMOV.I32. A (very) minor optimization would be to replicate the value
6948 // and fall through here to test for a valid 64-bit splat. But, then the
6949 // caller would also need to check and handle the change in size.
6950 return SDValue();
6951
6952 case 64: {
6953 if (type != VMOVModImm)
6954 return SDValue();
6955 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6956 uint64_t BitMask = 0xff;
6957 unsigned ImmMask = 1;
6958 Imm = 0;
6959 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6960 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6961 Imm |= ImmMask;
6962 } else if ((SplatBits & BitMask) != 0) {
6963 return SDValue();
6964 }
6965 BitMask <<= 8;
6966 ImmMask <<= 1;
6967 }
6968
6969 if (DAG.getDataLayout().isBigEndian()) {
6970 // Reverse the order of elements within the vector.
6971 unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8;
6972 unsigned Mask = (1 << BytesPerElem) - 1;
6973 unsigned NumElems = 8 / BytesPerElem;
6974 unsigned NewImm = 0;
6975 for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) {
6976 unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask);
6977 NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem;
6978 }
6979 Imm = NewImm;
6980 }
6981
6982 // Op=1, Cmode=1110.
6983 OpCmode = 0x1e;
6984 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6985 break;
6986 }
6987
6988 default:
6989 llvm_unreachable("unexpected size for isVMOVModifiedImm")::llvm::llvm_unreachable_internal("unexpected size for isVMOVModifiedImm"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6989)
;
6990 }
6991
6992 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6993 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6994}
6995
6996SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6997 const ARMSubtarget *ST) const {
6998 EVT VT = Op.getValueType();
6999 bool IsDouble = (VT == MVT::f64);
7000 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
7001 const APFloat &FPVal = CFP->getValueAPF();
7002
7003 // Prevent floating-point constants from using literal loads
7004 // when execute-only is enabled.
7005 if (ST->genExecuteOnly()) {
7006 // If we can represent the constant as an immediate, don't lower it
7007 if (isFPImmLegal(FPVal, VT))
7008 return Op;
7009 // Otherwise, construct as integer, and move to float register
7010 APInt INTVal = FPVal.bitcastToAPInt();
7011 SDLoc DL(CFP);
7012 switch (VT.getSimpleVT().SimpleTy) {
7013 default:
7014 llvm_unreachable("Unknown floating point type!")::llvm::llvm_unreachable_internal("Unknown floating point type!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 7014)
;
7015 break;
7016 case MVT::f64: {
7017 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
7018 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
7019 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
7020 }
7021 case MVT::f32:
7022 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
7023 DAG.getConstant(INTVal, DL, MVT::i32));
7024 }
7025 }
7026
7027 if (!ST->hasVFP3Base())
7028 return SDValue();
7029
7030 // Use the default (constant pool) lowering for double constants when we have
7031 // an SP-only FPU
7032 if (IsDouble && !Subtarget->hasFP64())
7033 return SDValue();
7034
7035 // Try splatting with a VMOV.f32...
7036 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
7037
7038 if (ImmVal != -1) {
7039 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
7040 // We have code in place to select a valid ConstantFP already, no need to
7041 // do any mangling.
7042 return Op;
7043 }
7044
7045 // It's a float and we are trying to use NEON operations where
7046 // possible. Lower it to a splat followed by an extract.
7047 SDLoc DL(Op);
7048 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
7049 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
7050 NewVal);
7051 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
7052 DAG.getConstant(0, DL, MVT::i32));
7053 }
7054
7055 // The rest of our options are NEON only, make sure that's allowed before
7056 // proceeding..
7057 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
7058 return SDValue();
7059
7060 EVT VMovVT;
7061 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
7062
7063 // It wouldn't really be worth bothering for doubles except for one very
7064 // important value, which does happen to match: 0.0. So make sure we don't do
7065 // anything stupid.
7066 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
7067 return SDValue();
7068
7069 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
7070 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
7071 VMovVT, VT, VMOVModImm);
7072 if (NewVal != SDValue()) {
7073 SDLoc DL(Op);
7074 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
7075 NewVal);
7076 if (IsDouble)
7077 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7078
7079 // It's a float: cast and extract a vector element.
7080 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7081 VecConstant);
7082 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7083 DAG.getConstant(0, DL, MVT::i32));
7084 }
7085
7086 // Finally, try a VMVN.i32
7087 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
7088 VT, VMVNModImm);
7089 if (NewVal != SDValue()) {
7090 SDLoc DL(Op);
7091 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
7092
7093 if (IsDouble)
7094 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7095
7096 // It's a float: cast and extract a vector element.
7097 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7098 VecConstant);
7099 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7100 DAG.getConstant(0, DL, MVT::i32));
7101 }
7102
7103 return SDValue();
7104}
7105
7106// check if an VEXT instruction can handle the shuffle mask when the
7107// vector sources of the shuffle are the same.
7108static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7109 unsigned NumElts = VT.getVectorNumElements();
7110
7111 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7112 if (M[0] < 0)
7113 return false;
7114
7115 Imm = M[0];
7116
7117 // If this is a VEXT shuffle, the immediate value is the index of the first
7118 // element. The other shuffle indices must be the successive elements after
7119 // the first one.
7120 unsigned ExpectedElt = Imm;
7121 for (unsigned i = 1; i < NumElts; ++i) {
7122 // Increment the expected index. If it wraps around, just follow it
7123 // back to index zero and keep going.
7124 ++ExpectedElt;
7125 if (ExpectedElt == NumElts)
7126 ExpectedElt = 0;
7127
7128 if (M[i] < 0) continue; // ignore UNDEF indices
7129 if (ExpectedElt != static_cast<unsigned>(M[i]))
7130 return false;
7131 }
7132
7133 return true;
7134}
7135
7136static bool isVEXTMask(ArrayRef<int> M, EVT VT,
7137 bool &ReverseVEXT, unsigned &Imm) {
7138 unsigned NumElts = VT.getVectorNumElements();
7139 ReverseVEXT = false;
7140
7141 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7142 if (M[0] < 0)
7143 return false;
7144
7145 Imm = M[0];
7146
7147 // If this is a VEXT shuffle, the immediate value is the index of the first
7148 // element. The other shuffle indices must be the successive elements after
7149 // the first one.
7150 unsigned ExpectedElt = Imm;
7151 for (unsigned i = 1; i < NumElts; ++i) {
7152 // Increment the expected index. If it wraps around, it may still be
7153 // a VEXT but the source vectors must be swapped.
7154 ExpectedElt += 1;
7155 if (ExpectedElt == NumElts * 2) {
7156 ExpectedElt = 0;
7157 ReverseVEXT = true;
7158 }
7159
7160 if (M[i] < 0) continue; // ignore UNDEF indices
7161 if (ExpectedElt != static_cast<unsigned>(M[i]))
7162 return false;
7163 }
7164
7165 // Adjust the index value if the source operands will be swapped.
7166 if (ReverseVEXT)
7167 Imm -= NumElts;
7168
7169 return true;
7170}
7171
7172static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
7173 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
7174 // range, then 0 is placed into the resulting vector. So pretty much any mask
7175 // of 8 elements can work here.
7176 return VT == MVT::v8i8 && M.size() == 8;
7177}
7178
7179static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
7180 unsigned Index) {
7181 if (Mask.size() == Elements * 2)
7182 return Index / Elements;
7183 return Mask[Index] == 0 ? 0 : 1;
7184}
7185
7186// Checks whether the shuffle mask represents a vector transpose (VTRN) by
7187// checking that pairs of elements in the shuffle mask represent the same index
7188// in each vector, incrementing the expected index by 2 at each step.
7189// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
7190// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
7191// v2={e,f,g,h}
7192// WhichResult gives the offset for each element in the mask based on which
7193// of the two results it belongs to.
7194//
7195// The transpose can be represented either as:
7196// result1 = shufflevector v1, v2, result1_shuffle_mask
7197// result2 = shufflevector v1, v2, result2_shuffle_mask
7198// where v1/v2 and the shuffle masks have the same number of elements
7199// (here WhichResult (see below) indicates which result is being checked)
7200//
7201// or as:
7202// results = shufflevector v1, v2, shuffle_mask
7203// where both results are returned in one vector and the shuffle mask has twice
7204// as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7205// want to check the low half and high half of the shuffle mask as if it were
7206// the other case
7207static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7208 unsigned EltSz = VT.getScalarSizeInBits();
7209 if (EltSz == 64)
7210 return false;
7211
7212 unsigned NumElts = VT.getVectorNumElements();
7213 if (M.size() != NumElts && M.size() != NumElts*2)
7214 return false;
7215
7216 // If the mask is twice as long as the input vector then we need to check the
7217 // upper and lower parts of the mask with a matching value for WhichResult
7218 // FIXME: A mask with only even values will be rejected in case the first
7219 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7220 // M[0] is used to determine WhichResult
7221 for (unsigned i = 0; i < M.size(); i += NumElts) {
7222 WhichResult = SelectPairHalf(NumElts, M, i);
7223 for (unsigned j = 0; j < NumElts; j += 2) {
7224 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7225 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7226 return false;
7227 }
7228 }
7229
7230 if (M.size() == NumElts*2)
7231 WhichResult = 0;
7232
7233 return true;
7234}
7235
7236/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7237/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7238/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7239static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7240 unsigned EltSz = VT.getScalarSizeInBits();
7241 if (EltSz == 64)
7242 return false;
7243
7244 unsigned NumElts = VT.getVectorNumElements();
7245 if (M.size() != NumElts && M.size() != NumElts*2)
7246 return false;
7247
7248 for (unsigned i = 0; i < M.size(); i += NumElts) {
7249 WhichResult = SelectPairHalf(NumElts, M, i);
7250 for (unsigned j = 0; j < NumElts; j += 2) {
7251 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7252 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7253 return false;
7254 }
7255 }
7256
7257 if (M.size() == NumElts*2)
7258 WhichResult = 0;
7259
7260 return true;
7261}
7262
7263// Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7264// that the mask elements are either all even and in steps of size 2 or all odd
7265// and in steps of size 2.
7266// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7267// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7268// v2={e,f,g,h}
7269// Requires similar checks to that of isVTRNMask with
7270// respect the how results are returned.
7271static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7272 unsigned EltSz = VT.getScalarSizeInBits();
7273 if (EltSz == 64)
7274 return false;
7275
7276 unsigned NumElts = VT.getVectorNumElements();
7277 if (M.size() != NumElts && M.size() != NumElts*2)
7278 return false;
7279
7280 for (unsigned i = 0; i < M.size(); i += NumElts) {
7281 WhichResult = SelectPairHalf(NumElts, M, i);
7282 for (unsigned j = 0; j < NumElts; ++j) {
7283 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7284 return false;
7285 }
7286 }
7287
7288 if (M.size() == NumElts*2)
7289 WhichResult = 0;
7290
7291 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7292 if (VT.is64BitVector() && EltSz == 32)
7293 return false;
7294
7295 return true;
7296}
7297
7298/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7299/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7300/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7301static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7302 unsigned EltSz = VT.getScalarSizeInBits();
7303 if (EltSz == 64)
7304 return false;
7305
7306 unsigned NumElts = VT.getVectorNumElements();
7307 if (M.size() != NumElts && M.size() != NumElts*2)
7308 return false;
7309
7310 unsigned Half = NumElts / 2;
7311 for (unsigned i = 0; i < M.size(); i += NumElts) {
7312 WhichResult = SelectPairHalf(NumElts, M, i);
7313 for (unsigned j = 0; j < NumElts; j += Half) {
7314 unsigned Idx = WhichResult;
7315 for (unsigned k = 0; k < Half; ++k) {
7316 int MIdx = M[i + j + k];
7317 if (MIdx >= 0 && (unsigned) MIdx != Idx)
7318 return false;
7319 Idx += 2;
7320 }
7321 }
7322 }
7323
7324 if (M.size() == NumElts*2)
7325 WhichResult = 0;
7326
7327 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7328 if (VT.is64BitVector() && EltSz == 32)
7329 return false;
7330
7331 return true;
7332}
7333
7334// Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7335// that pairs of elements of the shufflemask represent the same index in each
7336// vector incrementing sequentially through the vectors.
7337// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7338// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7339// v2={e,f,g,h}
7340// Requires similar checks to that of isVTRNMask with respect the how results
7341// are returned.
7342static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7343 unsigned EltSz = VT.getScalarSizeInBits();
7344 if (EltSz == 64)
7345 return false;
7346
7347 unsigned NumElts = VT.getVectorNumElements();
7348 if (M.size() != NumElts && M.size() != NumElts*2)
7349 return false;
7350
7351 for (unsigned i = 0; i < M.size(); i += NumElts) {
7352 WhichResult = SelectPairHalf(NumElts, M, i);
7353 unsigned Idx = WhichResult * NumElts / 2;
7354 for (unsigned j = 0; j < NumElts; j += 2) {
7355 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7356 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7357 return false;
7358 Idx += 1;
7359 }
7360 }
7361
7362 if (M.size() == NumElts*2)
7363 WhichResult = 0;
7364
7365 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7366 if (VT.is64BitVector() && EltSz == 32)
7367 return false;
7368
7369 return true;
7370}
7371
7372/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7373/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7374/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7375static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7376 unsigned EltSz = VT.getScalarSizeInBits();
7377 if (EltSz == 64)
7378 return false;
7379
7380 unsigned NumElts = VT.getVectorNumElements();
7381 if (M.size() != NumElts && M.size() != NumElts*2)
7382 return false;
7383
7384 for (unsigned i = 0; i < M.size(); i += NumElts) {
7385 WhichResult = SelectPairHalf(NumElts, M, i);
7386 unsigned Idx = WhichResult * NumElts / 2;
7387 for (unsigned j = 0; j < NumElts; j += 2) {
7388 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7389 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7390 return false;
7391 Idx += 1;
7392 }
7393 }
7394
7395 if (M.size() == NumElts*2)
7396 WhichResult = 0;
7397
7398 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7399 if (VT.is64BitVector() && EltSz == 32)
7400 return false;
7401
7402 return true;
7403}
7404
7405/// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7406/// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7407static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7408 unsigned &WhichResult,
7409 bool &isV_UNDEF) {
7410 isV_UNDEF = false;
7411 if (isVTRNMask(ShuffleMask, VT, WhichResult))
7412 return ARMISD::VTRN;
7413 if (isVUZPMask(ShuffleMask, VT, WhichResult))
7414 return ARMISD::VUZP;
7415 if (isVZIPMask(ShuffleMask, VT, WhichResult))
7416 return ARMISD::VZIP;
7417
7418 isV_UNDEF = true;
7419 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7420 return ARMISD::VTRN;
7421 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7422 return ARMISD::VUZP;
7423 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7424 return ARMISD::VZIP;
7425
7426 return 0;
7427}
7428
7429/// \return true if this is a reverse operation on an vector.
7430static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7431 unsigned NumElts = VT.getVectorNumElements();
7432 // Make sure the mask has the right size.
7433 if (NumElts != M.size())
7434 return false;
7435
7436 // Look for <15, ..., 3, -1, 1, 0>.
7437 for (unsigned i = 0; i != NumElts; ++i)
7438 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7439 return false;
7440
7441 return true;
7442}
7443
7444static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7445 unsigned NumElts = VT.getVectorNumElements();
7446 // Make sure the mask has the right size.
7447 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7448 return false;
7449
7450 // If Top
7451 // Look for <0, N, 2, N+2, 4, N+4, ..>.
7452 // This inserts Input2 into Input1
7453 // else if not Top
7454 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
7455 // This inserts Input1 into Input2
7456 unsigned Offset = Top ? 0 : 1;
7457 unsigned N = SingleSource ? 0 : NumElts;
7458 for (unsigned i = 0; i < NumElts; i += 2) {
7459 if (M[i] >= 0 && M[i] != (int)i)
7460 return false;
7461 if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset))
7462 return false;
7463 }
7464
7465 return true;
7466}
7467
7468static bool isVMOVNTruncMask(ArrayRef<int> M, EVT ToVT, bool rev) {
7469 unsigned NumElts = ToVT.getVectorNumElements();
7470 if (NumElts != M.size())
7471 return false;
7472
7473 // Test if the Trunc can be convertable to a VMOVN with this shuffle. We are
7474 // looking for patterns of:
7475 // !rev: 0 N/2 1 N/2+1 2 N/2+2 ...
7476 // rev: N/2 0 N/2+1 1 N/2+2 2 ...
7477
7478 unsigned Off0 = rev ? NumElts / 2 : 0;
7479 unsigned Off1 = rev ? 0 : NumElts / 2;
7480 for (unsigned i = 0; i < NumElts; i += 2) {
7481 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
7482 return false;
7483 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
7484 return false;
7485 }
7486
7487 return true;
7488}
7489
7490// Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7491// from a pair of inputs. For example:
7492// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7493// FP_ROUND(EXTRACT_ELT(Y, 0),
7494// FP_ROUND(EXTRACT_ELT(X, 1),
7495// FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7496static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG,
7497 const ARMSubtarget *ST) {
7498 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 7498, __extension__ __PRETTY_FUNCTION__))
;
7499 if (!ST->hasMVEFloatOps())
7500 return SDValue();
7501
7502 SDLoc dl(BV);
7503 EVT VT = BV.getValueType();
7504 if (VT != MVT::v8f16)
7505 return SDValue();
7506
7507 // We are looking for a buildvector of fptrunc elements, where all the
7508 // elements are interleavingly extracted from two sources. Check the first two
7509 // items are valid enough and extract some info from them (they are checked
7510 // properly in the loop below).
7511 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7512 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7513 BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0)
7514 return SDValue();
7515 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7516 BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7517 BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0)
7518 return SDValue();
7519 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7520 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7521 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7522 return SDValue();
7523
7524 // Check all the values in the BuildVector line up with our expectations.
7525 for (unsigned i = 1; i < 4; i++) {
7526 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7527 return Trunc.getOpcode() == ISD::FP_ROUND &&
7528 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7529 Trunc.getOperand(0).getOperand(0) == Op &&
7530 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7531 };
7532 if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7533 return SDValue();
7534 if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7535 return SDValue();
7536 }
7537
7538 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7539 DAG.getConstant(0, dl, MVT::i32));
7540 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7541 DAG.getConstant(1, dl, MVT::i32));
7542}
7543
7544// Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7545// from a single input on alternating lanes. For example:
7546// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7547// FP_ROUND(EXTRACT_ELT(X, 2),
7548// FP_ROUND(EXTRACT_ELT(X, 4), ...)
7549static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG,
7550 const ARMSubtarget *ST) {
7551 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 7551, __extension__ __PRETTY_FUNCTION__))
;
7552 if (!ST->hasMVEFloatOps())
7553 return SDValue();
7554
7555 SDLoc dl(BV);
7556 EVT VT = BV.getValueType();
7557 if (VT != MVT::v4f32)
7558 return SDValue();
7559
7560 // We are looking for a buildvector of fptext elements, where all the
7561 // elements are alternating lanes from a single source. For example <0,2,4,6>
7562 // or <1,3,5,7>. Check the first two items are valid enough and extract some
7563 // info from them (they are checked properly in the loop below).
7564 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7565 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7566 return SDValue();
7567 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7568 int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1);
7569 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7570 return SDValue();
7571
7572 // Check all the values in the BuildVector line up with our expectations.
7573 for (unsigned i = 1; i < 4; i++) {
7574 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7575 return Trunc.getOpcode() == ISD::FP_EXTEND &&
7576 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7577 Trunc.getOperand(0).getOperand(0) == Op &&
7578 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7579 };
7580 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7581 return SDValue();
7582 }
7583
7584 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7585 DAG.getConstant(Offset, dl, MVT::i32));
7586}
7587
7588// If N is an integer constant that can be moved into a register in one
7589// instruction, return an SDValue of such a constant (will become a MOV
7590// instruction). Otherwise return null.
7591static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7592 const ARMSubtarget *ST, const SDLoc &dl) {
7593 uint64_t Val;
7594 if (!isa<ConstantSDNode>(N))
7595 return SDValue();
7596 Val = cast<ConstantSDNode>(N)->getZExtValue();
7597
7598 if (ST->isThumb1Only()) {
7599 if (Val <= 255 || ~Val <= 255)
7600 return DAG.getConstant(Val, dl, MVT::i32);
7601 } else {
7602 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7603 return DAG.getConstant(Val, dl, MVT::i32);
7604 }
7605 return SDValue();
7606}
7607
7608static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7609 const ARMSubtarget *ST) {
7610 SDLoc dl(Op);
7611 EVT VT = Op.getValueType();
7612
7613 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 7613, __extension__ __PRETTY_FUNCTION__))
;
7614
7615 unsigned NumElts = VT.getVectorNumElements();
7616 unsigned BoolMask;
7617 unsigned BitsPerBool;
7618 if (NumElts == 4) {
7619 BitsPerBool = 4;
7620 BoolMask = 0xf;
7621 } else if (NumElts == 8) {
7622 BitsPerBool = 2;
7623 BoolMask = 0x3;
7624 } else if (NumElts == 16) {
7625 BitsPerBool = 1;
7626 BoolMask = 0x1;
7627 } else
7628 return SDValue();
7629
7630 // If this is a single value copied into all lanes (a splat), we can just sign
7631 // extend that single value
7632 SDValue FirstOp = Op.getOperand(0);
7633 if (!isa<ConstantSDNode>(FirstOp) &&
7634 std::all_of(std::next(Op->op_begin()), Op->op_end(),
7635 [&FirstOp](SDUse &U) {
7636 return U.get().isUndef() || U.get() == FirstOp;
7637 })) {
7638 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7639 DAG.getValueType(MVT::i1));
7640 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7641 }
7642
7643 // First create base with bits set where known
7644 unsigned Bits32 = 0;
7645 for (unsigned i = 0; i < NumElts; ++i) {
7646 SDValue V = Op.getOperand(i);
7647 if (!isa<ConstantSDNode>(V) && !V.isUndef())
7648 continue;
7649 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7650 if (BitSet)
7651 Bits32 |= BoolMask << (i * BitsPerBool);
7652 }
7653
7654 // Add in unknown nodes
7655 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7656 DAG.getConstant(Bits32, dl, MVT::i32));
7657 for (unsigned i = 0; i < NumElts; ++i) {
7658 SDValue V = Op.getOperand(i);
7659 if (isa<ConstantSDNode>(V) || V.isUndef())
7660 continue;
7661 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7662 DAG.getConstant(i, dl, MVT::i32));
7663 }
7664
7665 return Base;
7666}
7667
7668static SDValue LowerBUILD_VECTORToVIDUP(SDValue Op, SelectionDAG &DAG,
7669 const ARMSubtarget *ST) {
7670 if (!ST->hasMVEIntegerOps())
7671 return SDValue();
7672
7673 // We are looking for a buildvector where each element is Op[0] + i*N
7674 EVT VT = Op.getValueType();
7675 SDValue Op0 = Op.getOperand(0);
7676 unsigned NumElts = VT.getVectorNumElements();
7677
7678 // Get the increment value from operand 1
7679 SDValue Op1 = Op.getOperand(1);
7680 if (Op1.getOpcode() != ISD::ADD || Op1.getOperand(0) != Op0 ||
7681 !isa<ConstantSDNode>(Op1.getOperand(1)))
7682 return SDValue();
7683 unsigned N = Op1.getConstantOperandVal(1);
7684 if (N != 1 && N != 2 && N != 4 && N != 8)
7685 return SDValue();
7686
7687 // Check that each other operand matches
7688 for (unsigned I = 2; I < NumElts; I++) {
7689 SDValue OpI = Op.getOperand(I);
7690 if (OpI.getOpcode() != ISD::ADD || OpI.getOperand(0) != Op0 ||
7691 !isa<ConstantSDNode>(OpI.getOperand(1)) ||
7692 OpI.getConstantOperandVal(1) != I * N)
7693 return SDValue();
7694 }
7695
7696 SDLoc DL(Op);
7697 return DAG.getNode(ARMISD::VIDUP, DL, DAG.getVTList(VT, MVT::i32), Op0,
7698 DAG.getConstant(N, DL, MVT::i32));
7699}
7700
7701// If this is a case we can't handle, return null and let the default
7702// expansion code take care of it.
7703SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7704 const ARMSubtarget *ST) const {
7705 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7706 SDLoc dl(Op);
7707 EVT VT = Op.getValueType();
7708
7709 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7710 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7711
7712 if (SDValue R = LowerBUILD_VECTORToVIDUP(Op, DAG, ST))
7713 return R;
7714
7715 APInt SplatBits, SplatUndef;
7716 unsigned SplatBitSize;
7717 bool HasAnyUndefs;
7718 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7719 if (SplatUndef.isAllOnes())
7720 return DAG.getUNDEF(VT);
7721
7722 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7723 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7724 // Check if an immediate VMOV works.
7725 EVT VmovVT;
7726 SDValue Val =
7727 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7728 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7729
7730 if (Val.getNode()) {
7731 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7732 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7733 }
7734
7735 // Try an immediate VMVN.
7736 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7737 Val = isVMOVModifiedImm(
7738 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7739 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7740 if (Val.getNode()) {
7741 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7742 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7743 }
7744
7745 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7746 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7747 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7748 if (ImmVal != -1) {
7749 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7750 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7751 }
7752 }
7753
7754 // If we are under MVE, generate a VDUP(constant), bitcast to the original
7755 // type.
7756 if (ST->hasMVEIntegerOps() &&
7757 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32)) {
7758 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7759 : SplatBitSize == 16 ? MVT::v8i16
7760 : MVT::v16i8;
7761 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7762 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7763 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7764 }
7765 }
7766 }
7767
7768 // Scan through the operands to see if only one value is used.
7769 //
7770 // As an optimisation, even if more than one value is used it may be more
7771 // profitable to splat with one value then change some lanes.
7772 //
7773 // Heuristically we decide to do this if the vector has a "dominant" value,
7774 // defined as splatted to more than half of the lanes.
7775 unsigned NumElts = VT.getVectorNumElements();
7776 bool isOnlyLowElement = true;
7777 bool usesOnlyOneValue = true;
7778 bool hasDominantValue = false;
7779 bool isConstant = true;
7780
7781 // Map of the number of times a particular SDValue appears in the
7782 // element list.
7783 DenseMap<SDValue, unsigned> ValueCounts;
7784 SDValue Value;
7785 for (unsigned i = 0; i < NumElts; ++i) {
7786 SDValue V = Op.getOperand(i);
7787 if (V.isUndef())
7788 continue;
7789 if (i > 0)
7790 isOnlyLowElement = false;
7791 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7792 isConstant = false;
7793
7794 ValueCounts.insert(std::make_pair(V, 0));
7795 unsigned &Count = ValueCounts[V];
7796
7797 // Is this value dominant? (takes up more than half of the lanes)
7798 if (++Count > (NumElts / 2)) {
7799 hasDominantValue = true;
7800 Value = V;
7801 }
7802 }
7803 if (ValueCounts.size() != 1)
7804 usesOnlyOneValue = false;
7805 if (!Value.getNode() && !ValueCounts.empty())
7806 Value = ValueCounts.begin()->first;
7807
7808 if (ValueCounts.empty())
7809 return DAG.getUNDEF(VT);
7810
7811 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7812 // Keep going if we are hitting this case.
7813 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7814 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7815
7816 unsigned EltSize = VT.getScalarSizeInBits();
7817
7818 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7819 // i32 and try again.
7820 if (hasDominantValue && EltSize <= 32) {
7821 if (!isConstant) {
7822 SDValue N;
7823
7824 // If we are VDUPing a value that comes directly from a vector, that will
7825 // cause an unnecessary move to and from a GPR, where instead we could
7826 // just use VDUPLANE. We can only do this if the lane being extracted
7827 // is at a constant index, as the VDUP from lane instructions only have
7828 // constant-index forms.
7829 ConstantSDNode *constIndex;
7830 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7831 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7832 // We need to create a new undef vector to use for the VDUPLANE if the
7833 // size of the vector from which we get the value is different than the
7834 // size of the vector that we need to create. We will insert the element
7835 // such that the register coalescer will remove unnecessary copies.
7836 if (VT != Value->getOperand(0).getValueType()) {
7837 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7838 VT.getVectorNumElements();
7839 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7840 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7841 Value, DAG.getConstant(index, dl, MVT::i32)),
7842 DAG.getConstant(index, dl, MVT::i32));
7843 } else
7844 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7845 Value->getOperand(0), Value->getOperand(1));
7846 } else
7847 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7848
7849 if (!usesOnlyOneValue) {
7850 // The dominant value was splatted as 'N', but we now have to insert
7851 // all differing elements.
7852 for (unsigned I = 0; I < NumElts; ++I) {
7853 if (Op.getOperand(I) == Value)
7854 continue;
7855 SmallVector<SDValue, 3> Ops;
7856 Ops.push_back(N);
7857 Ops.push_back(Op.getOperand(I));
7858 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7859 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7860 }
7861 }
7862 return N;
7863 }
7864 if (VT.getVectorElementType().isFloatingPoint()) {
7865 SmallVector<SDValue, 8> Ops;
7866 MVT FVT = VT.getVectorElementType().getSimpleVT();
7867 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"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 7867, __extension__ __PRETTY_FUNCTION__))
;
7868 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7869 for (unsigned i = 0; i < NumElts; ++i)
7870 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7871 Op.getOperand(i)));
7872 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7873 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7874 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7875 if (Val.getNode())
7876 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7877 }
7878 if (usesOnlyOneValue) {
7879 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7880 if (isConstant && Val.getNode())
7881 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7882 }
7883 }
7884
7885 // If all elements are constants and the case above didn't get hit, fall back
7886 // to the default expansion, which will generate a load from the constant
7887 // pool.
7888 if (isConstant)
7889 return SDValue();
7890
7891 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7892 // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7893 // length <= 2.
7894 if (NumElts >= 4)
7895 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7896 return shuffle;
7897
7898 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7899 // VCVT's
7900 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
7901 return VCVT;
7902 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
7903 return VCVT;
7904
7905 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7906 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7907 // into two 64-bit vectors; we might discover a better way to lower it.
7908 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7909 EVT ExtVT = VT.getVectorElementType();
7910 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7911 SDValue Lower =
7912 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7913 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7914 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7915 SDValue Upper = DAG.getBuildVector(
7916 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7917 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7918 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7919 if (Lower && Upper)
7920 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7921 }
7922
7923 // Vectors with 32- or 64-bit elements can be built by directly assigning
7924 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7925 // will be legalized.
7926 if (EltSize >= 32) {
7927 // Do the expansion with floating-point types, since that is what the VFP
7928 // registers are defined to use, and since i64 is not legal.
7929 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7930 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7931 SmallVector<SDValue, 8> Ops;
7932 for (unsigned i = 0; i < NumElts; ++i)
7933 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7934 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7935 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7936 }
7937
7938 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7939 // know the default expansion would otherwise fall back on something even
7940 // worse. For a vector with one or two non-undef values, that's
7941 // scalar_to_vector for the elements followed by a shuffle (provided the
7942 // shuffle is valid for the target) and materialization element by element
7943 // on the stack followed by a load for everything else.
7944 if (!isConstant && !usesOnlyOneValue) {
7945 SDValue Vec = DAG.getUNDEF(VT);
7946 for (unsigned i = 0 ; i < NumElts; ++i) {
7947 SDValue V = Op.getOperand(i);
7948 if (V.isUndef())
7949 continue;
7950 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7951 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7952 }
7953 return Vec;
7954 }
7955
7956 return SDValue();
7957}
7958
7959// Gather data to see if the operation can be modelled as a
7960// shuffle in combination with VEXTs.
7961SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7962 SelectionDAG &DAG) const {
7963 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 7963, __extension__ __PRETTY_FUNCTION__))
;
7964 SDLoc dl(Op);
7965 EVT VT = Op.getValueType();
7966 unsigned NumElts = VT.getVectorNumElements();
7967
7968 struct ShuffleSourceInfo {
7969 SDValue Vec;
7970 unsigned MinElt = std::numeric_limits<unsigned>::max();
7971 unsigned MaxElt = 0;
7972
7973 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7974 // be compatible with the shuffle we intend to construct. As a result
7975 // ShuffleVec will be some sliding window into the original Vec.
7976 SDValue ShuffleVec;
7977
7978 // Code should guarantee that element i in Vec starts at element "WindowBase
7979 // + i * WindowScale in ShuffleVec".
7980 int WindowBase = 0;
7981 int WindowScale = 1;
7982
7983 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7984
7985 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7986 };
7987
7988 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7989 // node.
7990 SmallVector<ShuffleSourceInfo, 2> Sources;
7991 for (unsigned i = 0; i < NumElts; ++i) {
7992 SDValue V = Op.getOperand(i);
7993 if (V.isUndef())
7994 continue;
7995 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7996 // A shuffle can only come from building a vector from various
7997 // elements of other vectors.
7998 return SDValue();
7999 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
8000 // Furthermore, shuffles require a constant mask, whereas extractelts
8001 // accept variable indices.
8002 return SDValue();
8003 }
8004
8005 // Add this element source to the list if it's not already there.
8006 SDValue SourceVec = V.getOperand(0);
8007 auto Source = llvm::find(Sources, SourceVec);
8008 if (Source == Sources.end())
8009 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
8010
8011 // Update the minimum and maximum lane number seen.
8012 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
8013 Source->MinElt = std::min(Source->MinElt, EltNo);
8014 Source->MaxElt = std::max(Source->MaxElt, EltNo);
8015 }
8016
8017 // Currently only do something sane when at most two source vectors
8018 // are involved.
8019 if (Sources.size() > 2)
8020 return SDValue();
8021
8022 // Find out the smallest element size among result and two sources, and use
8023 // it as element size to build the shuffle_vector.
8024 EVT SmallestEltTy = VT.getVectorElementType();
8025 for (auto &Source : Sources) {
8026 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
8027 if (SrcEltTy.bitsLT(SmallestEltTy))
8028 SmallestEltTy = SrcEltTy;
8029 }
8030 unsigned ResMultiplier =
8031 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
8032 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
8033 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
8034
8035 // If the source vector is too wide or too narrow, we may nevertheless be able
8036 // to construct a compatible shuffle either by concatenating it with UNDEF or
8037 // extracting a suitable range of elements.
8038 for (auto &Src : Sources) {
8039 EVT SrcVT = Src.ShuffleVec.getValueType();
8040
8041 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
8042 uint64_t VTSize = VT.getFixedSizeInBits();
8043 if (SrcVTSize == VTSize)
8044 continue;
8045
8046 // This stage of the search produces a source with the same element type as
8047 // the original, but with a total width matching the BUILD_VECTOR output.
8048 EVT EltVT = SrcVT.getVectorElementType();
8049 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
8050 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
8051
8052 if (SrcVTSize < VTSize) {
8053 if (2 * SrcVTSize != VTSize)
8054 return SDValue();
8055 // We can pad out the smaller vector for free, so if it's part of a
8056 // shuffle...
8057 Src.ShuffleVec =
8058 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
8059 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
8060 continue;
8061 }
8062
8063 if (SrcVTSize != 2 * VTSize)
8064 return SDValue();
8065
8066 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
8067 // Span too large for a VEXT to cope
8068 return SDValue();
8069 }
8070
8071 if (Src.MinElt >= NumSrcElts) {
8072 // The extraction can just take the second half
8073 Src.ShuffleVec =
8074 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8075 DAG.getConstant(NumSrcElts, dl, MVT::i32));
8076 Src.WindowBase = -NumSrcElts;
8077 } else if (Src.MaxElt < NumSrcElts) {
8078 // The extraction can just take the first half
8079 Src.ShuffleVec =
8080 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8081 DAG.getConstant(0, dl, MVT::i32));
8082 } else {
8083 // An actual VEXT is needed
8084 SDValue VEXTSrc1 =
8085 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8086 DAG.getConstant(0, dl, MVT::i32));
8087 SDValue VEXTSrc2 =
8088 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8089 DAG.getConstant(NumSrcElts, dl, MVT::i32));
8090
8091 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
8092 VEXTSrc2,
8093 DAG.getConstant(Src.MinElt, dl, MVT::i32));
8094 Src.WindowBase = -Src.MinElt;
8095 }
8096 }
8097
8098 // Another possible incompatibility occurs from the vector element types. We
8099 // can fix this by bitcasting the source vectors to the same type we intend
8100 // for the shuffle.
8101 for (auto &Src : Sources) {
8102 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8103 if (SrcEltTy == SmallestEltTy)
8104 continue;
8105 assert(ShuffleVT.getVectorElementType() == SmallestEltTy)(static_cast <bool> (ShuffleVT.getVectorElementType() ==
SmallestEltTy) ? void (0) : __assert_fail ("ShuffleVT.getVectorElementType() == SmallestEltTy"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8105, __extension__ __PRETTY_FUNCTION__))
;
8106 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
8107 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
8108 Src.WindowBase *= Src.WindowScale;
8109 }
8110
8111 // Final sanity check before we try to actually produce a shuffle.
8112 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",
"/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8114, __extension__ __PRETTY_FUNCTION__));; } } while (false
)
8113 : 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",
"/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8114, __extension__ __PRETTY_FUNCTION__));; } } while (false
)
8114 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",
"/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8114, __extension__ __PRETTY_FUNCTION__));; } } while (false
)
;
8115
8116 // The stars all align, our next step is to produce the mask for the shuffle.
8117 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8118 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8119 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8120 SDValue Entry = Op.getOperand(i);
8121 if (Entry.isUndef())
8122 continue;
8123
8124 auto Src = llvm::find(Sources, Entry.getOperand(0));
8125 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
8126
8127 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8128 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8129 // segment.
8130 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
8131 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
8132 VT.getScalarSizeInBits());
8133 int LanesDefined = BitsDefined / BitsPerShuffleLane;
8134
8135 // This source is expected to fill ResMultiplier lanes of the final shuffle,
8136 // starting at the appropriate offset.
8137 int *LaneMask = &Mask[i * ResMultiplier];
8138
8139 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8140 ExtractBase += NumElts * (Src - Sources.begin());
8141 for (int j = 0; j < LanesDefined; ++j)
8142 LaneMask[j] = ExtractBase + j;
8143 }
8144
8145
8146 // We can't handle more than two sources. This should have already
8147 // been checked before this point.
8148 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8148, __extension__ __PRETTY_FUNCTION__))
;
8149
8150 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
8151 for (unsigned i = 0; i < Sources.size(); ++i)
8152 ShuffleOps[i] = Sources[i].ShuffleVec;
8153
8154 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
8155 ShuffleOps[1], Mask, DAG);
8156 if (!Shuffle)
8157 return SDValue();
8158 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
8159}
8160
8161enum ShuffleOpCodes {
8162 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8163 OP_VREV,
8164 OP_VDUP0,
8165 OP_VDUP1,
8166 OP_VDUP2,
8167 OP_VDUP3,
8168 OP_VEXT1,
8169 OP_VEXT2,
8170 OP_VEXT3,
8171 OP_VUZPL, // VUZP, left result
8172 OP_VUZPR, // VUZP, right result
8173 OP_VZIPL, // VZIP, left result
8174 OP_VZIPR, // VZIP, right result
8175 OP_VTRNL, // VTRN, left result
8176 OP_VTRNR // VTRN, right result
8177};
8178
8179static bool isLegalMVEShuffleOp(unsigned PFEntry) {
8180 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8181 switch (OpNum) {
8182 case OP_COPY:
8183 case OP_VREV:
8184 case OP_VDUP0:
8185 case OP_VDUP1:
8186 case OP_VDUP2:
8187 case OP_VDUP3:
8188 return true;
8189 }
8190 return false;
8191}
8192
8193/// isShuffleMaskLegal - Targets can use this to indicate that they only
8194/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8195/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8196/// are assumed to be legal.
8197bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8198 if (VT.getVectorNumElements() == 4 &&
8199 (VT.is128BitVector() || VT.is64BitVector())) {
8200 unsigned PFIndexes[4];
8201 for (unsigned i = 0; i != 4; ++i) {
8202 if (M[i] < 0)
8203 PFIndexes[i] = 8;
8204 else
8205 PFIndexes[i] = M[i];
8206 }
8207
8208 // Compute the index in the perfect shuffle table.
8209 unsigned PFTableIndex =
8210 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8211 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8212 unsigned Cost = (PFEntry >> 30);
8213
8214 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
8215 return true;
8216 }
8217
8218 bool ReverseVEXT, isV_UNDEF;
8219 unsigned Imm, WhichResult;
8220
8221 unsigned EltSize = VT.getScalarSizeInBits();
8222 if (EltSize >= 32 ||
8223 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8224 ShuffleVectorInst::isIdentityMask(M) ||
8225 isVREVMask(M, VT, 64) ||
8226 isVREVMask(M, VT, 32) ||
8227 isVREVMask(M, VT, 16))
8228 return true;
8229 else if (Subtarget->hasNEON() &&
8230 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
8231 isVTBLMask(M, VT) ||
8232 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
8233 return true;
8234 else if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8235 isReverseMask(M, VT))
8236 return true;
8237 else if (Subtarget->hasMVEIntegerOps() &&
8238 (isVMOVNMask(M, VT, true, false) ||
8239 isVMOVNMask(M, VT, false, false) || isVMOVNMask(M, VT, true, true)))
8240 return true;
8241 else
8242 return false;
8243}
8244
8245/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8246/// the specified operations to build the shuffle.
8247static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8248 SDValue RHS, SelectionDAG &DAG,
8249 const SDLoc &dl) {
8250 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8251 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8252 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8253
8254 if (OpNum == OP_COPY) {
8255 if (LHSID == (1*9+2)*9+3) return LHS;
8256 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8256, __extension__ __PRETTY_FUNCTION__))
;
8257 return RHS;
8258 }
8259
8260 SDValue OpLHS, OpRHS;
8261 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8262 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8263 EVT VT = OpLHS.getValueType();
8264
8265 switch (OpNum) {
8266 default: llvm_unreachable("Unknown shuffle opcode!")::llvm::llvm_unreachable_internal("Unknown shuffle opcode!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8266)
;
8267 case OP_VREV:
8268 // VREV divides the vector in half and swaps within the half.
8269 if (VT.getVectorElementType() == MVT::i32 ||
8270 VT.getVectorElementType() == MVT::f32)
8271 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
8272 // vrev <4 x i16> -> VREV32
8273 if (VT.getVectorElementType() == MVT::i16 ||
8274 VT.getVectorElementType() == MVT::f16)
8275 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
8276 // vrev <4 x i8> -> VREV16
8277 assert(VT.getVectorElementType() == MVT::i8)(static_cast <bool> (VT.getVectorElementType() == MVT::
i8) ? void (0) : __assert_fail ("VT.getVectorElementType() == MVT::i8"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8277, __extension__ __PRETTY_FUNCTION__))
;
8278 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
8279 case OP_VDUP0:
8280 case OP_VDUP1:
8281 case OP_VDUP2:
8282 case OP_VDUP3:
8283 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8284 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8285 case OP_VEXT1:
8286 case OP_VEXT2:
8287 case OP_VEXT3:
8288 return DAG.getNode(ARMISD::VEXT, dl, VT,
8289 OpLHS, OpRHS,
8290 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8291 case OP_VUZPL:
8292 case OP_VUZPR:
8293 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8294 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8295 case OP_VZIPL:
8296 case OP_VZIPR:
8297 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8298 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8299 case OP_VTRNL:
8300 case OP_VTRNR:
8301 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8302 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8303 }
8304}
8305
8306static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
8307 ArrayRef<int> ShuffleMask,
8308 SelectionDAG &DAG) {
8309 // Check to see if we can use the VTBL instruction.
8310 SDValue V1 = Op.getOperand(0);
8311 SDValue V2 = Op.getOperand(1);
8312 SDLoc DL(Op);
8313
8314 SmallVector<SDValue, 8> VTBLMask;
8315 for (ArrayRef<int>::iterator
8316 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
8317 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
8318
8319 if (V2.getNode()->isUndef())
8320 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8321 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8322
8323 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8324 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8325}
8326
8327static SDValue LowerReverse_VECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
8328 SDLoc DL(Op);
8329 EVT VT = Op.getValueType();
8330
8331 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8332, __extension__ __PRETTY_FUNCTION__))
8332 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8332, __extension__ __PRETTY_FUNCTION__))
;
8333 SDValue OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, Op.getOperand(0));
8334 // For a v16i8 type: After the VREV, we have got <7, ..., 0, 15, ..., 8>. Now,
8335 // extract the first 8 bytes into the top double word and the last 8 bytes
8336 // into the bottom double word, through a new vector shuffle that will be
8337 // turned into a VEXT on Neon, or a couple of VMOVDs on MVE.
8338 std::vector<int> NewMask;
8339 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8340 NewMask.push_back(VT.getVectorNumElements() / 2 + i);
8341 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8342 NewMask.push_back(i);
8343 return DAG.getVectorShuffle(VT, DL, OpLHS, OpLHS, NewMask);
8344}
8345
8346static EVT getVectorTyFromPredicateVector(EVT VT) {
8347 switch (VT.getSimpleVT().SimpleTy) {
8348 case MVT::v4i1:
8349 return MVT::v4i32;
8350 case MVT::v8i1:
8351 return MVT::v8i16;
8352 case MVT::v16i1:
8353 return MVT::v16i8;
8354 default:
8355 llvm_unreachable("Unexpected vector predicate type")::llvm::llvm_unreachable_internal("Unexpected vector predicate type"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8355)
;
8356 }
8357}
8358
8359static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
8360 SelectionDAG &DAG) {
8361 // Converting from boolean predicates to integers involves creating a vector
8362 // of all ones or all zeroes and selecting the lanes based upon the real
8363 // predicate.
8364 SDValue AllOnes =
8365 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8366 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8367
8368 SDValue AllZeroes =
8369 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8370 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8371
8372 // Get full vector type from predicate type
8373 EVT NewVT = getVectorTyFromPredicateVector(VT);
8374
8375 SDValue RecastV1;
8376 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8377 // this to a v16i1. This cannot be done with an ordinary bitcast because the
8378 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8379 // since we know in hardware the sizes are really the same.
8380 if (VT != MVT::v16i1)
8381 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8382 else
8383 RecastV1 = Pred;
8384
8385 // Select either all ones or zeroes depending upon the real predicate bits.
8386 SDValue PredAsVector =
8387 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8388
8389 // Recast our new predicate-as-integer v16i8 vector into something
8390 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8391 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8392}
8393
8394static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
8395 const ARMSubtarget *ST) {
8396 EVT VT = Op.getValueType();
8397 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8398 ArrayRef<int> ShuffleMask = SVN->getMask();
8399
8400 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8401, __extension__ __PRETTY_FUNCTION__))
8401 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8401, __extension__ __PRETTY_FUNCTION__))
;
8402
8403 SDValue V1 = Op.getOperand(0);
8404 SDLoc dl(Op);
8405 if (isReverseMask(ShuffleMask, VT)) {
8406 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8407 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8408 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8409 DAG.getConstant(16, dl, MVT::i32));
8410 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8411 }
8412
8413 // Until we can come up with optimised cases for every single vector
8414 // shuffle in existence we have chosen the least painful strategy. This is
8415 // to essentially promote the boolean predicate to a 8-bit integer, where
8416 // each predicate represents a byte. Then we fall back on a normal integer
8417 // vector shuffle and convert the result back into a predicate vector. In
8418 // many cases the generated code might be even better than scalar code
8419 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8420 // fields in a register into 8 other arbitrary 2-bit fields!
8421 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
8422 EVT NewVT = PredAsVector.getValueType();
8423
8424 // Do the shuffle!
8425 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
8426 DAG.getUNDEF(NewVT), ShuffleMask);
8427
8428 // Now return the result of comparing the shuffled vector with zero,
8429 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8430 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8431 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8432}
8433
8434static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
8435 ArrayRef<int> ShuffleMask,
8436 SelectionDAG &DAG) {
8437 // Attempt to lower the vector shuffle using as many whole register movs as
8438 // possible. This is useful for types smaller than 32bits, which would
8439 // often otherwise become a series for grp movs.
8440 SDLoc dl(Op);
8441 EVT VT = Op.getValueType();
8442 if (VT.getScalarSizeInBits() >= 32)
8443 return SDValue();
8444
8445 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8446, __extension__ __PRETTY_FUNCTION__))
8446 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8446, __extension__ __PRETTY_FUNCTION__))
;
8447 int NumElts = VT.getVectorNumElements();
8448 int QuarterSize = NumElts / 4;
8449 // The four final parts of the vector, as i32's
8450 SDValue Parts[4];
8451
8452 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8453 // <u,u,u,u>), returning the vmov lane index
8454 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8455 // Detect which mov lane this would be from the first non-undef element.
8456 int MovIdx = -1;
8457 for (int i = 0; i < Length; i++) {
8458 if (ShuffleMask[Start + i] >= 0) {
8459 if (ShuffleMask[Start + i] % Length != i)
8460 return -1;
8461 MovIdx = ShuffleMask[Start + i] / Length;
8462 break;
8463 }
8464 }
8465 // If all items are undef, leave this for other combines
8466 if (MovIdx == -1)
8467 return -1;
8468 // Check the remaining values are the correct part of the same mov
8469 for (int i = 1; i < Length; i++) {
8470 if (ShuffleMask[Start + i] >= 0 &&
8471 (ShuffleMask[Start + i] / Length != MovIdx ||
8472 ShuffleMask[Start + i] % Length != i))
8473 return -1;
8474 }
8475 return MovIdx;
8476 };
8477
8478 for (int Part = 0; Part < 4; ++Part) {
8479 // Does this part look like a mov
8480 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8481 if (Elt != -1) {
8482 SDValue Input = Op->getOperand(0);
8483 if (Elt >= 4) {
8484 Input = Op->getOperand(1);
8485 Elt -= 4;
8486 }
8487 SDValue BitCast = DAG.getBitcast(MVT::v4f32, Input);
8488 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, BitCast,
8489 DAG.getConstant(Elt, dl, MVT::i32));
8490 }
8491 }
8492
8493 // Nothing interesting found, just return
8494 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8495 return SDValue();
8496
8497 // The other parts need to be built with the old shuffle vector, cast to a
8498 // v4i32 and extract_vector_elts
8499 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8500 SmallVector<int, 16> NewShuffleMask;
8501 for (int Part = 0; Part < 4; ++Part)
8502 for (int i = 0; i < QuarterSize; i++)
8503 NewShuffleMask.push_back(
8504 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8505 SDValue NewShuffle = DAG.getVectorShuffle(
8506 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8507 SDValue BitCast = DAG.getBitcast(MVT::v4f32, NewShuffle);
8508
8509 for (int Part = 0; Part < 4; ++Part)
8510 if (!Parts[Part])
8511 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32,
8512 BitCast, DAG.getConstant(Part, dl, MVT::i32));
8513 }
8514 // Build a vector out of the various parts and bitcast it back to the original
8515 // type.
8516 SDValue NewVec = DAG.getNode(ARMISD::BUILD_VECTOR, dl, MVT::v4f32, Parts);
8517 return DAG.getBitcast(VT, NewVec);
8518}
8519
8520static SDValue LowerVECTOR_SHUFFLEUsingOneOff(SDValue Op,
8521 ArrayRef<int> ShuffleMask,
8522 SelectionDAG &DAG) {
8523 SDValue V1 = Op.getOperand(0);
8524 SDValue V2 = Op.getOperand(1);
8525 EVT VT = Op.getValueType();
8526 unsigned NumElts = VT.getVectorNumElements();
8527
8528 // An One-Off Identity mask is one that is mostly an identity mask from as
8529 // single source but contains a single element out-of-place, either from a
8530 // different vector or from another position in the same vector. As opposed to
8531 // lowering this via a ARMISD::BUILD_VECTOR we can generate an extract/insert
8532 // pair directly.
8533 auto isOneOffIdentityMask = [](ArrayRef<int> Mask, EVT VT, int BaseOffset,
8534 int &OffElement) {
8535 OffElement = -1;
8536 int NonUndef = 0;
8537 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
8538 if (Mask[i] == -1)
8539 continue;
8540 NonUndef++;
8541 if (Mask[i] != i + BaseOffset) {
8542 if (OffElement == -1)
8543 OffElement = i;
8544 else
8545 return false;
8546 }
8547 }
8548 return NonUndef > 2 && OffElement != -1;
8549 };
8550 int OffElement;
8551 SDValue VInput;
8552 if (isOneOffIdentityMask(ShuffleMask, VT, 0, OffElement))
8553 VInput = V1;
8554 else if (isOneOffIdentityMask(ShuffleMask, VT, NumElts, OffElement))
8555 VInput = V2;
8556 else
8557 return SDValue();
8558
8559 SDLoc dl(Op);
8560 EVT SVT = VT.getScalarType() == MVT::i8 || VT.getScalarType() == MVT::i16
8561 ? MVT::i32
8562 : VT.getScalarType();
8563 SDValue Elt = DAG.getNode(
8564 ISD::EXTRACT_VECTOR_ELT, dl, SVT,
8565 ShuffleMask[OffElement] < (int)NumElts ? V1 : V2,
8566 DAG.getVectorIdxConstant(ShuffleMask[OffElement] % NumElts, dl));
8567 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, VInput, Elt,
8568 DAG.getVectorIdxConstant(OffElement % NumElts, dl));
8569}
8570
8571static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
8572 const ARMSubtarget *ST) {
8573 SDValue V1 = Op.getOperand(0);
8574 SDValue V2 = Op.getOperand(1);
8575 SDLoc dl(Op);
8576 EVT VT = Op.getValueType();
8577 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8578 unsigned EltSize = VT.getScalarSizeInBits();
8579
8580 if (ST->hasMVEIntegerOps() && EltSize == 1)
8581 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8582
8583 // Convert shuffles that are directly supported on NEON to target-specific
8584 // DAG nodes, instead of keeping them as shuffles and matching them again
8585 // during code selection. This is more efficient and avoids the possibility
8586 // of inconsistencies between legalization and selection.
8587 // FIXME: floating-point vectors should be canonicalized to integer vectors
8588 // of the same time so that they get CSEd properly.
8589 ArrayRef<int> ShuffleMask = SVN->getMask();
8590
8591 if (EltSize <= 32) {
8592 if (SVN->isSplat()) {
8593 int Lane = SVN->getSplatIndex();
8594 // If this is undef splat, generate it via "just" vdup, if possible.
8595 if (Lane == -1) Lane = 0;
8596
8597 // Test if V1 is a SCALAR_TO_VECTOR.
8598 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8599 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8600 }
8601 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8602 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8603 // reaches it).
8604 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8605 !isa<ConstantSDNode>(V1.getOperand(0))) {
8606 bool IsScalarToVector = true;
8607 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8608 if (!V1.getOperand(i).isUndef()) {
8609 IsScalarToVector = false;
8610 break;
8611 }
8612 if (IsScalarToVector)
8613 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8614 }
8615 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8616 DAG.getConstant(Lane, dl, MVT::i32));
8617 }
8618
8619 bool ReverseVEXT = false;
8620 unsigned Imm = 0;
8621 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8622 if (ReverseVEXT)
8623 std::swap(V1, V2);
8624 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8625 DAG.getConstant(Imm, dl, MVT::i32));
8626 }
8627
8628 if (isVREVMask(ShuffleMask, VT, 64))
8629 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8630 if (isVREVMask(ShuffleMask, VT, 32))
8631 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8632 if (isVREVMask(ShuffleMask, VT, 16))
8633 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8634
8635 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8636 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8637 DAG.getConstant(Imm, dl, MVT::i32));
8638 }
8639
8640 // Check for Neon shuffles that modify both input vectors in place.
8641 // If both results are used, i.e., if there are two shuffles with the same
8642 // source operands and with masks corresponding to both results of one of
8643 // these operations, DAG memoization will ensure that a single node is
8644 // used for both shuffles.
8645 unsigned WhichResult = 0;
8646 bool isV_UNDEF = false;
8647 if (ST->hasNEON()) {
8648 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8649 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8650 if (isV_UNDEF)
8651 V2 = V1;
8652 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8653 .getValue(WhichResult);
8654 }
8655 }
8656 if (ST->hasMVEIntegerOps()) {
8657 if (isVMOVNMask(ShuffleMask, VT, false, false))
8658 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8659 DAG.getConstant(0, dl, MVT::i32));
8660 if (isVMOVNMask(ShuffleMask, VT, true, false))
8661 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8662 DAG.getConstant(1, dl, MVT::i32));
8663 if (isVMOVNMask(ShuffleMask, VT, true, true))
8664 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V1,
8665 DAG.getConstant(1, dl, MVT::i32));
8666 }
8667
8668 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8669 // shuffles that produce a result larger than their operands with:
8670 // shuffle(concat(v1, undef), concat(v2, undef))
8671 // ->
8672 // shuffle(concat(v1, v2), undef)
8673 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8674 //
8675 // This is useful in the general case, but there are special cases where
8676 // native shuffles produce larger results: the two-result ops.
8677 //
8678 // Look through the concat when lowering them:
8679 // shuffle(concat(v1, v2), undef)
8680 // ->
8681 // concat(VZIP(v1, v2):0, :1)
8682 //
8683 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8684 SDValue SubV1 = V1->getOperand(0);
8685 SDValue SubV2 = V1->getOperand(1);
8686 EVT SubVT = SubV1.getValueType();
8687
8688 // We expect these to have been canonicalized to -1.
8689 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8691, __extension__ __PRETTY_FUNCTION__))
8690 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8691, __extension__ __PRETTY_FUNCTION__))
8691 }) && "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8691, __extension__ __PRETTY_FUNCTION__))
;
8692
8693 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8694 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8695 if (isV_UNDEF)
8696 SubV2 = SubV1;
8697 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8698, __extension__ __PRETTY_FUNCTION__))
8698 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8698, __extension__ __PRETTY_FUNCTION__))
;
8699 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8700 SubV1, SubV2);
8701 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8702 Res.getValue(1));
8703 }
8704 }
8705 }
8706
8707 if (ST->hasMVEIntegerOps() && EltSize <= 32)
8708 if (SDValue V = LowerVECTOR_SHUFFLEUsingOneOff(Op, ShuffleMask, DAG))
8709 return V;
8710
8711 // If the shuffle is not directly supported and it has 4 elements, use
8712 // the PerfectShuffle-generated table to synthesize it from other shuffles.
8713 unsigned NumElts = VT.getVectorNumElements();
8714 if (NumElts == 4) {
8715 unsigned PFIndexes[4];
8716 for (unsigned i = 0; i != 4; ++i) {
8717 if (ShuffleMask[i] < 0)
8718 PFIndexes[i] = 8;
8719 else
8720 PFIndexes[i] = ShuffleMask[i];
8721 }
8722
8723 // Compute the index in the perfect shuffle table.
8724 unsigned PFTableIndex =
8725 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8726 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8727 unsigned Cost = (PFEntry >> 30);
8728
8729 if (Cost <= 4) {
8730 if (ST->hasNEON())
8731 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8732 else if (isLegalMVEShuffleOp(PFEntry)) {
8733 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8734 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8735 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8736 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8737 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8738 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8739 }
8740 }
8741 }
8742
8743 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8744 if (EltSize >= 32) {
8745 // Do the expansion with floating-point types, since that is what the VFP
8746 // registers are defined to use, and since i64 is not legal.
8747 EVT EltVT = EVT::getFloatingPointVT(EltSize);
8748 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8749 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8750 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8751 SmallVector<SDValue, 8> Ops;
8752 for (unsigned i = 0; i < NumElts; ++i) {
8753 if (ShuffleMask[i] < 0)
8754 Ops.push_back(DAG.getUNDEF(EltVT));
8755 else
8756 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8757 ShuffleMask[i] < (int)NumElts ? V1 : V2,
8758 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8759 dl, MVT::i32)));
8760 }
8761 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8762 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8763 }
8764
8765 if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8766 isReverseMask(ShuffleMask, VT))
8767 return LowerReverse_VECTOR_SHUFFLE(Op, DAG);
8768
8769 if (ST->hasNEON() && VT == MVT::v8i8)
8770 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8771 return NewOp;
8772
8773 if (ST->hasMVEIntegerOps())
8774 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8775 return NewOp;
8776
8777 return SDValue();
8778}
8779
8780static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8781 const ARMSubtarget *ST) {
8782 EVT VecVT = Op.getOperand(0).getValueType();
8783 SDLoc dl(Op);
8784
8785 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8786, __extension__ __PRETTY_FUNCTION__))
8786 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8786, __extension__ __PRETTY_FUNCTION__))
;
8787
8788 SDValue Conv =
8789 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8790 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8791 unsigned LaneWidth =
8792 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8793 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8794 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8795 Op.getOperand(1), DAG.getValueType(MVT::i1));
8796 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8797 DAG.getConstant(~Mask, dl, MVT::i32));
8798 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8799}
8800
8801SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8802 SelectionDAG &DAG) const {
8803 // INSERT_VECTOR_ELT is legal only for immediate indexes.
8804 SDValue Lane = Op.getOperand(2);
8805 if (!isa<ConstantSDNode>(Lane))
8806 return SDValue();
8807
8808 SDValue Elt = Op.getOperand(1);
8809 EVT EltVT = Elt.getValueType();
8810
8811 if (Subtarget->hasMVEIntegerOps() &&
8812 Op.getValueType().getScalarSizeInBits() == 1)
8813 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8814
8815 if (getTypeAction(*DAG.getContext(), EltVT) ==
8816 TargetLowering::TypePromoteFloat) {
8817 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8818 // but the type system will try to do that if we don't intervene.
8819 // Reinterpret any such vector-element insertion as one with the
8820 // corresponding integer types.
8821
8822 SDLoc dl(Op);
8823
8824 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8825 assert(getTypeAction(*DAG.getContext(), IEltVT) !=(static_cast <bool> (getTypeAction(*DAG.getContext(), IEltVT
) != TargetLowering::TypePromoteFloat) ? void (0) : __assert_fail
("getTypeAction(*DAG.getContext(), IEltVT) != TargetLowering::TypePromoteFloat"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8826, __extension__ __PRETTY_FUNCTION__))
8826 TargetLowering::TypePromoteFloat)(static_cast <bool> (getTypeAction(*DAG.getContext(), IEltVT
) != TargetLowering::TypePromoteFloat) ? void (0) : __assert_fail
("getTypeAction(*DAG.getContext(), IEltVT) != TargetLowering::TypePromoteFloat"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8826, __extension__ __PRETTY_FUNCTION__))
;
8827
8828 SDValue VecIn = Op.getOperand(0);
8829 EVT VecVT = VecIn.getValueType();
8830 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8831 VecVT.getVectorNumElements());
8832
8833 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8834 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8835 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8836 IVecIn, IElt, Lane);
8837 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8838 }
8839
8840 return Op;
8841}
8842
8843static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8844 const ARMSubtarget *ST) {
8845 EVT VecVT = Op.getOperand(0).getValueType();
8846 SDLoc dl(Op);
8847
8848 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8849, __extension__ __PRETTY_FUNCTION__))
8849 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8849, __extension__ __PRETTY_FUNCTION__))
;
8850
8851 SDValue Conv =
8852 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8853 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8854 unsigned LaneWidth =
8855 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8856 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8857 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8858 return Shift;
8859}
8860
8861static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8862 const ARMSubtarget *ST) {
8863 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8864 SDValue Lane = Op.getOperand(1);
8865 if (!isa<ConstantSDNode>(Lane))
8866 return SDValue();
8867
8868 SDValue Vec = Op.getOperand(0);
8869 EVT VT = Vec.getValueType();
8870
8871 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8872 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8873
8874 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8875 SDLoc dl(Op);
8876 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8877 }
8878
8879 return Op;
8880}
8881
8882static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8883 const ARMSubtarget *ST) {
8884 SDLoc dl(Op);
8885 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8886, __extension__ __PRETTY_FUNCTION__))
8886 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8886, __extension__ __PRETTY_FUNCTION__))
;
8887 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8888, __extension__ __PRETTY_FUNCTION__))
8888 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8888, __extension__ __PRETTY_FUNCTION__))
;
8889 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8890, __extension__ __PRETTY_FUNCTION__))
8890 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8890, __extension__ __PRETTY_FUNCTION__))
;
8891
8892 auto ConcatPair = [&](SDValue V1, SDValue V2) {
8893 EVT Op1VT = V1.getValueType();
8894 EVT Op2VT = V2.getValueType();
8895 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8895, __extension__ __PRETTY_FUNCTION__))
;
8896 EVT VT = Op1VT.getDoubleNumVectorElementsVT(*DAG.getContext());
8897
8898 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8899 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8900
8901 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8902 // promoted to v8i16, etc.
8903 MVT ElType =
8904 getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8905 unsigned NumElts = 2 * Op1VT.getVectorNumElements();
8906
8907 // Extract the vector elements from Op1 and Op2 one by one and truncate them
8908 // to be the right size for the destination. For example, if Op1 is v4i1
8909 // then the promoted vector is v4i32. The result of concatentation gives a
8910 // v8i1, which when promoted is v8i16. That means each i32 element from Op1
8911 // needs truncating to i16 and inserting in the result.
8912 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8913 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8914 auto ExtractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8915 EVT NewVT = NewV.getValueType();
8916 EVT ConcatVT = ConVec.getValueType();
8917 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8918 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8919 DAG.getIntPtrConstant(i, dl));
8920 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8921 DAG.getConstant(j, dl, MVT::i32));
8922 }
8923 return ConVec;
8924 };
8925 unsigned j = 0;
8926 ConVec = ExtractInto(NewV1, ConVec, j);
8927 ConVec = ExtractInto(NewV2, ConVec, j);
8928
8929 // Now return the result of comparing the subvector with zero,
8930 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8931 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8932 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8933 };
8934
8935 // Concat each pair of subvectors and pack into the lower half of the array.
8936 SmallVector<SDValue> ConcatOps(Op->op_begin(), Op->op_end());
8937 while (ConcatOps.size() > 1) {
8938 for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
8939 SDValue V1 = ConcatOps[I];
8940 SDValue V2 = ConcatOps[I + 1];
8941 ConcatOps[I / 2] = ConcatPair(V1, V2);
8942 }
8943 ConcatOps.resize(ConcatOps.size() / 2);
8944 }
8945 return ConcatOps[0];
8946}
8947
8948static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8949 const ARMSubtarget *ST) {
8950 EVT VT = Op->getValueType(0);
8951 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8952 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8953
8954 // The only time a CONCAT_VECTORS operation can have legal types is when
8955 // two 64-bit vectors are concatenated to a 128-bit vector.
8956 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8957, __extension__ __PRETTY_FUNCTION__))
8957 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8957, __extension__ __PRETTY_FUNCTION__))
;
8958 SDLoc dl(Op);
8959 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8960 SDValue Op0 = Op.getOperand(0);
8961 SDValue Op1 = Op.getOperand(1);
8962 if (!Op0.isUndef())
8963 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8964 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8965 DAG.getIntPtrConstant(0, dl));
8966 if (!Op1.isUndef())
8967 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8968 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8969 DAG.getIntPtrConstant(1, dl));
8970 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8971}
8972
8973static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8974 const ARMSubtarget *ST) {
8975 SDValue V1 = Op.getOperand(0);
8976 SDValue V2 = Op.getOperand(1);
8977 SDLoc dl(Op);
8978 EVT VT = Op.getValueType();
8979 EVT Op1VT = V1.getValueType();
8980 unsigned NumElts = VT.getVectorNumElements();
8981 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8982
8983 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8984, __extension__ __PRETTY_FUNCTION__))
8984 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8984, __extension__ __PRETTY_FUNCTION__))
;
8985 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8986, __extension__ __PRETTY_FUNCTION__))
8986 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8986, __extension__ __PRETTY_FUNCTION__))
;
8987
8988 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8989
8990 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8991 // promoted to v8i16, etc.
8992
8993 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8994
8995 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8996 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8997 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8998 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8999 DAG.getIntPtrConstant(i, dl));
9000 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9001 DAG.getConstant(j, dl, MVT::i32));
9002 }
9003
9004 // Now return the result of comparing the subvector with zero,
9005 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
9006 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
9007 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9008}
9009
9010// Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0).
9011static SDValue LowerTruncatei1(SDNode *N, SelectionDAG &DAG,
9012 const ARMSubtarget *ST) {
9013 assert(ST->hasMVEIntegerOps() && "Expected MVE!")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"Expected MVE!") ? void (0) : __assert_fail ("ST->hasMVEIntegerOps() && \"Expected MVE!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9013, __extension__ __PRETTY_FUNCTION__))
;
9014 EVT VT = N->getValueType(0);
9015 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9016, __extension__ __PRETTY_FUNCTION__))
9016 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9016, __extension__ __PRETTY_FUNCTION__))
;
9017 SDValue Op = N->getOperand(0);
9018 EVT FromVT = Op.getValueType();
9019 SDLoc DL(N);
9020
9021 SDValue And =
9022 DAG.getNode(ISD::AND, DL, FromVT, Op, DAG.getConstant(1, DL, FromVT));
9023 return DAG.getNode(ISD::SETCC, DL, VT, And, DAG.getConstant(0, DL, FromVT),
9024 DAG.getCondCode(ISD::SETNE));
9025}
9026
9027static SDValue LowerTruncate(SDNode *N, SelectionDAG &DAG,
9028 const ARMSubtarget *Subtarget) {
9029 if (!Subtarget->hasMVEIntegerOps())
9030 return SDValue();
9031
9032 EVT ToVT = N->getValueType(0);
9033 if (ToVT.getScalarType() == MVT::i1)
9034 return LowerTruncatei1(N, DAG, Subtarget);
9035
9036 // MVE does not have a single instruction to perform the truncation of a v4i32
9037 // into the lower half of a v8i16, in the same way that a NEON vmovn would.
9038 // Most of the instructions in MVE follow the 'Beats' system, where moving
9039 // values from different lanes is usually something that the instructions
9040 // avoid.
9041 //
9042 // Instead it has top/bottom instructions such as VMOVLT/B and VMOVNT/B,
9043 // which take a the top/bottom half of a larger lane and extend it (or do the
9044 // opposite, truncating into the top/bottom lane from a larger lane). Note
9045 // that because of the way we widen lanes, a v4i16 is really a v4i32 using the
9046 // bottom 16bits from each vector lane. This works really well with T/B
9047 // instructions, but that doesn't extend to v8i32->v8i16 where the lanes need
9048 // to move order.
9049 //
9050 // But truncates and sext/zext are always going to be fairly common from llvm.
9051 // We have several options for how to deal with them:
9052 // - Wherever possible combine them into an instruction that makes them
9053 // "free". This includes loads/stores, which can perform the trunc as part
9054 // of the memory operation. Or certain shuffles that can be turned into
9055 // VMOVN/VMOVL.
9056 // - Lane Interleaving to transform blocks surrounded by ext/trunc. So
9057 // trunc(mul(sext(a), sext(b))) may become
9058 // VMOVNT(VMUL(VMOVLB(a), VMOVLB(b)), VMUL(VMOVLT(a), VMOVLT(b))). (Which in
9059 // this case can use VMULL). This is performed in the
9060 // MVELaneInterleavingPass.
9061 // - Otherwise we have an option. By default we would expand the
9062 // zext/sext/trunc into a series of lane extract/inserts going via GPR
9063 // registers. One for each vector lane in the vector. This can obviously be
9064 // very expensive.
9065 // - The other option is to use the fact that loads/store can extend/truncate
9066 // to turn a trunc into two truncating stack stores and a stack reload. This
9067 // becomes 3 back-to-back memory operations, but at least that is less than
9068 // all the insert/extracts.
9069 //
9070 // In order to do the last, we convert certain trunc's into MVETRUNC, which
9071 // are either optimized where they can be, or eventually lowered into stack
9072 // stores/loads. This prevents us from splitting a v8i16 trunc into two stores
9073 // two early, where other instructions would be better, and stops us from
9074 // having to reconstruct multiple buildvector shuffles into loads/stores.
9075 if (ToVT != MVT::v8i16 && ToVT != MVT::v16i8)
9076 return SDValue();
9077 EVT FromVT = N->getOperand(0).getValueType();
9078 if (FromVT != MVT::v8i32 && FromVT != MVT::v16i16)
9079 return SDValue();
9080
9081 SDValue Lo, Hi;
9082 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9083 SDLoc DL(N);
9084 return DAG.getNode(ARMISD::MVETRUNC, DL, ToVT, Lo, Hi);
9085}
9086
9087static SDValue LowerVectorExtend(SDNode *N, SelectionDAG &DAG,
9088 const ARMSubtarget *Subtarget) {
9089 if (!Subtarget->hasMVEIntegerOps())
9090 return SDValue();
9091
9092 // See LowerTruncate above for an explanation of MVEEXT/MVETRUNC.
9093
9094 EVT ToVT = N->getValueType(0);
9095 if (ToVT != MVT::v16i32 && ToVT != MVT::v8i32 && ToVT != MVT::v16i16)
9096 return SDValue();
9097 SDValue Op = N->getOperand(0);
9098 EVT FromVT = Op.getValueType();
9099 if (FromVT != MVT::v8i16 && FromVT != MVT::v16i8)
9100 return SDValue();
9101
9102 SDLoc DL(N);
9103 EVT ExtVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
9104 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8)
9105 ExtVT = MVT::v8i16;
9106
9107 unsigned Opcode =
9108 N->getOpcode() == ISD::SIGN_EXTEND ? ARMISD::MVESEXT : ARMISD::MVEZEXT;
9109 SDValue Ext = DAG.getNode(Opcode, DL, DAG.getVTList(ExtVT, ExtVT), Op);
9110 SDValue Ext1 = Ext.getValue(1);
9111
9112 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8) {
9113 Ext = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext);
9114 Ext1 = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext1);
9115 }
9116
9117 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Ext, Ext1);
9118}
9119
9120/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
9121/// element has been zero/sign-extended, depending on the isSigned parameter,
9122/// from an integer type half its size.
9123static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
9124 bool isSigned) {
9125 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
9126 EVT VT = N->getValueType(0);
9127 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
9128 SDNode *BVN = N->getOperand(0).getNode();
9129 if (BVN->getValueType(0) != MVT::v4i32 ||
9130 BVN->getOpcode() != ISD::BUILD_VECTOR)
9131 return false;
9132 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9133 unsigned HiElt = 1 - LoElt;
9134 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
9135 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
9136 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
9137 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
9138 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
9139 return false;
9140 if (isSigned) {
9141 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
9142 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
9143 return true;
9144 } else {
9145 if (Hi0->isZero() && Hi1->isZero())
9146 return true;
9147 }
9148 return false;
9149 }
9150
9151 if (N->getOpcode() != ISD::BUILD_VECTOR)
9152 return false;
9153
9154 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9155 SDNode *Elt = N->getOperand(i).getNode();
9156 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
9157 unsigned EltSize = VT.getScalarSizeInBits();
9158 unsigned HalfSize = EltSize / 2;
9159 if (isSigned) {
9160 if (!isIntN(HalfSize, C->getSExtValue()))
9161 return false;
9162 } else {
9163 if (!isUIntN(HalfSize, C->getZExtValue()))
9164 return false;
9165 }
9166 continue;
9167 }
9168 return false;
9169 }
9170
9171 return true;
9172}
9173
9174/// isSignExtended - Check if a node is a vector value that is sign-extended
9175/// or a constant BUILD_VECTOR with sign-extended elements.
9176static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
9177 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
9178 return true;
9179 if (isExtendedBUILD_VECTOR(N, DAG, true))
9180 return true;
9181 return false;
9182}
9183
9184/// isZeroExtended - Check if a node is a vector value that is zero-extended (or
9185/// any-extended) or a constant BUILD_VECTOR with zero-extended elements.
9186static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
9187 if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND ||
9188 ISD::isZEXTLoad(N))
9189 return true;
9190 if (isExtendedBUILD_VECTOR(N, DAG, false))
9191 return true;
9192 return false;
9193}
9194
9195static EVT getExtensionTo64Bits(const EVT &OrigVT) {
9196 if (OrigVT.getSizeInBits() >= 64)
9197 return OrigVT;
9198
9199 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9199, __extension__ __PRETTY_FUNCTION__))
;
9200
9201 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
9202 switch (OrigSimpleTy) {
9203 default: llvm_unreachable("Unexpected Vector Type")::llvm::llvm_unreachable_internal("Unexpected Vector Type", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9203)
;
9204 case MVT::v2i8:
9205 case MVT::v2i16:
9206 return MVT::v2i32;
9207 case MVT::v4i8:
9208 return MVT::v4i16;
9209 }
9210}
9211
9212/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
9213/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
9214/// We insert the required extension here to get the vector to fill a D register.
9215static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
9216 const EVT &OrigTy,
9217 const EVT &ExtTy,
9218 unsigned ExtOpcode) {
9219 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
9220 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
9221 // 64-bits we need to insert a new extension so that it will be 64-bits.
9222 assert(ExtTy.is128BitVector() && "Unexpected extension size")(static_cast <bool> (ExtTy.is128BitVector() && "Unexpected extension size"
) ? void (0) : __assert_fail ("ExtTy.is128BitVector() && \"Unexpected extension size\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9222, __extension__ __PRETTY_FUNCTION__))
;
9223 if (OrigTy.getSizeInBits() >= 64)
9224 return N;
9225
9226 // Must extend size to at least 64 bits to be used as an operand for VMULL.
9227 EVT NewVT = getExtensionTo64Bits(OrigTy);
9228
9229 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
9230}
9231
9232/// SkipLoadExtensionForVMULL - return a load of the original vector size that
9233/// does not do any sign/zero extension. If the original vector is less
9234/// than 64 bits, an appropriate extension will be added after the load to
9235/// reach a total size of 64 bits. We have to add the extension separately
9236/// because ARM does not have a sign/zero extending load for vectors.
9237static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
9238 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
9239
9240 // The load already has the right type.
9241 if (ExtendedTy == LD->getMemoryVT())
9242 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
9243 LD->getBasePtr(), LD->getPointerInfo(),
9244 LD->getAlignment(), LD->getMemOperand()->getFlags());
9245
9246 // We need to create a zextload/sextload. We cannot just create a load
9247 // followed by a zext/zext node because LowerMUL is also run during normal
9248 // operation legalization where we can't create illegal types.
9249 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
9250 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
9251 LD->getMemoryVT(), LD->getAlignment(),
9252 LD->getMemOperand()->getFlags());
9253}
9254
9255/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
9256/// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return
9257/// the unextended value. The unextended vector should be 64 bits so that it can
9258/// be used as an operand to a VMULL instruction. If the original vector size
9259/// before extension is less than 64 bits we add a an extension to resize
9260/// the vector to 64 bits.
9261static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
9262 if (N->getOpcode() == ISD::SIGN_EXTEND ||
9263 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
9264 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
9265 N->getOperand(0)->getValueType(0),
9266 N->getValueType(0),
9267 N->getOpcode());
9268
9269 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9270 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9271, __extension__ __PRETTY_FUNCTION__))
9271 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9271, __extension__ __PRETTY_FUNCTION__))
;
9272
9273 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
9274 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
9275 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9276 SDValue extLoad =
9277 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
9278 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
9279
9280 return newLoad;
9281 }
9282
9283 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
9284 // have been legalized as a BITCAST from v4i32.
9285 if (N->getOpcode() == ISD::BITCAST) {
9286 SDNode *BVN = N->getOperand(0).getNode();
9287 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9288, __extension__ __PRETTY_FUNCTION__))
9288 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9288, __extension__ __PRETTY_FUNCTION__))
;
9289 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9290 return DAG.getBuildVector(
9291 MVT::v2i32, SDLoc(N),
9292 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
9293 }
9294 // Construct a new BUILD_VECTOR with elements truncated to half the size.
9295 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9295, __extension__ __PRETTY_FUNCTION__))
;
9296 EVT VT = N->getValueType(0);
9297 unsigned EltSize = VT.getScalarSizeInBits() / 2;
9298 unsigned NumElts = VT.getVectorNumElements();
9299 MVT TruncVT = MVT::getIntegerVT(EltSize);
9300 SmallVector<SDValue, 8> Ops;
9301 SDLoc dl(N);
9302 for (unsigned i = 0; i != NumElts; ++i) {
9303 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
9304 const APInt &CInt = C->getAPIntValue();
9305 // Element types smaller than 32 bits are not legal, so use i32 elements.
9306 // The values are implicitly truncated so sext vs. zext doesn't matter.
9307 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
9308 }
9309 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
9310}
9311
9312static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
9313 unsigned Opcode = N->getOpcode();
9314 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9315 SDNode *N0 = N->getOperand(0).getNode();
9316 SDNode *N1 = N->getOperand(1).getNode();
9317 return N0->hasOneUse() && N1->hasOneUse() &&
9318 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
9319 }
9320 return false;
9321}
9322
9323static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
9324 unsigned Opcode = N->getOpcode();
9325 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9326 SDNode *N0 = N->getOperand(0).getNode();
9327 SDNode *N1 = N->getOperand(1).getNode();
9328 return N0->hasOneUse() && N1->hasOneUse() &&
9329 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
9330 }
9331 return false;
9332}
9333
9334static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
9335 // Multiplications are only custom-lowered for 128-bit vectors so that
9336 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
9337 EVT VT = Op.getValueType();
9338 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9339, __extension__ __PRETTY_FUNCTION__))
9339 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9339, __extension__ __PRETTY_FUNCTION__))
;
9340 SDNode *N0 = Op.getOperand(0).getNode();
9341 SDNode *N1 = Op.getOperand(1).getNode();
9342 unsigned NewOpc = 0;
9343 bool isMLA = false;
9344 bool isN0SExt = isSignExtended(N0, DAG);
9345 bool isN1SExt = isSignExtended(N1, DAG);
9346 if (isN0SExt && isN1SExt)
9347 NewOpc = ARMISD::VMULLs;
9348 else {
9349 bool isN0ZExt = isZeroExtended(N0, DAG);
9350 bool isN1ZExt = isZeroExtended(N1, DAG);
9351 if (isN0ZExt && isN1ZExt)
9352 NewOpc = ARMISD::VMULLu;
9353 else if (isN1SExt || isN1ZExt) {
9354 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
9355 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
9356 if (isN1SExt && isAddSubSExt(N0, DAG)) {
9357 NewOpc = ARMISD::VMULLs;
9358 isMLA = true;
9359 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
9360 NewOpc = ARMISD::VMULLu;
9361 isMLA = true;
9362 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
9363 std::swap(N0, N1);
9364 NewOpc = ARMISD::VMULLu;
9365 isMLA = true;
9366 }
9367 }
9368
9369 if (!NewOpc) {
9370 if (VT == MVT::v2i64)
9371 // Fall through to expand this. It is not legal.
9372 return SDValue();
9373 else
9374 // Other vector multiplications are legal.
9375 return Op;
9376 }
9377 }
9378
9379 // Legalize to a VMULL instruction.
9380 SDLoc DL(Op);
9381 SDValue Op0;
9382 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
9383 if (!isMLA) {
9384 Op0 = SkipExtensionForVMULL(N0, DAG);
9385 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9387, __extension__ __PRETTY_FUNCTION__))
9386 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9387, __extension__ __PRETTY_FUNCTION__))
9387 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9387, __extension__ __PRETTY_FUNCTION__))
;
9388 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
9389 }
9390
9391 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
9392 // isel lowering to take advantage of no-stall back to back vmul + vmla.
9393 // vmull q0, d4, d6
9394 // vmlal q0, d5, d6
9395 // is faster than
9396 // vaddl q0, d4, d5
9397 // vmovl q1, d6
9398 // vmul q0, q0, q1
9399 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
9400 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
9401 EVT Op1VT = Op1.getValueType();
9402 return DAG.getNode(N0->getOpcode(), DL, VT,
9403 DAG.getNode(NewOpc, DL, VT,
9404 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
9405 DAG.getNode(NewOpc, DL, VT,
9406 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
9407}
9408
9409static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
9410 SelectionDAG &DAG) {
9411 // TODO: Should this propagate fast-math-flags?
9412
9413 // Convert to float
9414 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
9415 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
9416 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
9417 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
9418 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
9419 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
9420 // Get reciprocal estimate.
9421 // float4 recip = vrecpeq_f32(yf);
9422 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9423 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9424 Y);
9425 // Because char has a smaller range than uchar, we can actually get away
9426 // without any newton steps. This requires that we use a weird bias
9427 // of 0xb000, however (again, this has been exhaustively tested).
9428 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
9429 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
9430 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
9431 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
9432 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
9433 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
9434 // Convert back to short.
9435 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
9436 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
9437 return X;
9438}
9439
9440static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
9441 SelectionDAG &DAG) {
9442 // TODO: Should this propagate fast-math-flags?
9443
9444 SDValue N2;
9445 // Convert to float.
9446 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
9447 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
9448 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
9449 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
9450 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9451 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9452
9453 // Use reciprocal estimate and one refinement step.
9454 // float4 recip = vrecpeq_f32(yf);
9455 // recip *= vrecpsq_f32(yf, recip);
9456 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9457 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9458 N1);
9459 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9460 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9461 N1, N2);
9462 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9463 // Because short has a smaller range than ushort, we can actually get away
9464 // with only a single newton step. This requires that we use a weird bias
9465 // of 89, however (again, this has been exhaustively tested).
9466 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9467 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9468 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9469 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
9470 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9471 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9472 // Convert back to integer and return.
9473 // return vmovn_s32(vcvt_s32_f32(result));
9474 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9475 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9476 return N0;
9477}
9478
9479static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
9480 const ARMSubtarget *ST) {
9481 EVT VT = Op.getValueType();
9482 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9483, __extension__ __PRETTY_FUNCTION__))
9483 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9483, __extension__ __PRETTY_FUNCTION__))
;
9484
9485 SDLoc dl(Op);
9486 SDValue N0 = Op.getOperand(0);
9487 SDValue N1 = Op.getOperand(1);
9488 SDValue N2, N3;
9489
9490 if (VT == MVT::v8i8) {
9491 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9492 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9493
9494 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9495 DAG.getIntPtrConstant(4, dl));
9496 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9497 DAG.getIntPtrConstant(4, dl));
9498 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9499 DAG.getIntPtrConstant(0, dl));
9500 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9501 DAG.getIntPtrConstant(0, dl));
9502
9503 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9504 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9505
9506 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9507 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9508
9509 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9510 return N0;
9511 }
9512 return LowerSDIV_v4i16(N0, N1, dl, DAG);
9513}
9514
9515static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
9516 const ARMSubtarget *ST) {
9517 // TODO: Should this propagate fast-math-flags?
9518 EVT VT = Op.getValueType();
9519 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9520, __extension__ __PRETTY_FUNCTION__))
9520 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9520, __extension__ __PRETTY_FUNCTION__))
;
9521
9522 SDLoc dl(Op);
9523 SDValue N0 = Op.getOperand(0);
9524 SDValue N1 = Op.getOperand(1);
9525 SDValue N2, N3;
9526
9527 if (VT == MVT::v8i8) {
9528 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9529 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9530
9531 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9532 DAG.getIntPtrConstant(4, dl));
9533 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9534 DAG.getIntPtrConstant(4, dl));
9535 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9536 DAG.getIntPtrConstant(0, dl));
9537 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9538 DAG.getIntPtrConstant(0, dl));
9539
9540 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9541 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9542
9543 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9544 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9545
9546 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9547 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9548 MVT::i32),
9549 N0);
9550 return N0;
9551 }
9552
9553 // v4i16 sdiv ... Convert to float.
9554 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9555 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9556 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9557 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9558 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9559 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9560
9561 // Use reciprocal estimate and two refinement steps.
9562 // float4 recip = vrecpeq_f32(yf);
9563 // recip *= vrecpsq_f32(yf, recip);
9564 // recip *= vrecpsq_f32(yf, recip);
9565 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9566 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9567 BN1);
9568 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9569 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9570 BN1, N2);
9571 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9572 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9573 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9574 BN1, N2);
9575 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9576 // Simply multiplying by the reciprocal estimate can leave us a few ulps
9577 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9578 // and that it will never cause us to return an answer too large).
9579 // float4 result = as_float4(as_int4(xf*recip) + 2);
9580 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9581 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9582 N1 = DAG.getConstant(2, dl, MVT::v4i32);
9583 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9584 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9585 // Convert back to integer and return.
9586 // return vmovn_u32(vcvt_s32_f32(result));
9587 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9588 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9589 return N0;
9590}
9591
9592static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
9593 SDNode *N = Op.getNode();
9594 EVT VT = N->getValueType(0);
9595 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9596
9597 SDValue Carry = Op.getOperand(2);
9598
9599 SDLoc DL(Op);
9600
9601 SDValue Result;
9602 if (Op.getOpcode() == ISD::ADDCARRY) {
9603 // This converts the boolean value carry into the carry flag.
9604 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9605
9606 // Do the addition proper using the carry flag we wanted.
9607 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
9608 Op.getOperand(1), Carry);
9609
9610 // Now convert the carry flag into a boolean value.
9611 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9612 } else {
9613 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
9614 // have to invert the carry first.
9615 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9616 DAG.getConstant(1, DL, MVT::i32), Carry);
9617 // This converts the boolean value carry into the carry flag.
9618 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9619
9620 // Do the subtraction proper using the carry flag we wanted.
9621 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
9622 Op.getOperand(1), Carry);
9623
9624 // Now convert the carry flag into a boolean value.
9625 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9626 // But the carry returned by ARMISD::SUBE is not a borrow as expected
9627 // by ISD::SUBCARRY, so compute 1 - C.
9628 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9629 DAG.getConstant(1, DL, MVT::i32), Carry);
9630 }
9631
9632 // Return both values.
9633 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
9634}
9635
9636SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
9637 assert(Subtarget->isTargetDarwin())(static_cast <bool> (Subtarget->isTargetDarwin()) ? void
(0) : __assert_fail ("Subtarget->isTargetDarwin()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9637, __extension__ __PRETTY_FUNCTION__))
;
9638
9639 // For iOS, we want to call an alternative entry point: __sincos_stret,
9640 // return values are passed via sret.
9641 SDLoc dl(Op);
9642 SDValue Arg = Op.getOperand(0);
9643 EVT ArgVT = Arg.getValueType();
9644 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9645 auto PtrVT = getPointerTy(DAG.getDataLayout());
9646
9647 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9649
9650 // Pair of floats / doubles used to pass the result.
9651 Type *RetTy = StructType::get(ArgTy, ArgTy);
9652 auto &DL = DAG.getDataLayout();
9653
9654 ArgListTy Args;
9655 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
9656 SDValue SRet;
9657 if (ShouldUseSRet) {
9658 // Create stack object for sret.
9659 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
9660 const Align StackAlign = DL.getPrefTypeAlign(RetTy);
9661 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
9662 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
9663
9664 ArgListEntry Entry;
9665 Entry.Node = SRet;
9666 Entry.Ty = RetTy->getPointerTo();
9667 Entry.IsSExt = false;
9668 Entry.IsZExt = false;
9669 Entry.IsSRet = true;
9670 Args.push_back(Entry);
9671 RetTy = Type::getVoidTy(*DAG.getContext());
9672 }
9673
9674 ArgListEntry Entry;
9675 Entry.Node = Arg;
9676 Entry.Ty = ArgTy;
9677 Entry.IsSExt = false;
9678 Entry.IsZExt = false;
9679 Args.push_back(Entry);
9680
9681 RTLIB::Libcall LC =
9682 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
9683 const char *LibcallName = getLibcallName(LC);
9684 CallingConv::ID CC = getLibcallCallingConv(LC);
9685 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
9686
9687 TargetLowering::CallLoweringInfo CLI(DAG);
9688 CLI.setDebugLoc(dl)
9689 .setChain(DAG.getEntryNode())
9690 .setCallee(CC, RetTy, Callee, std::move(Args))
9691 .setDiscardResult(ShouldUseSRet);
9692 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
9693
9694 if (!ShouldUseSRet)
9695 return CallResult.first;
9696
9697 SDValue LoadSin =
9698 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
9699
9700 // Address of cos field.
9701 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
9702 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
9703 SDValue LoadCos =
9704 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
9705
9706 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
9707 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
9708 LoadSin.getValue(0), LoadCos.getValue(0));
9709}
9710
9711SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9712 bool Signed,
9713 SDValue &Chain) const {
9714 EVT VT = Op.getValueType();
9715 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9716, __extension__ __PRETTY_FUNCTION__))
9716 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9716, __extension__ __PRETTY_FUNCTION__))
;
9717 SDLoc dl(Op);
9718
9719 const auto &DL = DAG.getDataLayout();
9720 const auto &TLI = DAG.getTargetLoweringInfo();
9721
9722 const char *Name = nullptr;
9723 if (Signed)
9724 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
9725 else
9726 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
9727
9728 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
9729
9730 ARMTargetLowering::ArgListTy Args;
9731
9732 for (auto AI : {1, 0}) {
9733 ArgListEntry Arg;
9734 Arg.Node = Op.getOperand(AI);
9735 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
9736 Args.push_back(Arg);
9737 }
9738
9739 CallLoweringInfo CLI(DAG);
9740 CLI.setDebugLoc(dl)
9741 .setChain(Chain)
9742 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
9743 ES, std::move(Args));
9744
9745 return LowerCallTo(CLI).first;
9746}
9747
9748// This is a code size optimisation: return the original SDIV node to
9749// DAGCombiner when we don't want to expand SDIV into a sequence of
9750// instructions, and an empty node otherwise which will cause the
9751// SDIV to be expanded in DAGCombine.
9752SDValue
9753ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9754 SelectionDAG &DAG,
9755 SmallVectorImpl<SDNode *> &Created) const {
9756 // TODO: Support SREM
9757 if (N->getOpcode() != ISD::SDIV)
9758 return SDValue();
9759
9760 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
9761 const bool MinSize = ST.hasMinSize();
9762 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9763 : ST.hasDivideInARMMode();
9764
9765 // Don't touch vector types; rewriting this may lead to scalarizing
9766 // the int divs.
9767 if (N->getOperand(0).getValueType().isVector())
9768 return SDValue();
9769
9770 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9771 // hwdiv support for this to be really profitable.
9772 if (!(MinSize && HasDivide))
9773 return SDValue();
9774
9775 // ARM mode is a bit simpler than Thumb: we can handle large power
9776 // of 2 immediates with 1 mov instruction; no further checks required,
9777 // just return the sdiv node.
9778 if (!ST.isThumb())
9779 return SDValue(N, 0);
9780
9781 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9782 // and thus lose the code size benefits of a MOVS that requires only 2.
9783 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9784 // but as it's doing exactly this, it's not worth the trouble to get TTI.
9785 if (Divisor.sgt(128))
9786 return SDValue();
9787
9788 return SDValue(N, 0);
9789}
9790
9791SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9792 bool Signed) const {
9793 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9794, __extension__ __PRETTY_FUNCTION__))
9794 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9794, __extension__ __PRETTY_FUNCTION__))
;
9795 SDLoc dl(Op);
9796
9797 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9798 DAG.getEntryNode(), Op.getOperand(1));
9799
9800 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9801}
9802
9803static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9804 SDLoc DL(N);
9805 SDValue Op = N->getOperand(1);
9806 if (N->getValueType(0) == MVT::i32)
9807 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9808 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9809 DAG.getConstant(0, DL, MVT::i32));
9810 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9811 DAG.getConstant(1, DL, MVT::i32));
9812 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9813 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9814}
9815
9816void ARMTargetLowering::ExpandDIV_Windows(
9817 SDValue Op, SelectionDAG &DAG, bool Signed,
9818 SmallVectorImpl<SDValue> &Results) const {
9819 const auto &DL = DAG.getDataLayout();
9820 const auto &TLI = DAG.getTargetLoweringInfo();
9821
9822 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9823, __extension__ __PRETTY_FUNCTION__))
9823 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9823, __extension__ __PRETTY_FUNCTION__))
;
9824 SDLoc dl(Op);
9825
9826 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9827
9828 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9829
9830 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9831 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9832 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
9833 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9834
9835 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9836}
9837
9838static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9839 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9840 EVT MemVT = LD->getMemoryVT();
9841 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&(static_cast <bool> ((MemVT == MVT::v4i1 || MemVT == MVT
::v8i1 || MemVT == MVT::v16i1) && "Expected a predicate type!"
) ? void (0) : __assert_fail ("(MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9842, __extension__ __PRETTY_FUNCTION__))
9842 "Expected a predicate type!")(static_cast <bool> ((MemVT == MVT::v4i1 || MemVT == MVT
::v8i1 || MemVT == MVT::v16i1) && "Expected a predicate type!"
) ? void (0) : __assert_fail ("(MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9842, __extension__ __PRETTY_FUNCTION__))
;
9843 assert(MemVT == Op.getValueType())(static_cast <bool> (MemVT == Op.getValueType()) ? void
(0) : __assert_fail ("MemVT == Op.getValueType()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9843, __extension__ __PRETTY_FUNCTION__))
;
9844 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9845, __extension__ __PRETTY_FUNCTION__))
9845 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9845, __extension__ __PRETTY_FUNCTION__))
;
9846 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9846, __extension__ __PRETTY_FUNCTION__))
;
9847
9848 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
9849 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9850 // need to make sure that 8/4 bits are actually loaded into the correct
9851 // place, which means loading the value and then shuffling the values into
9852 // the bottom bits of the predicate.
9853 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9854 // for BE).
9855 // Speaking of BE, apparently the rest of llvm will assume a reverse order to
9856 // a natural VMSR(load), so needs to be reversed.
9857
9858 SDLoc dl(Op);
9859 SDValue Load = DAG.getExtLoad(
9860 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9861 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9862 LD->getMemOperand());
9863 SDValue Val = Load;
9864 if (DAG.getDataLayout().isBigEndian())
9865 Val = DAG.getNode(ISD::SRL, dl, MVT::i32,
9866 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Load),
9867 DAG.getConstant(32 - MemVT.getSizeInBits(), dl, MVT::i32));
9868 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Val);
9869 if (MemVT != MVT::v16i1)
9870 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9871 DAG.getConstant(0, dl, MVT::i32));
9872 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9873}
9874
9875void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9876 SelectionDAG &DAG) const {
9877 LoadSDNode *LD = cast<LoadSDNode>(N);
9878 EVT MemVT = LD->getMemoryVT();
9879 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.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9879, __extension__ __PRETTY_FUNCTION__))
;
9880
9881 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9882 !Subtarget->isThumb1Only() && LD->isVolatile()) {
9883 SDLoc dl(N);
9884 SDValue Result = DAG.getMemIntrinsicNode(
9885 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9886 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9887 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9888 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9889 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9890 Results.append({Pair, Result.getValue(2)});
9891 }
9892}
9893
9894static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9895 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9896 EVT MemVT = ST->getMemoryVT();
9897 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&(static_cast <bool> ((MemVT == MVT::v4i1 || MemVT == MVT
::v8i1 || MemVT == MVT::v16i1) && "Expected a predicate type!"
) ? void (0) : __assert_fail ("(MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9898, __extension__ __PRETTY_FUNCTION__))
9898 "Expected a predicate type!")(static_cast <bool> ((MemVT == MVT::v4i1 || MemVT == MVT
::v8i1 || MemVT == MVT::v16i1) && "Expected a predicate type!"
) ? void (0) : __assert_fail ("(MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9898, __extension__ __PRETTY_FUNCTION__))
;
9899 assert(MemVT == ST->getValue().getValueType())(static_cast <bool> (MemVT == ST->getValue().getValueType
()) ? void (0) : __assert_fail ("MemVT == ST->getValue().getValueType()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9899, __extension__ __PRETTY_FUNCTION__))
;
9900 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9900, __extension__ __PRETTY_FUNCTION__))
;
9901 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9901, __extension__ __PRETTY_FUNCTION__))
;
9902
9903 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
9904 // unset and a scalar store.
9905 SDLoc dl(Op);
9906 SDValue Build = ST->getValue();
9907 if (MemVT != MVT::v16i1) {
9908 SmallVector<SDValue, 16> Ops;
9909 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) {
9910 unsigned Elt = DAG.getDataLayout().isBigEndian()
9911 ? MemVT.getVectorNumElements() - I - 1
9912 : I;
9913 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9914 DAG.getConstant(Elt, dl, MVT::i32)));
9915 }
9916 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9917 Ops.push_back(DAG.getUNDEF(MVT::i32));
9918 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9919 }
9920 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9921 if (MemVT == MVT::v16i1 && DAG.getDataLayout().isBigEndian())
9922 GRP = DAG.getNode(ISD::SRL, dl, MVT::i32,
9923 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, GRP),
9924 DAG.getConstant(16, dl, MVT::i32));
9925 return DAG.getTruncStore(
9926 ST->getChain(), dl, GRP, ST->getBasePtr(),
9927 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9928 ST->getMemOperand());
9929}
9930
9931static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
9932 const ARMSubtarget *Subtarget) {
9933 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9934 EVT MemVT = ST->getMemoryVT();
9935 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.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9935, __extension__ __PRETTY_FUNCTION__))
;
9936
9937 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9938 !Subtarget->isThumb1Only() && ST->isVolatile()) {
9939 SDNode *N = Op.getNode();
9940 SDLoc dl(N);
9941
9942 SDValue Lo = DAG.getNode(
9943 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9944 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9945 MVT::i32));
9946 SDValue Hi = DAG.getNode(
9947 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9948 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9949 MVT::i32));
9950
9951 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9952 {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9953 MemVT, ST->getMemOperand());
9954 } else if (Subtarget->hasMVEIntegerOps() &&
9955 ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9956 MemVT == MVT::v16i1))) {
9957 return LowerPredicateStore(Op, DAG);
9958 }
9959
9960 return SDValue();
9961}
9962
9963static bool isZeroVector(SDValue N) {
9964 return (ISD::isBuildVectorAllZeros(N.getNode()) ||
9965 (N->getOpcode() == ARMISD::VMOVIMM &&
9966 isNullConstant(N->getOperand(0))));
9967}
9968
9969static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9970 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
9971 MVT VT = Op.getSimpleValueType();
9972 SDValue Mask = N->getMask();
9973 SDValue PassThru = N->getPassThru();
9974 SDLoc dl(Op);
9975
9976 if (isZeroVector(PassThru))
9977 return Op;
9978
9979 // MVE Masked loads use zero as the passthru value. Here we convert undef to
9980 // zero too, and other values are lowered to a select.
9981 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9982 DAG.getTargetConstant(0, dl, MVT::i32));
9983 SDValue NewLoad = DAG.getMaskedLoad(
9984 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9985 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9986 N->getExtensionType(), N->isExpandingLoad());
9987 SDValue Combo = NewLoad;
9988 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9989 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9990 isZeroVector(PassThru->getOperand(0));
9991 if (!PassThru.isUndef() && !PassThruIsCastZero)
9992 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9993 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9994}
9995
9996static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG,
9997 const ARMSubtarget *ST) {
9998 if (!ST->hasMVEIntegerOps())
9999 return SDValue();
10000
10001 SDLoc dl(Op);
10002 unsigned BaseOpcode = 0;
10003 switch (Op->getOpcode()) {
10004 default: llvm_unreachable("Expected VECREDUCE opcode")::llvm::llvm_unreachable_internal("Expected VECREDUCE opcode"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10004)
;
10005 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
10006 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
10007 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break;
10008 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break;
10009 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break;
10010 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break;
10011 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
10012 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
10013 }
10014
10015 SDValue Op0 = Op->getOperand(0);
10016 EVT VT = Op0.getValueType();
10017 EVT EltVT = VT.getVectorElementType();
10018 unsigned NumElts = VT.getVectorNumElements();
10019 unsigned NumActiveLanes = NumElts;
10020
10021 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10023, __extension__ __PRETTY_FUNCTION__))
10022 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10023, __extension__ __PRETTY_FUNCTION__))
10023 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10023, __extension__ __PRETTY_FUNCTION__))
;
10024
10025 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
10026 // allows us to easily extract vector elements from the lanes.
10027 while (NumActiveLanes > 4) {
10028 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
10029 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
10030 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
10031 NumActiveLanes /= 2;
10032 }
10033
10034 SDValue Res;
10035 if (NumActiveLanes == 4) {
10036 // The remaining 4 elements are summed sequentially
10037 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10038 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
10039 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10040 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
10041 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10042 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
10043 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10044 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
10045 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10046 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
10047 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
10048 } else {
10049 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10050 DAG.getConstant(0, dl, MVT::i32));
10051 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10052 DAG.getConstant(1, dl, MVT::i32));
10053 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10054 }
10055
10056 // Result type may be wider than element type.
10057 if (EltVT != Op->getValueType(0))
10058 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
10059 return Res;
10060}
10061
10062static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG,
10063 const ARMSubtarget *ST) {
10064 if (!ST->hasMVEFloatOps())
10065 return SDValue();
10066 return LowerVecReduce(Op, DAG, ST);
10067}
10068
10069static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
10070 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getSuccessOrdering()))
10071 // Acquire/Release load/store is not legal for targets without a dmb or
10072 // equivalent available.
10073 return SDValue();
10074
10075 // Monotonic load/store is legal for all targets.
10076 return Op;
10077}
10078
10079static void ReplaceREADCYCLECOUNTER(SDNode *N,
10080 SmallVectorImpl<SDValue> &Results,
10081 SelectionDAG &DAG,
10082 const ARMSubtarget *Subtarget) {
10083 SDLoc DL(N);
10084 // Under Power Management extensions, the cycle-count is:
10085 // mrc p15, #0, <Rt>, c9, c13, #0
10086 SDValue Ops[] = { N->getOperand(0), // Chain
10087 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
10088 DAG.getTargetConstant(15, DL, MVT::i32),
10089 DAG.getTargetConstant(0, DL, MVT::i32),
10090 DAG.getTargetConstant(9, DL, MVT::i32),
10091 DAG.getTargetConstant(13, DL, MVT::i32),
10092 DAG.getTargetConstant(0, DL, MVT::i32)
10093 };
10094
10095 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
10096 DAG.getVTList(MVT::i32, MVT::Other), Ops);
10097 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
10098 DAG.getConstant(0, DL, MVT::i32)));
10099 Results.push_back(Cycles32.getValue(1));
10100}
10101
10102static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
10103 SDLoc dl(V.getNode());
10104 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
10105 SDValue VHi = DAG.getAnyExtOrTrunc(
10106 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
10107 dl, MVT::i32);
10108 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10109 if (isBigEndian)
10110 std::swap (VLo, VHi);
10111 SDValue RegClass =
10112 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
10113 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
10114 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
10115 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
10116 return SDValue(
10117 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
10118}
10119
10120static void ReplaceCMP_SWAP_64Results(SDNode *N,
10121 SmallVectorImpl<SDValue> & Results,
10122 SelectionDAG &DAG) {
10123 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10124, __extension__ __PRETTY_FUNCTION__))
10124 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10124, __extension__ __PRETTY_FUNCTION__))
;
10125 SDValue Ops[] = {N->getOperand(1),
10126 createGPRPairNode(DAG, N->getOperand(2)),
10127 createGPRPairNode(DAG, N->getOperand(3)),
10128 N->getOperand(0)};
10129 SDNode *CmpSwap = DAG.getMachineNode(
10130 ARM::CMP_SWAP_64, SDLoc(N),
10131 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
10132
10133 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
10134 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
10135
10136 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10137
10138 SDValue Lo =
10139 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
10140 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10141 SDValue Hi =
10142 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
10143 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10144 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
10145 Results.push_back(SDValue(CmpSwap, 2));
10146}
10147
10148SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
10149 SDLoc dl(Op);
10150 EVT VT = Op.getValueType();
10151 SDValue Chain = Op.getOperand(0);
10152 SDValue LHS = Op.getOperand(1);
10153 SDValue RHS = Op.getOperand(2);
10154 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
10155 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
10156
10157 // If we don't have instructions of this float type then soften to a libcall
10158 // and use SETCC instead.
10159 if (isUnsupportedFloatingType(LHS.getValueType())) {
10160 DAG.getTargetLoweringInfo().softenSetCCOperands(
10161 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling);
10162 if (!RHS.getNode()) {
10163 RHS = DAG.getConstant(0, dl, LHS.getValueType());
10164 CC = ISD::SETNE;
10165 }
10166 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
10167 DAG.getCondCode(CC));
10168 return DAG.getMergeValues({Result, Chain}, dl);
10169 }
10170
10171 ARMCC::CondCodes CondCode, CondCode2;
10172 FPCCToARMCC(CC, CondCode, CondCode2);
10173
10174 // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit
10175 // in CMPFP and CMPFPE, but instead it should be made explicit by these
10176 // instructions using a chain instead of glue. This would also fix the problem
10177 // here (and also in LowerSELECT_CC) where we generate two comparisons when
10178 // CondCode2 != AL.
10179 SDValue True = DAG.getConstant(1, dl, VT);
10180 SDValue False = DAG.getConstant(0, dl, VT);
10181 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
10182 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
10183 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10184 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG);
10185 if (CondCode2 != ARMCC::AL) {
10186 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
10187 Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10188 Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG);
10189 }
10190 return DAG.getMergeValues({Result, Chain}, dl);
10191}
10192
10193SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10194 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "Lowering node: "; Op.dump();
} } while (false)
;
10195 switch (Op.getOpcode()) {
10196 default: llvm_unreachable("Don't know how to custom lower this!")::llvm::llvm_unreachable_internal("Don't know how to custom lower this!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10196)
;
10197 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
10198 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10199 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10200 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10201 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10202 case ISD::SELECT: return LowerSELECT(Op, DAG);
10203 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
10204 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10205 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
10206 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
10207 case ISD::VASTART: return LowerVASTART(Op, DAG);
10208 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
10209 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
10210 case ISD::SINT_TO_FP:
10211 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
10212 case ISD::STRICT_FP_TO_SINT:
10213 case ISD::STRICT_FP_TO_UINT:
10214 case ISD::FP_TO_SINT:
10215 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
10216 case ISD::FP_TO_SINT_SAT:
10217 case ISD::FP_TO_UINT_SAT: return LowerFP_TO_INT_SAT(Op, DAG, Subtarget);
10218 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10219 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10220 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10221 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
10222 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
10223 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
10224 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
10225 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
10226 Subtarget);
10227 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
10228 case ISD::SHL:
10229 case ISD::SRL:
10230 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
10231 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
10232 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
10233 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
10234 case ISD::SRL_PARTS:
10235 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
10236 case ISD::CTTZ:
10237 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
10238 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
10239 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
10240 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
10241 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
10242 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
10243 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
10244 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
10245 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10246 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
10247 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
10248 case ISD::TRUNCATE: return LowerTruncate(Op.getNode(), DAG, Subtarget);
10249 case ISD::SIGN_EXTEND:
10250 case ISD::ZERO_EXTEND: return LowerVectorExtend(Op.getNode(), DAG, Subtarget);
10251 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10252 case ISD::SET_ROUNDING: return LowerSET_ROUNDING(Op, DAG);
10253 case ISD::MUL: return LowerMUL(Op, DAG);
10254 case ISD::SDIV:
10255 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
10256 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
10257 return LowerSDIV(Op, DAG, Subtarget);
10258 case ISD::UDIV:
10259 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
10260 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
10261 return LowerUDIV(Op, DAG, Subtarget);
10262 case ISD::ADDCARRY:
10263 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
10264 case ISD::SADDO:
10265 case ISD::SSUBO:
10266 return LowerSignedALUO(Op, DAG);
10267 case ISD::UADDO:
10268 case ISD::USUBO:
10269 return LowerUnsignedALUO(Op, DAG);
10270 case ISD::SADDSAT:
10271 case ISD::SSUBSAT:
10272 case ISD::UADDSAT:
10273 case ISD::USUBSAT:
10274 return LowerADDSUBSAT(Op, DAG, Subtarget);
10275 case ISD::LOAD:
10276 return LowerPredicateLoad(Op, DAG);
10277 case ISD::STORE:
10278 return LowerSTORE(Op, DAG, Subtarget);
10279 case ISD::MLOAD:
10280 return LowerMLOAD(Op, DAG);
10281 case ISD::VECREDUCE_MUL:
10282 case ISD::VECREDUCE_AND:
10283 case ISD::VECREDUCE_OR:
10284 case ISD::VECREDUCE_XOR:
10285 return LowerVecReduce(Op, DAG, Subtarget);
10286 case ISD::VECREDUCE_FADD:
10287 case ISD::VECREDUCE_FMUL:
10288 case ISD::VECREDUCE_FMIN:
10289 case ISD::VECREDUCE_FMAX:
10290 return LowerVecReduceF(Op, DAG, Subtarget);
10291 case ISD::ATOMIC_LOAD:
10292 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
10293 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
10294 case ISD::SDIVREM:
10295 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
10296 case ISD::DYNAMIC_STACKALLOC:
10297 if (Subtarget->isTargetWindows())
10298 return LowerDYNAMIC_STACKALLOC(Op, DAG);
10299 llvm_unreachable("Don't know how to custom lower this!")::llvm::llvm_unreachable_internal("Don't know how to custom lower this!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10299)
;
10300 case ISD::STRICT_FP_ROUND:
10301 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
10302 case ISD::STRICT_FP_EXTEND:
10303 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
10304 case ISD::STRICT_FSETCC:
10305 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
10306 case ARMISD::WIN__DBZCHK: return SDValue();
10307 }
10308}
10309
10310static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
10311 SelectionDAG &DAG) {
10312 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10313 unsigned Opc = 0;
10314 if (IntNo == Intrinsic::arm_smlald)
10315 Opc = ARMISD::SMLALD;
10316 else if (IntNo == Intrinsic::arm_smlaldx)
10317 Opc = ARMISD::SMLALDX;
10318 else if (IntNo == Intrinsic::arm_smlsld)
10319 Opc = ARMISD::SMLSLD;
10320 else if (IntNo == Intrinsic::arm_smlsldx)
10321 Opc = ARMISD::SMLSLDX;
10322 else
10323 return;
10324
10325 SDLoc dl(N);
10326 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10327 N->getOperand(3),
10328 DAG.getConstant(0, dl, MVT::i32));
10329 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10330 N->getOperand(3),
10331 DAG.getConstant(1, dl, MVT::i32));
10332
10333 SDValue LongMul = DAG.getNode(Opc, dl,
10334 DAG.getVTList(MVT::i32, MVT::i32),
10335 N->getOperand(1), N->getOperand(2),
10336 Lo, Hi);
10337 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
10338 LongMul.getValue(0), LongMul.getValue(1)));
10339}
10340
10341/// ReplaceNodeResults - Replace the results of node with an illegal result
10342/// type with new values built out of custom code.
10343void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
10344 SmallVectorImpl<SDValue> &Results,
10345 SelectionDAG &DAG) const {
10346 SDValue Res;
10347 switch (N->getOpcode()) {
10348 default:
10349 llvm_unreachable("Don't know how to custom expand this!")::llvm::llvm_unreachable_internal("Don't know how to custom expand this!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10349)
;
10350 case ISD::READ_REGISTER:
10351 ExpandREAD_REGISTER(N, Results, DAG);
10352 break;
10353 case ISD::BITCAST:
10354 Res = ExpandBITCAST(N, DAG, Subtarget);
10355 break;
10356 case ISD::SRL:
10357 case ISD::SRA:
10358 case ISD::SHL:
10359 Res = Expand64BitShift(N, DAG, Subtarget);
10360 break;
10361 case ISD::SREM:
10362 case ISD::UREM:
10363 Res = LowerREM(N, DAG);
10364 break;
10365 case ISD::SDIVREM:
10366 case ISD::UDIVREM:
10367 Res = LowerDivRem(SDValue(N, 0), DAG);
10368 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10368, __extension__ __PRETTY_FUNCTION__))
;
10369 Results.push_back(Res.getValue(0));
10370 Results.push_back(Res.getValue(1));
10371 return;
10372 case ISD::SADDSAT:
10373 case ISD::SSUBSAT:
10374 case ISD::UADDSAT:
10375 case ISD::USUBSAT:
10376 Res = LowerADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
10377 break;
10378 case ISD::READCYCLECOUNTER:
10379 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
10380 return;
10381 case ISD::UDIV:
10382 case ISD::SDIV:
10383 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10383, __extension__ __PRETTY_FUNCTION__))
;
10384 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
10385 Results);
10386 case ISD::ATOMIC_CMP_SWAP:
10387 ReplaceCMP_SWAP_64Results(N, Results, DAG);
10388 return;
10389 case ISD::INTRINSIC_WO_CHAIN:
10390 return ReplaceLongIntrinsic(N, Results, DAG);
10391 case ISD::ABS:
10392 lowerABS(N, Results, DAG);
10393 return ;
10394 case ISD::LOAD:
10395 LowerLOAD(N, Results, DAG);
10396 break;
10397 case ISD::TRUNCATE:
10398 Res = LowerTruncate(N, DAG, Subtarget);
10399 break;
10400 case ISD::SIGN_EXTEND:
10401 case ISD::ZERO_EXTEND:
10402 Res = LowerVectorExtend(N, DAG, Subtarget);
10403 break;
10404 case ISD::FP_TO_SINT_SAT:
10405 case ISD::FP_TO_UINT_SAT:
10406 Res = LowerFP_TO_INT_SAT(SDValue(N, 0), DAG, Subtarget);
10407 break;
10408 }
10409 if (Res.getNode())
10410 Results.push_back(Res);
10411}
10412
10413//===----------------------------------------------------------------------===//
10414// ARM Scheduler Hooks
10415//===----------------------------------------------------------------------===//
10416
10417/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
10418/// registers the function context.
10419void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
10420 MachineBasicBlock *MBB,
10421 MachineBasicBlock *DispatchBB,
10422 int FI) const {
10423 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10424, __extension__ __PRETTY_FUNCTION__))
10424 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10424, __extension__ __PRETTY_FUNCTION__))
;
10425 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10426 DebugLoc dl = MI.getDebugLoc();
10427 MachineFunction *MF = MBB->getParent();
10428 MachineRegisterInfo *MRI = &MF->getRegInfo();
10429 MachineConstantPool *MCP = MF->getConstantPool();
10430 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
10431 const Function &F = MF->getFunction();
10432
10433 bool isThumb = Subtarget->isThumb();
10434 bool isThumb2 = Subtarget->isThumb2();
10435
10436 unsigned PCLabelId = AFI->createPICLabelUId();
10437 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
10438 ARMConstantPoolValue *CPV =
10439 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
10440 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
10441
10442 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
10443 : &ARM::GPRRegClass;
10444
10445 // Grab constant pool and fixed stack memory operands.
10446 MachineMemOperand *CPMMO =
10447 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10448 MachineMemOperand::MOLoad, 4, Align(4));
10449
10450 MachineMemOperand *FIMMOSt =
10451 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
10452 MachineMemOperand::MOStore, 4, Align(4));
10453
10454 // Load the address of the dispatch MBB into the jump buffer.
10455 if (isThumb2) {
10456 // Incoming value: jbuf
10457 // ldr.n r5, LCPI1_1
10458 // orr r5, r5, #1
10459 // add r5, pc
10460 // str r5, [$jbuf, #+4] ; &jbuf[1]
10461 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10462 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
10463 .addConstantPoolIndex(CPI)
10464 .addMemOperand(CPMMO)
10465 .add(predOps(ARMCC::AL));
10466 // Set the low bit because of thumb mode.
10467 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10468 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
10469 .addReg(NewVReg1, RegState::Kill)
10470 .addImm(0x01)
10471 .add(predOps(ARMCC::AL))
10472 .add(condCodeOp());
10473 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10474 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
10475 .addReg(NewVReg2, RegState::Kill)
10476 .addImm(PCLabelId);
10477 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
10478 .addReg(NewVReg3, RegState::Kill)
10479 .addFrameIndex(FI)
10480 .addImm(36) // &jbuf[1] :: pc
10481 .addMemOperand(FIMMOSt)
10482 .add(predOps(ARMCC::AL));
10483 } else if (isThumb) {
10484 // Incoming value: jbuf
10485 // ldr.n r1, LCPI1_4
10486 // add r1, pc
10487 // mov r2, #1
10488 // orrs r1, r2
10489 // add r2, $jbuf, #+4 ; &jbuf[1]
10490 // str r1, [r2]
10491 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10492 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
10493 .addConstantPoolIndex(CPI)
10494 .addMemOperand(CPMMO)
10495 .add(predOps(ARMCC::AL));
10496 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10497 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
10498 .addReg(NewVReg1, RegState::Kill)
10499 .addImm(PCLabelId);
10500 // Set the low bit because of thumb mode.
10501 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10502 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
10503 .addReg(ARM::CPSR, RegState::Define)
10504 .addImm(1)
10505 .add(predOps(ARMCC::AL));
10506 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10507 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10508 .addReg(ARM::CPSR, RegState::Define)
10509 .addReg(NewVReg2, RegState::Kill)
10510 .addReg(NewVReg3, RegState::Kill)
10511 .add(predOps(ARMCC::AL));
10512 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10513 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10514 .addFrameIndex(FI)
10515 .addImm(36); // &jbuf[1] :: pc
10516 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10517 .addReg(NewVReg4, RegState::Kill)
10518 .addReg(NewVReg5, RegState::Kill)
10519 .addImm(0)
10520 .addMemOperand(FIMMOSt)
10521 .add(predOps(ARMCC::AL));
10522 } else {
10523 // Incoming value: jbuf
10524 // ldr r1, LCPI1_1
10525 // add r1, pc, r1
10526 // str r1, [$jbuf, #+4] ; &jbuf[1]
10527 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10528 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10529 .addConstantPoolIndex(CPI)
10530 .addImm(0)
10531 .addMemOperand(CPMMO)
10532 .add(predOps(ARMCC::AL));
10533 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10534 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10535 .addReg(NewVReg1, RegState::Kill)
10536 .addImm(PCLabelId)
10537 .add(predOps(ARMCC::AL));
10538 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10539 .addReg(NewVReg2, RegState::Kill)
10540 .addFrameIndex(FI)
10541 .addImm(36) // &jbuf[1] :: pc
10542 .addMemOperand(FIMMOSt)
10543 .add(predOps(ARMCC::AL));
10544 }
10545}
10546
10547void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10548 MachineBasicBlock *MBB) const {
10549 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10550 DebugLoc dl = MI.getDebugLoc();
10551 MachineFunction *MF = MBB->getParent();
10552 MachineRegisterInfo *MRI = &MF->getRegInfo();
10553 MachineFrameInfo &MFI = MF->getFrameInfo();
10554 int FI = MFI.getFunctionContextIndex();
10555
10556 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10557 : &ARM::GPRnopcRegClass;
10558
10559 // Get a mapping of the call site numbers to all of the landing pads they're
10560 // associated with.
10561 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10562 unsigned MaxCSNum = 0;
10563 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
10564 ++BB) {
10565 if (!BB->isEHPad()) continue;
10566
10567 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10568 // pad.
10569 for (MachineBasicBlock::iterator
10570 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
10571 if (!II->isEHLabel()) continue;
10572
10573 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
10574 if (!MF->hasCallSiteLandingPad(Sym)) continue;
10575
10576 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10577 for (SmallVectorImpl<unsigned>::iterator
10578 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
10579 CSI != CSE; ++CSI) {
10580 CallSiteNumToLPad[*CSI].push_back(&*BB);
10581 MaxCSNum = std::max(MaxCSNum, *CSI);
10582 }
10583 break;
10584 }
10585 }
10586
10587 // Get an ordered list of the machine basic blocks for the jump table.
10588 std::vector<MachineBasicBlock*> LPadList;
10589 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10590 LPadList.reserve(CallSiteNumToLPad.size());
10591 for (unsigned I = 1; I <= MaxCSNum; ++I) {
10592 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10593 for (SmallVectorImpl<MachineBasicBlock*>::iterator
10594 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
10595 LPadList.push_back(*II);
10596 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
10597 }
10598 }
10599
10600 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10601, __extension__ __PRETTY_FUNCTION__))
10601 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10601, __extension__ __PRETTY_FUNCTION__))
;
10602
10603 // Create the jump table and associated information.
10604 MachineJumpTableInfo *JTI =
10605 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
10606 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
10607
10608 // Create the MBBs for the dispatch code.
10609
10610 // Shove the dispatch's address into the return slot in the function context.
10611 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10612 DispatchBB->setIsEHPad();
10613
10614 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10615 unsigned trap_opcode;
10616 if (Subtarget->isThumb())
10617 trap_opcode = ARM::tTRAP;
10618 else
10619 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
10620
10621 BuildMI(TrapBB, dl, TII->get(trap_opcode));
10622 DispatchBB->addSuccessor(TrapBB);
10623
10624 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10625 DispatchBB->addSuccessor(DispContBB);
10626
10627 // Insert and MBBs.
10628 MF->insert(MF->end(), DispatchBB);
10629 MF->insert(MF->end(), DispContBB);
10630 MF->insert(MF->end(), TrapBB);
10631
10632 // Insert code into the entry block that creates and registers the function
10633 // context.
10634 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10635
10636 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10637 MachinePointerInfo::getFixedStack(*MF, FI),
10638 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
10639
10640 MachineInstrBuilder MIB;
10641 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
10642
10643 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10644 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10645
10646 // Add a register mask with no preserved registers. This results in all
10647 // registers being marked as clobbered. This can't work if the dispatch block
10648 // is in a Thumb1 function and is linked with ARM code which uses the FP
10649 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10650 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
10651
10652 bool IsPositionIndependent = isPositionIndependent();
10653 unsigned NumLPads = LPadList.size();
10654 if (Subtarget->isThumb2()) {
10655 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10656 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
10657 .addFrameIndex(FI)
10658 .addImm(4)
10659 .addMemOperand(FIMMOLd)
10660 .add(predOps(ARMCC::AL));
10661
10662 if (NumLPads < 256) {
10663 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
10664 .addReg(NewVReg1)
10665 .addImm(LPadList.size())
10666 .add(predOps(ARMCC::AL));
10667 } else {
10668 Register VReg1 = MRI->createVirtualRegister(TRC);
10669 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
10670 .addImm(NumLPads & 0xFFFF)
10671 .add(predOps(ARMCC::AL));
10672
10673 unsigned VReg2 = VReg1;
10674 if ((NumLPads & 0xFFFF0000) != 0) {
10675 VReg2 = MRI->createVirtualRegister(TRC);
10676 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
10677 .addReg(VReg1)
10678 .addImm(NumLPads >> 16)
10679 .add(predOps(ARMCC::AL));
10680 }
10681
10682 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
10683 .addReg(NewVReg1)
10684 .addReg(VReg2)
10685 .add(predOps(ARMCC::AL));
10686 }
10687
10688 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
10689 .addMBB(TrapBB)
10690 .addImm(ARMCC::HI)
10691 .addReg(ARM::CPSR);
10692
10693 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10694 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
10695 .addJumpTableIndex(MJTI)
10696 .add(predOps(ARMCC::AL));
10697
10698 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10699 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
10700 .addReg(NewVReg3, RegState::Kill)
10701 .addReg(NewVReg1)
10702 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10703 .add(predOps(ARMCC::AL))
10704 .add(condCodeOp());
10705
10706 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
10707 .addReg(NewVReg4, RegState::Kill)
10708 .addReg(NewVReg1)
10709 .addJumpTableIndex(MJTI);
10710 } else if (Subtarget->isThumb()) {
10711 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10712 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
10713 .addFrameIndex(FI)
10714 .addImm(1)
10715 .addMemOperand(FIMMOLd)
10716 .add(predOps(ARMCC::AL));
10717
10718 if (NumLPads < 256) {
10719 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
10720 .addReg(NewVReg1)
10721 .addImm(NumLPads)
10722 .add(predOps(ARMCC::AL));
10723 } else {
10724 MachineConstantPool *ConstantPool = MF->getConstantPool();
10725 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10726 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10727
10728 // MachineConstantPool wants an explicit alignment.
10729 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10730 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10731
10732 Register VReg1 = MRI->createVirtualRegister(TRC);
10733 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
10734 .addReg(VReg1, RegState::Define)
10735 .addConstantPoolIndex(Idx)
10736 .add(predOps(ARMCC::AL));
10737 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
10738 .addReg(NewVReg1)
10739 .addReg(VReg1)
10740 .add(predOps(ARMCC::AL));
10741 }
10742
10743 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
10744 .addMBB(TrapBB)
10745 .addImm(ARMCC::HI)
10746 .addReg(ARM::CPSR);
10747
10748 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10749 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
10750 .addReg(ARM::CPSR, RegState::Define)
10751 .addReg(NewVReg1)
10752 .addImm(2)
10753 .add(predOps(ARMCC::AL));
10754
10755 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10756 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
10757 .addJumpTableIndex(MJTI)
10758 .add(predOps(ARMCC::AL));
10759
10760 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10761 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
10762 .addReg(ARM::CPSR, RegState::Define)
10763 .addReg(NewVReg2, RegState::Kill)
10764 .addReg(NewVReg3)
10765 .add(predOps(ARMCC::AL));
10766
10767 MachineMemOperand *JTMMOLd =
10768 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10769 MachineMemOperand::MOLoad, 4, Align(4));
10770
10771 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10772 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
10773 .addReg(NewVReg4, RegState::Kill)
10774 .addImm(0)
10775 .addMemOperand(JTMMOLd)
10776 .add(predOps(ARMCC::AL));
10777
10778 unsigned NewVReg6 = NewVReg5;
10779 if (IsPositionIndependent) {
10780 NewVReg6 = MRI->createVirtualRegister(TRC);
10781 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
10782 .addReg(ARM::CPSR, RegState::Define)
10783 .addReg(NewVReg5, RegState::Kill)
10784 .addReg(NewVReg3)
10785 .add(predOps(ARMCC::AL));
10786 }
10787
10788 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
10789 .addReg(NewVReg6, RegState::Kill)
10790 .addJumpTableIndex(MJTI);
10791 } else {
10792 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10793 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
10794 .addFrameIndex(FI)
10795 .addImm(4)
10796 .addMemOperand(FIMMOLd)
10797 .add(predOps(ARMCC::AL));
10798
10799 if (NumLPads < 256) {
10800 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
10801 .addReg(NewVReg1)
10802 .addImm(NumLPads)
10803 .add(predOps(ARMCC::AL));
10804 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
10805 Register VReg1 = MRI->createVirtualRegister(TRC);
10806 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
10807 .addImm(NumLPads & 0xFFFF)
10808 .add(predOps(ARMCC::AL));
10809
10810 unsigned VReg2 = VReg1;
10811 if ((NumLPads & 0xFFFF0000) != 0) {
10812 VReg2 = MRI->createVirtualRegister(TRC);
10813 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
10814 .addReg(VReg1)
10815 .addImm(NumLPads >> 16)
10816 .add(predOps(ARMCC::AL));
10817 }
10818
10819 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10820 .addReg(NewVReg1)
10821 .addReg(VReg2)
10822 .add(predOps(ARMCC::AL));
10823 } else {
10824 MachineConstantPool *ConstantPool = MF->getConstantPool();
10825 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10826 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10827
10828 // MachineConstantPool wants an explicit alignment.
10829 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10830 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10831
10832 Register VReg1 = MRI->createVirtualRegister(TRC);
10833 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
10834 .addReg(VReg1, RegState::Define)
10835 .addConstantPoolIndex(Idx)
10836 .addImm(0)
10837 .add(predOps(ARMCC::AL));
10838 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10839 .addReg(NewVReg1)
10840 .addReg(VReg1, RegState::Kill)
10841 .add(predOps(ARMCC::AL));
10842 }
10843
10844 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
10845 .addMBB(TrapBB)
10846 .addImm(ARMCC::HI)
10847 .addReg(ARM::CPSR);
10848
10849 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10850 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
10851 .addReg(NewVReg1)
10852 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10853 .add(predOps(ARMCC::AL))
10854 .add(condCodeOp());
10855 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10856 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
10857 .addJumpTableIndex(MJTI)
10858 .add(predOps(ARMCC::AL));
10859
10860 MachineMemOperand *JTMMOLd =
10861 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10862 MachineMemOperand::MOLoad, 4, Align(4));
10863 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10864 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
10865 .addReg(NewVReg3, RegState::Kill)
10866 .addReg(NewVReg4)
10867 .addImm(0)
10868 .addMemOperand(JTMMOLd)
10869 .add(predOps(ARMCC::AL));
10870
10871 if (IsPositionIndependent) {
10872 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
10873 .addReg(NewVReg5, RegState::Kill)
10874 .addReg(NewVReg4)
10875 .addJumpTableIndex(MJTI);
10876 } else {
10877 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
10878 .addReg(NewVReg5, RegState::Kill)
10879 .addJumpTableIndex(MJTI);
10880 }
10881 }
10882
10883 // Add the jump table entries as successors to the MBB.
10884 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
10885 for (std::vector<MachineBasicBlock*>::iterator
10886 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
10887 MachineBasicBlock *CurMBB = *I;
10888 if (SeenMBBs.insert(CurMBB).second)
10889 DispContBB->addSuccessor(CurMBB);
10890 }
10891
10892 // N.B. the order the invoke BBs are processed in doesn't matter here.
10893 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
10894 SmallVector<MachineBasicBlock*, 64> MBBLPads;
10895 for (MachineBasicBlock *BB : InvokeBBs) {
10896
10897 // Remove the landing pad successor from the invoke block and replace it
10898 // with the new dispatch block.
10899 SmallVector<MachineBasicBlock*, 4> Successors(BB->successors());
10900 while (!Successors.empty()) {
10901 MachineBasicBlock *SMBB = Successors.pop_back_val();
10902 if (SMBB->isEHPad()) {
10903 BB->removeSuccessor(SMBB);
10904 MBBLPads.push_back(SMBB);
10905 }
10906 }
10907
10908 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
10909 BB->normalizeSuccProbs();
10910
10911 // Find the invoke call and mark all of the callee-saved registers as
10912 // 'implicit defined' so that they're spilled. This prevents code from
10913 // moving instructions to before the EH block, where they will never be
10914 // executed.
10915 for (MachineBasicBlock::reverse_iterator
10916 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
10917 if (!II->isCall()) continue;
10918
10919 DenseMap<unsigned, bool> DefRegs;
10920 for (MachineInstr::mop_iterator
10921 OI = II->operands_begin(), OE = II->operands_end();
10922 OI != OE; ++OI) {
10923 if (!OI->isReg()) continue;
10924 DefRegs[OI->getReg()] = true;
10925 }
10926
10927 MachineInstrBuilder MIB(*MF, &*II);
10928
10929 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
10930 unsigned Reg = SavedRegs[i];
10931 if (Subtarget->isThumb2() &&
10932 !ARM::tGPRRegClass.contains(Reg) &&
10933 !ARM::hGPRRegClass.contains(Reg))
10934 continue;
10935 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
10936 continue;
10937 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
10938 continue;
10939 if (!DefRegs[Reg])
10940 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
10941 }
10942
10943 break;
10944 }
10945 }
10946
10947 // Mark all former landing pads as non-landing pads. The dispatch is the only
10948 // landing pad now.
10949 for (SmallVectorImpl<MachineBasicBlock*>::iterator
10950 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
10951 (*I)->setIsEHPad(false);
10952
10953 // The instruction is gone now.
10954 MI.eraseFromParent();
10955}
10956
10957static
10958MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
10959 for (MachineBasicBlock *S : MBB->successors())
10960 if (S != Succ)
10961 return S;
10962 llvm_unreachable("Expecting a BB with two successors!")::llvm::llvm_unreachable_internal("Expecting a BB with two successors!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10962)
;
10963}
10964
10965/// Return the load opcode for a given load size. If load size >= 8,
10966/// neon opcode will be returned.
10967static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
10968 if (LdSize >= 8)
10969 return LdSize == 16 ? ARM::VLD1q32wb_fixed
10970 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
10971 if (IsThumb1)
10972 return LdSize == 4 ? ARM::tLDRi
10973 : LdSize == 2 ? ARM::tLDRHi
10974 : LdSize == 1 ? ARM::tLDRBi : 0;
10975 if (IsThumb2)
10976 return LdSize == 4 ? ARM::t2LDR_POST
10977 : LdSize == 2 ? ARM::t2LDRH_POST
10978 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
10979 return LdSize == 4 ? ARM::LDR_POST_IMM
10980 : LdSize == 2 ? ARM::LDRH_POST
10981 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
10982}
10983
10984/// Return the store opcode for a given store size. If store size >= 8,
10985/// neon opcode will be returned.
10986static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
10987 if (StSize >= 8)
10988 return StSize == 16 ? ARM::VST1q32wb_fixed
10989 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
10990 if (IsThumb1)
10991 return StSize == 4 ? ARM::tSTRi
10992 : StSize == 2 ? ARM::tSTRHi
10993 : StSize == 1 ? ARM::tSTRBi : 0;
10994 if (IsThumb2)
10995 return StSize == 4 ? ARM::t2STR_POST
10996 : StSize == 2 ? ARM::t2STRH_POST
10997 : StSize == 1 ? ARM::t2STRB_POST : 0;
10998 return StSize == 4 ? ARM::STR_POST_IMM
10999 : StSize == 2 ? ARM::STRH_POST
11000 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
11001}
11002
11003/// Emit a post-increment load operation with given size. The instructions
11004/// will be added to BB at Pos.
11005static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11006 const TargetInstrInfo *TII, const DebugLoc &dl,
11007 unsigned LdSize, unsigned Data, unsigned AddrIn,
11008 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11009 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
11010 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11010, __extension__ __PRETTY_FUNCTION__))
;
11011 if (LdSize >= 8) {
11012 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11013 .addReg(AddrOut, RegState::Define)
11014 .addReg(AddrIn)
11015 .addImm(0)
11016 .add(predOps(ARMCC::AL));
11017 } else if (IsThumb1) {
11018 // load + update AddrIn
11019 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11020 .addReg(AddrIn)
11021 .addImm(0)
11022 .add(predOps(ARMCC::AL));
11023 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11024 .add(t1CondCodeOp())
11025 .addReg(AddrIn)
11026 .addImm(LdSize)
11027 .add(predOps(ARMCC::AL));
11028 } else if (IsThumb2) {
11029 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11030 .addReg(AddrOut, RegState::Define)
11031 .addReg(AddrIn)
11032 .addImm(LdSize)
11033 .add(predOps(ARMCC::AL));
11034 } else { // arm
11035 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11036 .addReg(AddrOut, RegState::Define)
11037 .addReg(AddrIn)
11038 .addReg(0)
11039 .addImm(LdSize)
11040 .add(predOps(ARMCC::AL));
11041 }
11042}
11043
11044/// Emit a post-increment store operation with given size. The instructions
11045/// will be added to BB at Pos.
11046static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11047 const TargetInstrInfo *TII, const DebugLoc &dl,
11048 unsigned StSize, unsigned Data, unsigned AddrIn,
11049 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11050 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
11051 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11051, __extension__ __PRETTY_FUNCTION__))
;
11052 if (StSize >= 8) {
11053 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11054 .addReg(AddrIn)
11055 .addImm(0)
11056 .addReg(Data)
11057 .add(predOps(ARMCC::AL));
11058 } else if (IsThumb1) {
11059 // store + update AddrIn
11060 BuildMI(*BB, Pos, dl, TII->get(StOpc))
11061 .addReg(Data)
11062 .addReg(AddrIn)
11063 .addImm(0)
11064 .add(predOps(ARMCC::AL));
11065 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11066 .add(t1CondCodeOp())
11067 .addReg(AddrIn)
11068 .addImm(StSize)
11069 .add(predOps(ARMCC::AL));
11070 } else if (IsThumb2) {
11071 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11072 .addReg(Data)
11073 .addReg(AddrIn)
11074 .addImm(StSize)
11075 .add(predOps(ARMCC::AL));
11076 } else { // arm
11077 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11078 .addReg(Data)
11079 .addReg(AddrIn)
11080 .addReg(0)
11081 .addImm(StSize)
11082 .add(predOps(ARMCC::AL));
11083 }
11084}
11085
11086MachineBasicBlock *
11087ARMTargetLowering::EmitStructByval(MachineInstr &MI,
11088 MachineBasicBlock *BB) const {
11089 // This pseudo instruction has 3 operands: dst, src, size
11090 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
11091 // Otherwise, we will generate unrolled scalar copies.
11092 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11093 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11094 MachineFunction::iterator It = ++BB->getIterator();
11095
11096 Register dest = MI.getOperand(0).getReg();
11097 Register src = MI.getOperand(1).getReg();
11098 unsigned SizeVal = MI.getOperand(2).getImm();
11099 unsigned Alignment = MI.getOperand(3).getImm();
11100 DebugLoc dl = MI.getDebugLoc();
11101
11102 MachineFunction *MF = BB->getParent();
11103 MachineRegisterInfo &MRI = MF->getRegInfo();
11104 unsigned UnitSize = 0;
11105 const TargetRegisterClass *TRC = nullptr;
11106 const TargetRegisterClass *VecTRC = nullptr;
11107
11108 bool IsThumb1 = Subtarget->isThumb1Only();
11109 bool IsThumb2 = Subtarget->isThumb2();
11110 bool IsThumb = Subtarget->isThumb();
11111
11112 if (Alignment & 1) {
11113 UnitSize = 1;
11114 } else if (Alignment & 2) {
11115 UnitSize = 2;
11116 } else {
11117 // Check whether we can use NEON instructions.
11118 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
11119 Subtarget->hasNEON()) {
11120 if ((Alignment % 16 == 0) && SizeVal >= 16)
11121 UnitSize = 16;
11122 else if ((Alignment % 8 == 0) && SizeVal >= 8)
11123 UnitSize = 8;
11124 }
11125 // Can't use NEON instructions.
11126 if (UnitSize == 0)
11127 UnitSize = 4;
11128 }
11129
11130 // Select the correct opcode and register class for unit size load/store
11131 bool IsNeon = UnitSize >= 8;
11132 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
11133 if (IsNeon)
11134 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
11135 : UnitSize == 8 ? &ARM::DPRRegClass
11136 : nullptr;
11137
11138 unsigned BytesLeft = SizeVal % UnitSize;
11139 unsigned LoopSize = SizeVal - BytesLeft;
11140
11141 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
11142 // Use LDR and STR to copy.
11143 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
11144 // [destOut] = STR_POST(scratch, destIn, UnitSize)
11145 unsigned srcIn = src;
11146 unsigned destIn = dest;
11147 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
11148 Register srcOut = MRI.createVirtualRegister(TRC);
11149 Register destOut = MRI.createVirtualRegister(TRC);
11150 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11151 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
11152 IsThumb1, IsThumb2);
11153 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
11154 IsThumb1, IsThumb2);
11155 srcIn = srcOut;
11156 destIn = destOut;
11157 }
11158
11159 // Handle the leftover bytes with LDRB and STRB.
11160 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
11161 // [destOut] = STRB_POST(scratch, destIn, 1)
11162 for (unsigned i = 0; i < BytesLeft; i++) {
11163 Register srcOut = MRI.createVirtualRegister(TRC);
11164 Register destOut = MRI.createVirtualRegister(TRC);
11165 Register scratch = MRI.createVirtualRegister(TRC);
11166 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
11167 IsThumb1, IsThumb2);
11168 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
11169 IsThumb1, IsThumb2);
11170 srcIn = srcOut;
11171 destIn = destOut;
11172 }
11173 MI.eraseFromParent(); // The instruction is gone now.
11174 return BB;
11175 }
11176
11177 // Expand the pseudo op to a loop.
11178 // thisMBB:
11179 // ...
11180 // movw varEnd, # --> with thumb2
11181 // movt varEnd, #
11182 // ldrcp varEnd, idx --> without thumb2
11183 // fallthrough --> loopMBB
11184 // loopMBB:
11185 // PHI varPhi, varEnd, varLoop
11186 // PHI srcPhi, src, srcLoop
11187 // PHI destPhi, dst, destLoop
11188 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11189 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
11190 // subs varLoop, varPhi, #UnitSize
11191 // bne loopMBB
11192 // fallthrough --> exitMBB
11193 // exitMBB:
11194 // epilogue to handle left-over bytes
11195 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11196 // [destOut] = STRB_POST(scratch, destLoop, 1)
11197 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11198 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11199 MF->insert(It, loopMBB);
11200 MF->insert(It, exitMBB);
11201
11202 // Transfer the remainder of BB and its successor edges to exitMBB.
11203 exitMBB->splice(exitMBB->begin(), BB,
11204 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11205 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11206
11207 // Load an immediate to varEnd.
11208 Register varEnd = MRI.createVirtualRegister(TRC);
11209 if (Subtarget->useMovt()) {
11210 unsigned Vtmp = varEnd;
11211 if ((LoopSize & 0xFFFF0000) != 0)
11212 Vtmp = MRI.createVirtualRegister(TRC);
11213 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
11214 .addImm(LoopSize & 0xFFFF)
11215 .add(predOps(ARMCC::AL));
11216
11217 if ((LoopSize & 0xFFFF0000) != 0)
11218 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
11219 .addReg(Vtmp)
11220 .addImm(LoopSize >> 16)
11221 .add(predOps(ARMCC::AL));
11222 } else {
11223 MachineConstantPool *ConstantPool = MF->getConstantPool();
11224 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11225 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
11226
11227 // MachineConstantPool wants an explicit alignment.
11228 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11229 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11230 MachineMemOperand *CPMMO =
11231 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
11232 MachineMemOperand::MOLoad, 4, Align(4));
11233
11234 if (IsThumb)
11235 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
11236 .addReg(varEnd, RegState::Define)
11237 .addConstantPoolIndex(Idx)
11238 .add(predOps(ARMCC::AL))
11239 .addMemOperand(CPMMO);
11240 else
11241 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
11242 .addReg(varEnd, RegState::Define)
11243 .addConstantPoolIndex(Idx)
11244 .addImm(0)
11245 .add(predOps(ARMCC::AL))
11246 .addMemOperand(CPMMO);
11247 }
11248 BB->addSuccessor(loopMBB);
11249
11250 // Generate the loop body:
11251 // varPhi = PHI(varLoop, varEnd)
11252 // srcPhi = PHI(srcLoop, src)
11253 // destPhi = PHI(destLoop, dst)
11254 MachineBasicBlock *entryBB = BB;
11255 BB = loopMBB;
11256 Register varLoop = MRI.createVirtualRegister(TRC);
11257 Register varPhi = MRI.createVirtualRegister(TRC);
11258 Register srcLoop = MRI.createVirtualRegister(TRC);
11259 Register srcPhi = MRI.createVirtualRegister(TRC);
11260 Register destLoop = MRI.createVirtualRegister(TRC);
11261 Register destPhi = MRI.createVirtualRegister(TRC);
11262
11263 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
11264 .addReg(varLoop).addMBB(loopMBB)
11265 .addReg(varEnd).addMBB(entryBB);
11266 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
11267 .addReg(srcLoop).addMBB(loopMBB)
11268 .addReg(src).addMBB(entryBB);
11269 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
11270 .addReg(destLoop).addMBB(loopMBB)
11271 .addReg(dest).addMBB(entryBB);
11272
11273 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11274 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
11275 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11276 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
11277 IsThumb1, IsThumb2);
11278 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
11279 IsThumb1, IsThumb2);
11280
11281 // Decrement loop variable by UnitSize.
11282 if (IsThumb1) {
11283 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
11284 .add(t1CondCodeOp())
11285 .addReg(varPhi)
11286 .addImm(UnitSize)
11287 .add(predOps(ARMCC::AL));
11288 } else {
11289 MachineInstrBuilder MIB =
11290 BuildMI(*BB, BB->end(), dl,
11291 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
11292 MIB.addReg(varPhi)
11293 .addImm(UnitSize)
11294 .add(predOps(ARMCC::AL))
11295 .add(condCodeOp());
11296 MIB->getOperand(5).setReg(ARM::CPSR);
11297 MIB->getOperand(5).setIsDef(true);
11298 }
11299 BuildMI(*BB, BB->end(), dl,
11300 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
11301 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
11302
11303 // loopMBB can loop back to loopMBB or fall through to exitMBB.
11304 BB->addSuccessor(loopMBB);
11305 BB->addSuccessor(exitMBB);
11306
11307 // Add epilogue to handle BytesLeft.
11308 BB = exitMBB;
11309 auto StartOfExit = exitMBB->begin();
11310
11311 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11312 // [destOut] = STRB_POST(scratch, destLoop, 1)
11313 unsigned srcIn = srcLoop;
11314 unsigned destIn = destLoop;
11315 for (unsigned i = 0; i < BytesLeft; i++) {
11316 Register srcOut = MRI.createVirtualRegister(TRC);
11317 Register destOut = MRI.createVirtualRegister(TRC);
11318 Register scratch = MRI.createVirtualRegister(TRC);
11319 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
11320 IsThumb1, IsThumb2);
11321 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
11322 IsThumb1, IsThumb2);
11323 srcIn = srcOut;
11324 destIn = destOut;
11325 }
11326
11327 MI.eraseFromParent(); // The instruction is gone now.
11328 return BB;
11329}
11330
11331MachineBasicBlock *
11332ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
11333 MachineBasicBlock *MBB) const {
11334 const TargetMachine &TM = getTargetMachine();
11335 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
11336 DebugLoc DL = MI.getDebugLoc();
11337
11338 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11339, __extension__ __PRETTY_FUNCTION__))
11339 "__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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11339, __extension__ __PRETTY_FUNCTION__))
;
11340 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11340, __extension__ __PRETTY_FUNCTION__))
;
11341
11342 // __chkstk takes the number of words to allocate on the stack in R4, and
11343 // returns the stack adjustment in number of bytes in R4. This will not
11344 // clober any other registers (other than the obvious lr).
11345 //
11346 // Although, technically, IP should be considered a register which may be
11347 // clobbered, the call itself will not touch it. Windows on ARM is a pure
11348 // thumb-2 environment, so there is no interworking required. As a result, we
11349 // do not expect a veneer to be emitted by the linker, clobbering IP.
11350 //
11351 // Each module receives its own copy of __chkstk, so no import thunk is
11352 // required, again, ensuring that IP is not clobbered.
11353 //
11354 // Finally, although some linkers may theoretically provide a trampoline for
11355 // out of range calls (which is quite common due to a 32M range limitation of
11356 // branches for Thumb), we can generate the long-call version via
11357 // -mcmodel=large, alleviating the need for the trampoline which may clobber
11358 // IP.
11359
11360 switch (TM.getCodeModel()) {
11361 case CodeModel::Tiny:
11362 llvm_unreachable("Tiny code model not available on ARM.")::llvm::llvm_unreachable_internal("Tiny code model not available on ARM."
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11362)
;
11363 case CodeModel::Small:
11364 case CodeModel::Medium:
11365 case CodeModel::Kernel:
11366 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
11367 .add(predOps(ARMCC::AL))
11368 .addExternalSymbol("__chkstk")
11369 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
11370 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
11371 .addReg(ARM::R12,
11372 RegState::Implicit | RegState::Define | RegState::Dead)
11373 .addReg(ARM::CPSR,
11374 RegState::Implicit | RegState::Define | RegState::Dead);
11375 break;
11376 case CodeModel::Large: {
11377 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11378 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11379
11380 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
11381 .addExternalSymbol("__chkstk");
11382 BuildMI(*MBB, MI, DL, TII.get(gettBLXrOpcode(*MBB->getParent())))
11383 .add(predOps(ARMCC::AL))
11384 .addReg(Reg, RegState::Kill)
11385 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
11386 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
11387 .addReg(ARM::R12,
11388 RegState::Implicit | RegState::Define | RegState::Dead)
11389 .addReg(ARM::CPSR,
11390 RegState::Implicit | RegState::Define | RegState::Dead);
11391 break;
11392 }
11393 }
11394
11395 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
11396 .addReg(ARM::SP, RegState::Kill)
11397 .addReg(ARM::R4, RegState::Kill)
11398 .setMIFlags(MachineInstr::FrameSetup)
11399 .add(predOps(ARMCC::AL))
11400 .add(condCodeOp());
11401
11402 MI.eraseFromParent();
11403 return MBB;
11404}
11405
11406MachineBasicBlock *
11407ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
11408 MachineBasicBlock *MBB) const {
11409 DebugLoc DL = MI.getDebugLoc();
11410 MachineFunction *MF = MBB->getParent();
11411 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11412
11413 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
11414 MF->insert(++MBB->getIterator(), ContBB);
11415 ContBB->splice(ContBB->begin(), MBB,
11416 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11417 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
11418 MBB->addSuccessor(ContBB);
11419
11420 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
11421 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
11422 MF->push_back(TrapBB);
11423 MBB->addSuccessor(TrapBB);
11424
11425 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
11426 .addReg(MI.getOperand(0).getReg())
11427 .addImm(0)
11428 .add(predOps(ARMCC::AL));
11429 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
11430 .addMBB(TrapBB)
11431 .addImm(ARMCC::EQ)
11432 .addReg(ARM::CPSR);
11433
11434 MI.eraseFromParent();
11435 return ContBB;
11436}
11437
11438// The CPSR operand of SelectItr might be missing a kill marker
11439// because there were multiple uses of CPSR, and ISel didn't know
11440// which to mark. Figure out whether SelectItr should have had a
11441// kill marker, and set it if it should. Returns the correct kill
11442// marker value.
11443static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
11444 MachineBasicBlock* BB,
11445 const TargetRegisterInfo* TRI) {
11446 // Scan forward through BB for a use/def of CPSR.
11447 MachineBasicBlock::iterator miI(std::next(SelectItr));
11448 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
11449 const MachineInstr& mi = *miI;
11450 if (mi.readsRegister(ARM::CPSR))
11451 return false;
11452 if (mi.definesRegister(ARM::CPSR))
11453 break; // Should have kill-flag - update below.
11454 }
11455
11456 // If we hit the end of the block, check whether CPSR is live into a
11457 // successor.
11458 if (miI == BB->end()) {
11459 for (MachineBasicBlock *Succ : BB->successors())
11460 if (Succ->isLiveIn(ARM::CPSR))
11461 return false;
11462 }
11463
11464 // We found a def, or hit the end of the basic block and CPSR wasn't live
11465 // out. SelectMI should have a kill flag on CPSR.
11466 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
11467 return true;
11468}
11469
11470/// Adds logic in loop entry MBB to calculate loop iteration count and adds
11471/// t2WhileLoopSetup and t2WhileLoopStart to generate WLS loop
11472static Register genTPEntry(MachineBasicBlock *TpEntry,
11473 MachineBasicBlock *TpLoopBody,
11474 MachineBasicBlock *TpExit, Register OpSizeReg,
11475 const TargetInstrInfo *TII, DebugLoc Dl,
11476 MachineRegisterInfo &MRI) {
11477 // Calculates loop iteration count = ceil(n/16) = (n + 15) >> 4.
11478 Register AddDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11479 BuildMI(TpEntry, Dl, TII->get(ARM::t2ADDri), AddDestReg)
11480 .addUse(OpSizeReg)
11481 .addImm(15)
11482 .add(predOps(ARMCC::AL))
11483 .addReg(0);
11484
11485 Register LsrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11486 BuildMI(TpEntry, Dl, TII->get(ARM::t2LSRri), LsrDestReg)
11487 .addUse(AddDestReg, RegState::Kill)
11488 .addImm(4)
11489 .add(predOps(ARMCC::AL))
11490 .addReg(0);
11491
11492 Register TotalIterationsReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11493 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopSetup), TotalIterationsReg)
11494 .addUse(LsrDestReg, RegState::Kill);
11495
11496 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopStart))
11497 .addUse(TotalIterationsReg)
11498 .addMBB(TpExit);
11499
11500 BuildMI(TpEntry, Dl, TII->get(ARM::t2B))
11501 .addMBB(TpLoopBody)
11502 .add(predOps(ARMCC::AL));
11503
11504 return TotalIterationsReg;
11505}
11506
11507/// Adds logic in the loopBody MBB to generate MVE_VCTP, t2DoLoopDec and
11508/// t2DoLoopEnd. These are used by later passes to generate tail predicated
11509/// loops.
11510static void genTPLoopBody(MachineBasicBlock *TpLoopBody,
11511 MachineBasicBlock *TpEntry, MachineBasicBlock *TpExit,
11512 const TargetInstrInfo *TII, DebugLoc Dl,
11513 MachineRegisterInfo &MRI, Register OpSrcReg,
11514 Register OpDestReg, Register ElementCountReg,
11515 Register TotalIterationsReg, bool IsMemcpy) {
11516 // First insert 4 PHI nodes for: Current pointer to Src (if memcpy), Dest
11517 // array, loop iteration counter, predication counter.
11518
11519 Register SrcPhiReg, CurrSrcReg;
11520 if (IsMemcpy) {
11521 // Current position in the src array
11522 SrcPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11523 CurrSrcReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11524 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), SrcPhiReg)
11525 .addUse(OpSrcReg)
11526 .addMBB(TpEntry)
11527 .addUse(CurrSrcReg)
11528 .addMBB(TpLoopBody);
11529 }
11530
11531 // Current position in the dest array
11532 Register DestPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11533 Register CurrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11534 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), DestPhiReg)
11535 .addUse(OpDestReg)
11536 .addMBB(TpEntry)
11537 .addUse(CurrDestReg)
11538 .addMBB(TpLoopBody);
11539
11540 // Current loop counter
11541 Register LoopCounterPhiReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11542 Register RemainingLoopIterationsReg =
11543 MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11544 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), LoopCounterPhiReg)
11545 .addUse(TotalIterationsReg)
11546 .addMBB(TpEntry)
11547 .addUse(RemainingLoopIterationsReg)
11548 .addMBB(TpLoopBody);
11549
11550 // Predication counter
11551 Register PredCounterPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11552 Register RemainingElementsReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11553 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), PredCounterPhiReg)
11554 .addUse(ElementCountReg)
11555 .addMBB(TpEntry)
11556 .addUse(RemainingElementsReg)
11557 .addMBB(TpLoopBody);
11558
11559 // Pass predication counter to VCTP
11560 Register VccrReg = MRI.createVirtualRegister(&ARM::VCCRRegClass);
11561 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VCTP8), VccrReg)
11562 .addUse(PredCounterPhiReg)
11563 .addImm(ARMVCC::None)
11564 .addReg(0)
11565 .addReg(0);
11566
11567 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2SUBri), RemainingElementsReg)
11568 .addUse(PredCounterPhiReg)
11569 .addImm(16)
11570 .add(predOps(ARMCC::AL))
11571 .addReg(0);
11572
11573 // VLDRB (only if memcpy) and VSTRB instructions, predicated using VPR
11574 Register SrcValueReg;
11575 if (IsMemcpy) {
11576 SrcValueReg = MRI.createVirtualRegister(&ARM::MQPRRegClass);
11577 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VLDRBU8_post))
11578 .addDef(CurrSrcReg)
11579 .addDef(SrcValueReg)
11580 .addReg(SrcPhiReg)
11581 .addImm(16)
11582 .addImm(ARMVCC::Then)
11583 .addUse(VccrReg)
11584 .addReg(0);
11585 } else
11586 SrcValueReg = OpSrcReg;
11587
11588 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VSTRBU8_post))
11589 .addDef(CurrDestReg)
11590 .addUse(SrcValueReg)
11591 .addReg(DestPhiReg)
11592 .addImm(16)
11593 .addImm(ARMVCC::Then)
11594 .addUse(VccrReg)
11595 .addReg(0);
11596
11597 // Add the pseudoInstrs for decrementing the loop counter and marking the
11598 // end:t2DoLoopDec and t2DoLoopEnd
11599 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopDec), RemainingLoopIterationsReg)
11600 .addUse(LoopCounterPhiReg)
11601 .addImm(1);
11602
11603 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopEnd))
11604 .addUse(RemainingLoopIterationsReg)
11605 .addMBB(TpLoopBody);
11606
11607 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2B))
11608 .addMBB(TpExit)
11609 .add(predOps(ARMCC::AL));
11610}
11611
11612MachineBasicBlock *
11613ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11614 MachineBasicBlock *BB) const {
11615 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11616 DebugLoc dl = MI.getDebugLoc();
11617 bool isThumb2 = Subtarget->isThumb2();
11618 switch (MI.getOpcode()) {
11619 default: {
11620 MI.print(errs());
11621 llvm_unreachable("Unexpected instr type to insert")::llvm::llvm_unreachable_internal("Unexpected instr type to insert"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11621)
;
11622 }
11623
11624 // Thumb1 post-indexed loads are really just single-register LDMs.
11625 case ARM::tLDR_postidx: {
11626 MachineOperand Def(MI.getOperand(1));
11627 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
11628 .add(Def) // Rn_wb
11629 .add(MI.getOperand(2)) // Rn
11630 .add(MI.getOperand(3)) // PredImm
11631 .add(MI.getOperand(4)) // PredReg
11632 .add(MI.getOperand(0)) // Rt
11633 .cloneMemRefs(MI);
11634 MI.eraseFromParent();
11635 return BB;
11636 }
11637
11638 case ARM::MVE_MEMCPYLOOPINST:
11639 case ARM::MVE_MEMSETLOOPINST: {
11640
11641 // Transformation below expands MVE_MEMCPYLOOPINST/MVE_MEMSETLOOPINST Pseudo
11642 // into a Tail Predicated (TP) Loop. It adds the instructions to calculate
11643 // the iteration count =ceil(size_in_bytes/16)) in the TP entry block and
11644 // adds the relevant instructions in the TP loop Body for generation of a
11645 // WLSTP loop.
11646
11647 // Below is relevant portion of the CFG after the transformation.
11648 // The Machine Basic Blocks are shown along with branch conditions (in
11649 // brackets). Note that TP entry/exit MBBs depict the entry/exit of this
11650 // portion of the CFG and may not necessarily be the entry/exit of the
11651 // function.
11652
11653 // (Relevant) CFG after transformation:
11654 // TP entry MBB
11655 // |
11656 // |-----------------|
11657 // (n <= 0) (n > 0)
11658 // | |
11659 // | TP loop Body MBB<--|
11660 // | | |
11661 // \ |___________|
11662 // \ /
11663 // TP exit MBB
11664
11665 MachineFunction *MF = BB->getParent();
11666 MachineFunctionProperties &Properties = MF->getProperties();
11667 MachineRegisterInfo &MRI = MF->getRegInfo();
11668
11669 Register OpDestReg = MI.getOperand(0).getReg();
11670 Register OpSrcReg = MI.getOperand(1).getReg();
11671 Register OpSizeReg = MI.getOperand(2).getReg();
11672
11673 // Allocate the required MBBs and add to parent function.
11674 MachineBasicBlock *TpEntry = BB;
11675 MachineBasicBlock *TpLoopBody = MF->CreateMachineBasicBlock();
11676 MachineBasicBlock *TpExit;
11677
11678 MF->push_back(TpLoopBody);
11679
11680 // If any instructions are present in the current block after
11681 // MVE_MEMCPYLOOPINST or MVE_MEMSETLOOPINST, split the current block and
11682 // move the instructions into the newly created exit block. If there are no
11683 // instructions add an explicit branch to the FallThrough block and then
11684 // split.
11685 //
11686 // The split is required for two reasons:
11687 // 1) A terminator(t2WhileLoopStart) will be placed at that site.
11688 // 2) Since a TPLoopBody will be added later, any phis in successive blocks
11689 // need to be updated. splitAt() already handles this.
11690 TpExit = BB->splitAt(MI, false);
11691 if (TpExit == BB) {
11692 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11693, __extension__ __PRETTY_FUNCTION__))
11693 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11693, __extension__ __PRETTY_FUNCTION__))
;
11694 TpExit = BB->getFallThrough();
11695 BuildMI(BB, dl, TII->get(ARM::t2B))
11696 .addMBB(TpExit)
11697 .add(predOps(ARMCC::AL));
11698 TpExit = BB->splitAt(MI, false);
11699 }
11700
11701 // Add logic for iteration count
11702 Register TotalIterationsReg =
11703 genTPEntry(TpEntry, TpLoopBody, TpExit, OpSizeReg, TII, dl, MRI);
11704
11705 // Add the vectorized (and predicated) loads/store instructions
11706 bool IsMemcpy = MI.getOpcode() == ARM::MVE_MEMCPYLOOPINST;
11707 genTPLoopBody(TpLoopBody, TpEntry, TpExit, TII, dl, MRI, OpSrcReg,
11708 OpDestReg, OpSizeReg, TotalIterationsReg, IsMemcpy);
11709
11710 // Required to avoid conflict with the MachineVerifier during testing.
11711 Properties.reset(MachineFunctionProperties::Property::NoPHIs);
11712
11713 // Connect the blocks
11714 TpEntry->addSuccessor(TpLoopBody);
11715 TpLoopBody->addSuccessor(TpLoopBody);
11716 TpLoopBody->addSuccessor(TpExit);
11717
11718 // Reorder for a more natural layout
11719 TpLoopBody->moveAfter(TpEntry);
11720 TpExit->moveAfter(TpLoopBody);
11721
11722 // Finally, remove the memcpy Psuedo Instruction
11723 MI.eraseFromParent();
11724
11725 // Return the exit block as it may contain other instructions requiring a
11726 // custom inserter
11727 return TpExit;
11728 }
11729
11730 // The Thumb2 pre-indexed stores have the same MI operands, they just
11731 // define them differently in the .td files from the isel patterns, so
11732 // they need pseudos.
11733 case ARM::t2STR_preidx:
11734 MI.setDesc(TII->get(ARM::t2STR_PRE));
11735 return BB;
11736 case ARM::t2STRB_preidx:
11737 MI.setDesc(TII->get(ARM::t2STRB_PRE));
11738 return BB;
11739 case ARM::t2STRH_preidx:
11740 MI.setDesc(TII->get(ARM::t2STRH_PRE));
11741 return BB;
11742
11743 case ARM::STRi_preidx:
11744 case ARM::STRBi_preidx: {
11745 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
11746 : ARM::STRB_PRE_IMM;
11747 // Decode the offset.
11748 unsigned Offset = MI.getOperand(4).getImm();
11749 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
11750 Offset = ARM_AM::getAM2Offset(Offset);
11751 if (isSub)
11752 Offset = -Offset;
11753
11754 MachineMemOperand *MMO = *MI.memoperands_begin();
11755 BuildMI(*BB, MI, dl, TII->get(NewOpc))
11756 .add(MI.getOperand(0)) // Rn_wb
11757 .add(MI.getOperand(1)) // Rt
11758 .add(MI.getOperand(2)) // Rn
11759 .addImm(Offset) // offset (skip GPR==zero_reg)
11760 .add(MI.getOperand(5)) // pred
11761 .add(MI.getOperand(6))
11762 .addMemOperand(MMO);
11763 MI.eraseFromParent();
11764 return BB;
11765 }
11766 case ARM::STRr_preidx:
11767 case ARM::STRBr_preidx:
11768 case ARM::STRH_preidx: {
11769 unsigned NewOpc;
11770 switch (MI.getOpcode()) {
11771 default: llvm_unreachable("unexpected opcode!")::llvm::llvm_unreachable_internal("unexpected opcode!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11771)
;
11772 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
11773 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
11774 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
11775 }
11776 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
11777 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
11778 MIB.add(MI.getOperand(i));
11779 MI.eraseFromParent();
11780 return BB;
11781 }
11782
11783 case ARM::tMOVCCr_pseudo: {
11784 // To "insert" a SELECT_CC instruction, we actually have to insert the
11785 // diamond control-flow pattern. The incoming instruction knows the
11786 // destination vreg to set, the condition code register to branch on, the
11787 // true/false values to select between, and a branch opcode to use.
11788 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11789 MachineFunction::iterator It = ++BB->getIterator();
11790
11791 // thisMBB:
11792 // ...
11793 // TrueVal = ...
11794 // cmpTY ccX, r1, r2
11795 // bCC copy1MBB
11796 // fallthrough --> copy0MBB
11797 MachineBasicBlock *thisMBB = BB;
11798 MachineFunction *F = BB->getParent();
11799 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11800 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11801 F->insert(It, copy0MBB);
11802 F->insert(It, sinkMBB);
11803
11804 // Check whether CPSR is live past the tMOVCCr_pseudo.
11805 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
11806 if (!MI.killsRegister(ARM::CPSR) &&
11807 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
11808 copy0MBB->addLiveIn(ARM::CPSR);
11809 sinkMBB->addLiveIn(ARM::CPSR);
11810 }
11811
11812 // Transfer the remainder of BB and its successor edges to sinkMBB.
11813 sinkMBB->splice(sinkMBB->begin(), BB,
11814 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11815 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11816
11817 BB->addSuccessor(copy0MBB);
11818 BB->addSuccessor(sinkMBB);
11819
11820 BuildMI(BB, dl, TII->get(ARM::tBcc))
11821 .addMBB(sinkMBB)
11822 .addImm(MI.getOperand(3).getImm())
11823 .addReg(MI.getOperand(4).getReg());
11824
11825 // copy0MBB:
11826 // %FalseValue = ...
11827 // # fallthrough to sinkMBB
11828 BB = copy0MBB;
11829
11830 // Update machine-CFG edges
11831 BB->addSuccessor(sinkMBB);
11832
11833 // sinkMBB:
11834 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11835 // ...
11836 BB = sinkMBB;
11837 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
11838 .addReg(MI.getOperand(1).getReg())
11839 .addMBB(copy0MBB)
11840 .addReg(MI.getOperand(2).getReg())
11841 .addMBB(thisMBB);
11842
11843 MI.eraseFromParent(); // The pseudo instruction is gone now.
11844 return BB;
11845 }
11846
11847 case ARM::BCCi64:
11848 case ARM::BCCZi64: {
11849 // If there is an unconditional branch to the other successor, remove it.
11850 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
11851
11852 // Compare both parts that make up the double comparison separately for
11853 // equality.
11854 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
11855
11856 Register LHS1 = MI.getOperand(1).getReg();
11857 Register LHS2 = MI.getOperand(2).getReg();
11858 if (RHSisZero) {
11859 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11860 .addReg(LHS1)
11861 .addImm(0)
11862 .add(predOps(ARMCC::AL));
11863 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11864 .addReg(LHS2).addImm(0)
11865 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11866 } else {
11867 Register RHS1 = MI.getOperand(3).getReg();
11868 Register RHS2 = MI.getOperand(4).getReg();
11869 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11870 .addReg(LHS1)
11871 .addReg(RHS1)
11872 .add(predOps(ARMCC::AL));
11873 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11874 .addReg(LHS2).addReg(RHS2)
11875 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11876 }
11877
11878 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
11879 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
11880 if (MI.getOperand(0).getImm() == ARMCC::NE)
11881 std::swap(destMBB, exitMBB);
11882
11883 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
11884 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
11885 if (isThumb2)
11886 BuildMI(BB, dl, TII->get(ARM::t2B))
11887 .addMBB(exitMBB)
11888 .add(predOps(ARMCC::AL));
11889 else
11890 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
11891
11892 MI.eraseFromParent(); // The pseudo instruction is gone now.
11893 return BB;
11894 }
11895
11896 case ARM::Int_eh_sjlj_setjmp:
11897 case ARM::Int_eh_sjlj_setjmp_nofp:
11898 case ARM::tInt_eh_sjlj_setjmp:
11899 case ARM::t2Int_eh_sjlj_setjmp:
11900 case ARM::t2Int_eh_sjlj_setjmp_nofp:
11901 return BB;
11902
11903 case ARM::Int_eh_sjlj_setup_dispatch:
11904 EmitSjLjDispatchBlock(MI, BB);
11905 return BB;
11906
11907 case ARM::ABS:
11908 case ARM::t2ABS: {
11909 // To insert an ABS instruction, we have to insert the
11910 // diamond control-flow pattern. The incoming instruction knows the
11911 // source vreg to test against 0, the destination vreg to set,
11912 // the condition code register to branch on, the
11913 // true/false values to select between, and a branch opcode to use.
11914 // It transforms
11915 // V1 = ABS V0
11916 // into
11917 // V2 = MOVS V0
11918 // BCC (branch to SinkBB if V0 >= 0)
11919 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
11920 // SinkBB: V1 = PHI(V2, V3)
11921 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11922 MachineFunction::iterator BBI = ++BB->getIterator();
11923 MachineFunction *Fn = BB->getParent();
11924 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
11925 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
11926 Fn->insert(BBI, RSBBB);
11927 Fn->insert(BBI, SinkBB);
11928
11929 Register ABSSrcReg = MI.getOperand(1).getReg();
11930 Register ABSDstReg = MI.getOperand(0).getReg();
11931 bool ABSSrcKIll = MI.getOperand(1).isKill();
11932 bool isThumb2 = Subtarget->isThumb2();
11933 MachineRegisterInfo &MRI = Fn->getRegInfo();
11934 // In Thumb mode S must not be specified if source register is the SP or
11935 // PC and if destination register is the SP, so restrict register class
11936 Register NewRsbDstReg = MRI.createVirtualRegister(
11937 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
11938
11939 // Transfer the remainder of BB and its successor edges to sinkMBB.
11940 SinkBB->splice(SinkBB->begin(), BB,
11941 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11942 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
11943
11944 BB->addSuccessor(RSBBB);
11945 BB->addSuccessor(SinkBB);
11946
11947 // fall through to SinkMBB
11948 RSBBB->addSuccessor(SinkBB);
11949
11950 // insert a cmp at the end of BB
11951 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11952 .addReg(ABSSrcReg)
11953 .addImm(0)
11954 .add(predOps(ARMCC::AL));
11955
11956 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
11957 BuildMI(BB, dl,
11958 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
11959 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
11960
11961 // insert rsbri in RSBBB
11962 // Note: BCC and rsbri will be converted into predicated rsbmi
11963 // by if-conversion pass
11964 BuildMI(*RSBBB, RSBBB->begin(), dl,
11965 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
11966 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
11967 .addImm(0)
11968 .add(predOps(ARMCC::AL))
11969 .add(condCodeOp());
11970
11971 // insert PHI in SinkBB,
11972 // reuse ABSDstReg to not change uses of ABS instruction
11973 BuildMI(*SinkBB, SinkBB->begin(), dl,
11974 TII->get(ARM::PHI), ABSDstReg)
11975 .addReg(NewRsbDstReg).addMBB(RSBBB)
11976 .addReg(ABSSrcReg).addMBB(BB);
11977
11978 // remove ABS instruction
11979 MI.eraseFromParent();
11980
11981 // return last added BB
11982 return SinkBB;
11983 }
11984 case ARM::COPY_STRUCT_BYVAL_I32:
11985 ++NumLoopByVals;
11986 return EmitStructByval(MI, BB);
11987 case ARM::WIN__CHKSTK:
11988 return EmitLowered__chkstk(MI, BB);
11989 case ARM::WIN__DBZCHK:
11990 return EmitLowered__dbzchk(MI, BB);
11991 }
11992}
11993
11994/// Attaches vregs to MEMCPY that it will use as scratch registers
11995/// when it is expanded into LDM/STM. This is done as a post-isel lowering
11996/// instead of as a custom inserter because we need the use list from the SDNode.
11997static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
11998 MachineInstr &MI, const SDNode *Node) {
11999 bool isThumb1 = Subtarget->isThumb1Only();
12000
12001 DebugLoc DL = MI.getDebugLoc();
12002 MachineFunction *MF = MI.getParent()->getParent();
12003 MachineRegisterInfo &MRI = MF->getRegInfo();
12004 MachineInstrBuilder MIB(*MF, MI);
12005
12006 // If the new dst/src is unused mark it as dead.
12007 if (!Node->hasAnyUseOfValue(0)) {
12008 MI.getOperand(0).setIsDead(true);
12009 }
12010 if (!Node->hasAnyUseOfValue(1)) {
12011 MI.getOperand(1).setIsDead(true);
12012 }
12013
12014 // The MEMCPY both defines and kills the scratch registers.
12015 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
12016 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
12017 : &ARM::GPRRegClass);
12018 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
12019 }
12020}
12021
12022void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
12023 SDNode *Node) const {
12024 if (MI.getOpcode() == ARM::MEMCPY) {
12025 attachMEMCPYScratchRegs(Subtarget, MI, Node);
12026 return;
12027 }
12028
12029 const MCInstrDesc *MCID = &MI.getDesc();
12030 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
12031 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
12032 // operand is still set to noreg. If needed, set the optional operand's
12033 // register to CPSR, and remove the redundant implicit def.
12034 //
12035 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
12036
12037 // Rename pseudo opcodes.
12038 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
12039 unsigned ccOutIdx;
12040 if (NewOpc) {
12041 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
12042 MCID = &TII->get(NewOpc);
12043
12044 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)\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12047, __extension__ __PRETTY_FUNCTION__))
12045 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)\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12047, __extension__ __PRETTY_FUNCTION__))
12046 && "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)\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12047, __extension__ __PRETTY_FUNCTION__))
12047 " (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)\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12047, __extension__ __PRETTY_FUNCTION__))
;
12048
12049 MI.setDesc(*MCID);
12050
12051 // Add the optional cc_out operand
12052 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
12053
12054 // On Thumb1, move all input operands to the end, then add the predicate
12055 if (Subtarget->isThumb1Only()) {
12056 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
12057 MI.addOperand(MI.getOperand(1));
12058 MI.RemoveOperand(1);
12059 }
12060
12061 // Restore the ties
12062 for (unsigned i = MI.getNumOperands(); i--;) {
12063 const MachineOperand& op = MI.getOperand(i);
12064 if (op.isReg() && op.isUse()) {
12065 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
12066 if (DefIdx != -1)
12067 MI.tieOperands(DefIdx, i);
12068 }
12069 }
12070
12071 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
12072 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
12073 ccOutIdx = 1;
12074 } else
12075 ccOutIdx = MCID->getNumOperands() - 1;
12076 } else
12077 ccOutIdx = MCID->getNumOperands() - 1;
12078
12079 // Any ARM instruction that sets the 's' bit should specify an optional
12080 // "cc_out" operand in the last operand position.
12081 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
12082 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12082, __extension__ __PRETTY_FUNCTION__))
;
12083 return;
12084 }
12085 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
12086 // since we already have an optional CPSR def.
12087 bool definesCPSR = false;
12088 bool deadCPSR = false;
12089 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
12090 ++i) {
12091 const MachineOperand &MO = MI.getOperand(i);
12092 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
12093 definesCPSR = true;
12094 if (MO.isDead())
12095 deadCPSR = true;
12096 MI.RemoveOperand(i);
12097 break;
12098 }
12099 }
12100 if (!definesCPSR) {
12101 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12101, __extension__ __PRETTY_FUNCTION__))
;
12102 return;
12103 }
12104 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12104, __extension__ __PRETTY_FUNCTION__))
;
12105 if (deadCPSR) {
12106 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12107, __extension__ __PRETTY_FUNCTION__))
12107 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12107, __extension__ __PRETTY_FUNCTION__))
;
12108 // Thumb1 instructions must have the S bit even if the CPSR is dead.
12109 if (!Subtarget->isThumb1Only())
12110 return;
12111 }
12112
12113 // If this instruction was defined with an optional CPSR def and its dag node
12114 // had a live implicit CPSR def, then activate the optional CPSR def.
12115 MachineOperand &MO = MI.getOperand(ccOutIdx);
12116 MO.setReg(ARM::CPSR);
12117 MO.setIsDef(true);
12118}
12119
12120//===----------------------------------------------------------------------===//
12121// ARM Optimization Hooks
12122//===----------------------------------------------------------------------===//
12123
12124// Helper function that checks if N is a null or all ones constant.
12125static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
12126 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
12127}
12128
12129// Return true if N is conditionally 0 or all ones.
12130// Detects these expressions where cc is an i1 value:
12131//
12132// (select cc 0, y) [AllOnes=0]
12133// (select cc y, 0) [AllOnes=0]
12134// (zext cc) [AllOnes=0]
12135// (sext cc) [AllOnes=0/1]
12136// (select cc -1, y) [AllOnes=1]
12137// (select cc y, -1) [AllOnes=1]
12138//
12139// Invert is set when N is the null/all ones constant when CC is false.
12140// OtherOp is set to the alternative value of N.
12141static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
12142 SDValue &CC, bool &Invert,
12143 SDValue &OtherOp,
12144 SelectionDAG &DAG) {
12145 switch (N->getOpcode()) {
12146 default: return false;
12147 case ISD::SELECT: {
12148 CC = N->getOperand(0);
12149 SDValue N1 = N->getOperand(1);
12150 SDValue N2 = N->getOperand(2);
12151 if (isZeroOrAllOnes(N1, AllOnes)) {
12152 Invert = false;
12153 OtherOp = N2;
12154 return true;
12155 }
12156 if (isZeroOrAllOnes(N2, AllOnes)) {
12157 Invert = true;
12158 OtherOp = N1;
12159 return true;
12160 }
12161 return false;
12162 }
12163 case ISD::ZERO_EXTEND:
12164 // (zext cc) can never be the all ones value.
12165 if (AllOnes)
12166 return false;
12167 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12168 case ISD::SIGN_EXTEND: {
12169 SDLoc dl(N);
12170 EVT VT = N->getValueType(0);
12171 CC = N->getOperand(0);
12172 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
12173 return false;
12174 Invert = !AllOnes;
12175 if (AllOnes)
12176 // When looking for an AllOnes constant, N is an sext, and the 'other'
12177 // value is 0.
12178 OtherOp = DAG.getConstant(0, dl, VT);
12179 else if (N->getOpcode() == ISD::ZERO_EXTEND)
12180 // When looking for a 0 constant, N can be zext or sext.
12181 OtherOp = DAG.getConstant(1, dl, VT);
12182 else
12183 OtherOp = DAG.getAllOnesConstant(dl, VT);
12184 return true;
12185 }
12186 }
12187}
12188
12189// Combine a constant select operand into its use:
12190//
12191// (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12192// (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12193// (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
12194// (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12195// (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12196//
12197// The transform is rejected if the select doesn't have a constant operand that
12198// is null, or all ones when AllOnes is set.
12199//
12200// Also recognize sext/zext from i1:
12201//
12202// (add (zext cc), x) -> (select cc (add x, 1), x)
12203// (add (sext cc), x) -> (select cc (add x, -1), x)
12204//
12205// These transformations eventually create predicated instructions.
12206//
12207// @param N The node to transform.
12208// @param Slct The N operand that is a select.
12209// @param OtherOp The other N operand (x above).
12210// @param DCI Context.
12211// @param AllOnes Require the select constant to be all ones instead of null.
12212// @returns The new node, or SDValue() on failure.
12213static
12214SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
12215 TargetLowering::DAGCombinerInfo &DCI,
12216 bool AllOnes = false) {
12217 SelectionDAG &DAG = DCI.DAG;
12218 EVT VT = N->getValueType(0);
12219 SDValue NonConstantVal;
12220 SDValue CCOp;
12221 bool SwapSelectOps;
12222 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
12223 NonConstantVal, DAG))
12224 return SDValue();
12225
12226 // Slct is now know to be the desired identity constant when CC is true.
12227 SDValue TrueVal = OtherOp;
12228 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12229 OtherOp, NonConstantVal);
12230 // Unless SwapSelectOps says CC should be false.
12231 if (SwapSelectOps)
12232 std::swap(TrueVal, FalseVal);
12233
12234 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
12235 CCOp, TrueVal, FalseVal);
12236}
12237
12238// Attempt combineSelectAndUse on each operand of a commutative operator N.
12239static
12240SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
12241 TargetLowering::DAGCombinerInfo &DCI) {
12242 SDValue N0 = N->getOperand(0);
12243 SDValue N1 = N->getOperand(1);
12244 if (N0.getNode()->hasOneUse())
12245 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
12246 return Result;
12247 if (N1.getNode()->hasOneUse())
12248 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
12249 return Result;
12250 return SDValue();
12251}
12252
12253static bool IsVUZPShuffleNode(SDNode *N) {
12254 // VUZP shuffle node.
12255 if (N->getOpcode() == ARMISD::VUZP)
12256 return true;
12257
12258 // "VUZP" on i32 is an alias for VTRN.
12259 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
12260 return true;
12261
12262 return false;
12263}
12264
12265static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
12266 TargetLowering::DAGCombinerInfo &DCI,
12267 const ARMSubtarget *Subtarget) {
12268 // Look for ADD(VUZP.0, VUZP.1).
12269 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
12270 N0 == N1)
12271 return SDValue();
12272
12273 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
12274 if (!N->getValueType(0).is64BitVector())
12275 return SDValue();
12276
12277 // Generate vpadd.
12278 SelectionDAG &DAG = DCI.DAG;
12279 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12280 SDLoc dl(N);
12281 SDNode *Unzip = N0.getNode();
12282 EVT VT = N->getValueType(0);
12283
12284 SmallVector<SDValue, 8> Ops;
12285 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
12286 TLI.getPointerTy(DAG.getDataLayout())));
12287 Ops.push_back(Unzip->getOperand(0));
12288 Ops.push_back(Unzip->getOperand(1));
12289
12290 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12291}
12292
12293static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12294 TargetLowering::DAGCombinerInfo &DCI,
12295 const ARMSubtarget *Subtarget) {
12296 // Check for two extended operands.
12297 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
12298 N1.getOpcode() == ISD::SIGN_EXTEND) &&
12299 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
12300 N1.getOpcode() == ISD::ZERO_EXTEND))
12301 return SDValue();
12302
12303 SDValue N00 = N0.getOperand(0);
12304 SDValue N10 = N1.getOperand(0);
12305
12306 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
12307 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
12308 N00 == N10)
12309 return SDValue();
12310
12311 // We only recognize Q register paddl here; this can't be reached until
12312 // after type legalization.
12313 if (!N00.getValueType().is64BitVector() ||
12314 !N0.getValueType().is128BitVector())
12315 return SDValue();
12316
12317 // Generate vpaddl.
12318 SelectionDAG &DAG = DCI.DAG;
12319 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12320 SDLoc dl(N);
12321 EVT VT = N->getValueType(0);
12322
12323 SmallVector<SDValue, 8> Ops;
12324 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
12325 unsigned Opcode;
12326 if (N0.getOpcode() == ISD::SIGN_EXTEND)
12327 Opcode = Intrinsic::arm_neon_vpaddls;
12328 else
12329 Opcode = Intrinsic::arm_neon_vpaddlu;
12330 Ops.push_back(DAG.getConstant(Opcode, dl,
12331 TLI.getPointerTy(DAG.getDataLayout())));
12332 EVT ElemTy = N00.getValueType().getVectorElementType();
12333 unsigned NumElts = VT.getVectorNumElements();
12334 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
12335 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
12336 N00.getOperand(0), N00.getOperand(1));
12337 Ops.push_back(Concat);
12338
12339 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12340}
12341
12342// FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
12343// an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
12344// much easier to match.
12345static SDValue
12346AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12347 TargetLowering::DAGCombinerInfo &DCI,
12348 const ARMSubtarget *Subtarget) {
12349 // Only perform optimization if after legalize, and if NEON is available. We
12350 // also expected both operands to be BUILD_VECTORs.
12351 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
12352 || N0.getOpcode() != ISD::BUILD_VECTOR
12353 || N1.getOpcode() != ISD::BUILD_VECTOR)
12354 return SDValue();
12355
12356 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
12357 EVT VT = N->getValueType(0);
12358 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
12359 return SDValue();
12360
12361 // Check that the vector operands are of the right form.
12362 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
12363 // operands, where N is the size of the formed vector.
12364 // Each EXTRACT_VECTOR should have the same input vector and odd or even
12365 // index such that we have a pair wise add pattern.
12366
12367 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
12368 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12369 return SDValue();
12370 SDValue Vec = N0->getOperand(0)->getOperand(0);
12371 SDNode *V = Vec.getNode();
12372 unsigned nextIndex = 0;
12373
12374 // For each operands to the ADD which are BUILD_VECTORs,
12375 // check to see if each of their operands are an EXTRACT_VECTOR with
12376 // the same vector and appropriate index.
12377 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
12378 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
12379 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12380
12381 SDValue ExtVec0 = N0->getOperand(i);
12382 SDValue ExtVec1 = N1->getOperand(i);
12383
12384 // First operand is the vector, verify its the same.
12385 if (V != ExtVec0->getOperand(0).getNode() ||
12386 V != ExtVec1->getOperand(0).getNode())
12387 return SDValue();
12388
12389 // Second is the constant, verify its correct.
12390 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
12391 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
12392
12393 // For the constant, we want to see all the even or all the odd.
12394 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
12395 || C1->getZExtValue() != nextIndex+1)
12396 return SDValue();
12397
12398 // Increment index.
12399 nextIndex+=2;
12400 } else
12401 return SDValue();
12402 }
12403
12404 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
12405 // we're using the entire input vector, otherwise there's a size/legality
12406 // mismatch somewhere.
12407 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
12408 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
12409 return SDValue();
12410
12411 // Create VPADDL node.
12412 SelectionDAG &DAG = DCI.DAG;
12413 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12414
12415 SDLoc dl(N);
12416
12417 // Build operand list.
12418 SmallVector<SDValue, 8> Ops;
12419 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
12420 TLI.getPointerTy(DAG.getDataLayout())));
12421
12422 // Input is the vector.
12423 Ops.push_back(Vec);
12424
12425 // Get widened type and narrowed type.
12426 MVT widenType;
12427 unsigned numElem = VT.getVectorNumElements();
12428
12429 EVT inputLaneType = Vec.getValueType().getVectorElementType();
12430 switch (inputLaneType.getSimpleVT().SimpleTy) {
12431 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
12432 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
12433 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
12434 default:
12435 llvm_unreachable("Invalid vector element type for padd optimization.")::llvm::llvm_unreachable_internal("Invalid vector element type for padd optimization."
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12435)
;
12436 }
12437
12438 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
12439 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
12440 return DAG.getNode(ExtOp, dl, VT, tmp);
12441}
12442
12443static SDValue findMUL_LOHI(SDValue V) {
12444 if (V->getOpcode() == ISD::UMUL_LOHI ||
12445 V->getOpcode() == ISD::SMUL_LOHI)
12446 return V;
12447 return SDValue();
12448}
12449
12450static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
12451 TargetLowering::DAGCombinerInfo &DCI,
12452 const ARMSubtarget *Subtarget) {
12453 if (!Subtarget->hasBaseDSP())
12454 return SDValue();
12455
12456 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
12457 // accumulates the product into a 64-bit value. The 16-bit values will
12458 // be sign extended somehow or SRA'd into 32-bit values
12459 // (addc (adde (mul 16bit, 16bit), lo), hi)
12460 SDValue Mul = AddcNode->getOperand(0);
12461 SDValue Lo = AddcNode->getOperand(1);
12462 if (Mul.getOpcode() != ISD::MUL) {
12463 Lo = AddcNode->getOperand(0);
12464 Mul = AddcNode->getOperand(1);
12465 if (Mul.getOpcode() != ISD::MUL)
12466 return SDValue();
12467 }
12468
12469 SDValue SRA = AddeNode->getOperand(0);
12470 SDValue Hi = AddeNode->getOperand(1);
12471 if (SRA.getOpcode() != ISD::SRA) {
12472 SRA = AddeNode->getOperand(1);
12473 Hi = AddeNode->getOperand(0);
12474 if (SRA.getOpcode() != ISD::SRA)
12475 return SDValue();
12476 }
12477 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
12478 if (Const->getZExtValue() != 31)
12479 return SDValue();
12480 } else
12481 return SDValue();
12482
12483 if (SRA.getOperand(0) != Mul)
12484 return SDValue();
12485
12486 SelectionDAG &DAG = DCI.DAG;
12487 SDLoc dl(AddcNode);
12488 unsigned Opcode = 0;
12489 SDValue Op0;
12490 SDValue Op1;
12491
12492 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
12493 Opcode = ARMISD::SMLALBB;
12494 Op0 = Mul.getOperand(0);
12495 Op1 = Mul.getOperand(1);
12496 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
12497 Opcode = ARMISD::SMLALBT;
12498 Op0 = Mul.getOperand(0);
12499 Op1 = Mul.getOperand(1).getOperand(0);
12500 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
12501 Opcode = ARMISD::SMLALTB;
12502 Op0 = Mul.getOperand(0).getOperand(0);
12503 Op1 = Mul.getOperand(1);
12504 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
12505 Opcode = ARMISD::SMLALTT;
12506 Op0 = Mul->getOperand(0).getOperand(0);
12507 Op1 = Mul->getOperand(1).getOperand(0);
12508 }
12509
12510 if (!Op0 || !Op1)
12511 return SDValue();
12512
12513 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
12514 Op0, Op1, Lo, Hi);
12515 // Replace the ADDs' nodes uses by the MLA node's values.
12516 SDValue HiMLALResult(SMLAL.getNode(), 1);
12517 SDValue LoMLALResult(SMLAL.getNode(), 0);
12518
12519 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
12520 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
12521
12522 // Return original node to notify the driver to stop replacing.
12523 SDValue resNode(AddcNode, 0);
12524 return resNode;
12525}
12526
12527static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
12528 TargetLowering::DAGCombinerInfo &DCI,
12529 const ARMSubtarget *Subtarget) {
12530 // Look for multiply add opportunities.
12531 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
12532 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
12533 // a glue link from the first add to the second add.
12534 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
12535 // a S/UMLAL instruction.
12536 // UMUL_LOHI
12537 // / :lo \ :hi
12538 // V \ [no multiline comment]
12539 // loAdd -> ADDC |
12540 // \ :carry /
12541 // V V
12542 // ADDE <- hiAdd
12543 //
12544 // In the special case where only the higher part of a signed result is used
12545 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
12546 // a constant with the exact value of 0x80000000, we recognize we are dealing
12547 // with a "rounded multiply and add" (or subtract) and transform it into
12548 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
12549
12550 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12552, __extension__ __PRETTY_FUNCTION__))
12551 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12552, __extension__ __PRETTY_FUNCTION__))
12552 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12552, __extension__ __PRETTY_FUNCTION__))
;
12553
12554 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12556, __extension__ __PRETTY_FUNCTION__))
12555 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12556, __extension__ __PRETTY_FUNCTION__))
12556 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12556, __extension__ __PRETTY_FUNCTION__))
;
12557
12558 // Check that we are chained to the right ADDC or SUBC node.
12559 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
12560 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12561 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
12562 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
12563 AddcSubcNode->getOpcode() != ARMISD::SUBC))
12564 return SDValue();
12565
12566 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
12567 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
12568
12569 // Check if the two operands are from the same mul_lohi node.
12570 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
12571 return SDValue();
12572
12573 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12575, __extension__ __PRETTY_FUNCTION__))
12574 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12575, __extension__ __PRETTY_FUNCTION__))
12575 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12575, __extension__ __PRETTY_FUNCTION__))
;
12576
12577 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
12578 // maybe a SMLAL which multiplies two 16-bit values.
12579 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12580 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
12581 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
12582 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
12583 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
12584 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
12585
12586 // Check for the triangle shape.
12587 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
12588 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
12589
12590 // Make sure that the ADDE/SUBE operands are not coming from the same node.
12591 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
12592 return SDValue();
12593
12594 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
12595 bool IsLeftOperandMUL = false;
12596 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
12597 if (MULOp == SDValue())
12598 MULOp = findMUL_LOHI(AddeSubeOp1);
12599 else
12600 IsLeftOperandMUL = true;
12601 if (MULOp == SDValue())
12602 return SDValue();
12603
12604 // Figure out the right opcode.
12605 unsigned Opc = MULOp->getOpcode();
12606 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
12607
12608 // Figure out the high and low input values to the MLAL node.
12609 SDValue *HiAddSub = nullptr;
12610 SDValue *LoMul = nullptr;
12611 SDValue *LowAddSub = nullptr;
12612
12613 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
12614 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
12615 return SDValue();
12616
12617 if (IsLeftOperandMUL)
12618 HiAddSub = &AddeSubeOp1;
12619 else
12620 HiAddSub = &AddeSubeOp0;
12621
12622 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
12623 // whose low result is fed to the ADDC/SUBC we are checking.
12624
12625 if (AddcSubcOp0 == MULOp.getValue(0)) {
12626 LoMul = &AddcSubcOp0;
12627 LowAddSub = &AddcSubcOp1;
12628 }
12629 if (AddcSubcOp1 == MULOp.getValue(0)) {
12630 LoMul = &AddcSubcOp1;
12631 LowAddSub = &AddcSubcOp0;
12632 }
12633
12634 if (!LoMul)
12635 return SDValue();
12636
12637 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
12638 // the replacement below will create a cycle.
12639 if (AddcSubcNode == HiAddSub->getNode() ||
12640 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
12641 return SDValue();
12642
12643 // Create the merged node.
12644 SelectionDAG &DAG = DCI.DAG;
12645
12646 // Start building operand list.
12647 SmallVector<SDValue, 8> Ops;
12648 Ops.push_back(LoMul->getOperand(0));
12649 Ops.push_back(LoMul->getOperand(1));
12650
12651 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
12652 // the case, we must be doing signed multiplication and only use the higher
12653 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
12654 // addition or subtraction with the value of 0x800000.
12655 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
12656 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
12657 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
12658 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
12659 0x80000000) {
12660 Ops.push_back(*HiAddSub);
12661 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
12662 FinalOpc = ARMISD::SMMLSR;
12663 } else {
12664 FinalOpc = ARMISD::SMMLAR;
12665 }
12666 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
12667 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
12668
12669 return SDValue(AddeSubeNode, 0);
12670 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
12671 // SMMLS is generated during instruction selection and the rest of this
12672 // function can not handle the case where AddcSubcNode is a SUBC.
12673 return SDValue();
12674
12675 // Finish building the operand list for {U/S}MLAL
12676 Ops.push_back(*LowAddSub);
12677 Ops.push_back(*HiAddSub);
12678
12679 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
12680 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12681
12682 // Replace the ADDs' nodes uses by the MLA node's values.
12683 SDValue HiMLALResult(MLALNode.getNode(), 1);
12684 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
12685
12686 SDValue LoMLALResult(MLALNode.getNode(), 0);
12687 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
12688
12689 // Return original node to notify the driver to stop replacing.
12690 return SDValue(AddeSubeNode, 0);
12691}
12692
12693static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
12694 TargetLowering::DAGCombinerInfo &DCI,
12695 const ARMSubtarget *Subtarget) {
12696 // UMAAL is similar to UMLAL except that it adds two unsigned values.
12697 // While trying to combine for the other MLAL nodes, first search for the
12698 // chance to use UMAAL. Check if Addc uses a node which has already
12699 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
12700 // as the addend, and it's handled in PerformUMLALCombine.
12701
12702 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12703 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12704
12705 // Check that we have a glued ADDC node.
12706 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
12707 if (AddcNode->getOpcode() != ARMISD::ADDC)
12708 return SDValue();
12709
12710 // Find the converted UMAAL or quit if it doesn't exist.
12711 SDNode *UmlalNode = nullptr;
12712 SDValue AddHi;
12713 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
12714 UmlalNode = AddcNode->getOperand(0).getNode();
12715 AddHi = AddcNode->getOperand(1);
12716 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
12717 UmlalNode = AddcNode->getOperand(1).getNode();
12718 AddHi = AddcNode->getOperand(0);
12719 } else {
12720 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12721 }
12722
12723 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
12724 // the ADDC as well as Zero.
12725 if (!isNullConstant(UmlalNode->getOperand(3)))
12726 return SDValue();
12727
12728 if ((isNullConstant(AddeNode->getOperand(0)) &&
12729 AddeNode->getOperand(1).getNode() == UmlalNode) ||
12730 (AddeNode->getOperand(0).getNode() == UmlalNode &&
12731 isNullConstant(AddeNode->getOperand(1)))) {
12732 SelectionDAG &DAG = DCI.DAG;
12733 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
12734 UmlalNode->getOperand(2), AddHi };
12735 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
12736 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12737
12738 // Replace the ADDs' nodes uses by the UMAAL node's values.
12739 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
12740 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
12741
12742 // Return original node to notify the driver to stop replacing.
12743 return SDValue(AddeNode, 0);
12744 }
12745 return SDValue();
12746}
12747
12748static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
12749 const ARMSubtarget *Subtarget) {
12750 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12751 return SDValue();
12752
12753 // Check that we have a pair of ADDC and ADDE as operands.
12754 // Both addends of the ADDE must be zero.
12755 SDNode* AddcNode = N->getOperand(2).getNode();
12756 SDNode* AddeNode = N->getOperand(3).getNode();
12757 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
12758 (AddeNode->getOpcode() == ARMISD::ADDE) &&
12759 isNullConstant(AddeNode->getOperand(0)) &&
12760 isNullConstant(AddeNode->getOperand(1)) &&
12761 (AddeNode->getOperand(2).getNode() == AddcNode))
12762 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
12763 DAG.getVTList(MVT::i32, MVT::i32),
12764 {N->getOperand(0), N->getOperand(1),
12765 AddcNode->getOperand(0), AddcNode->getOperand(1)});
12766 else
12767 return SDValue();
12768}
12769
12770static SDValue PerformAddcSubcCombine(SDNode *N,
12771 TargetLowering::DAGCombinerInfo &DCI,
12772 const ARMSubtarget *Subtarget) {
12773 SelectionDAG &DAG(DCI.DAG);
12774
12775 if (N->getOpcode() == ARMISD::SUBC && N->hasAnyUseOfValue(1)) {
12776 // (SUBC (ADDE 0, 0, C), 1) -> C
12777 SDValue LHS = N->getOperand(0);
12778 SDValue RHS = N->getOperand(1);
12779 if (LHS->getOpcode() == ARMISD::ADDE &&
12780 isNullConstant(LHS->getOperand(0)) &&
12781 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
12782 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
12783 }
12784 }
12785
12786 if (Subtarget->isThumb1Only()) {
12787 SDValue RHS = N->getOperand(1);
12788 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12789 int32_t imm = C->getSExtValue();
12790 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
12791 SDLoc DL(N);
12792 RHS = DAG.getConstant(-imm, DL, MVT::i32);
12793 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
12794 : ARMISD::ADDC;
12795 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
12796 }
12797 }
12798 }
12799
12800 return SDValue();
12801}
12802
12803static SDValue PerformAddeSubeCombine(SDNode *N,
12804 TargetLowering::DAGCombinerInfo &DCI,
12805 const ARMSubtarget *Subtarget) {
12806 if (Subtarget->isThumb1Only()) {
12807 SelectionDAG &DAG = DCI.DAG;
12808 SDValue RHS = N->getOperand(1);
12809 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12810 int64_t imm = C->getSExtValue();
12811 if (imm < 0) {
12812 SDLoc DL(N);
12813
12814 // The with-carry-in form matches bitwise not instead of the negation.
12815 // Effectively, the inverse interpretation of the carry flag already
12816 // accounts for part of the negation.
12817 RHS = DAG.getConstant(~imm, DL, MVT::i32);
12818
12819 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
12820 : ARMISD::ADDE;
12821 return DAG.getNode(Opcode, DL, N->getVTList(),
12822 N->getOperand(0), RHS, N->getOperand(2));
12823 }
12824 }
12825 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
12826 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
12827 }
12828 return SDValue();
12829}
12830
12831static SDValue PerformSELECTCombine(SDNode *N,
12832 TargetLowering::DAGCombinerInfo &DCI,
12833 const ARMSubtarget *Subtarget) {
12834 if (!Subtarget->hasMVEIntegerOps())
12835 return SDValue();
12836
12837 SDLoc dl(N);
12838 SDValue SetCC;
12839 SDValue LHS;
12840 SDValue RHS;
12841 ISD::CondCode CC;
12842 SDValue TrueVal;
12843 SDValue FalseVal;
12844
12845 if (N->getOpcode() == ISD::SELECT &&
12846 N->getOperand(0)->getOpcode() == ISD::SETCC) {
12847 SetCC = N->getOperand(0);
12848 LHS = SetCC->getOperand(0);
12849 RHS = SetCC->getOperand(1);
12850 CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
12851 TrueVal = N->getOperand(1);
12852 FalseVal = N->getOperand(2);
12853 } else if (N->getOpcode() == ISD::SELECT_CC) {
12854 LHS = N->getOperand(0);
12855 RHS = N->getOperand(1);
12856 CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
12857 TrueVal = N->getOperand(2);
12858 FalseVal = N->getOperand(3);
12859 } else {
12860 return SDValue();
12861 }
12862
12863 unsigned int Opcode = 0;
12864 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
12865 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
12866 (CC == ISD::SETULT || CC == ISD::SETUGT)) {
12867 Opcode = ARMISD::VMINVu;
12868 if (CC == ISD::SETUGT)
12869 std::swap(TrueVal, FalseVal);
12870 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
12871 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
12872 (CC == ISD::SETLT || CC == ISD::SETGT)) {
12873 Opcode = ARMISD::VMINVs;
12874 if (CC == ISD::SETGT)
12875 std::swap(TrueVal, FalseVal);
12876 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
12877 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
12878 (CC == ISD::SETUGT || CC == ISD::SETULT)) {
12879 Opcode = ARMISD::VMAXVu;
12880 if (CC == ISD::SETULT)
12881 std::swap(TrueVal, FalseVal);
12882 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
12883 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
12884 (CC == ISD::SETGT || CC == ISD::SETLT)) {
12885 Opcode = ARMISD::VMAXVs;
12886 if (CC == ISD::SETLT)
12887 std::swap(TrueVal, FalseVal);
12888 } else
12889 return SDValue();
12890
12891 // Normalise to the right hand side being the vector reduction
12892 switch (TrueVal->getOpcode()) {
12893 case ISD::VECREDUCE_UMIN:
12894 case ISD::VECREDUCE_SMIN:
12895 case ISD::VECREDUCE_UMAX:
12896 case ISD::VECREDUCE_SMAX:
12897 std::swap(LHS, RHS);
12898 std::swap(TrueVal, FalseVal);
12899 break;
12900 }
12901
12902 EVT VectorType = FalseVal->getOperand(0).getValueType();
12903
12904 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
12905 VectorType != MVT::v4i32)
12906 return SDValue();
12907
12908 EVT VectorScalarType = VectorType.getVectorElementType();
12909
12910 // The values being selected must also be the ones being compared
12911 if (TrueVal != LHS || FalseVal != RHS)
12912 return SDValue();
12913
12914 EVT LeftType = LHS->getValueType(0);
12915 EVT RightType = RHS->getValueType(0);
12916
12917 // The types must match the reduced type too
12918 if (LeftType != VectorScalarType || RightType != VectorScalarType)
12919 return SDValue();
12920
12921 // Legalise the scalar to an i32
12922 if (VectorScalarType != MVT::i32)
12923 LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12924
12925 // Generate the reduction as an i32 for legalisation purposes
12926 auto Reduction =
12927 DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0));
12928
12929 // The result isn't actually an i32 so truncate it back to its original type
12930 if (VectorScalarType != MVT::i32)
12931 Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction);
12932
12933 return Reduction;
12934}
12935
12936// A special combine for the vqdmulh family of instructions. This is one of the
12937// potential set of patterns that could patch this instruction. The base pattern
12938// you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
12939// This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
12940// which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
12941// the max is unnecessary.
12942static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) {
12943 EVT VT = N->getValueType(0);
12944 SDValue Shft;
12945 ConstantSDNode *Clamp;
12946
12947 if (!VT.isVector() || VT.getScalarSizeInBits() > 64)
12948 return SDValue();
12949
12950 if (N->getOpcode() == ISD::SMIN) {
12951 Shft = N->getOperand(0);
12952 Clamp = isConstOrConstSplat(N->getOperand(1));
12953 } else if (N->getOpcode() == ISD::VSELECT) {
12954 // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
12955 SDValue Cmp = N->getOperand(0);
12956 if (Cmp.getOpcode() != ISD::SETCC ||
12957 cast<CondCodeSDNode>(Cmp.getOperand(2))->get() != ISD::SETLT ||
12958 Cmp.getOperand(0) != N->getOperand(1) ||
12959 Cmp.getOperand(1) != N->getOperand(2))
12960 return SDValue();
12961 Shft = N->getOperand(1);
12962 Clamp = isConstOrConstSplat(N->getOperand(2));
12963 } else
12964 return SDValue();
12965
12966 if (!Clamp)
12967 return SDValue();
12968
12969 MVT ScalarType;
12970 int ShftAmt = 0;
12971 switch (Clamp->getSExtValue()) {
12972 case (1 << 7) - 1:
12973 ScalarType = MVT::i8;
12974 ShftAmt = 7;
12975 break;
12976 case (1 << 15) - 1:
12977 ScalarType = MVT::i16;
12978 ShftAmt = 15;
12979 break;
12980 case (1ULL << 31) - 1:
12981 ScalarType = MVT::i32;
12982 ShftAmt = 31;
12983 break;
12984 default:
12985 return SDValue();
12986 }
12987
12988 if (Shft.getOpcode() != ISD::SRA)
12989 return SDValue();
12990 ConstantSDNode *N1 = isConstOrConstSplat(Shft.getOperand(1));
12991 if (!N1 || N1->getSExtValue() != ShftAmt)
12992 return SDValue();
12993
12994 SDValue Mul = Shft.getOperand(0);
12995 if (Mul.getOpcode() != ISD::MUL)
12996 return SDValue();
12997
12998 SDValue Ext0 = Mul.getOperand(0);
12999 SDValue Ext1 = Mul.getOperand(1);
13000 if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
13001 Ext1.getOpcode() != ISD::SIGN_EXTEND)
13002 return SDValue();
13003 EVT VecVT = Ext0.getOperand(0).getValueType();
13004 if (!VecVT.isPow2VectorType() || VecVT.getVectorNumElements() == 1)
13005 return SDValue();
13006 if (Ext1.getOperand(0).getValueType() != VecVT ||
13007 VecVT.getScalarType() != ScalarType ||
13008 VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
13009 return SDValue();
13010
13011 SDLoc DL(Mul);
13012 unsigned LegalLanes = 128 / (ShftAmt + 1);
13013 EVT LegalVecVT = MVT::getVectorVT(ScalarType, LegalLanes);
13014 // For types smaller than legal vectors extend to be legal and only use needed
13015 // lanes.
13016 if (VecVT.getSizeInBits() < 128) {
13017 EVT ExtVecVT =
13018 MVT::getVectorVT(MVT::getIntegerVT(128 / VecVT.getVectorNumElements()),
13019 VecVT.getVectorNumElements());
13020 SDValue Inp0 =
13021 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext0.getOperand(0));
13022 SDValue Inp1 =
13023 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext1.getOperand(0));
13024 Inp0 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp0);
13025 Inp1 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp1);
13026 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13027 SDValue Trunc = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, ExtVecVT, VQDMULH);
13028 Trunc = DAG.getNode(ISD::TRUNCATE, DL, VecVT, Trunc);
13029 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Trunc);
13030 }
13031
13032 // For larger types, split into legal sized chunks.
13033 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 13033, __extension__ __PRETTY_FUNCTION__))
;
13034 unsigned NumParts = VecVT.getSizeInBits() / 128;
13035 SmallVector<SDValue> Parts;
13036 for (unsigned I = 0; I < NumParts; ++I) {
13037 SDValue Inp0 =
13038 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext0.getOperand(0),
13039 DAG.getVectorIdxConstant(I * LegalLanes, DL));
13040 SDValue Inp1 =
13041 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext1.getOperand(0),
13042 DAG.getVectorIdxConstant(I * LegalLanes, DL));
13043 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13044 Parts.push_back(VQDMULH);
13045 }
13046 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT,
13047 DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Parts));
13048}
13049
13050static SDValue PerformVSELECTCombine(SDNode *N,
13051 TargetLowering::DAGCombinerInfo &DCI,
13052 const ARMSubtarget *Subtarget) {
13053 if (!Subtarget->hasMVEIntegerOps())
13054 return SDValue();
13055
13056 if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG))
13057 return V;
13058
13059 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
13060 //
13061 // We need to re-implement this optimization here as the implementation in the
13062 // Target-Independent DAGCombiner does not handle the kind of constant we make
13063 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
13064 // good reason, allowing truncation there would break other targets).
13065 //
13066 // Currently, this is only done for MVE, as it's the only target that benefits
13067 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
13068 if (N->getOperand(0).getOpcode() != ISD::XOR)
13069 return SDValue();
13070 SDValue XOR = N->getOperand(0);
13071
13072 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
13073 // It is important to check with truncation allowed as the BUILD_VECTORs we
13074 // generate in those situations will truncate their operands.
13075 ConstantSDNode *Const =
13076 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
13077 /*AllowTruncation*/ true);
13078 if (!Const || !Const->isOne())
13079 return SDValue();
13080
13081 // Rewrite into vselect(cond, rhs, lhs).
13082 SDValue Cond = XOR->getOperand(0);
13083 SDValue LHS = N->getOperand(1);
13084 SDValue RHS = N->getOperand(2);
13085 EVT Type = N->getValueType(0);
13086 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
13087}
13088
13089static SDValue PerformABSCombine(SDNode *N,
13090 TargetLowering::DAGCombinerInfo &DCI,
13091 const ARMSubtarget *Subtarget) {
13092 SelectionDAG &DAG = DCI.DAG;
13093 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13094
13095 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
13096 return SDValue();
13097
13098 return TLI.expandABS(N, DAG);
13099}
13100
13101/// PerformADDECombine - Target-specific dag combine transform from
13102/// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
13103/// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
13104static SDValue PerformADDECombine(SDNode *N,
13105 TargetLowering::DAGCombinerInfo &DCI,
13106 const ARMSubtarget *Subtarget) {
13107 // Only ARM and Thumb2 support UMLAL/SMLAL.
13108 if (Subtarget->isThumb1Only())
13109 return PerformAddeSubeCombine(N, DCI, Subtarget);
13110
13111 // Only perform the checks after legalize when the pattern is available.
13112 if (DCI.isBeforeLegalize()) return SDValue();
13113
13114 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
13115}
13116
13117/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
13118/// operands N0 and N1. This is a helper for PerformADDCombine that is
13119/// called with the default operands, and if that fails, with commuted
13120/// operands.
13121static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
13122 TargetLowering::DAGCombinerInfo &DCI,
13123 const ARMSubtarget *Subtarget){
13124 // Attempt to create vpadd for this add.
13125 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
13126 return Result;
13127
13128 // Attempt to create vpaddl for this add.
13129 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
13130 return Result;
13131 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
13132 Subtarget))
13133 return Result;
13134
13135 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
13136 if (N0.getNode()->hasOneUse())
13137 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
13138 return Result;
13139 return SDValue();
13140}
13141
13142static SDValue TryDistrubutionADDVecReduce(SDNode *N, SelectionDAG &DAG) {
13143 EVT VT = N->getValueType(0);
13144 SDValue N0 = N->getOperand(0);
13145 SDValue N1 = N->getOperand(1);
13146 SDLoc dl(N);
13147
13148 auto IsVecReduce = [](SDValue Op) {
13149 switch (Op.getOpcode()) {
13150 case ISD::VECREDUCE_ADD:
13151 case ARMISD::VADDVs:
13152 case ARMISD::VADDVu:
13153 case ARMISD::VMLAVs:
13154 case ARMISD::VMLAVu:
13155 return true;
13156 }
13157 return false;
13158 };
13159
13160 auto DistrubuteAddAddVecReduce = [&](SDValue N0, SDValue N1) {
13161 // Distribute add(X, add(vecreduce(Y), vecreduce(Z))) ->
13162 // add(add(X, vecreduce(Y)), vecreduce(Z))
13163 // to make better use of vaddva style instructions.
13164 if (VT == MVT::i32 && N1.getOpcode() == ISD::ADD && !IsVecReduce(N0) &&
13165 IsVecReduce(N1.getOperand(0)) && IsVecReduce(N1.getOperand(1)) &&
13166 !isa<ConstantSDNode>(N0)) {
13167 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0, N1.getOperand(0));
13168 return DAG.getNode(ISD::ADD, dl, VT, Add0, N1.getOperand(1));
13169 }
13170 // And turn add(add(A, reduce(B)), add(C, reduce(D))) ->
13171 // add(add(add(A, C), reduce(B)), reduce(D))
13172 if (VT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
13173 N1.getOpcode() == ISD::ADD) {
13174 unsigned N0RedOp = 0;
13175 if (!IsVecReduce(N0.getOperand(N0RedOp))) {
13176 N0RedOp = 1;
13177 if (!IsVecReduce(N0.getOperand(N0RedOp)))
13178 return SDValue();
13179 }
13180
13181 unsigned N1RedOp = 0;
13182 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13183 N1RedOp = 1;
13184 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13185 return SDValue();
13186
13187 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0.getOperand(1 - N0RedOp),
13188 N1.getOperand(1 - N1RedOp));
13189 SDValue Add1 =
13190 DAG.getNode(ISD::ADD, dl, VT, Add0, N0.getOperand(N0RedOp));
13191 return DAG.getNode(ISD::ADD, dl, VT, Add1, N1.getOperand(N1RedOp));
13192 }
13193 return SDValue();
13194 };
13195 if (SDValue R = DistrubuteAddAddVecReduce(N0, N1))
13196 return R;
13197 if (SDValue R = DistrubuteAddAddVecReduce(N1, N0))
13198 return R;
13199
13200 // Distribute add(vecreduce(load(Y)), vecreduce(load(Z)))
13201 // Or add(add(X, vecreduce(load(Y))), vecreduce(load(Z)))
13202 // by ascending load offsets. This can help cores prefetch if the order of
13203 // loads is more predictable.
13204 auto DistrubuteVecReduceLoad = [&](SDValue N0, SDValue N1, bool IsForward) {
13205 // Check if two reductions are known to load data where one is before/after
13206 // another. Return negative if N0 loads data before N1, positive if N1 is
13207 // before N0 and 0 otherwise if nothing is known.
13208 auto IsKnownOrderedLoad = [&](SDValue N0, SDValue N1) {
13209 // Look through to the first operand of a MUL, for the VMLA case.
13210 // Currently only looks at the first operand, in the hope they are equal.
13211 if (N0.getOpcode() == ISD::MUL)
13212 N0 = N0.getOperand(0);
13213 if (N1.getOpcode() == ISD::MUL)
13214 N1 = N1.getOperand(0);
13215
13216 // Return true if the two operands are loads to the same object and the
13217 // offset of the first is known to be less than the offset of the second.
13218 LoadSDNode *Load0 = dyn_cast<LoadSDNode>(N0);
13219 LoadSDNode *Load1 = dyn_cast<LoadSDNode>(N1);
13220 if (!Load0 || !Load1 || Load0->getChain() != Load1->getChain() ||
13221 !Load0->isSimple() || !Load1->isSimple() || Load0->isIndexed() ||
13222 Load1->isIndexed())
13223 return 0;
13224
13225 auto BaseLocDecomp0 = BaseIndexOffset::match(Load0, DAG);
13226 auto BaseLocDecomp1 = BaseIndexOffset::match(Load1, DAG);
13227
13228 if (!BaseLocDecomp0.getBase() ||
13229 BaseLocDecomp0.getBase() != BaseLocDecomp1.getBase() ||
13230 !BaseLocDecomp0.hasValidOffset() || !BaseLocDecomp1.hasValidOffset())
13231 return 0;
13232 if (BaseLocDecomp0.getOffset() < BaseLocDecomp1.getOffset())
13233 return -1;
13234 if (BaseLocDecomp0.getOffset() > BaseLocDecomp1.getOffset())
13235 return 1;
13236 return 0;
13237 };
13238
13239 SDValue X;
13240 if (N0.getOpcode() == ISD::ADD) {
13241 if (IsVecReduce(N0.getOperand(0)) && IsVecReduce(N0.getOperand(1))) {
13242 int IsBefore = IsKnownOrderedLoad(N0.getOperand(0).getOperand(0),
13243 N0.getOperand(1).getOperand(0));
13244 if (IsBefore < 0) {
13245 X = N0.getOperand(0);
13246 N0 = N0.getOperand(1);
13247 } else if (IsBefore > 0) {
13248 X = N0.getOperand(1);
13249 N0 = N0.getOperand(0);
13250 } else
13251 return SDValue();
13252 } else if (IsVecReduce(N0.getOperand(0))) {
13253 X = N0.getOperand(1);
13254 N0 = N0.getOperand(0);
13255 } else if (IsVecReduce(N0.getOperand(1))) {
13256 X = N0.getOperand(0);
13257 N0 = N0.getOperand(1);
13258 } else
13259 return SDValue();
13260 } else if (IsForward && IsVecReduce(N0) && IsVecReduce(N1) &&
13261 IsKnownOrderedLoad(N0.getOperand(0), N1.getOperand(0)) < 0) {
13262 // Note this is backward to how you would expect. We create
13263 // add(reduce(load + 16), reduce(load + 0)) so that the
13264 // add(reduce(load+16), X) is combined into VADDVA(X, load+16)), leaving
13265 // the X as VADDV(load + 0)
13266 return DAG.getNode(ISD::ADD, dl, VT, N1, N0);
13267 } else
13268 return SDValue();
13269
13270 if (!IsVecReduce(N0) || !IsVecReduce(N1))
13271 return SDValue();
13272
13273 if (IsKnownOrderedLoad(N1.getOperand(0), N0.getOperand(0)) >= 0)
13274 return SDValue();
13275
13276 // Switch from add(add(X, N0), N1) to add(add(X, N1), N0)
13277 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, X, N1);
13278 return DAG.getNode(ISD::ADD, dl, VT, Add0, N0);
13279 };
13280 if (SDValue R = DistrubuteVecReduceLoad(N0, N1, true))
13281 return R;
13282 if (SDValue R = DistrubuteVecReduceLoad(N1, N0, false))
13283 return R;
13284 return SDValue();
13285}
13286
13287static SDValue PerformADDVecReduce(SDNode *N, SelectionDAG &DAG,
13288 const ARMSubtarget *Subtarget) {
13289 if (!Subtarget->hasMVEIntegerOps())
13290 return SDValue();
13291
13292 if (SDValue R = TryDistrubutionADDVecReduce(N, DAG))
13293 return R;
13294
13295 EVT VT = N->getValueType(0);
13296 SDValue N0 = N->getOperand(0);
13297 SDValue N1 = N->getOperand(1);
13298 SDLoc dl(N);
13299
13300 if (VT != MVT::i64)
13301 return SDValue();
13302
13303 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
13304 // will look like:
13305 // t1: i32,i32 = ARMISD::VADDLVs x
13306 // t2: i64 = build_pair t1, t1:1
13307 // t3: i64 = add t2, y
13308 // Otherwise we try to push the add up above VADDLVAx, to potentially allow
13309 // the add to be simplified seperately.
13310 // We also need to check for sext / zext and commutitive adds.
13311 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
13312 SDValue NB) {
13313 if (NB->getOpcode() != ISD::BUILD_PAIR)
13314 return SDValue();
13315 SDValue VecRed = NB->getOperand(0);
13316 if ((VecRed->getOpcode() != Opcode && VecRed->getOpcode() != OpcodeA) ||
13317 VecRed.getResNo() != 0 ||
13318 NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
13319 return SDValue();
13320
13321 if (VecRed->getOpcode() == OpcodeA) {
13322 // add(NA, VADDLVA(Inp), Y) -> VADDLVA(add(NA, Inp), Y)
13323 SDValue Inp = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
13324 VecRed.getOperand(0), VecRed.getOperand(1));
13325 NA = DAG.getNode(ISD::ADD, dl, MVT::i64, Inp, NA);
13326 }
13327
13328 SmallVector<SDValue, 4> Ops;
13329 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
13330 DAG.getConstant(0, dl, MVT::i32)));
13331 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
13332 DAG.getConstant(1, dl, MVT::i32)));
13333 unsigned S = VecRed->getOpcode() == OpcodeA ? 2 : 0;
13334 for (unsigned I = S, E = VecRed.getNumOperands(); I < E; I++)
13335 Ops.push_back(VecRed->getOperand(I));
13336 SDValue Red =
13337 DAG.getNode(OpcodeA, dl, DAG.getVTList({MVT::i32, MVT::i32}), Ops);
13338 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
13339 SDValue(Red.getNode(), 1));
13340 };
13341
13342 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
13343 return M;
13344 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
13345 return M;
13346 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
13347 return M;
13348 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
13349 return M;
13350 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
13351 return M;
13352 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
13353 return M;
13354 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
13355 return M;
13356 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
13357 return M;
13358 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
13359 return M;
13360 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
13361 return M;
13362 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
13363 return M;
13364 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
13365 return M;
13366 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
13367 return M;
13368 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
13369 return M;
13370 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
13371 return M;
13372 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
13373 return M;
13374 return SDValue();
13375}
13376
13377bool
13378ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
13379 CombineLevel Level) const {
13380 if (Level == BeforeLegalizeTypes)
13381 return true;
13382
13383 if (N->getOpcode() != ISD::SHL)
13384 return true;
13385
13386 if (Subtarget->isThumb1Only()) {
13387 // Avoid making expensive immediates by commuting shifts. (This logic
13388 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
13389 // for free.)
13390 if (N->getOpcode() != ISD::SHL)
13391 return true;
13392 SDValue N1 = N->getOperand(0);
13393 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
13394 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
13395 return true;
13396 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
13397 if (Const->getAPIntValue().ult(256))
13398 return false;
13399 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
13400 Const->getAPIntValue().sgt(-256))
13401 return false;
13402 }
13403 return true;
13404 }
13405
13406 // Turn off commute-with-shift transform after legalization, so it doesn't
13407 // conflict with PerformSHLSimplify. (We could try to detect when
13408 // PerformSHLSimplify would trigger more precisely, but it isn't
13409 // really necessary.)
13410 return false;
13411}
13412
13413bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
13414 const SDNode *N, CombineLevel Level) const {
13415 if (!Subtarget->isThumb1Only())
13416 return true;
13417
13418 if (Level == BeforeLegalizeTypes)
13419 return true;
13420
13421 return false;
13422}
13423
13424bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13425 if (!Subtarget->hasNEON()) {
13426 if (Subtarget->isThumb1Only())
13427 return VT.getScalarSizeInBits() <= 32;
13428 return true;
13429 }
13430 return VT.isScalarInteger();
13431}
13432
13433static SDValue PerformSHLSimplify(SDNode *N,
13434 TargetLowering::DAGCombinerInfo &DCI,
13435 const ARMSubtarget *ST) {
13436 // Allow the generic combiner to identify potential bswaps.
13437 if (DCI.isBeforeLegalize())
13438 return SDValue();
13439
13440 // DAG combiner will fold:
13441 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
13442 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
13443 // Other code patterns that can be also be modified have the following form:
13444 // b + ((a << 1) | 510)
13445 // b + ((a << 1) & 510)
13446 // b + ((a << 1) ^ 510)
13447 // b + ((a << 1) + 510)
13448
13449 // Many instructions can perform the shift for free, but it requires both
13450 // the operands to be registers. If c1 << c2 is too large, a mov immediate
13451 // instruction will needed. So, unfold back to the original pattern if:
13452 // - if c1 and c2 are small enough that they don't require mov imms.
13453 // - the user(s) of the node can perform an shl
13454
13455 // No shifted operands for 16-bit instructions.
13456 if (ST->isThumb() && ST->isThumb1Only())
13457 return SDValue();
13458
13459 // Check that all the users could perform the shl themselves.
13460 for (auto U : N->uses()) {
13461 switch(U->getOpcode()) {
13462 default:
13463 return SDValue();
13464 case ISD::SUB:
13465 case ISD::ADD:
13466 case ISD::AND:
13467 case ISD::OR:
13468 case ISD::XOR:
13469 case ISD::SETCC:
13470 case ARMISD::CMP:
13471 // Check that the user isn't already using a constant because there
13472 // aren't any instructions that support an immediate operand and a
13473 // shifted operand.
13474 if (isa<ConstantSDNode>(U->getOperand(0)) ||
13475 isa<ConstantSDNode>(U->getOperand(1)))
13476 return SDValue();
13477
13478 // Check that it's not already using a shift.
13479 if (U->getOperand(0).getOpcode() == ISD::SHL ||
13480 U->getOperand(1).getOpcode() == ISD::SHL)
13481 return SDValue();
13482 break;
13483 }
13484 }
13485
13486 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
13487 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
13488 return SDValue();
13489
13490 if (N->getOperand(0).getOpcode() != ISD::SHL)
13491 return SDValue();
13492
13493 SDValue SHL = N->getOperand(0);
13494
13495 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
13496 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
13497 if (!C1ShlC2 || !C2)
13498 return SDValue();
13499
13500 APInt C2Int = C2->getAPIntValue();
13501 APInt C1Int = C1ShlC2->getAPIntValue();
13502
13503 // Check that performing a lshr will not lose any information.
13504 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
13505 C2Int.getBitWidth() - C2->getZExtValue());
13506 if ((C1Int & Mask) != C1Int)
13507 return SDValue();
13508
13509 // Shift the first constant.
13510 C1Int.lshrInPlace(C2Int);
13511
13512 // The immediates are encoded as an 8-bit value that can be rotated.
13513 auto LargeImm = [](const APInt &Imm) {
13514 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
13515 return Imm.getBitWidth() - Zeros > 8;
13516 };
13517
13518 if (LargeImm(C1Int) || LargeImm(C2Int))
13519 return SDValue();
13520
13521 SelectionDAG &DAG = DCI.DAG;
13522 SDLoc dl(N);
13523 SDValue X = SHL.getOperand(0);
13524 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
13525 DAG.getConstant(C1Int, dl, MVT::i32));
13526 // Shift left to compensate for the lshr of C1Int.
13527 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
13528
13529 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)
13530 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)
;
13531 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)
;
13532 return Res;
13533}
13534
13535
13536/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
13537///
13538static SDValue PerformADDCombine(SDNode *N,
13539 TargetLowering::DAGCombinerInfo &DCI,
13540 const ARMSubtarget *Subtarget) {
13541 SDValue N0 = N->getOperand(0);
13542 SDValue N1 = N->getOperand(1);
13543
13544 // Only works one way, because it needs an immediate operand.
13545 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13546 return Result;
13547
13548 if (SDValue Result = PerformADDVecReduce(N, DCI.DAG, Subtarget))
13549 return Result;
13550
13551 // First try with the default operand order.
13552 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
13553 return Result;
13554
13555 // If that didn't work, try again with the operands commuted.
13556 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
13557}
13558
13559// Combine (sub 0, (csinc X, Y, CC)) -> (csinv -X, Y, CC)
13560// providing -X is as cheap as X (currently, just a constant).
13561static SDValue PerformSubCSINCCombine(SDNode *N, SelectionDAG &DAG) {
13562 if (N->getValueType(0) != MVT::i32 || !isNullConstant(N->getOperand(0)))
13563 return SDValue();
13564 SDValue CSINC = N->getOperand(1);
13565 if (CSINC.getOpcode() != ARMISD::CSINC || !CSINC.hasOneUse())
13566 return SDValue();
13567
13568 ConstantSDNode *X = dyn_cast<ConstantSDNode>(CSINC.getOperand(0));
13569 if (!X)
13570 return SDValue();
13571
13572 return DAG.getNode(ARMISD::CSINV, SDLoc(N), MVT::i32,
13573 DAG.getNode(ISD::SUB, SDLoc(N), MVT::i32, N->getOperand(0),
13574 CSINC.getOperand(0)),
13575 CSINC.getOperand(1), CSINC.getOperand(2),
13576 CSINC.getOperand(3));
13577}
13578
13579/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
13580///
13581static SDValue PerformSUBCombine(SDNode *N,
13582 TargetLowering::DAGCombinerInfo &DCI,
13583 const ARMSubtarget *Subtarget) {
13584 SDValue N0 = N->getOperand(0);
13585 SDValue N1 = N->getOperand(1);
13586
13587 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
13588 if (N1.getNode()->hasOneUse())
13589 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
13590 return Result;
13591
13592 if (SDValue R = PerformSubCSINCCombine(N, DCI.DAG))
13593 return R;
13594
13595 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
13596 return SDValue();
13597
13598 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
13599 // so that we can readily pattern match more mve instructions which can use
13600 // a scalar operand.
13601 SDValue VDup = N->getOperand(1);
13602 if (VDup->getOpcode() != ARMISD::VDUP)
13603 return SDValue();
13604
13605 SDValue VMov = N->getOperand(0);
13606 if (VMov->getOpcode() == ISD::BITCAST)
13607 VMov = VMov->getOperand(0);
13608
13609 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
13610 return SDValue();
13611
13612 SDLoc dl(N);
13613 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
13614 DCI.DAG.getConstant(0, dl, MVT::i32),
13615 VDup->getOperand(0));
13616 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
13617}
13618
13619/// PerformVMULCombine
13620/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
13621/// special multiplier accumulator forwarding.
13622/// vmul d3, d0, d2
13623/// vmla d3, d1, d2
13624/// is faster than
13625/// vadd d3, d0, d1
13626/// vmul d3, d3, d2
13627// However, for (A + B) * (A + B),
13628// vadd d2, d0, d1
13629// vmul d3, d0, d2
13630// vmla d3, d1, d2
13631// is slower than
13632// vadd d2, d0, d1
13633// vmul d3, d2, d2
13634static SDValue PerformVMULCombine(SDNode *N,
13635 TargetLowering::DAGCombinerInfo &DCI,
13636 const ARMSubtarget *Subtarget) {
13637 if (!Subtarget->hasVMLxForwarding())
13638 return SDValue();
13639
13640 SelectionDAG &DAG = DCI.DAG;
13641 SDValue N0 = N->getOperand(0);
13642 SDValue N1 = N->getOperand(1);
13643 unsigned Opcode = N0.getOpcode();
13644 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
13645 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
13646 Opcode = N1.getOpcode();
13647 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
13648 Opcode != ISD::FADD && Opcode != ISD::FSUB)
13649 return SDValue();
13650 std::swap(N0, N1);
13651 }
13652
13653 if (N0 == N1)
13654 return SDValue();
13655
13656 EVT VT = N->getValueType(0);
13657 SDLoc DL(N);
13658 SDValue N00 = N0->getOperand(0);
13659 SDValue N01 = N0->getOperand(1);
13660 return DAG.getNode(Opcode, DL, VT,
13661 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
13662 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
13663}
13664
13665static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
13666 const ARMSubtarget *Subtarget) {
13667 EVT VT = N->getValueType(0);
13668 if (VT != MVT::v2i64)
13669 return SDValue();
13670
13671 SDValue N0 = N->getOperand(0);
13672 SDValue N1 = N->getOperand(1);
13673
13674 auto IsSignExt = [&](SDValue Op) {
13675 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
13676 return SDValue();
13677 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
13678 if (VT.getScalarSizeInBits() == 32)
13679 return Op->getOperand(0);
13680 return SDValue();
13681 };
13682 auto IsZeroExt = [&](SDValue Op) {
13683 // Zero extends are a little more awkward. At the point we are matching
13684 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
13685 // That might be before of after a bitcast depending on how the and is
13686 // placed. Because this has to look through bitcasts, it is currently only
13687 // supported on LE.
13688 if (!Subtarget->isLittle())
13689 return SDValue();
13690
13691 SDValue And = Op;
13692 if (And->getOpcode() == ISD::BITCAST)
13693 And = And->getOperand(0);
13694 if (And->getOpcode() != ISD::AND)
13695 return SDValue();
13696 SDValue Mask = And->getOperand(1);
13697 if (Mask->getOpcode() == ISD::BITCAST)
13698 Mask = Mask->getOperand(0);
13699
13700 if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
13701 Mask.getValueType() != MVT::v4i32)
13702 return SDValue();
13703 if (isAllOnesConstant(Mask->getOperand(0)) &&
13704 isNullConstant(Mask->getOperand(1)) &&
13705 isAllOnesConstant(Mask->getOperand(2)) &&
13706 isNullConstant(Mask->getOperand(3)))
13707 return And->getOperand(0);
13708 return SDValue();
13709 };
13710
13711 SDLoc dl(N);
13712 if (SDValue Op0 = IsSignExt(N0)) {
13713 if (SDValue Op1 = IsSignExt(N1)) {
13714 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
13715 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
13716 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
13717 }
13718 }
13719 if (SDValue Op0 = IsZeroExt(N0)) {
13720 if (SDValue Op1 = IsZeroExt(N1)) {
13721 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
13722 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
13723 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
13724 }
13725 }
13726
13727 return SDValue();
13728}
13729
13730static SDValue PerformMULCombine(SDNode *N,
13731 TargetLowering::DAGCombinerInfo &DCI,
13732 const ARMSubtarget *Subtarget) {
13733 SelectionDAG &DAG = DCI.DAG;
13734
13735 EVT VT = N->getValueType(0);
13736 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
13737 return PerformMVEVMULLCombine(N, DAG, Subtarget);
13738
13739 if (Subtarget->isThumb1Only())
13740 return SDValue();
13741
13742 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13743 return SDValue();
13744
13745 if (VT.is64BitVector() || VT.is128BitVector())
13746 return PerformVMULCombine(N, DCI, Subtarget);
13747 if (VT != MVT::i32)
13748 return SDValue();
13749
13750 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13751 if (!C)
13752 return SDValue();
13753
13754 int64_t MulAmt = C->getSExtValue();
13755 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
13756
13757 ShiftAmt = ShiftAmt & (32 - 1);
13758 SDValue V = N->getOperand(0);
13759 SDLoc DL(N);
13760
13761 SDValue Res;
13762 MulAmt >>= ShiftAmt;
13763
13764 if (MulAmt >= 0) {
13765 if (isPowerOf2_32(MulAmt - 1)) {
13766 // (mul x, 2^N + 1) => (add (shl x, N), x)
13767 Res = DAG.getNode(ISD::ADD, DL, VT,
13768 V,
13769 DAG.getNode(ISD::SHL, DL, VT,
13770 V,
13771 DAG.getConstant(Log2_32(MulAmt - 1), DL,
13772 MVT::i32)));
13773 } else if (isPowerOf2_32(MulAmt + 1)) {
13774 // (mul x, 2^N - 1) => (sub (shl x, N), x)
13775 Res = DAG.getNode(ISD::SUB, DL, VT,
13776 DAG.getNode(ISD::SHL, DL, VT,
13777 V,
13778 DAG.getConstant(Log2_32(MulAmt + 1), DL,
13779 MVT::i32)),
13780 V);
13781 } else
13782 return SDValue();
13783 } else {
13784 uint64_t MulAmtAbs = -MulAmt;
13785 if (isPowerOf2_32(MulAmtAbs + 1)) {
13786 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
13787 Res = DAG.getNode(ISD::SUB, DL, VT,
13788 V,
13789 DAG.getNode(ISD::SHL, DL, VT,
13790 V,
13791 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
13792 MVT::i32)));
13793 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
13794 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
13795 Res = DAG.getNode(ISD::ADD, DL, VT,
13796 V,
13797 DAG.getNode(ISD::SHL, DL, VT,
13798 V,
13799 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
13800 MVT::i32)));
13801 Res = DAG.getNode(ISD::SUB, DL, VT,
13802 DAG.getConstant(0, DL, MVT::i32), Res);
13803 } else
13804 return SDValue();
13805 }
13806
13807 if (ShiftAmt != 0)
13808 Res = DAG.getNode(ISD::SHL, DL, VT,
13809 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
13810
13811 // Do not add new nodes to DAG combiner worklist.
13812 DCI.CombineTo(N, Res, false);
13813 return SDValue();
13814}
13815
13816static SDValue CombineANDShift(SDNode *N,
13817 TargetLowering::DAGCombinerInfo &DCI,
13818 const ARMSubtarget *Subtarget) {
13819 // Allow DAGCombine to pattern-match before we touch the canonical form.
13820 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13821 return SDValue();
13822
13823 if (N->getValueType(0) != MVT::i32)
13824 return SDValue();
13825
13826 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13827 if (!N1C)
13828 return SDValue();
13829
13830 uint32_t C1 = (uint32_t)N1C->getZExtValue();
13831 // Don't transform uxtb/uxth.
13832 if (C1 == 255 || C1 == 65535)
13833 return SDValue();
13834
13835 SDNode *N0 = N->getOperand(0).getNode();
13836 if (!N0->hasOneUse())
13837 return SDValue();
13838
13839 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
13840 return SDValue();
13841
13842 bool LeftShift = N0->getOpcode() == ISD::SHL;
13843
13844 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13845 if (!N01C)
13846 return SDValue();
13847
13848 uint32_t C2 = (uint32_t)N01C->getZExtValue();
13849 if (!C2 || C2 >= 32)
13850 return SDValue();
13851
13852 // Clear irrelevant bits in the mask.
13853 if (LeftShift)
13854 C1 &= (-1U << C2);
13855 else
13856 C1 &= (-1U >> C2);
13857
13858 SelectionDAG &DAG = DCI.DAG;
13859 SDLoc DL(N);
13860
13861 // We have a pattern of the form "(and (shl x, c2) c1)" or
13862 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
13863 // transform to a pair of shifts, to save materializing c1.
13864
13865 // First pattern: right shift, then mask off leading bits.
13866 // FIXME: Use demanded bits?
13867 if (!LeftShift && isMask_32(C1)) {
13868 uint32_t C3 = countLeadingZeros(C1);
13869 if (C2 < C3) {
13870 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13871 DAG.getConstant(C3 - C2, DL, MVT::i32));
13872 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
13873 DAG.getConstant(C3, DL, MVT::i32));
13874 }
13875 }
13876
13877 // First pattern, reversed: left shift, then mask off trailing bits.
13878 if (LeftShift && isMask_32(~C1)) {
13879 uint32_t C3 = countTrailingZeros(C1);
13880 if (C2 < C3) {
13881 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
13882 DAG.getConstant(C3 - C2, DL, MVT::i32));
13883 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
13884 DAG.getConstant(C3, DL, MVT::i32));
13885 }
13886 }
13887
13888 // Second pattern: left shift, then mask off leading bits.
13889 // FIXME: Use demanded bits?
13890 if (LeftShift && isShiftedMask_32(C1)) {
13891 uint32_t Trailing = countTrailingZeros(C1);
13892 uint32_t C3 = countLeadingZeros(C1);
13893 if (Trailing == C2 && C2 + C3 < 32) {
13894 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13895 DAG.getConstant(C2 + C3, DL, MVT::i32));
13896 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
13897 DAG.getConstant(C3, DL, MVT::i32));
13898 }
13899 }
13900
13901 // Second pattern, reversed: right shift, then mask off trailing bits.
13902 // FIXME: Handle other patterns of known/demanded bits.
13903 if (!LeftShift && isShiftedMask_32(C1)) {
13904 uint32_t Leading = countLeadingZeros(C1);
13905 uint32_t C3 = countTrailingZeros(C1);
13906 if (Leading == C2 && C2 + C3 < 32) {
13907 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
13908 DAG.getConstant(C2 + C3, DL, MVT::i32));
13909 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
13910 DAG.getConstant(C3, DL, MVT::i32));
13911 }
13912 }
13913
13914 // FIXME: Transform "(and (shl x, c2) c1)" ->
13915 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
13916 // c1.
13917 return SDValue();
13918}
13919
13920static SDValue PerformANDCombine(SDNode *N,
13921 TargetLowering::DAGCombinerInfo &DCI,
13922 const ARMSubtarget *Subtarget) {
13923 // Attempt to use immediate-form VBIC
13924 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
13925 SDLoc dl(N);
13926 EVT VT = N->getValueType(0);
13927 SelectionDAG &DAG = DCI.DAG;
13928
13929 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 ||
13930 VT == MVT::v8i1 || VT == MVT::v16i1)
13931 return SDValue();
13932
13933 APInt SplatBits, SplatUndef;
13934 unsigned SplatBitSize;
13935 bool HasAnyUndefs;
13936 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
13937 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
13938 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
13939 SplatBitSize == 64) {
13940 EVT VbicVT;
13941 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
13942 SplatUndef.getZExtValue(), SplatBitSize,
13943 DAG, dl, VbicVT, VT, OtherModImm);
13944 if (Val.getNode()) {
13945 SDValue Input =
13946 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
13947 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
13948 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
13949 }
13950 }
13951 }
13952
13953 if (!Subtarget->isThumb1Only()) {
13954 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
13955 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
13956 return Result;
13957
13958 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13959 return Result;
13960 }
13961
13962 if (Subtarget->isThumb1Only())
13963 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
13964 return Result;
13965
13966 return SDValue();
13967}
13968
13969// Try combining OR nodes to SMULWB, SMULWT.
13970static SDValue PerformORCombineToSMULWBT(SDNode *OR,
13971 TargetLowering::DAGCombinerInfo &DCI,
13972 const ARMSubtarget *Subtarget) {
13973 if (!Subtarget->hasV6Ops() ||
13974 (Subtarget->isThumb() &&
13975 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
13976 return SDValue();
13977
13978 SDValue SRL = OR->getOperand(0);
13979 SDValue SHL = OR->getOperand(1);
13980
13981 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
13982 SRL = OR->getOperand(1);
13983 SHL = OR->getOperand(0);
13984 }
13985 if (!isSRL16(SRL) || !isSHL16(SHL))
13986 return SDValue();
13987
13988 // The first operands to the shifts need to be the two results from the
13989 // same smul_lohi node.
13990 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
13991 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
13992 return SDValue();
13993
13994 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
13995 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
13996 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
13997 return SDValue();
13998
13999 // Now we have:
14000 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
14001 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
14002 // For SMUWB the 16-bit value will signed extended somehow.
14003 // For SMULWT only the SRA is required.
14004 // Check both sides of SMUL_LOHI
14005 SDValue OpS16 = SMULLOHI->getOperand(0);
14006 SDValue OpS32 = SMULLOHI->getOperand(1);
14007
14008 SelectionDAG &DAG = DCI.DAG;
14009 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
14010 OpS16 = OpS32;
14011 OpS32 = SMULLOHI->getOperand(0);
14012 }
14013
14014 SDLoc dl(OR);
14015 unsigned Opcode = 0;
14016 if (isS16(OpS16, DAG))
14017 Opcode = ARMISD::SMULWB;
14018 else if (isSRA16(OpS16)) {
14019 Opcode = ARMISD::SMULWT;
14020 OpS16 = OpS16->getOperand(0);
14021 }
14022 else
14023 return SDValue();
14024
14025 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
14026 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
14027 return SDValue(OR, 0);
14028}
14029
14030static SDValue PerformORCombineToBFI(SDNode *N,
14031 TargetLowering::DAGCombinerInfo &DCI,
14032 const ARMSubtarget *Subtarget) {
14033 // BFI is only available on V6T2+
14034 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
14035 return SDValue();
14036
14037 EVT VT = N->getValueType(0);
14038 SDValue N0 = N->getOperand(0);
14039 SDValue N1 = N->getOperand(1);
14040 SelectionDAG &DAG = DCI.DAG;
14041 SDLoc DL(N);
14042 // 1) or (and A, mask), val => ARMbfi A, val, mask
14043 // iff (val & mask) == val
14044 //
14045 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14046 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
14047 // && mask == ~mask2
14048 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
14049 // && ~mask == mask2
14050 // (i.e., copy a bitfield value into another bitfield of the same width)
14051
14052 if (VT != MVT::i32)
14053 return SDValue();
14054
14055 SDValue N00 = N0.getOperand(0);
14056
14057 // The value and the mask need to be constants so we can verify this is
14058 // actually a bitfield set. If the mask is 0xffff, we can do better
14059 // via a movt instruction, so don't use BFI in that case.
14060 SDValue MaskOp = N0.getOperand(1);
14061 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
14062 if (!MaskC)
14063 return SDValue();
14064 unsigned Mask = MaskC->getZExtValue();
14065 if (Mask == 0xffff)
14066 return SDValue();
14067 SDValue Res;
14068 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
14069 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14070 if (N1C) {
14071 unsigned Val = N1C->getZExtValue();
14072 if ((Val & ~Mask) != Val)
14073 return SDValue();
14074
14075 if (ARM::isBitFieldInvertedMask(Mask)) {
14076 Val >>= countTrailingZeros(~Mask);
14077
14078 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
14079 DAG.getConstant(Val, DL, MVT::i32),
14080 DAG.getConstant(Mask, DL, MVT::i32));
14081
14082 DCI.CombineTo(N, Res, false);
14083 // Return value from the original node to inform the combiner than N is
14084 // now dead.
14085 return SDValue(N, 0);
14086 }
14087 } else if (N1.getOpcode() == ISD::AND) {
14088 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14089 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
14090 if (!N11C)
14091 return SDValue();
14092 unsigned Mask2 = N11C->getZExtValue();
14093
14094 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
14095 // as is to match.
14096 if (ARM::isBitFieldInvertedMask(Mask) &&
14097 (Mask == ~Mask2)) {
14098 // The pack halfword instruction works better for masks that fit it,
14099 // so use that when it's available.
14100 if (Subtarget->hasDSP() &&
14101 (Mask == 0xffff || Mask == 0xffff0000))
14102 return SDValue();
14103 // 2a
14104 unsigned amt = countTrailingZeros(Mask2);
14105 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
14106 DAG.getConstant(amt, DL, MVT::i32));
14107 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
14108 DAG.getConstant(Mask, DL, MVT::i32));
14109 DCI.CombineTo(N, Res, false);
14110 // Return value from the original node to inform the combiner than N is
14111 // now dead.
14112 return SDValue(N, 0);
14113 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
14114 (~Mask == Mask2)) {
14115 // The pack halfword instruction works better for masks that fit it,
14116 // so use that when it's available.
14117 if (Subtarget->hasDSP() &&
14118 (Mask2 == 0xffff || Mask2 == 0xffff0000))
14119 return SDValue();
14120 // 2b
14121 unsigned lsb = countTrailingZeros(Mask);
14122 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
14123 DAG.getConstant(lsb, DL, MVT::i32));
14124 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
14125 DAG.getConstant(Mask2, DL, MVT::i32));
14126 DCI.CombineTo(N, Res, false);
14127 // Return value from the original node to inform the combiner than N is
14128 // now dead.
14129 return SDValue(N, 0);
14130 }
14131 }
14132
14133 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
14134 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
14135 ARM::isBitFieldInvertedMask(~Mask)) {
14136 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
14137 // where lsb(mask) == #shamt and masked bits of B are known zero.
14138 SDValue ShAmt = N00.getOperand(1);
14139 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
14140 unsigned LSB = countTrailingZeros(Mask);
14141 if (ShAmtC != LSB)
14142 return SDValue();
14143
14144 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
14145 DAG.getConstant(~Mask, DL, MVT::i32));
14146
14147 DCI.CombineTo(N, Res, false);
14148 // Return value from the original node to inform the combiner than N is
14149 // now dead.
14150 return SDValue(N, 0);
14151 }
14152
14153 return SDValue();
14154}
14155
14156static bool isValidMVECond(unsigned CC, bool IsFloat) {
14157 switch (CC) {
14158 case ARMCC::EQ:
14159 case ARMCC::NE:
14160 case ARMCC::LE:
14161 case ARMCC::GT:
14162 case ARMCC::GE:
14163 case ARMCC::LT:
14164 return true;
14165 case ARMCC::HS:
14166 case ARMCC::HI:
14167 return !IsFloat;
14168 default:
14169 return false;
14170 };
14171}
14172
14173static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
14174 if (N->getOpcode() == ARMISD::VCMP)
14175 return (ARMCC::CondCodes)N->getConstantOperandVal(2);
14176 else if (N->getOpcode() == ARMISD::VCMPZ)
14177 return (ARMCC::CondCodes)N->getConstantOperandVal(1);
14178 else
14179 llvm_unreachable("Not a VCMP/VCMPZ!")::llvm::llvm_unreachable_internal("Not a VCMP/VCMPZ!", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14179)
;
14180}
14181
14182static bool CanInvertMVEVCMP(SDValue N) {
14183 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N));
14184 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
14185}
14186
14187static SDValue PerformORCombine_i1(SDNode *N, SelectionDAG &DAG,
14188 const ARMSubtarget *Subtarget) {
14189 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
14190 // together with predicates
14191 EVT VT = N->getValueType(0);
14192 SDLoc DL(N);
14193 SDValue N0 = N->getOperand(0);
14194 SDValue N1 = N->getOperand(1);
14195
14196 auto IsFreelyInvertable = [&](SDValue V) {
14197 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
14198 return CanInvertMVEVCMP(V);
14199 return false;
14200 };
14201
14202 // At least one operand must be freely invertable.
14203 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
14204 return SDValue();
14205
14206 SDValue NewN0 = DAG.getLogicalNOT(DL, N0, VT);
14207 SDValue NewN1 = DAG.getLogicalNOT(DL, N1, VT);
14208 SDValue And = DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
14209 return DAG.getLogicalNOT(DL, And, VT);
14210}
14211
14212/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
14213static SDValue PerformORCombine(SDNode *N,
14214 TargetLowering::DAGCombinerInfo &DCI,
14215 const ARMSubtarget *Subtarget) {
14216 // Attempt to use immediate-form VORR
14217 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14218 SDLoc dl(N);
14219 EVT VT = N->getValueType(0);
14220 SelectionDAG &DAG = DCI.DAG;
14221
14222 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14223 return SDValue();
14224
14225 if (Subtarget->hasMVEIntegerOps() &&
14226 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
14227 return PerformORCombine_i1(N, DAG, Subtarget);
14228
14229 APInt SplatBits, SplatUndef;
14230 unsigned SplatBitSize;
14231 bool HasAnyUndefs;
14232 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14233 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14234 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14235 SplatBitSize == 64) {
14236 EVT VorrVT;
14237 SDValue Val =
14238 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
14239 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
14240 if (Val.getNode()) {
14241 SDValue Input =
14242 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
14243 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
14244 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
14245 }
14246 }
14247 }
14248
14249 if (!Subtarget->isThumb1Only()) {
14250 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
14251 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14252 return Result;
14253 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
14254 return Result;
14255 }
14256
14257 SDValue N0 = N->getOperand(0);
14258 SDValue N1 = N->getOperand(1);
14259
14260 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
14261 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
14262 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14263
14264 // The code below optimizes (or (and X, Y), Z).
14265 // The AND operand needs to have a single user to make these optimizations
14266 // profitable.
14267 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
14268 return SDValue();
14269
14270 APInt SplatUndef;
14271 unsigned SplatBitSize;
14272 bool HasAnyUndefs;
14273
14274 APInt SplatBits0, SplatBits1;
14275 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
14276 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
14277 // Ensure that the second operand of both ands are constants
14278 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
14279 HasAnyUndefs) && !HasAnyUndefs) {
14280 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
14281 HasAnyUndefs) && !HasAnyUndefs) {
14282 // Ensure that the bit width of the constants are the same and that
14283 // the splat arguments are logical inverses as per the pattern we
14284 // are trying to simplify.
14285 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
14286 SplatBits0 == ~SplatBits1) {
14287 // Canonicalize the vector type to make instruction selection
14288 // simpler.
14289 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
14290 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT,
14291 N0->getOperand(1),
14292 N0->getOperand(0),
14293 N1->getOperand(0));
14294 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14295 }
14296 }
14297 }
14298 }
14299
14300 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
14301 // reasonable.
14302 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
14303 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
14304 return Res;
14305 }
14306
14307 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14308 return Result;
14309
14310 return SDValue();
14311}
14312
14313static SDValue PerformXORCombine(SDNode *N,
14314 TargetLowering::DAGCombinerInfo &DCI,
14315 const ARMSubtarget *Subtarget) {
14316 EVT VT = N->getValueType(0);
14317 SelectionDAG &DAG = DCI.DAG;
14318
14319 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14320 return SDValue();
14321
14322 if (!Subtarget->isThumb1Only()) {
14323 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
14324 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14325 return Result;
14326
14327 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14328 return Result;
14329 }
14330
14331 if (Subtarget->hasMVEIntegerOps()) {
14332 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
14333 SDValue N0 = N->getOperand(0);
14334 SDValue N1 = N->getOperand(1);
14335 const TargetLowering *TLI = Subtarget->getTargetLowering();
14336 if (TLI->isConstTrueVal(N1.getNode()) &&
14337 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
14338 if (CanInvertMVEVCMP(N0)) {
14339 SDLoc DL(N0);
14340 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0));
14341
14342 SmallVector<SDValue, 4> Ops;
14343 Ops.push_back(N0->getOperand(0));
14344 if (N0->getOpcode() == ARMISD::VCMP)
14345 Ops.push_back(N0->getOperand(1));
14346 Ops.push_back(DAG.getConstant(CC, DL, MVT::i32));
14347 return DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
14348 }
14349 }
14350 }
14351
14352 return SDValue();
14353}
14354
14355// ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
14356// and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
14357// their position in "to" (Rd).
14358static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
14359 assert(N->getOpcode() == ARMISD::BFI)(static_cast <bool> (N->getOpcode() == ARMISD::BFI) ?
void (0) : __assert_fail ("N->getOpcode() == ARMISD::BFI"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14359, __extension__ __PRETTY_FUNCTION__))
;
14360
14361 SDValue From = N->getOperand(1);
14362 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
14363 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
14364
14365 // If the Base came from a SHR #C, we can deduce that it is really testing bit
14366 // #C in the base of the SHR.
14367 if (From->getOpcode() == ISD::SRL &&
14368 isa<ConstantSDNode>(From->getOperand(1))) {
14369 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
14370 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14370, __extension__ __PRETTY_FUNCTION__))
;
14371 FromMask <<= Shift.getLimitedValue(31);
14372 From = From->getOperand(0);
14373 }
14374
14375 return From;
14376}
14377
14378// If A and B contain one contiguous set of bits, does A | B == A . B?
14379//
14380// Neither A nor B must be zero.
14381static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
14382 unsigned LastActiveBitInA = A.countTrailingZeros();
14383 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
14384 return LastActiveBitInA - 1 == FirstActiveBitInB;
14385}
14386
14387static SDValue FindBFIToCombineWith(SDNode *N) {
14388 // We have a BFI in N. Find a BFI it can combine with, if one exists.
14389 APInt ToMask, FromMask;
14390 SDValue From = ParseBFI(N, ToMask, FromMask);
14391 SDValue To = N->getOperand(0);
14392
14393 SDValue V = To;
14394 if (V.getOpcode() != ARMISD::BFI)
14395 return SDValue();
14396
14397 APInt NewToMask, NewFromMask;
14398 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
14399 if (NewFrom != From)
14400 return SDValue();
14401
14402 // Do the written bits conflict with any we've seen so far?
14403 if ((NewToMask & ToMask).getBoolValue())
14404 // Conflicting bits.
14405 return SDValue();
14406
14407 // Are the new bits contiguous when combined with the old bits?
14408 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
14409 BitsProperlyConcatenate(FromMask, NewFromMask))
14410 return V;
14411 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
14412 BitsProperlyConcatenate(NewFromMask, FromMask))
14413 return V;
14414
14415 return SDValue();
14416}
14417
14418static SDValue PerformBFICombine(SDNode *N, SelectionDAG &DAG) {
14419 SDValue N0 = N->getOperand(0);
14420 SDValue N1 = N->getOperand(1);
14421
14422 if (N1.getOpcode() == ISD::AND) {
14423 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
14424 // the bits being cleared by the AND are not demanded by the BFI.
14425 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
14426 if (!N11C)
14427 return SDValue();
14428 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14429 unsigned LSB = countTrailingZeros(~InvMask);
14430 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
14431 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14433, __extension__ __PRETTY_FUNCTION__))
14432 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14433, __extension__ __PRETTY_FUNCTION__))
14433 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14433, __extension__ __PRETTY_FUNCTION__))
;
14434 unsigned Mask = (1u << Width) - 1;
14435 unsigned Mask2 = N11C->getZExtValue();
14436 if ((Mask & (~Mask2)) == 0)
14437 return DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
14438 N->getOperand(0), N1.getOperand(0), N->getOperand(2));
14439 return SDValue();
14440 }
14441
14442 // Look for another BFI to combine with.
14443 if (SDValue CombineBFI = FindBFIToCombineWith(N)) {
14444 // We've found a BFI.
14445 APInt ToMask1, FromMask1;
14446 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
14447
14448 APInt ToMask2, FromMask2;
14449 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
14450 assert(From1 == From2)(static_cast <bool> (From1 == From2) ? void (0) : __assert_fail
("From1 == From2", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14450, __extension__ __PRETTY_FUNCTION__))
;
14451 (void)From2;
14452
14453 // Create a new BFI, combining the two together.
14454 APInt NewFromMask = FromMask1 | FromMask2;
14455 APInt NewToMask = ToMask1 | ToMask2;
14456
14457 EVT VT = N->getValueType(0);
14458 SDLoc dl(N);
14459
14460 if (NewFromMask[0] == 0)
14461 From1 = DAG.getNode(
14462 ISD::SRL, dl, VT, From1,
14463 DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
14464 return DAG.getNode(ARMISD::BFI, dl, VT, CombineBFI.getOperand(0), From1,
14465 DAG.getConstant(~NewToMask, dl, VT));
14466 }
14467
14468 // Reassociate BFI(BFI (A, B, M1), C, M2) to BFI(BFI (A, C, M2), B, M1) so
14469 // that lower bit insertions are performed first, providing that M1 and M2
14470 // do no overlap. This can allow multiple BFI instructions to be combined
14471 // together by the other folds above.
14472 if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
14473 APInt ToMask1 = ~N->getConstantOperandAPInt(2);
14474 APInt ToMask2 = ~N0.getConstantOperandAPInt(2);
14475
14476 if (!N0.hasOneUse() || (ToMask1 & ToMask2) != 0 ||
14477 ToMask1.countLeadingZeros() < ToMask2.countLeadingZeros())
14478 return SDValue();
14479
14480 EVT VT = N->getValueType(0);
14481 SDLoc dl(N);
14482 SDValue BFI1 = DAG.getNode(ARMISD::BFI, dl, VT, N0.getOperand(0),
14483 N->getOperand(1), N->getOperand(2));
14484 return DAG.getNode(ARMISD::BFI, dl, VT, BFI1, N0.getOperand(1),
14485 N0.getOperand(2));
14486 }
14487
14488 return SDValue();
14489}
14490
14491/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
14492/// ARMISD::VMOVRRD.
14493static SDValue PerformVMOVRRDCombine(SDNode *N,
14494 TargetLowering::DAGCombinerInfo &DCI,
14495 const ARMSubtarget *Subtarget) {
14496 // vmovrrd(vmovdrr x, y) -> x,y
14497 SDValue InDouble = N->getOperand(0);
14498 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
14499 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
14500
14501 // vmovrrd(load f64) -> (load i32), (load i32)
14502 SDNode *InNode = InDouble.getNode();
14503 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
14504 InNode->getValueType(0) == MVT::f64 &&
14505 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
14506 !cast<LoadSDNode>(InNode)->isVolatile()) {
14507 // TODO: Should this be done for non-FrameIndex operands?
14508 LoadSDNode *LD = cast<LoadSDNode>(InNode);
14509
14510 SelectionDAG &DAG = DCI.DAG;
14511 SDLoc DL(LD);
14512 SDValue BasePtr = LD->getBasePtr();
14513 SDValue NewLD1 =
14514 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
14515 LD->getAlignment(), LD->getMemOperand()->getFlags());
14516
14517 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
14518 DAG.getConstant(4, DL, MVT::i32));
14519
14520 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
14521 LD->getPointerInfo().getWithOffset(4),
14522 std::min(4U, LD->getAlignment()),
14523 LD->getMemOperand()->getFlags());
14524
14525 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
14526 if (DCI.DAG.getDataLayout().isBigEndian())
14527 std::swap (NewLD1, NewLD2);
14528 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
14529 return Result;
14530 }
14531
14532 // VMOVRRD(extract(..(build_vector(a, b, c, d)))) -> a,b or c,d
14533 // VMOVRRD(extract(insert_vector(insert_vector(.., a, l1), b, l2))) -> a,b
14534 if (InDouble.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14535 isa<ConstantSDNode>(InDouble.getOperand(1))) {
14536 SDValue BV = InDouble.getOperand(0);
14537 // Look up through any nop bitcasts and vector_reg_casts. bitcasts may
14538 // change lane order under big endian.
14539 bool BVSwap = BV.getOpcode() == ISD::BITCAST;
14540 while (
14541 (BV.getOpcode() == ISD::BITCAST ||
14542 BV.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
14543 (BV.getValueType() == MVT::v2f64 || BV.getValueType() == MVT::v2i64)) {
14544 BVSwap = BV.getOpcode() == ISD::BITCAST;
14545 BV = BV.getOperand(0);
14546 }
14547 if (BV.getValueType() != MVT::v4i32)
14548 return SDValue();
14549
14550 // Handle buildvectors, pulling out the correct lane depending on
14551 // endianness.
14552 unsigned Offset = InDouble.getConstantOperandVal(1) == 1 ? 2 : 0;
14553 if (BV.getOpcode() == ISD::BUILD_VECTOR) {
14554 SDValue Op0 = BV.getOperand(Offset);
14555 SDValue Op1 = BV.getOperand(Offset + 1);
14556 if (!Subtarget->isLittle() && BVSwap)
14557 std::swap(Op0, Op1);
14558
14559 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
14560 }
14561
14562 // A chain of insert_vectors, grabbing the correct value of the chain of
14563 // inserts.
14564 SDValue Op0, Op1;
14565 while (BV.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14566 if (isa<ConstantSDNode>(BV.getOperand(2))) {
14567 if (BV.getConstantOperandVal(2) == Offset)
14568 Op0 = BV.getOperand(1);
14569 if (BV.getConstantOperandVal(2) == Offset + 1)
14570 Op1 = BV.getOperand(1);
14571 }
14572 BV = BV.getOperand(0);
14573 }
14574 if (!Subtarget->isLittle() && BVSwap)
14575 std::swap(Op0, Op1);
14576 if (Op0 && Op1)
14577 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
14578 }
14579
14580 return SDValue();
14581}
14582
14583/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
14584/// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
14585static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
14586 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
14587 SDValue Op0 = N->getOperand(0);
14588 SDValue Op1 = N->getOperand(1);
14589 if (Op0.getOpcode() == ISD::BITCAST)
14590 Op0 = Op0.getOperand(0);
14591 if (Op1.getOpcode() == ISD::BITCAST)
14592 Op1 = Op1.getOperand(0);
14593 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
14594 Op0.getNode() == Op1.getNode() &&
14595 Op0.getResNo() == 0 && Op1.getResNo() == 1)
14596 return DAG.getNode(ISD::BITCAST, SDLoc(N),
14597 N->getValueType(0), Op0.getOperand(0));
14598 return SDValue();
14599}
14600
14601static SDValue PerformVMOVhrCombine(SDNode *N,
14602 TargetLowering::DAGCombinerInfo &DCI) {
14603 SDValue Op0 = N->getOperand(0);
14604
14605 // VMOVhr (VMOVrh (X)) -> X
14606 if (Op0->getOpcode() == ARMISD::VMOVrh)
14607 return Op0->getOperand(0);
14608
14609 // FullFP16: half values are passed in S-registers, and we don't
14610 // need any of the bitcast and moves:
14611 //
14612 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
14613 // t5: i32 = bitcast t2
14614 // t18: f16 = ARMISD::VMOVhr t5
14615 if (Op0->getOpcode() == ISD::BITCAST) {
14616 SDValue Copy = Op0->getOperand(0);
14617 if (Copy.getValueType() == MVT::f32 &&
14618 Copy->getOpcode() == ISD::CopyFromReg) {
14619 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)};
14620 SDValue NewCopy =
14621 DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops);
14622 return NewCopy;
14623 }
14624 }
14625
14626 // fold (VMOVhr (load x)) -> (load (f16*)x)
14627 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
14628 if (LN0->hasOneUse() && LN0->isUnindexed() &&
14629 LN0->getMemoryVT() == MVT::i16) {
14630 SDValue Load =
14631 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
14632 LN0->getBasePtr(), LN0->getMemOperand());
14633 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
14634 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
14635 return Load;
14636 }
14637 }
14638
14639 // Only the bottom 16 bits of the source register are used.
14640 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
14641 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
14642 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
14643 return SDValue(N, 0);
14644
14645 return SDValue();
14646}
14647
14648static SDValue PerformVMOVrhCombine(SDNode *N, SelectionDAG &DAG) {
14649 SDValue N0 = N->getOperand(0);
14650 EVT VT = N->getValueType(0);
14651
14652 // fold (VMOVrh (fpconst x)) -> const x
14653 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) {
14654 APFloat V = C->getValueAPF();
14655 return DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
14656 }
14657
14658 // fold (VMOVrh (load x)) -> (zextload (i16*)x)
14659 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
14660 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
14661
14662 SDValue Load =
14663 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
14664 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
14665 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
14666 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
14667 return Load;
14668 }
14669
14670 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
14671 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14672 isa<ConstantSDNode>(N0->getOperand(1)))
14673 return DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
14674 N0->getOperand(1));
14675
14676 return SDValue();
14677}
14678
14679/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
14680/// are normal, non-volatile loads. If so, it is profitable to bitcast an
14681/// i64 vector to have f64 elements, since the value can then be loaded
14682/// directly into a VFP register.
14683static bool hasNormalLoadOperand(SDNode *N) {
14684 unsigned NumElts = N->getValueType(0).getVectorNumElements();
14685 for (unsigned i = 0; i < NumElts; ++i) {
14686 SDNode *Elt = N->getOperand(i).getNode();
14687 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
14688 return true;
14689 }
14690 return false;
14691}
14692
14693/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
14694/// ISD::BUILD_VECTOR.
14695static SDValue PerformBUILD_VECTORCombine(SDNode *N,
14696 TargetLowering::DAGCombinerInfo &DCI,
14697 const ARMSubtarget *Subtarget) {
14698 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
14699 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
14700 // into a pair of GPRs, which is fine when the value is used as a scalar,
14701 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
14702 SelectionDAG &DAG = DCI.DAG;
14703 if (N->getNumOperands() == 2)
14704 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
14705 return RV;
14706
14707 // Load i64 elements as f64 values so that type legalization does not split
14708 // them up into i32 values.
14709 EVT VT = N->getValueType(0);
14710 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
14711 return SDValue();
14712 SDLoc dl(N);
14713 SmallVector<SDValue, 8> Ops;
14714 unsigned NumElts = VT.getVectorNumElements();
14715 for (unsigned i = 0; i < NumElts; ++i) {
14716 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
14717 Ops.push_back(V);
14718 // Make the DAGCombiner fold the bitcast.
14719 DCI.AddToWorklist(V.getNode());
14720 }
14721 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
14722 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
14723 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
14724}
14725
14726/// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
14727static SDValue
14728PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
14729 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
14730 // At that time, we may have inserted bitcasts from integer to float.
14731 // If these bitcasts have survived DAGCombine, change the lowering of this
14732 // BUILD_VECTOR in something more vector friendly, i.e., that does not
14733 // force to use floating point types.
14734
14735 // Make sure we can change the type of the vector.
14736 // This is possible iff:
14737 // 1. The vector is only used in a bitcast to a integer type. I.e.,
14738 // 1.1. Vector is used only once.
14739 // 1.2. Use is a bit convert to an integer type.
14740 // 2. The size of its operands are 32-bits (64-bits are not legal).
14741 EVT VT = N->getValueType(0);
14742 EVT EltVT = VT.getVectorElementType();
14743
14744 // Check 1.1. and 2.
14745 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
14746 return SDValue();
14747
14748 // By construction, the input type must be float.
14749 assert(EltVT == MVT::f32 && "Unexpected type!")(static_cast <bool> (EltVT == MVT::f32 && "Unexpected type!"
) ? void (0) : __assert_fail ("EltVT == MVT::f32 && \"Unexpected type!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14749, __extension__ __PRETTY_FUNCTION__))
;
14750
14751 // Check 1.2.
14752 SDNode *Use = *N->use_begin();
14753 if (Use->getOpcode() != ISD::BITCAST ||
14754 Use->getValueType(0).isFloatingPoint())
14755 return SDValue();
14756
14757 // Check profitability.
14758 // Model is, if more than half of the relevant operands are bitcast from
14759 // i32, turn the build_vector into a sequence of insert_vector_elt.
14760 // Relevant operands are everything that is not statically
14761 // (i.e., at compile time) bitcasted.
14762 unsigned NumOfBitCastedElts = 0;
14763 unsigned NumElts = VT.getVectorNumElements();
14764 unsigned NumOfRelevantElts = NumElts;
14765 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
14766 SDValue Elt = N->getOperand(Idx);
14767 if (Elt->getOpcode() == ISD::BITCAST) {
14768 // Assume only bit cast to i32 will go away.
14769 if (Elt->getOperand(0).getValueType() == MVT::i32)
14770 ++NumOfBitCastedElts;
14771 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
14772 // Constants are statically casted, thus do not count them as
14773 // relevant operands.
14774 --NumOfRelevantElts;
14775 }
14776
14777 // Check if more than half of the elements require a non-free bitcast.
14778 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
14779 return SDValue();
14780
14781 SelectionDAG &DAG = DCI.DAG;
14782 // Create the new vector type.
14783 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
14784 // Check if the type is legal.
14785 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14786 if (!TLI.isTypeLegal(VecVT))
14787 return SDValue();
14788
14789 // Combine:
14790 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
14791 // => BITCAST INSERT_VECTOR_ELT
14792 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
14793 // (BITCAST EN), N.
14794 SDValue Vec = DAG.getUNDEF(VecVT);
14795 SDLoc dl(N);
14796 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
14797 SDValue V = N->getOperand(Idx);
14798 if (V.isUndef())
14799 continue;
14800 if (V.getOpcode() == ISD::BITCAST &&
14801 V->getOperand(0).getValueType() == MVT::i32)
14802 // Fold obvious case.
14803 V = V.getOperand(0);
14804 else {
14805 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
14806 // Make the DAGCombiner fold the bitcasts.
14807 DCI.AddToWorklist(V.getNode());
14808 }
14809 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
14810 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
14811 }
14812 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
14813 // Make the DAGCombiner fold the bitcasts.
14814 DCI.AddToWorklist(Vec.getNode());
14815 return Vec;
14816}
14817
14818static SDValue
14819PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
14820 EVT VT = N->getValueType(0);
14821 SDValue Op = N->getOperand(0);
14822 SDLoc dl(N);
14823
14824 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
14825 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
14826 // If the valuetypes are the same, we can remove the cast entirely.
14827 if (Op->getOperand(0).getValueType() == VT)
14828 return Op->getOperand(0);
14829 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
14830 }
14831
14832 // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
14833 // more VPNOT which might get folded as else predicates.
14834 if (Op.getValueType() == MVT::i32 && isBitwiseNot(Op)) {
14835 SDValue X =
14836 DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
14837 SDValue C = DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
14838 DCI.DAG.getConstant(65535, dl, MVT::i32));
14839 return DCI.DAG.getNode(ISD::XOR, dl, VT, X, C);
14840 }
14841
14842 // Only the bottom 16 bits of the source register are used.
14843 if (Op.getValueType() == MVT::i32) {
14844 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
14845 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
14846 if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
14847 return SDValue(N, 0);
14848 }
14849 return SDValue();
14850}
14851
14852static SDValue PerformVECTOR_REG_CASTCombine(SDNode *N, SelectionDAG &DAG,
14853 const ARMSubtarget *ST) {
14854 EVT VT = N->getValueType(0);
14855 SDValue Op = N->getOperand(0);
14856 SDLoc dl(N);
14857
14858 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
14859 if (ST->isLittle())
14860 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14861
14862 // VECTOR_REG_CAST undef -> undef
14863 if (Op.isUndef())
14864 return DAG.getUNDEF(VT);
14865
14866 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
14867 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
14868 // If the valuetypes are the same, we can remove the cast entirely.
14869 if (Op->getOperand(0).getValueType() == VT)
14870 return Op->getOperand(0);
14871 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
14872 }
14873
14874 return SDValue();
14875}
14876
14877static SDValue PerformVCMPCombine(SDNode *N, SelectionDAG &DAG,
14878 const ARMSubtarget *Subtarget) {
14879 if (!Subtarget->hasMVEIntegerOps())
14880 return SDValue();
14881
14882 EVT VT = N->getValueType(0);
14883 SDValue Op0 = N->getOperand(0);
14884 SDValue Op1 = N->getOperand(1);
14885 ARMCC::CondCodes Cond =
14886 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14887 SDLoc dl(N);
14888
14889 // vcmp X, 0, cc -> vcmpz X, cc
14890 if (isZeroVector(Op1))
14891 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, N->getOperand(2));
14892
14893 unsigned SwappedCond = getSwappedCondition(Cond);
14894 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
14895 // vcmp 0, X, cc -> vcmpz X, reversed(cc)
14896 if (isZeroVector(Op0))
14897 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
14898 DAG.getConstant(SwappedCond, dl, MVT::i32));
14899 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
14900 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
14901 return DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
14902 DAG.getConstant(SwappedCond, dl, MVT::i32));
14903 }
14904
14905 return SDValue();
14906}
14907
14908/// PerformInsertEltCombine - Target-specific dag combine xforms for
14909/// ISD::INSERT_VECTOR_ELT.
14910static SDValue PerformInsertEltCombine(SDNode *N,
14911 TargetLowering::DAGCombinerInfo &DCI) {
14912 // Bitcast an i64 load inserted into a vector to f64.
14913 // Otherwise, the i64 value will be legalized to a pair of i32 values.
14914 EVT VT = N->getValueType(0);
14915 SDNode *Elt = N->getOperand(1).getNode();
14916 if (VT.getVectorElementType() != MVT::i64 ||
14917 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
14918 return SDValue();
14919
14920 SelectionDAG &DAG = DCI.DAG;
14921 SDLoc dl(N);
14922 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
14923 VT.getVectorNumElements());
14924 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
14925 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
14926 // Make the DAGCombiner fold the bitcasts.
14927 DCI.AddToWorklist(Vec.getNode());
14928 DCI.AddToWorklist(V.getNode());
14929 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
14930 Vec, V, N->getOperand(2));
14931 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
14932}
14933
14934// Convert a pair of extracts from the same base vector to a VMOVRRD. Either
14935// directly or bitcast to an integer if the original is a float vector.
14936// extract(x, n); extract(x, n+1) -> VMOVRRD(extract v2f64 x, n/2)
14937// bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD(extract x, n/2)
14938static SDValue
14939PerformExtractEltToVMOVRRD(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
14940 EVT VT = N->getValueType(0);
14941 SDLoc dl(N);
14942
14943 if (!DCI.isAfterLegalizeDAG() || VT != MVT::i32 ||
14944 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(MVT::f64))
14945 return SDValue();
14946
14947 SDValue Ext = SDValue(N, 0);
14948 if (Ext.getOpcode() == ISD::BITCAST &&
14949 Ext.getOperand(0).getValueType() == MVT::f32)
14950 Ext = Ext.getOperand(0);
14951 if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14952 !isa<ConstantSDNode>(Ext.getOperand(1)) ||
14953 Ext.getConstantOperandVal(1) % 2 != 0)
14954 return SDValue();
14955 if (Ext->use_size() == 1 &&
14956 (Ext->use_begin()->getOpcode() == ISD::SINT_TO_FP ||
14957 Ext->use_begin()->getOpcode() == ISD::UINT_TO_FP))
14958 return SDValue();
14959
14960 SDValue Op0 = Ext.getOperand(0);
14961 EVT VecVT = Op0.getValueType();
14962 unsigned ResNo = Op0.getResNo();
14963 unsigned Lane = Ext.getConstantOperandVal(1);
14964 if (VecVT.getVectorNumElements() != 4)
14965 return SDValue();
14966
14967 // Find another extract, of Lane + 1
14968 auto OtherIt = find_if(Op0->uses(), [&](SDNode *V) {
14969 return V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14970 isa<ConstantSDNode>(V->getOperand(1)) &&
14971 V->getConstantOperandVal(1) == Lane + 1 &&
14972 V->getOperand(0).getResNo() == ResNo;
14973 });
14974 if (OtherIt == Op0->uses().end())
14975 return SDValue();
14976
14977 // For float extracts, we need to be converting to a i32 for both vector
14978 // lanes.
14979 SDValue OtherExt(*OtherIt, 0);
14980 if (OtherExt.getValueType() != MVT::i32) {
14981 if (OtherExt->use_size() != 1 ||
14982 OtherExt->use_begin()->getOpcode() != ISD::BITCAST ||
14983 OtherExt->use_begin()->getValueType(0) != MVT::i32)
14984 return SDValue();
14985 OtherExt = SDValue(*OtherExt->use_begin(), 0);
14986 }
14987
14988 // Convert the type to a f64 and extract with a VMOVRRD.
14989 SDValue F64 = DCI.DAG.getNode(
14990 ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
14991 DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v2f64, Op0),
14992 DCI.DAG.getConstant(Ext.getConstantOperandVal(1) / 2, dl, MVT::i32));
14993 SDValue VMOVRRD =
14994 DCI.DAG.getNode(ARMISD::VMOVRRD, dl, {MVT::i32, MVT::i32}, F64);
14995
14996 DCI.CombineTo(OtherExt.getNode(), SDValue(VMOVRRD.getNode(), 1));
14997 return VMOVRRD;
14998}
14999
15000static SDValue PerformExtractEltCombine(SDNode *N,
15001 TargetLowering::DAGCombinerInfo &DCI,
15002 const ARMSubtarget *ST) {
15003 SDValue Op0 = N->getOperand(0);
15004 EVT VT = N->getValueType(0);
15005 SDLoc dl(N);
15006
15007 // extract (vdup x) -> x
15008 if (Op0->getOpcode() == ARMISD::VDUP) {
15009 SDValue X = Op0->getOperand(0);
15010 if (VT == MVT::f16 && X.getValueType() == MVT::i32)
15011 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
15012 if (VT == MVT::i32 && X.getValueType() == MVT::f16)
15013 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
15014 if (VT == MVT::f32 && X.getValueType() == MVT::i32)
15015 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, X);
15016
15017 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
15018 X = X->getOperand(0);
15019 if (X.getValueType() == VT)
15020 return X;
15021 }
15022
15023 // extract ARM_BUILD_VECTOR -> x
15024 if (Op0->getOpcode() == ARMISD::BUILD_VECTOR &&
15025 isa<ConstantSDNode>(N->getOperand(1)) &&
15026 N->getConstantOperandVal(1) < Op0.getNumOperands()) {
15027 return Op0.getOperand(N->getConstantOperandVal(1));
15028 }
15029
15030 // extract(bitcast(BUILD_VECTOR(VMOVDRR(a, b), ..))) -> a or b
15031 if (Op0.getValueType() == MVT::v4i32 &&
15032 isa<ConstantSDNode>(N->getOperand(1)) &&
15033 Op0.getOpcode() == ISD::BITCAST &&
15034 Op0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
15035 Op0.getOperand(0).getValueType() == MVT::v2f64) {
15036 SDValue BV = Op0.getOperand(0);
15037 unsigned Offset = N->getConstantOperandVal(1);
15038 SDValue MOV = BV.getOperand(Offset < 2 ? 0 : 1);
15039 if (MOV.getOpcode() == ARMISD::VMOVDRR)
15040 return MOV.getOperand(ST->isLittle() ? Offset % 2 : 1 - Offset % 2);
15041 }
15042
15043 // extract x, n; extract x, n+1 -> VMOVRRD x
15044 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
15045 return R;
15046
15047 // extract (MVETrunc(x)) -> extract x
15048 if (Op0->getOpcode() == ARMISD::MVETRUNC) {
15049 unsigned Idx = N->getConstantOperandVal(1);
15050 unsigned Vec =
15051 Idx / Op0->getOperand(0).getValueType().getVectorNumElements();
15052 unsigned SubIdx =
15053 Idx % Op0->getOperand(0).getValueType().getVectorNumElements();
15054 return DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Op0.getOperand(Vec),
15055 DCI.DAG.getConstant(SubIdx, dl, MVT::i32));
15056 }
15057
15058 return SDValue();
15059}
15060
15061static SDValue PerformSignExtendInregCombine(SDNode *N, SelectionDAG &DAG) {
15062 SDValue Op = N->getOperand(0);
15063 EVT VT = N->getValueType(0);
15064
15065 // sext_inreg(VGETLANEu) -> VGETLANEs
15066 if (Op.getOpcode() == ARMISD::VGETLANEu &&
15067 cast<VTSDNode>(N->getOperand(1))->getVT() ==
15068 Op.getOperand(0).getValueType().getScalarType())
15069 return DAG.getNode(ARMISD::VGETLANEs, SDLoc(N), VT, Op.getOperand(0),
15070 Op.getOperand(1));
15071
15072 return SDValue();
15073}
15074
15075// When lowering complex nodes that we recognize, like VQDMULH and MULH, we
15076// can end up with shuffle(binop(shuffle, shuffle)), that can be simplified to
15077// binop as the shuffles cancel out.
15078static SDValue FlattenVectorShuffle(ShuffleVectorSDNode *N, SelectionDAG &DAG) {
15079 EVT VT = N->getValueType(0);
15080 if (!N->getOperand(1).isUndef() || N->getOperand(0).getValueType() != VT)
15081 return SDValue();
15082 SDValue Op = N->getOperand(0);
15083
15084 // Looking for binary operators that will have been folded from
15085 // truncates/extends.
15086 switch (Op.getOpcode()) {
15087 case ARMISD::VQDMULH:
15088 case ISD::MULHS:
15089 case ISD::MULHU:
15090 case ISD::ABDS:
15091 case ISD::ABDU:
15092 break;
15093 default:
15094 return SDValue();
15095 }
15096
15097 ShuffleVectorSDNode *Op0 = dyn_cast<ShuffleVectorSDNode>(Op.getOperand(0));
15098 ShuffleVectorSDNode *Op1 = dyn_cast<ShuffleVectorSDNode>(Op.getOperand(1));
15099 if (!Op0 || !Op1 || !Op0->getOperand(1).isUndef() ||
15100 !Op1->getOperand(1).isUndef() || Op0->getMask() != Op1->getMask() ||
15101 Op0->getOperand(0).getValueType() != VT)
15102 return SDValue();
15103
15104 // Check the mask turns into an identity shuffle.
15105 ArrayRef<int> NMask = N->getMask();
15106 ArrayRef<int> OpMask = Op0->getMask();
15107 for (int i = 0, e = NMask.size(); i != e; i++) {
15108 if (NMask[i] > 0 && OpMask[NMask[i]] > 0 && OpMask[NMask[i]] != i)
15109 return SDValue();
15110 }
15111
15112 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
15113 Op0->getOperand(0), Op1->getOperand(0));
15114}
15115
15116static SDValue
15117PerformInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15118 SDValue Vec = N->getOperand(0);
15119 SDValue SubVec = N->getOperand(1);
15120 uint64_t IdxVal = N->getConstantOperandVal(2);
15121 EVT VecVT = Vec.getValueType();
15122 EVT SubVT = SubVec.getValueType();
15123
15124 // Only do this for legal fixed vector types.
15125 if (!VecVT.isFixedLengthVector() ||
15126 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
15127 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
15128 return SDValue();
15129
15130 // Ignore widening patterns.
15131 if (IdxVal == 0 && Vec.isUndef())
15132 return SDValue();
15133
15134 // Subvector must be half the width and an "aligned" insertion.
15135 unsigned NumSubElts = SubVT.getVectorNumElements();
15136 if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
15137 (IdxVal != 0 && IdxVal != NumSubElts))
15138 return SDValue();
15139
15140 // Fold insert_subvector -> concat_vectors
15141 // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
15142 // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
15143 SDLoc DL(N);
15144 SDValue Lo, Hi;
15145 if (IdxVal == 0) {
15146 Lo = SubVec;
15147 Hi = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15148 DCI.DAG.getVectorIdxConstant(NumSubElts, DL));
15149 } else {
15150 Lo = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15151 DCI.DAG.getVectorIdxConstant(0, DL));
15152 Hi = SubVec;
15153 }
15154 return DCI.DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
15155}
15156
15157// shuffle(MVETrunc(x, y)) -> VMOVN(x, y)
15158static SDValue PerformShuffleVMOVNCombine(ShuffleVectorSDNode *N,
15159 SelectionDAG &DAG) {
15160 SDValue Trunc = N->getOperand(0);
15161 EVT VT = Trunc.getValueType();
15162 if (Trunc.getOpcode() != ARMISD::MVETRUNC || !N->getOperand(1).isUndef())
15163 return SDValue();
15164
15165 SDLoc DL(Trunc);
15166 if (isVMOVNTruncMask(N->getMask(), VT, 0))
15167 return DAG.getNode(
15168 ARMISD::VMOVN, DL, VT,
15169 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15170 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15171 DAG.getConstant(1, DL, MVT::i32));
15172 else if (isVMOVNTruncMask(N->getMask(), VT, 1))
15173 return DAG.getNode(
15174 ARMISD::VMOVN, DL, VT,
15175 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15176 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15177 DAG.getConstant(1, DL, MVT::i32));
15178 return SDValue();
15179}
15180
15181/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
15182/// ISD::VECTOR_SHUFFLE.
15183static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
15184 if (SDValue R = FlattenVectorShuffle(cast<ShuffleVectorSDNode>(N), DAG))
15185 return R;
15186 if (SDValue R = PerformShuffleVMOVNCombine(cast<ShuffleVectorSDNode>(N), DAG))
15187 return R;
15188
15189 // The LLVM shufflevector instruction does not require the shuffle mask
15190 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
15191 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
15192 // operands do not match the mask length, they are extended by concatenating
15193 // them with undef vectors. That is probably the right thing for other
15194 // targets, but for NEON it is better to concatenate two double-register
15195 // size vector operands into a single quad-register size vector. Do that
15196 // transformation here:
15197 // shuffle(concat(v1, undef), concat(v2, undef)) ->
15198 // shuffle(concat(v1, v2), undef)
15199 SDValue Op0 = N->getOperand(0);
15200 SDValue Op1 = N->getOperand(1);
15201 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
15202 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
15203 Op0.getNumOperands() != 2 ||
15204 Op1.getNumOperands() != 2)
15205 return SDValue();
15206 SDValue Concat0Op1 = Op0.getOperand(1);
15207 SDValue Concat1Op1 = Op1.getOperand(1);
15208 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
15209 return SDValue();
15210 // Skip the transformation if any of the types are illegal.
15211 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15212 EVT VT = N->getValueType(0);
15213 if (!TLI.isTypeLegal(VT) ||
15214 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
15215 !TLI.isTypeLegal(Concat1Op1.getValueType()))
15216 return SDValue();
15217
15218 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
15219 Op0.getOperand(0), Op1.getOperand(0));
15220 // Translate the shuffle mask.
15221 SmallVector<int, 16> NewMask;
15222 unsigned NumElts = VT.getVectorNumElements();
15223 unsigned HalfElts = NumElts/2;
15224 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15225 for (unsigned n = 0; n < NumElts; ++n) {
15226 int MaskElt = SVN->getMaskElt(n);
15227 int NewElt = -1;
15228 if (MaskElt < (int)HalfElts)
15229 NewElt = MaskElt;
15230 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
15231 NewElt = HalfElts + MaskElt - NumElts;
15232 NewMask.push_back(NewElt);
15233 }
15234 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
15235 DAG.getUNDEF(VT), NewMask);
15236}
15237
15238/// Load/store instruction that can be merged with a base address
15239/// update
15240struct BaseUpdateTarget {
15241 SDNode *N;
15242 bool isIntrinsic;
15243 bool isStore;
15244 unsigned AddrOpIdx;
15245};
15246
15247struct BaseUpdateUser {
15248 /// Instruction that updates a pointer
15249 SDNode *N;
15250 /// Pointer increment operand
15251 SDValue Inc;
15252 /// Pointer increment value if it is a constant, or 0 otherwise
15253 unsigned ConstInc;
15254};
15255
15256static bool TryCombineBaseUpdate(struct BaseUpdateTarget &Target,
15257 struct BaseUpdateUser &User,
15258 bool SimpleConstIncOnly,
15259 TargetLowering::DAGCombinerInfo &DCI) {
15260 SelectionDAG &DAG = DCI.DAG;
15261 SDNode *N = Target.N;
15262 MemSDNode *MemN = cast<MemSDNode>(N);
15263 SDLoc dl(N);
15264
15265 // Find the new opcode for the updating load/store.
15266 bool isLoadOp = true;
15267 bool isLaneOp = false;
15268 // Workaround for vst1x and vld1x intrinsics which do not have alignment
15269 // as an operand.
15270 bool hasAlignment = true;
15271 unsigned NewOpc = 0;
15272 unsigned NumVecs = 0;
15273 if (Target.isIntrinsic) {
15274 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15275 switch (IntNo) {
15276 default:
15277 llvm_unreachable("unexpected intrinsic for Neon base update")::llvm::llvm_unreachable_internal("unexpected intrinsic for Neon base update"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15277)
;
15278 case Intrinsic::arm_neon_vld1:
15279 NewOpc = ARMISD::VLD1_UPD;
15280 NumVecs = 1;
15281 break;
15282 case Intrinsic::arm_neon_vld2:
15283 NewOpc = ARMISD::VLD2_UPD;
15284 NumVecs = 2;
15285 break;
15286 case Intrinsic::arm_neon_vld3:
15287 NewOpc = ARMISD::VLD3_UPD;
15288 NumVecs = 3;
15289 break;
15290 case Intrinsic::arm_neon_vld4:
15291 NewOpc = ARMISD::VLD4_UPD;
15292 NumVecs = 4;
15293 break;
15294 case Intrinsic::arm_neon_vld1x2:
15295 NewOpc = ARMISD::VLD1x2_UPD;
15296 NumVecs = 2;
15297 hasAlignment = false;
15298 break;
15299 case Intrinsic::arm_neon_vld1x3:
15300 NewOpc = ARMISD::VLD1x3_UPD;
15301 NumVecs = 3;
15302 hasAlignment = false;
15303 break;
15304 case Intrinsic::arm_neon_vld1x4:
15305 NewOpc = ARMISD::VLD1x4_UPD;
15306 NumVecs = 4;
15307 hasAlignment = false;
15308 break;
15309 case Intrinsic::arm_neon_vld2dup:
15310 NewOpc = ARMISD::VLD2DUP_UPD;
15311 NumVecs = 2;
15312 break;
15313 case Intrinsic::arm_neon_vld3dup:
15314 NewOpc = ARMISD::VLD3DUP_UPD;
15315 NumVecs = 3;
15316 break;
15317 case Intrinsic::arm_neon_vld4dup:
15318 NewOpc = ARMISD::VLD4DUP_UPD;
15319 NumVecs = 4;
15320 break;
15321 case Intrinsic::arm_neon_vld2lane:
15322 NewOpc = ARMISD::VLD2LN_UPD;
15323 NumVecs = 2;
15324 isLaneOp = true;
15325 break;
15326 case Intrinsic::arm_neon_vld3lane:
15327 NewOpc = ARMISD::VLD3LN_UPD;
15328 NumVecs = 3;
15329 isLaneOp = true;
15330 break;
15331 case Intrinsic::arm_neon_vld4lane:
15332 NewOpc = ARMISD::VLD4LN_UPD;
15333 NumVecs = 4;
15334 isLaneOp = true;
15335 break;
15336 case Intrinsic::arm_neon_vst1:
15337 NewOpc = ARMISD::VST1_UPD;
15338 NumVecs = 1;
15339 isLoadOp = false;
15340 break;
15341 case Intrinsic::arm_neon_vst2:
15342 NewOpc = ARMISD::VST2_UPD;
15343 NumVecs = 2;
15344 isLoadOp = false;
15345 break;
15346 case Intrinsic::arm_neon_vst3:
15347 NewOpc = ARMISD::VST3_UPD;
15348 NumVecs = 3;
15349 isLoadOp = false;
15350 break;
15351 case Intrinsic::arm_neon_vst4:
15352 NewOpc = ARMISD::VST4_UPD;
15353 NumVecs = 4;
15354 isLoadOp = false;
15355 break;
15356 case Intrinsic::arm_neon_vst2lane:
15357 NewOpc = ARMISD::VST2LN_UPD;
15358 NumVecs = 2;
15359 isLoadOp = false;
15360 isLaneOp = true;
15361 break;
15362 case Intrinsic::arm_neon_vst3lane:
15363 NewOpc = ARMISD::VST3LN_UPD;
15364 NumVecs = 3;
15365 isLoadOp = false;
15366 isLaneOp = true;
15367 break;
15368 case Intrinsic::arm_neon_vst4lane:
15369 NewOpc = ARMISD::VST4LN_UPD;
15370 NumVecs = 4;
15371 isLoadOp = false;
15372 isLaneOp = true;
15373 break;
15374 case Intrinsic::arm_neon_vst1x2:
15375 NewOpc = ARMISD::VST1x2_UPD;
15376 NumVecs = 2;
15377 isLoadOp = false;
15378 hasAlignment = false;
15379 break;
15380 case Intrinsic::arm_neon_vst1x3:
15381 NewOpc = ARMISD::VST1x3_UPD;
15382 NumVecs = 3;
15383 isLoadOp = false;
15384 hasAlignment = false;
15385 break;
15386 case Intrinsic::arm_neon_vst1x4:
15387 NewOpc = ARMISD::VST1x4_UPD;
15388 NumVecs = 4;
15389 isLoadOp = false;
15390 hasAlignment = false;
15391 break;
15392 }
15393 } else {
15394 isLaneOp = true;
15395 switch (N->getOpcode()) {
15396 default:
15397 llvm_unreachable("unexpected opcode for Neon base update")::llvm::llvm_unreachable_internal("unexpected opcode for Neon base update"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15397)
;
15398 case ARMISD::VLD1DUP:
15399 NewOpc = ARMISD::VLD1DUP_UPD;
15400 NumVecs = 1;
15401 break;
15402 case ARMISD::VLD2DUP:
15403 NewOpc = ARMISD::VLD2DUP_UPD;
15404 NumVecs = 2;
15405 break;
15406 case ARMISD::VLD3DUP:
15407 NewOpc = ARMISD::VLD3DUP_UPD;
15408 NumVecs = 3;
15409 break;
15410 case ARMISD::VLD4DUP:
15411 NewOpc = ARMISD::VLD4DUP_UPD;
15412 NumVecs = 4;
15413 break;
15414 case ISD::LOAD:
15415 NewOpc = ARMISD::VLD1_UPD;
15416 NumVecs = 1;
15417 isLaneOp = false;
15418 break;
15419 case ISD::STORE:
15420 NewOpc = ARMISD::VST1_UPD;
15421 NumVecs = 1;
15422 isLaneOp = false;
15423 isLoadOp = false;
15424 break;
15425 }
15426 }
15427
15428 // Find the size of memory referenced by the load/store.
15429 EVT VecTy;
15430 if (isLoadOp) {
15431 VecTy = N->getValueType(0);
15432 } else if (Target.isIntrinsic) {
15433 VecTy = N->getOperand(Target.AddrOpIdx + 1).getValueType();
15434 } else {
15435 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15436, __extension__ __PRETTY_FUNCTION__))
15436 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15436, __extension__ __PRETTY_FUNCTION__))
;
15437 VecTy = N->getOperand(1).getValueType();
15438 }
15439
15440 bool isVLDDUPOp =
15441 NewOpc == ARMISD::VLD1DUP_UPD || NewOpc == ARMISD::VLD2DUP_UPD ||
15442 NewOpc == ARMISD::VLD3DUP_UPD || NewOpc == ARMISD::VLD4DUP_UPD;
15443
15444 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
15445 if (isLaneOp || isVLDDUPOp)
15446 NumBytes /= VecTy.getVectorNumElements();
15447
15448 if (NumBytes >= 3 * 16 && User.ConstInc != NumBytes) {
15449 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
15450 // separate instructions that make it harder to use a non-constant update.
15451 return false;
15452 }
15453
15454 if (SimpleConstIncOnly && User.ConstInc != NumBytes)
15455 return false;
15456
15457 // OK, we found an ADD we can fold into the base update.
15458 // Now, create a _UPD node, taking care of not breaking alignment.
15459
15460 EVT AlignedVecTy = VecTy;
15461 unsigned Alignment = MemN->getAlignment();
15462
15463 // If this is a less-than-standard-aligned load/store, change the type to
15464 // match the standard alignment.
15465 // The alignment is overlooked when selecting _UPD variants; and it's
15466 // easier to introduce bitcasts here than fix that.
15467 // There are 3 ways to get to this base-update combine:
15468 // - intrinsics: they are assumed to be properly aligned (to the standard
15469 // alignment of the memory type), so we don't need to do anything.
15470 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
15471 // intrinsics, so, likewise, there's nothing to do.
15472 // - generic load/store instructions: the alignment is specified as an
15473 // explicit operand, rather than implicitly as the standard alignment
15474 // of the memory type (like the intrisics). We need to change the
15475 // memory type to match the explicit alignment. That way, we don't
15476 // generate non-standard-aligned ARMISD::VLDx nodes.
15477 if (isa<LSBaseSDNode>(N)) {
15478 if (Alignment == 0)
15479 Alignment = 1;
15480 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
15481 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
15482 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.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15482, __extension__ __PRETTY_FUNCTION__))
;
15483 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.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15483, __extension__ __PRETTY_FUNCTION__))
;
15484 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
15485 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
15486 }
15487 // Don't set an explicit alignment on regular load/stores that we want
15488 // to transform to VLD/VST 1_UPD nodes.
15489 // This matches the behavior of regular load/stores, which only get an
15490 // explicit alignment if the MMO alignment is larger than the standard
15491 // alignment of the memory type.
15492 // Intrinsics, however, always get an explicit alignment, set to the
15493 // alignment of the MMO.
15494 Alignment = 1;
15495 }
15496
15497 // Create the new updating load/store node.
15498 // First, create an SDVTList for the new updating node's results.
15499 EVT Tys[6];
15500 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
15501 unsigned n;
15502 for (n = 0; n < NumResultVecs; ++n)
15503 Tys[n] = AlignedVecTy;
15504 Tys[n++] = MVT::i32;
15505 Tys[n] = MVT::Other;
15506 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
15507
15508 // Then, gather the new node's operands.
15509 SmallVector<SDValue, 8> Ops;
15510 Ops.push_back(N->getOperand(0)); // incoming chain
15511 Ops.push_back(N->getOperand(Target.AddrOpIdx));
15512 Ops.push_back(User.Inc);
15513
15514 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
15515 // Try to match the intrinsic's signature
15516 Ops.push_back(StN->getValue());
15517 } else {
15518 // Loads (and of course intrinsics) match the intrinsics' signature,
15519 // so just add all but the alignment operand.
15520 unsigned LastOperand =
15521 hasAlignment ? N->getNumOperands() - 1 : N->getNumOperands();
15522 for (unsigned i = Target.AddrOpIdx + 1; i < LastOperand; ++i)
15523 Ops.push_back(N->getOperand(i));
15524 }
15525
15526 // For all node types, the alignment operand is always the last one.
15527 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
15528
15529 // If this is a non-standard-aligned STORE, the penultimate operand is the
15530 // stored value. Bitcast it to the aligned type.
15531 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
15532 SDValue &StVal = Ops[Ops.size() - 2];
15533 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
15534 }
15535
15536 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
15537 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
15538 MemN->getMemOperand());
15539
15540 // Update the uses.
15541 SmallVector<SDValue, 5> NewResults;
15542 for (unsigned i = 0; i < NumResultVecs; ++i)
15543 NewResults.push_back(SDValue(UpdN.getNode(), i));
15544
15545 // If this is an non-standard-aligned LOAD, the first result is the loaded
15546 // value. Bitcast it to the expected result type.
15547 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
15548 SDValue &LdVal = NewResults[0];
15549 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
15550 }
15551
15552 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
15553 DCI.CombineTo(N, NewResults);
15554 DCI.CombineTo(User.N, SDValue(UpdN.getNode(), NumResultVecs));
15555
15556 return true;
15557}
15558
15559// If (opcode ptr inc) is and ADD-like instruction, return the
15560// increment value. Otherwise return 0.
15561static unsigned getPointerConstIncrement(unsigned Opcode, SDValue Ptr,
15562 SDValue Inc, const SelectionDAG &DAG) {
15563 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
15564 if (!CInc)
15565 return 0;
15566
15567 switch (Opcode) {
15568 case ARMISD::VLD1_UPD:
15569 case ISD::ADD:
15570 return CInc->getZExtValue();
15571 case ISD::OR: {
15572 if (DAG.haveNoCommonBitsSet(Ptr, Inc)) {
15573 // (OR ptr inc) is the same as (ADD ptr inc)
15574 return CInc->getZExtValue();
15575 }
15576 return 0;
15577 }
15578 default:
15579 return 0;
15580 }
15581}
15582
15583static bool findPointerConstIncrement(SDNode *N, SDValue *Ptr, SDValue *CInc) {
15584 switch (N->getOpcode()) {
15585 case ISD::ADD:
15586 case ISD::OR: {
15587 if (isa<ConstantSDNode>(N->getOperand(1))) {
15588 *Ptr = N->getOperand(0);
15589 *CInc = N->getOperand(1);
15590 return true;
15591 }
15592 return false;
15593 }
15594 case ARMISD::VLD1_UPD: {
15595 if (isa<ConstantSDNode>(N->getOperand(2))) {
15596 *Ptr = N->getOperand(1);
15597 *CInc = N->getOperand(2);
15598 return true;
15599 }
15600 return false;
15601 }
15602 default:
15603 return false;
15604 }
15605}
15606
15607static bool isValidBaseUpdate(SDNode *N, SDNode *User) {
15608 // Check that the add is independent of the load/store.
15609 // Otherwise, folding it would create a cycle. Search through Addr
15610 // as well, since the User may not be a direct user of Addr and
15611 // only share a base pointer.
15612 SmallPtrSet<const SDNode *, 32> Visited;
15613 SmallVector<const SDNode *, 16> Worklist;
15614 Worklist.push_back(N);
15615 Worklist.push_back(User);
15616 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
15617 SDNode::hasPredecessorHelper(User, Visited, Worklist))
15618 return false;
15619 return true;
15620}
15621
15622/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
15623/// NEON load/store intrinsics, and generic vector load/stores, to merge
15624/// base address updates.
15625/// For generic load/stores, the memory type is assumed to be a vector.
15626/// The caller is assumed to have checked legality.
15627static SDValue CombineBaseUpdate(SDNode *N,
15628 TargetLowering::DAGCombinerInfo &DCI) {
15629 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
15630 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
15631 const bool isStore = N->getOpcode() == ISD::STORE;
15632 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
15633 BaseUpdateTarget Target = {N, isIntrinsic, isStore, AddrOpIdx};
15634
15635 SDValue Addr = N->getOperand(AddrOpIdx);
15636
15637 SmallVector<BaseUpdateUser, 8> BaseUpdates;
15638
15639 // Search for a use of the address operand that is an increment.
15640 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
15641 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
15642 SDNode *User = *UI;
15643 if (UI.getUse().getResNo() != Addr.getResNo() ||
15644 User->getNumOperands() != 2)
15645 continue;
15646
15647 SDValue Inc = User->getOperand(UI.getOperandNo() == 1 ? 0 : 1);
15648 unsigned ConstInc =
15649 getPointerConstIncrement(User->getOpcode(), Addr, Inc, DCI.DAG);
15650
15651 if (ConstInc || User->getOpcode() == ISD::ADD)
15652 BaseUpdates.push_back({User, Inc, ConstInc});
15653 }
15654
15655 // If the address is a constant pointer increment itself, find
15656 // another constant increment that has the same base operand
15657 SDValue Base;
15658 SDValue CInc;
15659 if (findPointerConstIncrement(Addr.getNode(), &Base, &CInc)) {
15660 unsigned Offset =
15661 getPointerConstIncrement(Addr->getOpcode(), Base, CInc, DCI.DAG);
15662 for (SDNode::use_iterator UI = Base->use_begin(), UE = Base->use_end();
15663 UI != UE; ++UI) {
15664
15665 SDNode *User = *UI;
15666 if (UI.getUse().getResNo() != Base.getResNo() || User == Addr.getNode() ||
15667 User->getNumOperands() != 2)
15668 continue;
15669
15670 SDValue UserInc = User->getOperand(UI.getOperandNo() == 0 ? 1 : 0);
15671 unsigned UserOffset =
15672 getPointerConstIncrement(User->getOpcode(), Base, UserInc, DCI.DAG);
15673
15674 if (!UserOffset || UserOffset <= Offset)
15675 continue;
15676
15677 unsigned NewConstInc = UserOffset - Offset;
15678 SDValue NewInc = DCI.DAG.getConstant(NewConstInc, SDLoc(N), MVT::i32);
15679 BaseUpdates.push_back({User, NewInc, NewConstInc});
15680 }
15681 }
15682
15683 // Try to fold the load/store with an update that matches memory
15684 // access size. This should work well for sequential loads.
15685 //
15686 // Filter out invalid updates as well.
15687 unsigned NumValidUpd = BaseUpdates.size();
15688 for (unsigned I = 0; I < NumValidUpd;) {
15689 BaseUpdateUser &User = BaseUpdates[I];
15690 if (!isValidBaseUpdate(N, User.N)) {
15691 --NumValidUpd;
15692 std::swap(BaseUpdates[I], BaseUpdates[NumValidUpd]);
15693 continue;
15694 }
15695
15696 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/true, DCI))
15697 return SDValue();
15698 ++I;
15699 }
15700 BaseUpdates.resize(NumValidUpd);
15701
15702 // Try to fold with other users. Non-constant updates are considered
15703 // first, and constant updates are sorted to not break a sequence of
15704 // strided accesses (if there is any).
15705 std::sort(BaseUpdates.begin(), BaseUpdates.end(),
15706 [](BaseUpdateUser &LHS, BaseUpdateUser &RHS) {
15707 return LHS.ConstInc < RHS.ConstInc;
15708 });
15709 for (BaseUpdateUser &User : BaseUpdates) {
15710 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/false, DCI))
15711 return SDValue();
15712 }
15713 return SDValue();
15714}
15715
15716static SDValue PerformVLDCombine(SDNode *N,
15717 TargetLowering::DAGCombinerInfo &DCI) {
15718 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15719 return SDValue();
15720
15721 return CombineBaseUpdate(N, DCI);
15722}
15723
15724static SDValue PerformMVEVLDCombine(SDNode *N,
15725 TargetLowering::DAGCombinerInfo &DCI) {
15726 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15727 return SDValue();
15728
15729 SelectionDAG &DAG = DCI.DAG;
15730 SDValue Addr = N->getOperand(2);
15731 MemSDNode *MemN = cast<MemSDNode>(N);
15732 SDLoc dl(N);
15733
15734 // For the stores, where there are multiple intrinsics we only actually want
15735 // to post-inc the last of the them.
15736 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15737 if (IntNo == Intrinsic::arm_mve_vst2q &&
15738 cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1)
15739 return SDValue();
15740 if (IntNo == Intrinsic::arm_mve_vst4q &&
15741 cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3)
15742 return SDValue();
15743
15744 // Search for a use of the address operand that is an increment.
15745 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
15746 UE = Addr.getNode()->use_end();
15747 UI != UE; ++UI) {
15748 SDNode *User = *UI;
15749 if (User->getOpcode() != ISD::ADD ||
15750 UI.getUse().getResNo() != Addr.getResNo())
15751 continue;
15752
15753 // Check that the add is independent of the load/store. Otherwise, folding
15754 // it would create a cycle. We can avoid searching through Addr as it's a
15755 // predecessor to both.
15756 SmallPtrSet<const SDNode *, 32> Visited;
15757 SmallVector<const SDNode *, 16> Worklist;
15758 Visited.insert(Addr.getNode());
15759 Worklist.push_back(N);
15760 Worklist.push_back(User);
15761 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
15762 SDNode::hasPredecessorHelper(User, Visited, Worklist))
15763 continue;
15764
15765 // Find the new opcode for the updating load/store.
15766 bool isLoadOp = true;
15767 unsigned NewOpc = 0;
15768 unsigned NumVecs = 0;
15769 switch (IntNo) {
15770 default:
15771 llvm_unreachable("unexpected intrinsic for MVE VLDn combine")::llvm::llvm_unreachable_internal("unexpected intrinsic for MVE VLDn combine"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15771)
;
15772 case Intrinsic::arm_mve_vld2q:
15773 NewOpc = ARMISD::VLD2_UPD;
15774 NumVecs = 2;
15775 break;
15776 case Intrinsic::arm_mve_vld4q:
15777 NewOpc = ARMISD::VLD4_UPD;
15778 NumVecs = 4;
15779 break;
15780 case Intrinsic::arm_mve_vst2q:
15781 NewOpc = ARMISD::VST2_UPD;
15782 NumVecs = 2;
15783 isLoadOp = false;
15784 break;
15785 case Intrinsic::arm_mve_vst4q:
15786 NewOpc = ARMISD::VST4_UPD;
15787 NumVecs = 4;
15788 isLoadOp = false;
15789 break;
15790 }
15791
15792 // Find the size of memory referenced by the load/store.
15793 EVT VecTy;
15794 if (isLoadOp) {
15795 VecTy = N->getValueType(0);
15796 } else {
15797 VecTy = N->getOperand(3).getValueType();
15798 }
15799
15800 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
15801
15802 // If the increment is a constant, it must match the memory ref size.
15803 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
15804 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
15805 if (!CInc || CInc->getZExtValue() != NumBytes)
15806 continue;
15807
15808 // Create the new updating load/store node.
15809 // First, create an SDVTList for the new updating node's results.
15810 EVT Tys[6];
15811 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
15812 unsigned n;
15813 for (n = 0; n < NumResultVecs; ++n)
15814 Tys[n] = VecTy;
15815 Tys[n++] = MVT::i32;
15816 Tys[n] = MVT::Other;
15817 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
15818
15819 // Then, gather the new node's operands.
15820 SmallVector<SDValue, 8> Ops;
15821 Ops.push_back(N->getOperand(0)); // incoming chain
15822 Ops.push_back(N->getOperand(2)); // ptr
15823 Ops.push_back(Inc);
15824
15825 for (unsigned i = 3; i < N->getNumOperands(); ++i)
15826 Ops.push_back(N->getOperand(i));
15827
15828 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
15829 MemN->getMemOperand());
15830
15831 // Update the uses.
15832 SmallVector<SDValue, 5> NewResults;
15833 for (unsigned i = 0; i < NumResultVecs; ++i)
15834 NewResults.push_back(SDValue(UpdN.getNode(), i));
15835
15836 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
15837 DCI.CombineTo(N, NewResults);
15838 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
15839
15840 break;
15841 }
15842
15843 return SDValue();
15844}
15845
15846/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
15847/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
15848/// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
15849/// return true.
15850static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15851 SelectionDAG &DAG = DCI.DAG;
15852 EVT VT = N->getValueType(0);
15853 // vldN-dup instructions only support 64-bit vectors for N > 1.
15854 if (!VT.is64BitVector())
15855 return false;
15856
15857 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
15858 SDNode *VLD = N->getOperand(0).getNode();
15859 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
15860 return false;
15861 unsigned NumVecs = 0;
15862 unsigned NewOpc = 0;
15863 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
15864 if (IntNo == Intrinsic::arm_neon_vld2lane) {
15865 NumVecs = 2;
15866 NewOpc = ARMISD::VLD2DUP;
15867 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
15868 NumVecs = 3;
15869 NewOpc = ARMISD::VLD3DUP;
15870 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
15871 NumVecs = 4;
15872 NewOpc = ARMISD::VLD4DUP;
15873 } else {
15874 return false;
15875 }
15876
15877 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
15878 // numbers match the load.
15879 unsigned VLDLaneNo =
15880 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
15881 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
15882 UI != UE; ++UI) {
15883 // Ignore uses of the chain result.
15884 if (UI.getUse().getResNo() == NumVecs)
15885 continue;
15886 SDNode *User = *UI;
15887 if (User->getOpcode() != ARMISD::VDUPLANE ||
15888 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
15889 return false;
15890 }
15891
15892 // Create the vldN-dup node.
15893 EVT Tys[5];
15894 unsigned n;
15895 for (n = 0; n < NumVecs; ++n)
15896 Tys[n] = VT;
15897 Tys[n] = MVT::Other;
15898 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
15899 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
15900 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
15901 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
15902 Ops, VLDMemInt->getMemoryVT(),
15903 VLDMemInt->getMemOperand());
15904
15905 // Update the uses.
15906 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
15907 UI != UE; ++UI) {
15908 unsigned ResNo = UI.getUse().getResNo();
15909 // Ignore uses of the chain result.
15910 if (ResNo == NumVecs)
15911 continue;
15912 SDNode *User = *UI;
15913 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
15914 }
15915
15916 // Now the vldN-lane intrinsic is dead except for its chain result.
15917 // Update uses of the chain.
15918 std::vector<SDValue> VLDDupResults;
15919 for (unsigned n = 0; n < NumVecs; ++n)
15920 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
15921 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
15922 DCI.CombineTo(VLD, VLDDupResults);
15923
15924 return true;
15925}
15926
15927/// PerformVDUPLANECombine - Target-specific dag combine xforms for
15928/// ARMISD::VDUPLANE.
15929static SDValue PerformVDUPLANECombine(SDNode *N,
15930 TargetLowering::DAGCombinerInfo &DCI,
15931 const ARMSubtarget *Subtarget) {
15932 SDValue Op = N->getOperand(0);
15933 EVT VT = N->getValueType(0);
15934
15935 // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
15936 if (Subtarget->hasMVEIntegerOps()) {
15937 EVT ExtractVT = VT.getVectorElementType();
15938 // We need to ensure we are creating a legal type.
15939 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
15940 ExtractVT = MVT::i32;
15941 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
15942 N->getOperand(0), N->getOperand(1));
15943 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
15944 }
15945
15946 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
15947 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
15948 if (CombineVLDDUP(N, DCI))
15949 return SDValue(N, 0);
15950
15951 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
15952 // redundant. Ignore bit_converts for now; element sizes are checked below.
15953 while (Op.getOpcode() == ISD::BITCAST)
15954 Op = Op.getOperand(0);
15955 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
15956 return SDValue();
15957
15958 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
15959 unsigned EltSize = Op.getScalarValueSizeInBits();
15960 // The canonical VMOV for a zero vector uses a 32-bit element size.
15961 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15962 unsigned EltBits;
15963 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
15964 EltSize = 8;
15965 if (EltSize > VT.getScalarSizeInBits())
15966 return SDValue();
15967
15968 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
15969}
15970
15971/// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
15972static SDValue PerformVDUPCombine(SDNode *N, SelectionDAG &DAG,
15973 const ARMSubtarget *Subtarget) {
15974 SDValue Op = N->getOperand(0);
15975 SDLoc dl(N);
15976
15977 if (Subtarget->hasMVEIntegerOps()) {
15978 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
15979 // need to come from a GPR.
15980 if (Op.getValueType() == MVT::f32)
15981 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
15982 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
15983 else if (Op.getValueType() == MVT::f16)
15984 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
15985 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
15986 }
15987
15988 if (!Subtarget->hasNEON())
15989 return SDValue();
15990
15991 // Match VDUP(LOAD) -> VLD1DUP.
15992 // We match this pattern here rather than waiting for isel because the
15993 // transform is only legal for unindexed loads.
15994 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
15995 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
15996 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
15997 SDValue Ops[] = {LD->getOperand(0), LD->getOperand(1),
15998 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32)};
15999 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
16000 SDValue VLDDup =
16001 DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, Ops,
16002 LD->getMemoryVT(), LD->getMemOperand());
16003 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
16004 return VLDDup;
16005 }
16006
16007 return SDValue();
16008}
16009
16010static SDValue PerformLOADCombine(SDNode *N,
16011 TargetLowering::DAGCombinerInfo &DCI,
16012 const ARMSubtarget *Subtarget) {
16013 EVT VT = N->getValueType(0);
16014
16015 // If this is a legal vector load, try to combine it into a VLD1_UPD.
16016 if (Subtarget->hasNEON() && ISD::isNormalLoad(N) && VT.isVector() &&
16017 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16018 return CombineBaseUpdate(N, DCI);
16019
16020 return SDValue();
16021}
16022
16023// Optimize trunc store (of multiple scalars) to shuffle and store. First,
16024// pack all of the elements in one place. Next, store to memory in fewer
16025// chunks.
16026static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
16027 SelectionDAG &DAG) {
16028 SDValue StVal = St->getValue();
16029 EVT VT = StVal.getValueType();
16030 if (!St->isTruncatingStore() || !VT.isVector())
16031 return SDValue();
16032 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16033 EVT StVT = St->getMemoryVT();
16034 unsigned NumElems = VT.getVectorNumElements();
16035 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16035, __extension__ __PRETTY_FUNCTION__))
;
16036 unsigned FromEltSz = VT.getScalarSizeInBits();
16037 unsigned ToEltSz = StVT.getScalarSizeInBits();
16038
16039 // From, To sizes and ElemCount must be pow of two
16040 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
16041 return SDValue();
16042
16043 // We are going to use the original vector elt for storing.
16044 // Accumulated smaller vector elements must be a multiple of the store size.
16045 if (0 != (NumElems * FromEltSz) % ToEltSz)
16046 return SDValue();
16047
16048 unsigned SizeRatio = FromEltSz / ToEltSz;
16049 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits())(static_cast <bool> (SizeRatio * NumElems * ToEltSz == VT
.getSizeInBits()) ? void (0) : __assert_fail ("SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16049, __extension__ __PRETTY_FUNCTION__))
;
16050
16051 // Create a type on which we perform the shuffle.
16052 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
16053 NumElems * SizeRatio);
16054 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits())(static_cast <bool> (WideVecVT.getSizeInBits() == VT.getSizeInBits
()) ? void (0) : __assert_fail ("WideVecVT.getSizeInBits() == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16054, __extension__ __PRETTY_FUNCTION__))
;
16055
16056 SDLoc DL(St);
16057 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
16058 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16059 for (unsigned i = 0; i < NumElems; ++i)
16060 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
16061 : i * SizeRatio;
16062
16063 // Can't shuffle using an illegal type.
16064 if (!TLI.isTypeLegal(WideVecVT))
16065 return SDValue();
16066
16067 SDValue Shuff = DAG.getVectorShuffle(
16068 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
16069 // At this point all of the data is stored at the bottom of the
16070 // register. We now need to save it to mem.
16071
16072 // Find the largest store unit
16073 MVT StoreType = MVT::i8;
16074 for (MVT Tp : MVT::integer_valuetypes()) {
16075 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
16076 StoreType = Tp;
16077 }
16078 // Didn't find a legal store type.
16079 if (!TLI.isTypeLegal(StoreType))
16080 return SDValue();
16081
16082 // Bitcast the original vector into a vector of store-size units
16083 EVT StoreVecVT =
16084 EVT::getVectorVT(*DAG.getContext(), StoreType,
16085 VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
16086 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits())(static_cast <bool> (StoreVecVT.getSizeInBits() == VT.getSizeInBits
()) ? void (0) : __assert_fail ("StoreVecVT.getSizeInBits() == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16086, __extension__ __PRETTY_FUNCTION__))
;
16087 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
16088 SmallVector<SDValue, 8> Chains;
16089 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
16090 TLI.getPointerTy(DAG.getDataLayout()));
16091 SDValue BasePtr = St->getBasePtr();
16092
16093 // Perform one or more big stores into memory.
16094 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
16095 for (unsigned I = 0; I < E; I++) {
16096 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
16097 ShuffWide, DAG.getIntPtrConstant(I, DL));
16098 SDValue Ch =
16099 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
16100 St->getAlignment(), St->getMemOperand()->getFlags());
16101 BasePtr =
16102 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
16103 Chains.push_back(Ch);
16104 }
16105 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
16106}
16107
16108// Try taking a single vector store from an fpround (which would otherwise turn
16109// into an expensive buildvector) and splitting it into a series of narrowing
16110// stores.
16111static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
16112 SelectionDAG &DAG) {
16113 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16114 return SDValue();
16115 SDValue Trunc = St->getValue();
16116 if (Trunc->getOpcode() != ISD::FP_ROUND)
16117 return SDValue();
16118 EVT FromVT = Trunc->getOperand(0).getValueType();
16119 EVT ToVT = Trunc.getValueType();
16120 if (!ToVT.isVector())
16121 return SDValue();
16122 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements())(static_cast <bool> (FromVT.getVectorNumElements() == ToVT
.getVectorNumElements()) ? void (0) : __assert_fail ("FromVT.getVectorNumElements() == ToVT.getVectorNumElements()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16122, __extension__ __PRETTY_FUNCTION__))
;
16123 EVT ToEltVT = ToVT.getVectorElementType();
16124 EVT FromEltVT = FromVT.getVectorElementType();
16125
16126 if (FromEltVT != MVT::f32 || ToEltVT != MVT::f16)
16127 return SDValue();
16128
16129 unsigned NumElements = 4;
16130 if (FromVT.getVectorNumElements() % NumElements != 0)
16131 return SDValue();
16132
16133 // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
16134 // use the VMOVN over splitting the store. We are looking for patterns of:
16135 // !rev: 0 N 1 N+1 2 N+2 ...
16136 // rev: N 0 N+1 1 N+2 2 ...
16137 // The shuffle may either be a single source (in which case N = NumElts/2) or
16138 // two inputs extended with concat to the same size (in which case N =
16139 // NumElts).
16140 auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) {
16141 ArrayRef<int> M = SVN->getMask();
16142 unsigned NumElts = ToVT.getVectorNumElements();
16143 if (SVN->getOperand(1).isUndef())
16144 NumElts /= 2;
16145
16146 unsigned Off0 = Rev ? NumElts : 0;
16147 unsigned Off1 = Rev ? 0 : NumElts;
16148
16149 for (unsigned I = 0; I < NumElts; I += 2) {
16150 if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2))
16151 return false;
16152 if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2))
16153 return false;
16154 }
16155
16156 return true;
16157 };
16158
16159 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc.getOperand(0)))
16160 if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true))
16161 return SDValue();
16162
16163 LLVMContext &C = *DAG.getContext();
16164 SDLoc DL(St);
16165 // Details about the old store
16166 SDValue Ch = St->getChain();
16167 SDValue BasePtr = St->getBasePtr();
16168 Align Alignment = St->getOriginalAlign();
16169 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16170 AAMDNodes AAInfo = St->getAAInfo();
16171
16172 // We split the store into slices of NumElements. fp16 trunc stores are vcvt
16173 // and then stored as truncating integer stores.
16174 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
16175 EVT NewToVT = EVT::getVectorVT(
16176 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
16177
16178 SmallVector<SDValue, 4> Stores;
16179 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
16180 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
16181 SDValue NewPtr =
16182 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
16183
16184 SDValue Extract =
16185 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
16186 DAG.getConstant(i * NumElements, DL, MVT::i32));
16187
16188 SDValue FPTrunc =
16189 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
16190 Extract, DAG.getConstant(0, DL, MVT::i32));
16191 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
16192
16193 SDValue Store = DAG.getTruncStore(
16194 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16195 NewToVT, Alignment.value(), MMOFlags, AAInfo);
16196 Stores.push_back(Store);
16197 }
16198 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16199}
16200
16201// Try taking a single vector store from an MVETRUNC (which would otherwise turn
16202// into an expensive buildvector) and splitting it into a series of narrowing
16203// stores.
16204static SDValue PerformSplittingMVETruncToNarrowingStores(StoreSDNode *St,
16205 SelectionDAG &DAG) {
16206 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16207 return SDValue();
16208 SDValue Trunc = St->getValue();
16209 if (Trunc->getOpcode() != ARMISD::MVETRUNC)
16210 return SDValue();
16211 EVT FromVT = Trunc->getOperand(0).getValueType();
16212 EVT ToVT = Trunc.getValueType();
16213
16214 LLVMContext &C = *DAG.getContext();
16215 SDLoc DL(St);
16216 // Details about the old store
16217 SDValue Ch = St->getChain();
16218 SDValue BasePtr = St->getBasePtr();
16219 Align Alignment = St->getOriginalAlign();
16220 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16221 AAMDNodes AAInfo = St->getAAInfo();
16222
16223 EVT NewToVT = EVT::getVectorVT(C, ToVT.getVectorElementType(),
16224 FromVT.getVectorNumElements());
16225
16226 SmallVector<SDValue, 4> Stores;
16227 for (unsigned i = 0; i < Trunc.getNumOperands(); i++) {
16228 unsigned NewOffset =
16229 i * FromVT.getVectorNumElements() * ToVT.getScalarSizeInBits() / 8;
16230 SDValue NewPtr =
16231 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
16232
16233 SDValue Extract = Trunc.getOperand(i);
16234 SDValue Store = DAG.getTruncStore(
16235 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16236 NewToVT, Alignment.value(), MMOFlags, AAInfo);
16237 Stores.push_back(Store);
16238 }
16239 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16240}
16241
16242// Given a floating point store from an extracted vector, with an integer
16243// VGETLANE that already exists, store the existing VGETLANEu directly. This can
16244// help reduce fp register pressure, doesn't require the fp extract and allows
16245// use of more integer post-inc stores not available with vstr.
16246static SDValue PerformExtractFpToIntStores(StoreSDNode *St, SelectionDAG &DAG) {
16247 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16248 return SDValue();
16249 SDValue Extract = St->getValue();
16250 EVT VT = Extract.getValueType();
16251 // For now only uses f16. This may be useful for f32 too, but that will
16252 // be bitcast(extract), not the VGETLANEu we currently check here.
16253 if (VT != MVT::f16 || Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16254 return SDValue();
16255
16256 SDNode *GetLane =
16257 DAG.getNodeIfExists(ARMISD::VGETLANEu, DAG.getVTList(MVT::i32),
16258 {Extract.getOperand(0), Extract.getOperand(1)});
16259 if (!GetLane)
16260 return SDValue();
16261
16262 LLVMContext &C = *DAG.getContext();
16263 SDLoc DL(St);
16264 // Create a new integer store to replace the existing floating point version.
16265 SDValue Ch = St->getChain();
16266 SDValue BasePtr = St->getBasePtr();
16267 Align Alignment = St->getOriginalAlign();
16268 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16269 AAMDNodes AAInfo = St->getAAInfo();
16270 EVT NewToVT = EVT::getIntegerVT(C, VT.getSizeInBits());
16271 SDValue Store = DAG.getTruncStore(Ch, DL, SDValue(GetLane, 0), BasePtr,
16272 St->getPointerInfo(), NewToVT,
16273 Alignment.value(), MMOFlags, AAInfo);
16274
16275 return Store;
16276}
16277
16278/// PerformSTORECombine - Target-specific dag combine xforms for
16279/// ISD::STORE.
16280static SDValue PerformSTORECombine(SDNode *N,
16281 TargetLowering::DAGCombinerInfo &DCI,
16282 const ARMSubtarget *Subtarget) {
16283 StoreSDNode *St = cast<StoreSDNode>(N);
16284 if (St->isVolatile())
16285 return SDValue();
16286 SDValue StVal = St->getValue();
16287 EVT VT = StVal.getValueType();
16288
16289 if (Subtarget->hasNEON())
16290 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
16291 return Store;
16292
16293 if (Subtarget->hasMVEIntegerOps()) {
16294 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
16295 return NewToken;
16296 if (SDValue NewChain = PerformExtractFpToIntStores(St, DCI.DAG))
16297 return NewChain;
16298 if (SDValue NewToken =
16299 PerformSplittingMVETruncToNarrowingStores(St, DCI.DAG))
16300 return NewToken;
16301 }
16302
16303 if (!ISD::isNormalStore(St))
16304 return SDValue();
16305
16306 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
16307 // ARM stores of arguments in the same cache line.
16308 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
16309 StVal.getNode()->hasOneUse()) {
16310 SelectionDAG &DAG = DCI.DAG;
16311 bool isBigEndian = DAG.getDataLayout().isBigEndian();
16312 SDLoc DL(St);
16313 SDValue BasePtr = St->getBasePtr();
16314 SDValue NewST1 = DAG.getStore(
16315 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
16316 BasePtr, St->getPointerInfo(), St->getOriginalAlign(),
16317 St->getMemOperand()->getFlags());
16318
16319 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
16320 DAG.getConstant(4, DL, MVT::i32));
16321 return DAG.getStore(NewST1.getValue(0), DL,
16322 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
16323 OffsetPtr, St->getPointerInfo().getWithOffset(4),
16324 St->getOriginalAlign(),
16325 St->getMemOperand()->getFlags());
16326 }
16327
16328 if (StVal.getValueType() == MVT::i64 &&
16329 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16330
16331 // Bitcast an i64 store extracted from a vector to f64.
16332 // Otherwise, the i64 value will be legalized to a pair of i32 values.
16333 SelectionDAG &DAG = DCI.DAG;
16334 SDLoc dl(StVal);
16335 SDValue IntVec = StVal.getOperand(0);
16336 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
16337 IntVec.getValueType().getVectorNumElements());
16338 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
16339 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
16340 Vec, StVal.getOperand(1));
16341 dl = SDLoc(N);
16342 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
16343 // Make the DAGCombiner fold the bitcasts.
16344 DCI.AddToWorklist(Vec.getNode());
16345 DCI.AddToWorklist(ExtElt.getNode());
16346 DCI.AddToWorklist(V.getNode());
16347 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
16348 St->getPointerInfo(), St->getAlignment(),
16349 St->getMemOperand()->getFlags(), St->getAAInfo());
16350 }
16351
16352 // If this is a legal vector store, try to combine it into a VST1_UPD.
16353 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
16354 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16355 return CombineBaseUpdate(N, DCI);
16356
16357 return SDValue();
16358}
16359
16360/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
16361/// can replace combinations of VMUL and VCVT (floating-point to integer)
16362/// when the VMUL has a constant operand that is a power of 2.
16363///
16364/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
16365/// vmul.f32 d16, d17, d16
16366/// vcvt.s32.f32 d16, d16
16367/// becomes:
16368/// vcvt.s32.f32 d16, d16, #3
16369static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
16370 const ARMSubtarget *Subtarget) {
16371 if (!Subtarget->hasNEON())
16372 return SDValue();
16373
16374 SDValue Op = N->getOperand(0);
16375 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
16376 Op.getOpcode() != ISD::FMUL)
16377 return SDValue();
16378
16379 SDValue ConstVec = Op->getOperand(1);
16380 if (!isa<BuildVectorSDNode>(ConstVec))
16381 return SDValue();
16382
16383 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
16384 uint32_t FloatBits = FloatTy.getSizeInBits();
16385 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
16386 uint32_t IntBits = IntTy.getSizeInBits();
16387 unsigned NumLanes = Op.getValueType().getVectorNumElements();
16388 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
16389 // These instructions only exist converting from f32 to i32. We can handle
16390 // smaller integers by generating an extra truncate, but larger ones would
16391 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
16392 // these intructions only support v2i32/v4i32 types.
16393 return SDValue();
16394 }
16395
16396 BitVector UndefElements;
16397 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
16398 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
16399 if (C == -1 || C == 0 || C > 32)
16400 return SDValue();
16401
16402 SDLoc dl(N);
16403 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
16404 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
16405 Intrinsic::arm_neon_vcvtfp2fxu;
16406 SDValue FixConv = DAG.getNode(
16407 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
16408 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
16409 DAG.getConstant(C, dl, MVT::i32));
16410
16411 if (IntBits < FloatBits)
16412 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
16413
16414 return FixConv;
16415}
16416
16417/// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
16418/// can replace combinations of VCVT (integer to floating-point) and VDIV
16419/// when the VDIV has a constant operand that is a power of 2.
16420///
16421/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
16422/// vcvt.f32.s32 d16, d16
16423/// vdiv.f32 d16, d17, d16
16424/// becomes:
16425/// vcvt.f32.s32 d16, d16, #3
16426static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
16427 const ARMSubtarget *Subtarget) {
16428 if (!Subtarget->hasNEON())
16429 return SDValue();
16430
16431 SDValue Op = N->getOperand(0);
16432 unsigned OpOpcode = Op.getNode()->getOpcode();
16433 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
16434 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
16435 return SDValue();
16436
16437 SDValue ConstVec = N->getOperand(1);
16438 if (!isa<BuildVectorSDNode>(ConstVec))
16439 return SDValue();
16440
16441 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
16442 uint32_t FloatBits = FloatTy.getSizeInBits();
16443 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
16444 uint32_t IntBits = IntTy.getSizeInBits();
16445 unsigned NumLanes = Op.getValueType().getVectorNumElements();
16446 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
16447 // These instructions only exist converting from i32 to f32. We can handle
16448 // smaller integers by generating an extra extend, but larger ones would
16449 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
16450 // these intructions only support v2i32/v4i32 types.
16451 return SDValue();
16452 }
16453
16454 BitVector UndefElements;
16455 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
16456 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
16457 if (C == -1 || C == 0 || C > 32)
16458 return SDValue();
16459
16460 SDLoc dl(N);
16461 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
16462 SDValue ConvInput = Op.getOperand(0);
16463 if (IntBits < FloatBits)
16464 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
16465 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
16466 ConvInput);
16467
16468 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
16469 Intrinsic::arm_neon_vcvtfxu2fp;
16470 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
16471 Op.getValueType(),
16472 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
16473 ConvInput, DAG.getConstant(C, dl, MVT::i32));
16474}
16475
16476static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
16477 const ARMSubtarget *ST) {
16478 if (!ST->hasMVEIntegerOps())
16479 return SDValue();
16480
16481 assert(N->getOpcode() == ISD::VECREDUCE_ADD)(static_cast <bool> (N->getOpcode() == ISD::VECREDUCE_ADD
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::VECREDUCE_ADD"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16481, __extension__ __PRETTY_FUNCTION__))
;
16482 EVT ResVT = N->getValueType(0);
16483 SDValue N0 = N->getOperand(0);
16484 SDLoc dl(N);
16485
16486 // Try to turn vecreduce_add(add(x, y)) into vecreduce(x) + vecreduce(y)
16487 if (ResVT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
16488 (N0.getValueType() == MVT::v4i32 || N0.getValueType() == MVT::v8i16 ||
16489 N0.getValueType() == MVT::v16i8)) {
16490 SDValue Red0 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(0));
16491 SDValue Red1 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(1));
16492 return DAG.getNode(ISD::ADD, dl, ResVT, Red0, Red1);
16493 }
16494
16495 // We are looking for something that will have illegal types if left alone,
16496 // but that we can convert to a single instruction under MVE. For example
16497 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
16498 // or
16499 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
16500
16501 // The legal cases are:
16502 // VADDV u/s 8/16/32
16503 // VMLAV u/s 8/16/32
16504 // VADDLV u/s 32
16505 // VMLALV u/s 16/32
16506
16507 // If the input vector is smaller than legal (v4i8/v4i16 for example) we can
16508 // extend it and use v4i32 instead.
16509 auto ExtTypeMatches = [](SDValue A, ArrayRef<MVT> ExtTypes) {
16510 EVT AVT = A.getValueType();
16511 return any_of(ExtTypes, [&](MVT Ty) {
16512 return AVT.getVectorNumElements() == Ty.getVectorNumElements() &&
16513 AVT.bitsLE(Ty);
16514 });
16515 };
16516 auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) {
16517 EVT AVT = A.getValueType();
16518 if (!AVT.is128BitVector())
16519 A = DAG.getNode(ExtendCode, dl,
16520 AVT.changeVectorElementType(MVT::getIntegerVT(
16521 128 / AVT.getVectorMinNumElements())),
16522 A);
16523 return A;
16524 };
16525 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
16526 if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
16527 return SDValue();
16528 SDValue A = N0->getOperand(0);
16529 if (ExtTypeMatches(A, ExtTypes))
16530 return ExtendIfNeeded(A, ExtendCode);
16531 return SDValue();
16532 };
16533 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
16534 ArrayRef<MVT> ExtTypes, SDValue &Mask) {
16535 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
16536 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
16537 return SDValue();
16538 Mask = N0->getOperand(0);
16539 SDValue Ext = N0->getOperand(1);
16540 if (Ext->getOpcode() != ExtendCode)
16541 return SDValue();
16542 SDValue A = Ext->getOperand(0);
16543 if (ExtTypeMatches(A, ExtTypes))
16544 return ExtendIfNeeded(A, ExtendCode);
16545 return SDValue();
16546 };
16547 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
16548 SDValue &A, SDValue &B) {
16549 // For a vmla we are trying to match a larger pattern:
16550 // ExtA = sext/zext A
16551 // ExtB = sext/zext B
16552 // Mul = mul ExtA, ExtB
16553 // vecreduce.add Mul
16554 // There might also be en extra extend between the mul and the addreduce, so
16555 // long as the bitwidth is high enough to make them equivalent (for example
16556 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
16557 if (ResVT != RetTy)
16558 return false;
16559 SDValue Mul = N0;
16560 if (Mul->getOpcode() == ExtendCode &&
16561 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
16562 ResVT.getScalarSizeInBits())
16563 Mul = Mul->getOperand(0);
16564 if (Mul->getOpcode() != ISD::MUL)
16565 return false;
16566 SDValue ExtA = Mul->getOperand(0);
16567 SDValue ExtB = Mul->getOperand(1);
16568 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
16569 return false;
16570 A = ExtA->getOperand(0);
16571 B = ExtB->getOperand(0);
16572 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
16573 A = ExtendIfNeeded(A, ExtendCode);
16574 B = ExtendIfNeeded(B, ExtendCode);
16575 return true;
16576 }
16577 return false;
16578 };
16579 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
16580 SDValue &A, SDValue &B, SDValue &Mask) {
16581 // Same as the pattern above with a select for the zero predicated lanes
16582 // ExtA = sext/zext A
16583 // ExtB = sext/zext B
16584 // Mul = mul ExtA, ExtB
16585 // N0 = select Mask, Mul, 0
16586 // vecreduce.add N0
16587 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
16588 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
16589 return false;
16590 Mask = N0->getOperand(0);
16591 SDValue Mul = N0->getOperand(1);
16592 if (Mul->getOpcode() == ExtendCode &&
16593 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
16594 ResVT.getScalarSizeInBits())
16595 Mul = Mul->getOperand(0);
16596 if (Mul->getOpcode() != ISD::MUL)
16597 return false;
16598 SDValue ExtA = Mul->getOperand(0);
16599 SDValue ExtB = Mul->getOperand(1);
16600 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
16601 return false;
16602 A = ExtA->getOperand(0);
16603 B = ExtB->getOperand(0);
16604 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
16605 A = ExtendIfNeeded(A, ExtendCode);
16606 B = ExtendIfNeeded(B, ExtendCode);
16607 return true;
16608 }
16609 return false;
16610 };
16611 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
16612 // Split illegal MVT::v16i8->i64 vector reductions into two legal v8i16->i64
16613 // reductions. The operands are extended with MVEEXT, but as they are
16614 // reductions the lane orders do not matter. MVEEXT may be combined with
16615 // loads to produce two extending loads, or else they will be expanded to
16616 // VREV/VMOVL.
16617 EVT VT = Ops[0].getValueType();
16618 if (VT == MVT::v16i8) {
16619 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16620, __extension__ __PRETTY_FUNCTION__))
16620 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16620, __extension__ __PRETTY_FUNCTION__))
;
16621 bool IsUnsigned = Opcode == ARMISD::VMLALVu;
16622
16623 SDValue Ext0 =
16624 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
16625 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[0]);
16626 SDValue Ext1 =
16627 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
16628 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[1]);
16629
16630 SDValue MLA0 = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
16631 Ext0, Ext1);
16632 SDValue MLA1 =
16633 DAG.getNode(IsUnsigned ? ARMISD::VMLALVAu : ARMISD::VMLALVAs, dl,
16634 DAG.getVTList(MVT::i32, MVT::i32), MLA0, MLA0.getValue(1),
16635 Ext0.getValue(1), Ext1.getValue(1));
16636 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, MLA1, MLA1.getValue(1));
16637 }
16638 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
16639 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
16640 SDValue(Node.getNode(), 1));
16641 };
16642
16643 SDValue A, B;
16644 SDValue Mask;
16645 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
16646 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
16647 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
16648 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
16649 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
16650 A, B))
16651 return Create64bitNode(ARMISD::VMLALVs, {A, B});
16652 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
16653 A, B))
16654 return Create64bitNode(ARMISD::VMLALVu, {A, B});
16655 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
16656 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16657 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
16658 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
16659 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16660 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
16661
16662 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
16663 Mask))
16664 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
16665 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
16666 Mask))
16667 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
16668 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
16669 Mask))
16670 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
16671 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
16672 Mask))
16673 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
16674 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
16675 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16676 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
16677 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
16678 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16679 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
16680
16681 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
16682 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
16683 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
16684 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
16685 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
16686 return Create64bitNode(ARMISD::VADDLVs, {A});
16687 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
16688 return Create64bitNode(ARMISD::VADDLVu, {A});
16689 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
16690 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16691 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
16692 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
16693 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16694 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
16695
16696 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
16697 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
16698 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
16699 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
16700 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
16701 return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
16702 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
16703 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
16704 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
16705 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16706 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
16707 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
16708 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16709 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
16710
16711 // Some complications. We can get a case where the two inputs of the mul are
16712 // the same, then the output sext will have been helpfully converted to a
16713 // zext. Turn it back.
16714 SDValue Op = N0;
16715 if (Op->getOpcode() == ISD::VSELECT)
16716 Op = Op->getOperand(1);
16717 if (Op->getOpcode() == ISD::ZERO_EXTEND &&
16718 Op->getOperand(0)->getOpcode() == ISD::MUL) {
16719 SDValue Mul = Op->getOperand(0);
16720 if (Mul->getOperand(0) == Mul->getOperand(1) &&
16721 Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
16722 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
16723 if (Op != N0)
16724 Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
16725 N0->getOperand(0), Ext, N0->getOperand(2));
16726 return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
16727 }
16728 }
16729
16730 return SDValue();
16731}
16732
16733static SDValue PerformVMOVNCombine(SDNode *N,
16734 TargetLowering::DAGCombinerInfo &DCI) {
16735 SDValue Op0 = N->getOperand(0);
16736 SDValue Op1 = N->getOperand(1);
16737 unsigned IsTop = N->getConstantOperandVal(2);
16738
16739 // VMOVNT a undef -> a
16740 // VMOVNB a undef -> a
16741 // VMOVNB undef a -> a
16742 if (Op1->isUndef())
16743 return Op0;
16744 if (Op0->isUndef() && !IsTop)
16745 return Op1;
16746
16747 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
16748 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
16749 if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
16750 Op1->getOpcode() == ARMISD::VQMOVNu) &&
16751 Op1->getConstantOperandVal(2) == 0)
16752 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
16753 Op0, Op1->getOperand(1), N->getOperand(2));
16754
16755 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
16756 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
16757 // into the top or bottom lanes.
16758 unsigned NumElts = N->getValueType(0).getVectorNumElements();
16759 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
16760 APInt Op0DemandedElts =
16761 IsTop ? Op1DemandedElts
16762 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
16763
16764 APInt KnownUndef, KnownZero;
16765 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
16766 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
16767 KnownZero, DCI))
16768 return SDValue(N, 0);
16769 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef,
16770 KnownZero, DCI))
16771 return SDValue(N, 0);
16772
16773 return SDValue();
16774}
16775
16776static SDValue PerformVQMOVNCombine(SDNode *N,
16777 TargetLowering::DAGCombinerInfo &DCI) {
16778 SDValue Op0 = N->getOperand(0);
16779 unsigned IsTop = N->getConstantOperandVal(2);
16780
16781 unsigned NumElts = N->getValueType(0).getVectorNumElements();
16782 APInt Op0DemandedElts =
16783 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
16784 : APInt::getHighBitsSet(2, 1));
16785
16786 APInt KnownUndef, KnownZero;
16787 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
16788 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
16789 KnownZero, DCI))
16790 return SDValue(N, 0);
16791 return SDValue();
16792}
16793
16794static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
16795 SDLoc DL(N);
16796 SDValue Op0 = N->getOperand(0);
16797 SDValue Op1 = N->getOperand(1);
16798
16799 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
16800 // uses of the intrinsics.
16801 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
16802 int ShiftAmt = C->getSExtValue();
16803 if (ShiftAmt == 0) {
16804 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
16805 DAG.ReplaceAllUsesWith(N, Merge.getNode());
16806 return SDValue();
16807 }
16808
16809 if (ShiftAmt >= -32 && ShiftAmt < 0) {
16810 unsigned NewOpcode =
16811 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
16812 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
16813 DAG.getConstant(-ShiftAmt, DL, MVT::i32));
16814 DAG.ReplaceAllUsesWith(N, NewShift.getNode());
16815 return NewShift;
16816 }
16817 }
16818
16819 return SDValue();
16820}
16821
16822/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
16823SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
16824 DAGCombinerInfo &DCI) const {
16825 SelectionDAG &DAG = DCI.DAG;
16826 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
16827 switch (IntNo) {
16828 default:
16829 // Don't do anything for most intrinsics.
16830 break;
16831
16832 // Vector shifts: check for immediate versions and lower them.
16833 // Note: This is done during DAG combining instead of DAG legalizing because
16834 // the build_vectors for 64-bit vector element shift counts are generally
16835 // not legal, and it is hard to see their values after they get legalized to
16836 // loads from a constant pool.
16837 case Intrinsic::arm_neon_vshifts:
16838 case Intrinsic::arm_neon_vshiftu:
16839 case Intrinsic::arm_neon_vrshifts:
16840 case Intrinsic::arm_neon_vrshiftu:
16841 case Intrinsic::arm_neon_vrshiftn:
16842 case Intrinsic::arm_neon_vqshifts:
16843 case Intrinsic::arm_neon_vqshiftu:
16844 case Intrinsic::arm_neon_vqshiftsu:
16845 case Intrinsic::arm_neon_vqshiftns:
16846 case Intrinsic::arm_neon_vqshiftnu:
16847 case Intrinsic::arm_neon_vqshiftnsu:
16848 case Intrinsic::arm_neon_vqrshiftns:
16849 case Intrinsic::arm_neon_vqrshiftnu:
16850 case Intrinsic::arm_neon_vqrshiftnsu: {
16851 EVT VT = N->getOperand(1).getValueType();
16852 int64_t Cnt;
16853 unsigned VShiftOpc = 0;
16854
16855 switch (IntNo) {
16856 case Intrinsic::arm_neon_vshifts:
16857 case Intrinsic::arm_neon_vshiftu:
16858 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
16859 VShiftOpc = ARMISD::VSHLIMM;
16860 break;
16861 }
16862 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
16863 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
16864 : ARMISD::VSHRuIMM);
16865 break;
16866 }
16867 return SDValue();
16868
16869 case Intrinsic::arm_neon_vrshifts:
16870 case Intrinsic::arm_neon_vrshiftu:
16871 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
16872 break;
16873 return SDValue();
16874
16875 case Intrinsic::arm_neon_vqshifts:
16876 case Intrinsic::arm_neon_vqshiftu:
16877 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
16878 break;
16879 return SDValue();
16880
16881 case Intrinsic::arm_neon_vqshiftsu:
16882 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
16883 break;
16884 llvm_unreachable("invalid shift count for vqshlu intrinsic")::llvm::llvm_unreachable_internal("invalid shift count for vqshlu intrinsic"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16884)
;
16885
16886 case Intrinsic::arm_neon_vrshiftn:
16887 case Intrinsic::arm_neon_vqshiftns:
16888 case Intrinsic::arm_neon_vqshiftnu:
16889 case Intrinsic::arm_neon_vqshiftnsu:
16890 case Intrinsic::arm_neon_vqrshiftns:
16891 case Intrinsic::arm_neon_vqrshiftnu:
16892 case Intrinsic::arm_neon_vqrshiftnsu:
16893 // Narrowing shifts require an immediate right shift.
16894 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
16895 break;
16896 llvm_unreachable("invalid shift count for narrowing vector shift "::llvm::llvm_unreachable_internal("invalid shift count for narrowing vector shift "
"intrinsic", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16897)
16897 "intrinsic")::llvm::llvm_unreachable_internal("invalid shift count for narrowing vector shift "
"intrinsic", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16897)
;
16898
16899 default:
16900 llvm_unreachable("unhandled vector shift")::llvm::llvm_unreachable_internal("unhandled vector shift", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16900)
;
16901 }
16902
16903 switch (IntNo) {
16904 case Intrinsic::arm_neon_vshifts:
16905 case Intrinsic::arm_neon_vshiftu:
16906 // Opcode already set above.
16907 break;
16908 case Intrinsic::arm_neon_vrshifts:
16909 VShiftOpc = ARMISD::VRSHRsIMM;
16910 break;
16911 case Intrinsic::arm_neon_vrshiftu:
16912 VShiftOpc = ARMISD::VRSHRuIMM;
16913 break;
16914 case Intrinsic::arm_neon_vrshiftn:
16915 VShiftOpc = ARMISD::VRSHRNIMM;
16916 break;
16917 case Intrinsic::arm_neon_vqshifts:
16918 VShiftOpc = ARMISD::VQSHLsIMM;
16919 break;
16920 case Intrinsic::arm_neon_vqshiftu:
16921 VShiftOpc = ARMISD::VQSHLuIMM;
16922 break;
16923 case Intrinsic::arm_neon_vqshiftsu:
16924 VShiftOpc = ARMISD::VQSHLsuIMM;
16925 break;
16926 case Intrinsic::arm_neon_vqshiftns:
16927 VShiftOpc = ARMISD::VQSHRNsIMM;
16928 break;
16929 case Intrinsic::arm_neon_vqshiftnu:
16930 VShiftOpc = ARMISD::VQSHRNuIMM;
16931 break;
16932 case Intrinsic::arm_neon_vqshiftnsu:
16933 VShiftOpc = ARMISD::VQSHRNsuIMM;
16934 break;
16935 case Intrinsic::arm_neon_vqrshiftns:
16936 VShiftOpc = ARMISD::VQRSHRNsIMM;
16937 break;
16938 case Intrinsic::arm_neon_vqrshiftnu:
16939 VShiftOpc = ARMISD::VQRSHRNuIMM;
16940 break;
16941 case Intrinsic::arm_neon_vqrshiftnsu:
16942 VShiftOpc = ARMISD::VQRSHRNsuIMM;
16943 break;
16944 }
16945
16946 SDLoc dl(N);
16947 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
16948 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
16949 }
16950
16951 case Intrinsic::arm_neon_vshiftins: {
16952 EVT VT = N->getOperand(1).getValueType();
16953 int64_t Cnt;
16954 unsigned VShiftOpc = 0;
16955
16956 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
16957 VShiftOpc = ARMISD::VSLIIMM;
16958 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
16959 VShiftOpc = ARMISD::VSRIIMM;
16960 else {
16961 llvm_unreachable("invalid shift count for vsli/vsri intrinsic")::llvm::llvm_unreachable_internal("invalid shift count for vsli/vsri intrinsic"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16961)
;
16962 }
16963
16964 SDLoc dl(N);
16965 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
16966 N->getOperand(1), N->getOperand(2),
16967 DAG.getConstant(Cnt, dl, MVT::i32));
16968 }
16969
16970 case Intrinsic::arm_neon_vqrshifts:
16971 case Intrinsic::arm_neon_vqrshiftu:
16972 // No immediate versions of these to check for.
16973 break;
16974
16975 case Intrinsic::arm_mve_vqdmlah:
16976 case Intrinsic::arm_mve_vqdmlash:
16977 case Intrinsic::arm_mve_vqrdmlah:
16978 case Intrinsic::arm_mve_vqrdmlash:
16979 case Intrinsic::arm_mve_vmla_n_predicated:
16980 case Intrinsic::arm_mve_vmlas_n_predicated:
16981 case Intrinsic::arm_mve_vqdmlah_predicated:
16982 case Intrinsic::arm_mve_vqdmlash_predicated:
16983 case Intrinsic::arm_mve_vqrdmlah_predicated:
16984 case Intrinsic::arm_mve_vqrdmlash_predicated: {
16985 // These intrinsics all take an i32 scalar operand which is narrowed to the
16986 // size of a single lane of the vector type they return. So we don't need
16987 // any bits of that operand above that point, which allows us to eliminate
16988 // uxth/sxth.
16989 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
16990 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
16991 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
16992 return SDValue();
16993 break;
16994 }
16995
16996 case Intrinsic::arm_mve_minv:
16997 case Intrinsic::arm_mve_maxv:
16998 case Intrinsic::arm_mve_minav:
16999 case Intrinsic::arm_mve_maxav:
17000 case Intrinsic::arm_mve_minv_predicated:
17001 case Intrinsic::arm_mve_maxv_predicated:
17002 case Intrinsic::arm_mve_minav_predicated:
17003 case Intrinsic::arm_mve_maxav_predicated: {
17004 // These intrinsics all take an i32 scalar operand which is narrowed to the
17005 // size of a single lane of the vector type they take as the other input.
17006 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
17007 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
17008 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
17009 return SDValue();
17010 break;
17011 }
17012
17013 case Intrinsic::arm_mve_addv: {
17014 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
17015 // which allow PerformADDVecReduce to turn it into VADDLV when possible.
17016 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
17017 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
17018 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
17019 }
17020
17021 case Intrinsic::arm_mve_addlv:
17022 case Intrinsic::arm_mve_addlv_predicated: {
17023 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
17024 // which recombines the two outputs into an i64
17025 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
17026 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
17027 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
17028 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
17029
17030 SmallVector<SDValue, 4> Ops;
17031 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
17032 if (i != 2) // skip the unsigned flag
17033 Ops.push_back(N->getOperand(i));
17034
17035 SDLoc dl(N);
17036 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
17037 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
17038 val.getValue(1));
17039 }
17040 }
17041
17042 return SDValue();
17043}
17044
17045/// PerformShiftCombine - Checks for immediate versions of vector shifts and
17046/// lowers them. As with the vector shift intrinsics, this is done during DAG
17047/// combining instead of DAG legalizing because the build_vectors for 64-bit
17048/// vector element shift counts are generally not legal, and it is hard to see
17049/// their values after they get legalized to loads from a constant pool.
17050static SDValue PerformShiftCombine(SDNode *N,
17051 TargetLowering::DAGCombinerInfo &DCI,
17052 const ARMSubtarget *ST) {
17053 SelectionDAG &DAG = DCI.DAG;
17054 EVT VT = N->getValueType(0);
17055 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
17056 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
17057 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
17058 SDValue N1 = N->getOperand(1);
17059 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
17060 SDValue N0 = N->getOperand(0);
17061 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
17062 DAG.MaskedValueIsZero(N0.getOperand(0),
17063 APInt::getHighBitsSet(32, 16)))
17064 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
17065 }
17066 }
17067
17068 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
17069 N->getOperand(0)->getOpcode() == ISD::AND &&
17070 N->getOperand(0)->hasOneUse()) {
17071 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17072 return SDValue();
17073 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
17074 // usually show up because instcombine prefers to canonicalize it to
17075 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
17076 // out of GEP lowering in some cases.
17077 SDValue N0 = N->getOperand(0);
17078 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
17079 if (!ShiftAmtNode)
17080 return SDValue();
17081 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
17082 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
17083 if (!AndMaskNode)
17084 return SDValue();
17085 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
17086 // Don't transform uxtb/uxth.
17087 if (AndMask == 255 || AndMask == 65535)
17088 return SDValue();
17089 if (isMask_32(AndMask)) {
17090 uint32_t MaskedBits = countLeadingZeros(AndMask);
17091 if (MaskedBits > ShiftAmt) {
17092 SDLoc DL(N);
17093 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
17094 DAG.getConstant(MaskedBits, DL, MVT::i32));
17095 return DAG.getNode(
17096 ISD::SRL, DL, MVT::i32, SHL,
17097 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
17098 }
17099 }
17100 }
17101
17102 // Nothing to be done for scalar shifts.
17103 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17104 if (!VT.isVector() || !TLI.isTypeLegal(VT))
17105 return SDValue();
17106 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
17107 return SDValue();
17108
17109 int64_t Cnt;
17110
17111 switch (N->getOpcode()) {
17112 default: llvm_unreachable("unexpected shift opcode")::llvm::llvm_unreachable_internal("unexpected shift opcode", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17112)
;
17113
17114 case ISD::SHL:
17115 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
17116 SDLoc dl(N);
17117 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
17118 DAG.getConstant(Cnt, dl, MVT::i32));
17119 }
17120 break;
17121
17122 case ISD::SRA:
17123 case ISD::SRL:
17124 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
17125 unsigned VShiftOpc =
17126 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
17127 SDLoc dl(N);
17128 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
17129 DAG.getConstant(Cnt, dl, MVT::i32));
17130 }
17131 }
17132 return SDValue();
17133}
17134
17135// Look for a sign/zero/fpextend extend of a larger than legal load. This can be
17136// split into multiple extending loads, which are simpler to deal with than an
17137// arbitrary extend. For fp extends we use an integer extending load and a VCVTL
17138// to convert the type to an f32.
17139static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
17140 SDValue N0 = N->getOperand(0);
17141 if (N0.getOpcode() != ISD::LOAD)
17142 return SDValue();
17143 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
17144 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
17145 LD->getExtensionType() != ISD::NON_EXTLOAD)
17146 return SDValue();
17147 EVT FromVT = LD->getValueType(0);
17148 EVT ToVT = N->getValueType(0);
17149 if (!ToVT.isVector())
17150 return SDValue();
17151 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements())(static_cast <bool> (FromVT.getVectorNumElements() == ToVT
.getVectorNumElements()) ? void (0) : __assert_fail ("FromVT.getVectorNumElements() == ToVT.getVectorNumElements()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17151, __extension__ __PRETTY_FUNCTION__))
;
17152 EVT ToEltVT = ToVT.getVectorElementType();
17153 EVT FromEltVT = FromVT.getVectorElementType();
17154
17155 unsigned NumElements = 0;
17156 if (ToEltVT == MVT::i32 && FromEltVT == MVT::i8)
17157 NumElements = 4;
17158 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
17159 NumElements = 4;
17160 if (NumElements == 0 ||
17161 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
17162 FromVT.getVectorNumElements() % NumElements != 0 ||
17163 !isPowerOf2_32(NumElements))
17164 return SDValue();
17165
17166 LLVMContext &C = *DAG.getContext();
17167 SDLoc DL(LD);
17168 // Details about the old load
17169 SDValue Ch = LD->getChain();
17170 SDValue BasePtr = LD->getBasePtr();
17171 Align Alignment = LD->getOriginalAlign();
17172 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
17173 AAMDNodes AAInfo = LD->getAAInfo();
17174
17175 ISD::LoadExtType NewExtType =
17176 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
17177 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
17178 EVT NewFromVT = EVT::getVectorVT(
17179 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
17180 EVT NewToVT = EVT::getVectorVT(
17181 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
17182
17183 SmallVector<SDValue, 4> Loads;
17184 SmallVector<SDValue, 4> Chains;
17185 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
17186 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
17187 SDValue NewPtr =
17188 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
17189
17190 SDValue NewLoad =
17191 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
17192 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
17193 Alignment, MMOFlags, AAInfo);
17194 Loads.push_back(NewLoad);
17195 Chains.push_back(SDValue(NewLoad.getNode(), 1));
17196 }
17197
17198 // Float truncs need to extended with VCVTB's into their floating point types.
17199 if (FromEltVT == MVT::f16) {
17200 SmallVector<SDValue, 4> Extends;
17201
17202 for (unsigned i = 0; i < Loads.size(); i++) {
17203 SDValue LoadBC =
17204 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
17205 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
17206 DAG.getConstant(0, DL, MVT::i32));
17207 Extends.push_back(FPExt);
17208 }
17209
17210 Loads = Extends;
17211 }
17212
17213 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
17214 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
17215 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
17216}
17217
17218/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
17219/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
17220static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
17221 const ARMSubtarget *ST) {
17222 SDValue N0 = N->getOperand(0);
17223
17224 // Check for sign- and zero-extensions of vector extract operations of 8- and
17225 // 16-bit vector elements. NEON and MVE support these directly. They are
17226 // handled during DAG combining because type legalization will promote them
17227 // to 32-bit types and it is messy to recognize the operations after that.
17228 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
17229 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17230 SDValue Vec = N0.getOperand(0);
17231 SDValue Lane = N0.getOperand(1);
17232 EVT VT = N->getValueType(0);
17233 EVT EltVT = N0.getValueType();
17234 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17235
17236 if (VT == MVT::i32 &&
17237 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
17238 TLI.isTypeLegal(Vec.getValueType()) &&
17239 isa<ConstantSDNode>(Lane)) {
17240
17241 unsigned Opc = 0;
17242 switch (N->getOpcode()) {
17243 default: llvm_unreachable("unexpected opcode")::llvm::llvm_unreachable_internal("unexpected opcode", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17243)
;
17244 case ISD::SIGN_EXTEND:
17245 Opc = ARMISD::VGETLANEs;
17246 break;
17247 case ISD::ZERO_EXTEND:
17248 case ISD::ANY_EXTEND:
17249 Opc = ARMISD::VGETLANEu;
17250 break;
17251 }
17252 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
17253 }
17254 }
17255
17256 if (ST->hasMVEIntegerOps())
17257 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
17258 return NewLoad;
17259
17260 return SDValue();
17261}
17262
17263static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG,
17264 const ARMSubtarget *ST) {
17265 if (ST->hasMVEFloatOps())
17266 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
17267 return NewLoad;
17268
17269 return SDValue();
17270}
17271
17272/// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
17273/// saturates.
17274static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
17275 const ARMSubtarget *ST) {
17276 EVT VT = N->getValueType(0);
17277 SDValue N0 = N->getOperand(0);
17278 if (!ST->hasMVEIntegerOps())
17279 return SDValue();
17280
17281 if (SDValue V = PerformVQDMULHCombine(N, DAG))
17282 return V;
17283
17284 if (VT != MVT::v4i32 && VT != MVT::v8i16)
17285 return SDValue();
17286
17287 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
17288 // Check one is a smin and the other is a smax
17289 if (Min->getOpcode() != ISD::SMIN)
17290 std::swap(Min, Max);
17291 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
17292 return false;
17293
17294 APInt SaturateC;
17295 if (VT == MVT::v4i32)
17296 SaturateC = APInt(32, (1 << 15) - 1, true);
17297 else //if (VT == MVT::v8i16)
17298 SaturateC = APInt(16, (1 << 7) - 1, true);
17299
17300 APInt MinC, MaxC;
17301 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
17302 MinC != SaturateC)
17303 return false;
17304 if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) ||
17305 MaxC != ~SaturateC)
17306 return false;
17307 return true;
17308 };
17309
17310 if (IsSignedSaturate(N, N0.getNode())) {
17311 SDLoc DL(N);
17312 MVT ExtVT, HalfVT;
17313 if (VT == MVT::v4i32) {
17314 HalfVT = MVT::v8i16;
17315 ExtVT = MVT::v4i16;
17316 } else { // if (VT == MVT::v8i16)
17317 HalfVT = MVT::v16i8;
17318 ExtVT = MVT::v8i8;
17319 }
17320
17321 // Create a VQMOVNB with undef top lanes, then signed extended into the top
17322 // half. That extend will hopefully be removed if only the bottom bits are
17323 // demanded (though a truncating store, for example).
17324 SDValue VQMOVN =
17325 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
17326 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
17327 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
17328 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
17329 DAG.getValueType(ExtVT));
17330 }
17331
17332 auto IsUnsignedSaturate = [&](SDNode *Min) {
17333 // For unsigned, we just need to check for <= 0xffff
17334 if (Min->getOpcode() != ISD::UMIN)
17335 return false;
17336
17337 APInt SaturateC;
17338 if (VT == MVT::v4i32)
17339 SaturateC = APInt(32, (1 << 16) - 1, true);
17340 else //if (VT == MVT::v8i16)
17341 SaturateC = APInt(16, (1 << 8) - 1, true);
17342
17343 APInt MinC;
17344 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
17345 MinC != SaturateC)
17346 return false;
17347 return true;
17348 };
17349
17350 if (IsUnsignedSaturate(N)) {
17351 SDLoc DL(N);
17352 MVT HalfVT;
17353 unsigned ExtConst;
17354 if (VT == MVT::v4i32) {
17355 HalfVT = MVT::v8i16;
17356 ExtConst = 0x0000FFFF;
17357 } else { //if (VT == MVT::v8i16)
17358 HalfVT = MVT::v16i8;
17359 ExtConst = 0x00FF;
17360 }
17361
17362 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
17363 // an AND. That extend will hopefully be removed if only the bottom bits are
17364 // demanded (though a truncating store, for example).
17365 SDValue VQMOVN =
17366 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
17367 DAG.getConstant(0, DL, MVT::i32));
17368 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
17369 return DAG.getNode(ISD::AND, DL, VT, Bitcast,
17370 DAG.getConstant(ExtConst, DL, VT));
17371 }
17372
17373 return SDValue();
17374}
17375
17376static const APInt *isPowerOf2Constant(SDValue V) {
17377 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
17378 if (!C)
17379 return nullptr;
17380 const APInt *CV = &C->getAPIntValue();
17381 return CV->isPowerOf2() ? CV : nullptr;
17382}
17383
17384SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
17385 // If we have a CMOV, OR and AND combination such as:
17386 // if (x & CN)
17387 // y |= CM;
17388 //
17389 // And:
17390 // * CN is a single bit;
17391 // * All bits covered by CM are known zero in y
17392 //
17393 // Then we can convert this into a sequence of BFI instructions. This will
17394 // always be a win if CM is a single bit, will always be no worse than the
17395 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
17396 // three bits (due to the extra IT instruction).
17397
17398 SDValue Op0 = CMOV->getOperand(0);
17399 SDValue Op1 = CMOV->getOperand(1);
17400 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
17401 auto CC = CCNode->getAPIntValue().getLimitedValue();
17402 SDValue CmpZ = CMOV->getOperand(4);
17403
17404 // The compare must be against zero.
17405 if (!isNullConstant(CmpZ->getOperand(1)))
17406 return SDValue();
17407
17408 assert(CmpZ->getOpcode() == ARMISD::CMPZ)(static_cast <bool> (CmpZ->getOpcode() == ARMISD::CMPZ
) ? void (0) : __assert_fail ("CmpZ->getOpcode() == ARMISD::CMPZ"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17408, __extension__ __PRETTY_FUNCTION__))
;
17409 SDValue And = CmpZ->getOperand(0);
17410 if (And->getOpcode() != ISD::AND)
17411 return SDValue();
17412 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
17413 if (!AndC)
17414 return SDValue();
17415 SDValue X = And->getOperand(0);
17416
17417 if (CC == ARMCC::EQ) {
17418 // We're performing an "equal to zero" compare. Swap the operands so we
17419 // canonicalize on a "not equal to zero" compare.
17420 std::swap(Op0, Op1);
17421 } else {
17422 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?\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17422, __extension__ __PRETTY_FUNCTION__))
;
17423 }
17424
17425 if (Op1->getOpcode() != ISD::OR)
17426 return SDValue();
17427
17428 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
17429 if (!OrC)
17430 return SDValue();
17431 SDValue Y = Op1->getOperand(0);
17432
17433 if (Op0 != Y)
17434 return SDValue();
17435
17436 // Now, is it profitable to continue?
17437 APInt OrCI = OrC->getAPIntValue();
17438 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
17439 if (OrCI.countPopulation() > Heuristic)
17440 return SDValue();
17441
17442 // Lastly, can we determine that the bits defined by OrCI
17443 // are zero in Y?
17444 KnownBits Known = DAG.computeKnownBits(Y);
17445 if ((OrCI & Known.Zero) != OrCI)
17446 return SDValue();
17447
17448 // OK, we can do the combine.
17449 SDValue V = Y;
17450 SDLoc dl(X);
17451 EVT VT = X.getValueType();
17452 unsigned BitInX = AndC->logBase2();
17453
17454 if (BitInX != 0) {
17455 // We must shift X first.
17456 X = DAG.getNode(ISD::SRL, dl, VT, X,
17457 DAG.getConstant(BitInX, dl, VT));
17458 }
17459
17460 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
17461 BitInY < NumActiveBits; ++BitInY) {
17462 if (OrCI[BitInY] == 0)
17463 continue;
17464 APInt Mask(VT.getSizeInBits(), 0);
17465 Mask.setBit(BitInY);
17466 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
17467 // Confusingly, the operand is an *inverted* mask.
17468 DAG.getConstant(~Mask, dl, VT));
17469 }
17470
17471 return V;
17472}
17473
17474// Given N, the value controlling the conditional branch, search for the loop
17475// intrinsic, returning it, along with how the value is used. We need to handle
17476// patterns such as the following:
17477// (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
17478// (brcond (setcc (loop.decrement), 0, eq), exit)
17479// (brcond (setcc (loop.decrement), 0, ne), header)
17480static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
17481 bool &Negate) {
17482 switch (N->getOpcode()) {
17483 default:
17484 break;
17485 case ISD::XOR: {
17486 if (!isa<ConstantSDNode>(N.getOperand(1)))
17487 return SDValue();
17488 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
17489 return SDValue();
17490 Negate = !Negate;
17491 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
17492 }
17493 case ISD::SETCC: {
17494 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
17495 if (!Const)
17496 return SDValue();
17497 if (Const->isZero())
17498 Imm = 0;
17499 else if (Const->isOne())
17500 Imm = 1;
17501 else
17502 return SDValue();
17503 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
17504 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
17505 }
17506 case ISD::INTRINSIC_W_CHAIN: {
17507 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
17508 if (IntOp != Intrinsic::test_start_loop_iterations &&
17509 IntOp != Intrinsic::loop_decrement_reg)
17510 return SDValue();
17511 return N;
17512 }
17513 }
17514 return SDValue();
17515}
17516
17517static SDValue PerformHWLoopCombine(SDNode *N,
17518 TargetLowering::DAGCombinerInfo &DCI,
17519 const ARMSubtarget *ST) {
17520
17521 // The hwloop intrinsics that we're interested are used for control-flow,
17522 // either for entering or exiting the loop:
17523 // - test.start.loop.iterations will test whether its operand is zero. If it
17524 // is zero, the proceeding branch should not enter the loop.
17525 // - loop.decrement.reg also tests whether its operand is zero. If it is
17526 // zero, the proceeding branch should not branch back to the beginning of
17527 // the loop.
17528 // So here, we need to check that how the brcond is using the result of each
17529 // of the intrinsics to ensure that we're branching to the right place at the
17530 // right time.
17531
17532 ISD::CondCode CC;
17533 SDValue Cond;
17534 int Imm = 1;
17535 bool Negate = false;
17536 SDValue Chain = N->getOperand(0);
17537 SDValue Dest;
17538
17539 if (N->getOpcode() == ISD::BRCOND) {
17540 CC = ISD::SETEQ;
17541 Cond = N->getOperand(1);
17542 Dest = N->getOperand(2);
17543 } else {
17544 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17544, __extension__ __PRETTY_FUNCTION__))
;
17545 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
17546 Cond = N->getOperand(2);
17547 Dest = N->getOperand(4);
17548 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
17549 if (!Const->isOne() && !Const->isZero())
17550 return SDValue();
17551 Imm = Const->getZExtValue();
17552 } else
17553 return SDValue();
17554 }
17555
17556 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
17557 if (!Int)
17558 return SDValue();
17559
17560 if (Negate)
17561 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
17562
17563 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
17564 return (CC == ISD::SETEQ && Imm == 0) ||
17565 (CC == ISD::SETNE && Imm == 1) ||
17566 (CC == ISD::SETLT && Imm == 1) ||
17567 (CC == ISD::SETULT && Imm == 1);
17568 };
17569
17570 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
17571 return (CC == ISD::SETEQ && Imm == 1) ||
17572 (CC == ISD::SETNE && Imm == 0) ||
17573 (CC == ISD::SETGT && Imm == 0) ||
17574 (CC == ISD::SETUGT && Imm == 0) ||
17575 (CC == ISD::SETGE && Imm == 1) ||
17576 (CC == ISD::SETUGE && Imm == 1);
17577 };
17578
17579 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17580, __extension__ __PRETTY_FUNCTION__))
17580 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17580, __extension__ __PRETTY_FUNCTION__))
;
17581
17582 SDLoc dl(Int);
17583 SelectionDAG &DAG = DCI.DAG;
17584 SDValue Elements = Int.getOperand(2);
17585 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
17586 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17587, __extension__ __PRETTY_FUNCTION__))
17587 && "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17587, __extension__ __PRETTY_FUNCTION__))
;
17588 SDNode *Br = *N->use_begin();
17589 SDValue OtherTarget = Br->getOperand(1);
17590
17591 // Update the unconditional branch to branch to the given Dest.
17592 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
17593 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
17594 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
17595 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
17596 };
17597
17598 if (IntOp == Intrinsic::test_start_loop_iterations) {
17599 SDValue Res;
17600 SDValue Setup = DAG.getNode(ARMISD::WLSSETUP, dl, MVT::i32, Elements);
17601 // We expect this 'instruction' to branch when the counter is zero.
17602 if (IsTrueIfZero(CC, Imm)) {
17603 SDValue Ops[] = {Chain, Setup, Dest};
17604 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
17605 } else {
17606 // The logic is the reverse of what we need for WLS, so find the other
17607 // basic block target: the target of the proceeding br.
17608 UpdateUncondBr(Br, Dest, DAG);
17609
17610 SDValue Ops[] = {Chain, Setup, OtherTarget};
17611 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
17612 }
17613 // Update LR count to the new value
17614 DAG.ReplaceAllUsesOfValueWith(Int.getValue(0), Setup);
17615 // Update chain
17616 DAG.ReplaceAllUsesOfValueWith(Int.getValue(2), Int.getOperand(0));
17617 return Res;
17618 } else {
17619 SDValue Size = DAG.getTargetConstant(
17620 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
17621 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
17622 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
17623 DAG.getVTList(MVT::i32, MVT::Other), Args);
17624 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
17625
17626 // We expect this instruction to branch when the count is not zero.
17627 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
17628
17629 // Update the unconditional branch to target the loop preheader if we've
17630 // found the condition has been reversed.
17631 if (Target == OtherTarget)
17632 UpdateUncondBr(Br, Dest, DAG);
17633
17634 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17635 SDValue(LoopDec.getNode(), 1), Chain);
17636
17637 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
17638 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
17639 }
17640 return SDValue();
17641}
17642
17643/// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
17644SDValue
17645ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
17646 SDValue Cmp = N->getOperand(4);
17647 if (Cmp.getOpcode() != ARMISD::CMPZ)
17648 // Only looking at NE cases.
17649 return SDValue();
17650
17651 EVT VT = N->getValueType(0);
17652 SDLoc dl(N);
17653 SDValue LHS = Cmp.getOperand(0);
17654 SDValue RHS = Cmp.getOperand(1);
17655 SDValue Chain = N->getOperand(0);
17656 SDValue BB = N->getOperand(1);
17657 SDValue ARMcc = N->getOperand(2);
17658 ARMCC::CondCodes CC =
17659 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
17660
17661 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
17662 // -> (brcond Chain BB CC CPSR Cmp)
17663 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
17664 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
17665 LHS->getOperand(0)->hasOneUse()) {
17666 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
17667 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
17668 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
17669 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
17670 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
17671 (LHS01C && LHS01C->getZExtValue() == 1) &&
17672 (LHS1C && LHS1C->getZExtValue() == 1) &&
17673 (RHSC && RHSC->getZExtValue() == 0)) {
17674 return DAG.getNode(
17675 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
17676 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
17677 }
17678 }
17679
17680 return SDValue();
17681}
17682
17683/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
17684SDValue
17685ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
17686 SDValue Cmp = N->getOperand(4);
17687 if (Cmp.getOpcode() != ARMISD::CMPZ)
17688 // Only looking at EQ and NE cases.
17689 return SDValue();
17690
17691 EVT VT = N->getValueType(0);
17692 SDLoc dl(N);
17693 SDValue LHS = Cmp.getOperand(0);
17694 SDValue RHS = Cmp.getOperand(1);
17695 SDValue FalseVal = N->getOperand(0);
17696 SDValue TrueVal = N->getOperand(1);
17697 SDValue ARMcc = N->getOperand(2);
17698 ARMCC::CondCodes CC =
17699 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
17700
17701 // BFI is only available on V6T2+.
17702 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
17703 SDValue R = PerformCMOVToBFICombine(N, DAG);
17704 if (R)
17705 return R;
17706 }
17707
17708 // Simplify
17709 // mov r1, r0
17710 // cmp r1, x
17711 // mov r0, y
17712 // moveq r0, x
17713 // to
17714 // cmp r0, x
17715 // movne r0, y
17716 //
17717 // mov r1, r0
17718 // cmp r1, x
17719 // mov r0, x
17720 // movne r0, y
17721 // to
17722 // cmp r0, x
17723 // movne r0, y
17724 /// FIXME: Turn this into a target neutral optimization?
17725 SDValue Res;
17726 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
17727 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
17728 N->getOperand(3), Cmp);
17729 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
17730 SDValue ARMcc;
17731 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
17732 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
17733 N->getOperand(3), NewCmp);
17734 }
17735
17736 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
17737 // -> (cmov F T CC CPSR Cmp)
17738 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
17739 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
17740 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
17741 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
17742 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
17743 (LHS1C && LHS1C->getZExtValue() == 1) &&
17744 (RHSC && RHSC->getZExtValue() == 0)) {
17745 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
17746 LHS->getOperand(2), LHS->getOperand(3),
17747 LHS->getOperand(4));
17748 }
17749 }
17750
17751 if (!VT.isInteger())
17752 return SDValue();
17753
17754 // Materialize a boolean comparison for integers so we can avoid branching.
17755 if (isNullConstant(FalseVal)) {
17756 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
17757 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
17758 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
17759 // right 5 bits will make that 32 be 1, otherwise it will be 0.
17760 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
17761 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
17762 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
17763 DAG.getConstant(5, dl, MVT::i32));
17764 } else {
17765 // CMOV 0, 1, ==, (CMPZ x, y) ->
17766 // (ADDCARRY (SUB x, y), t:0, t:1)
17767 // where t = (SUBCARRY 0, (SUB x, y), 0)
17768 //
17769 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
17770 // x != y. In other words, a carry C == 1 when x == y, C == 0
17771 // otherwise.
17772 // The final ADDCARRY computes
17773 // x - y + (0 - (x - y)) + C == C
17774 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
17775 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17776 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
17777 // ISD::SUBCARRY returns a borrow but we want the carry here
17778 // actually.
17779 SDValue Carry =
17780 DAG.getNode(ISD::SUB, dl, MVT::i32,
17781 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
17782 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
17783 }
17784 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
17785 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
17786 // This seems pointless but will allow us to combine it further below.
17787 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
17788 SDValue Sub =
17789 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
17790 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
17791 Sub.getValue(1), SDValue());
17792 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
17793 N->getOperand(3), CPSRGlue.getValue(1));
17794 FalseVal = Sub;
17795 }
17796 } else if (isNullConstant(TrueVal)) {
17797 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
17798 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
17799 // This seems pointless but will allow us to combine it further below
17800 // Note that we change == for != as this is the dual for the case above.
17801 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
17802 SDValue Sub =
17803 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
17804 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
17805 Sub.getValue(1), SDValue());
17806 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
17807 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
17808 N->getOperand(3), CPSRGlue.getValue(1));
17809 FalseVal = Sub;
17810 }
17811 }
17812
17813 // On Thumb1, the DAG above may be further combined if z is a power of 2
17814 // (z == 2 ^ K).
17815 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
17816 // t1 = (USUBO (SUB x, y), 1)
17817 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
17818 // Result = if K != 0 then (SHL t2:0, K) else t2:0
17819 //
17820 // This also handles the special case of comparing against zero; it's
17821 // essentially, the same pattern, except there's no SUBS:
17822 // CMOV x, z, !=, (CMPZ x, 0) ->
17823 // t1 = (USUBO x, 1)
17824 // t2 = (SUBCARRY x, t1:0, t1:1)
17825 // Result = if K != 0 then (SHL t2:0, K) else t2:0
17826 const APInt *TrueConst;
17827 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
17828 ((FalseVal.getOpcode() == ARMISD::SUBS &&
17829 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
17830 (FalseVal == LHS && isNullConstant(RHS))) &&
17831 (TrueConst = isPowerOf2Constant(TrueVal))) {
17832 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17833 unsigned ShiftAmount = TrueConst->logBase2();
17834 if (ShiftAmount)
17835 TrueVal = DAG.getConstant(1, dl, VT);
17836 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
17837 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
17838
17839 if (ShiftAmount)
17840 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
17841 DAG.getConstant(ShiftAmount, dl, MVT::i32));
17842 }
17843
17844 if (Res.getNode()) {
17845 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
17846 // Capture demanded bits information that would be otherwise lost.
17847 if (Known.Zero == 0xfffffffe)
17848 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
17849 DAG.getValueType(MVT::i1));
17850 else if (Known.Zero == 0xffffff00)
17851 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
17852 DAG.getValueType(MVT::i8));
17853 else if (Known.Zero == 0xffff0000)
17854 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
17855 DAG.getValueType(MVT::i16));
17856 }
17857
17858 return Res;
17859}
17860
17861static SDValue PerformBITCASTCombine(SDNode *N,
17862 TargetLowering::DAGCombinerInfo &DCI,
17863 const ARMSubtarget *ST) {
17864 SelectionDAG &DAG = DCI.DAG;
17865 SDValue Src = N->getOperand(0);
17866 EVT DstVT = N->getValueType(0);
17867
17868 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
17869 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
17870 EVT SrcVT = Src.getValueType();
17871 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
17872 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
17873 }
17874
17875 // We may have a bitcast of something that has already had this bitcast
17876 // combine performed on it, so skip past any VECTOR_REG_CASTs.
17877 while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST)
17878 Src = Src.getOperand(0);
17879
17880 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
17881 // would be generated is at least the width of the element type.
17882 EVT SrcVT = Src.getValueType();
17883 if ((Src.getOpcode() == ARMISD::VMOVIMM ||
17884 Src.getOpcode() == ARMISD::VMVNIMM ||
17885 Src.getOpcode() == ARMISD::VMOVFPIMM) &&
17886 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
17887 DAG.getDataLayout().isBigEndian())
17888 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
17889
17890 // bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD x
17891 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
17892 return R;
17893
17894 return SDValue();
17895}
17896
17897// Some combines for the MVETrunc truncations legalizer helper. Also lowers the
17898// node into stack operations after legalizeOps.
17899SDValue ARMTargetLowering::PerformMVETruncCombine(
17900 SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
17901 SelectionDAG &DAG = DCI.DAG;
17902 EVT VT = N->getValueType(0);
17903 SDLoc DL(N);
17904
17905 // MVETrunc(Undef, Undef) -> Undef
17906 if (all_of(N->ops(), [](SDValue Op) { return Op.isUndef(); }))
17907 return DAG.getUNDEF(VT);
17908
17909 // MVETrunc(MVETrunc a b, MVETrunc c, d) -> MVETrunc
17910 if (N->getNumOperands() == 2 &&
17911 N->getOperand(0).getOpcode() == ARMISD::MVETRUNC &&
17912 N->getOperand(1).getOpcode() == ARMISD::MVETRUNC)
17913 return DAG.getNode(ARMISD::MVETRUNC, DL, VT, N->getOperand(0).getOperand(0),
17914 N->getOperand(0).getOperand(1),
17915 N->getOperand(1).getOperand(0),
17916 N->getOperand(1).getOperand(1));
17917
17918 // MVETrunc(shuffle, shuffle) -> VMOVN
17919 if (N->getNumOperands() == 2 &&
17920 N->getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
17921 N->getOperand(1).getOpcode() == ISD::VECTOR_SHUFFLE) {
17922 auto *S0 = cast<ShuffleVectorSDNode>(N->getOperand(0).getNode());
17923 auto *S1 = cast<ShuffleVectorSDNode>(N->getOperand(1).getNode());
17924
17925 if (S0->getOperand(0) == S1->getOperand(0) &&
17926 S0->getOperand(1) == S1->getOperand(1)) {
17927 // Construct complete shuffle mask
17928 SmallVector<int, 8> Mask(S0->getMask().begin(), S0->getMask().end());
17929 Mask.append(S1->getMask().begin(), S1->getMask().end());
17930
17931 if (isVMOVNTruncMask(Mask, VT, 0))
17932 return DAG.getNode(
17933 ARMISD::VMOVN, DL, VT,
17934 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
17935 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
17936 DAG.getConstant(1, DL, MVT::i32));
17937 if (isVMOVNTruncMask(Mask, VT, 1))
17938 return DAG.getNode(
17939 ARMISD::VMOVN, DL, VT,
17940 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
17941 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
17942 DAG.getConstant(1, DL, MVT::i32));
17943 }
17944 }
17945
17946 // For MVETrunc of a buildvector or shuffle, it can be beneficial to lower the
17947 // truncate to a buildvector to allow the generic optimisations to kick in.
17948 if (all_of(N->ops(), [](SDValue Op) {
17949 return Op.getOpcode() == ISD::BUILD_VECTOR ||
17950 Op.getOpcode() == ISD::VECTOR_SHUFFLE ||
17951 (Op.getOpcode() == ISD::BITCAST &&
17952 Op.getOperand(0).getOpcode() == ISD::BUILD_VECTOR);
17953 })) {
17954 SmallVector<SDValue, 8> Extracts;
17955 for (unsigned Op = 0; Op < N->getNumOperands(); Op++) {
17956 SDValue O = N->getOperand(Op);
17957 for (unsigned i = 0; i < O.getValueType().getVectorNumElements(); i++) {
17958 SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, O,
17959 DAG.getConstant(i, DL, MVT::i32));
17960 Extracts.push_back(Ext);
17961 }
17962 }
17963 return DAG.getBuildVector(VT, DL, Extracts);
17964 }
17965
17966 // If we are late in the legalization process and nothing has optimised
17967 // the trunc to anything better, lower it to a stack store and reload,
17968 // performing the truncation whilst keeping the lanes in the correct order:
17969 // VSTRH.32 a, stack; VSTRH.32 b, stack+8; VLDRW.32 stack;
17970 if (!DCI.isAfterLegalizeDAG())
17971 return SDValue();
17972
17973 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::Fixed(16), Align(4));
17974 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
17975 int NumIns = N->getNumOperands();
17976 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17977, __extension__ __PRETTY_FUNCTION__))
17977 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17977, __extension__ __PRETTY_FUNCTION__))
;
17978 EVT StoreVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
17979 if (N->getNumOperands() == 4)
17980 StoreVT = StoreVT.getHalfNumVectorElementsVT(*DAG.getContext());
17981
17982 SmallVector<SDValue> Chains;
17983 for (int I = 0; I < NumIns; I++) {
17984 SDValue Ptr = DAG.getNode(
17985 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
17986 DAG.getConstant(I * 16 / NumIns, DL, StackPtr.getValueType()));
17987 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
17988 DAG.getMachineFunction(), SPFI, I * 16 / NumIns);
17989 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), DL, N->getOperand(I),
17990 Ptr, MPI, StoreVT, Align(4));
17991 Chains.push_back(Ch);
17992 }
17993
17994 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
17995 MachinePointerInfo MPI =
17996 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI, 0);
17997 return DAG.getLoad(VT, DL, Chain, StackPtr, MPI, Align(4));
17998}
17999
18000// Take a MVEEXT(load x) and split that into (extload x, extload x+8)
18001static SDValue PerformSplittingMVEEXTToWideningLoad(SDNode *N,
18002 SelectionDAG &DAG) {
18003 SDValue N0 = N->getOperand(0);
18004 LoadSDNode *LD = dyn_cast<LoadSDNode>(N0.getNode());
18005 if (!LD || !LD->isSimple() || !N0.hasOneUse() || LD->isIndexed())
18006 return SDValue();
18007
18008 EVT FromVT = LD->getMemoryVT();
18009 EVT ToVT = N->getValueType(0);
18010 if (!ToVT.isVector())
18011 return SDValue();
18012 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2)(static_cast <bool> (FromVT.getVectorNumElements() == ToVT
.getVectorNumElements() * 2) ? void (0) : __assert_fail ("FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18012, __extension__ __PRETTY_FUNCTION__))
;
18013 EVT ToEltVT = ToVT.getVectorElementType();
18014 EVT FromEltVT = FromVT.getVectorElementType();
18015
18016 unsigned NumElements = 0;
18017 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
18018 NumElements = 4;
18019 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
18020 NumElements = 8;
18021 assert(NumElements != 0)(static_cast <bool> (NumElements != 0) ? void (0) : __assert_fail
("NumElements != 0", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18021, __extension__ __PRETTY_FUNCTION__))
;
18022
18023 ISD::LoadExtType NewExtType =
18024 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
18025 if (LD->getExtensionType() != ISD::NON_EXTLOAD &&
18026 LD->getExtensionType() != ISD::EXTLOAD &&
18027 LD->getExtensionType() != NewExtType)
18028 return SDValue();
18029
18030 LLVMContext &C = *DAG.getContext();
18031 SDLoc DL(LD);
18032 // Details about the old load
18033 SDValue Ch = LD->getChain();
18034 SDValue BasePtr = LD->getBasePtr();
18035 Align Alignment = LD->getOriginalAlign();
18036 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
18037 AAMDNodes AAInfo = LD->getAAInfo();
18038
18039 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
18040 EVT NewFromVT = EVT::getVectorVT(
18041 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
18042 EVT NewToVT = EVT::getVectorVT(
18043 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
18044
18045 SmallVector<SDValue, 4> Loads;
18046 SmallVector<SDValue, 4> Chains;
18047 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
18048 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
18049 SDValue NewPtr =
18050 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
18051
18052 SDValue NewLoad =
18053 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
18054 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
18055 Alignment, MMOFlags, AAInfo);
18056 Loads.push_back(NewLoad);
18057 Chains.push_back(SDValue(NewLoad.getNode(), 1));
18058 }
18059
18060 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18061 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
18062 return DAG.getMergeValues(Loads, DL);
18063}
18064
18065// Perform combines for MVEEXT. If it has not be optimized to anything better
18066// before lowering, it gets converted to stack store and extloads performing the
18067// extend whilst still keeping the same lane ordering.
18068SDValue ARMTargetLowering::PerformMVEExtCombine(
18069 SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
18070 SelectionDAG &DAG = DCI.DAG;
18071 EVT VT = N->getValueType(0);
18072 SDLoc DL(N);
18073 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18073, __extension__ __PRETTY_FUNCTION__))
;
18074 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18074, __extension__ __PRETTY_FUNCTION__))
;
18075
18076 EVT ExtVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
18077 *DAG.getContext());
18078 auto Extend = [&](SDValue V) {
18079 SDValue VVT = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, V);
18080 return N->getOpcode() == ARMISD::MVESEXT
18081 ? DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, VVT,
18082 DAG.getValueType(ExtVT))
18083 : DAG.getZeroExtendInReg(VVT, DL, ExtVT);
18084 };
18085
18086 // MVEEXT(VDUP) -> SIGN_EXTEND_INREG(VDUP)
18087 if (N->getOperand(0).getOpcode() == ARMISD::VDUP) {
18088 SDValue Ext = Extend(N->getOperand(0));
18089 return DAG.getMergeValues({Ext, Ext}, DL);
18090 }
18091
18092 // MVEEXT(shuffle) -> SIGN_EXTEND_INREG/ZERO_EXTEND_INREG
18093 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N->getOperand(0))) {
18094 ArrayRef<int> Mask = SVN->getMask();
18095 assert(Mask.size() == 2 * VT.getVectorNumElements())(static_cast <bool> (Mask.size() == 2 * VT.getVectorNumElements
()) ? void (0) : __assert_fail ("Mask.size() == 2 * VT.getVectorNumElements()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18095, __extension__ __PRETTY_FUNCTION__))
;
18096 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()"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18096, __extension__ __PRETTY_FUNCTION__))
;
18097 unsigned Rev = VT == MVT::v4i32 ? ARMISD::VREV32 : ARMISD::VREV16;
18098 SDValue Op0 = SVN->getOperand(0);
18099 SDValue Op1 = SVN->getOperand(1);
18100
18101 auto CheckInregMask = [&](int Start, int Offset) {
18102 for (int Idx = 0, E = VT.getVectorNumElements(); Idx < E; ++Idx)
18103 if (Mask[Start + Idx] >= 0 && Mask[Start + Idx] != Idx * 2 + Offset)
18104 return false;
18105 return true;
18106 };
18107 SDValue V0 = SDValue(N, 0);
18108 SDValue V1 = SDValue(N, 1);
18109 if (CheckInregMask(0, 0))
18110 V0 = Extend(Op0);
18111 else if (CheckInregMask(0, 1))
18112 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
18113 else if (CheckInregMask(0, Mask.size()))
18114 V0 = Extend(Op1);
18115 else if (CheckInregMask(0, Mask.size() + 1))
18116 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
18117
18118 if (CheckInregMask(VT.getVectorNumElements(), Mask.size()))
18119 V1 = Extend(Op1);
18120 else if (CheckInregMask(VT.getVectorNumElements(), Mask.size() + 1))
18121 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
18122 else if (CheckInregMask(VT.getVectorNumElements(), 0))
18123 V1 = Extend(Op0);
18124 else if (CheckInregMask(VT.getVectorNumElements(), 1))
18125 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
18126
18127 if (V0.getNode() != N || V1.getNode() != N)
18128 return DAG.getMergeValues({V0, V1}, DL);
18129 }
18130
18131 // MVEEXT(load) -> extload, extload
18132 if (N->getOperand(0)->getOpcode() == ISD::LOAD)
18133 if (SDValue L = PerformSplittingMVEEXTToWideningLoad(N, DAG))
18134 return L;
18135
18136 if (!DCI.isAfterLegalizeDAG())
18137 return SDValue();
18138
18139 // Lower to a stack store and reload:
18140 // VSTRW.32 a, stack; VLDRH.32 stack; VLDRH.32 stack+8;
18141 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::Fixed(16), Align(4));
18142 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
18143 int NumOuts = N->getNumValues();
18144 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18145, __extension__ __PRETTY_FUNCTION__))
18145 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18145, __extension__ __PRETTY_FUNCTION__))
;
18146 EVT LoadVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
18147 *DAG.getContext());
18148 if (N->getNumOperands() == 4)
18149 LoadVT = LoadVT.getHalfNumVectorElementsVT(*DAG.getContext());
18150
18151 MachinePointerInfo MPI =
18152 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI, 0);
18153 SDValue Chain = DAG.getStore(DAG.getEntryNode(), DL, N->getOperand(0),
18154 StackPtr, MPI, Align(4));
18155
18156 SmallVector<SDValue> Loads;
18157 for (int I = 0; I < NumOuts; I++) {
18158 SDValue Ptr = DAG.getNode(
18159 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
18160 DAG.getConstant(I * 16 / NumOuts, DL, StackPtr.getValueType()));
18161 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
18162 DAG.getMachineFunction(), SPFI, I * 16 / NumOuts);
18163 SDValue Load = DAG.getExtLoad(
18164 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL,
18165 VT, Chain, Ptr, MPI, LoadVT, Align(4));
18166 Loads.push_back(Load);
18167 }
18168
18169 return DAG.getMergeValues(Loads, DL);
18170}
18171
18172SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
18173 DAGCombinerInfo &DCI) const {
18174 switch (N->getOpcode()) {
18175 default: break;
18176 case ISD::SELECT_CC:
18177 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget);
18178 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget);
18179 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
18180 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
18181 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
18182 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
18183 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget);
18184 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
18185 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
18186 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
18187 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
18188 case ISD::BRCOND:
18189 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
18190 case ARMISD::ADDC:
18191 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
18192 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
18193 case ARMISD::BFI: return PerformBFICombine(N, DCI.DAG);
18194 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
18195 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
18196 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI);
18197 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI.DAG);
18198 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
18199 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
18200 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
18201 case ISD::EXTRACT_VECTOR_ELT:
18202 return PerformExtractEltCombine(N, DCI, Subtarget);
18203 case ISD::SIGN_EXTEND_INREG: return PerformSignExtendInregCombine(N, DCI.DAG);
18204 case ISD::INSERT_SUBVECTOR: return PerformInsertSubvectorCombine(N, DCI);
18205 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
18206 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
18207 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI.DAG, Subtarget);
18208 case ISD::FP_TO_SINT:
18209 case ISD::FP_TO_UINT:
18210 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
18211 case ISD::FDIV:
18212 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
18213 case ISD::INTRINSIC_WO_CHAIN:
18214 return PerformIntrinsicCombine(N, DCI);
18215 case ISD::SHL:
18216 case ISD::SRA:
18217 case ISD::SRL:
18218 return PerformShiftCombine(N, DCI, Subtarget);
18219 case ISD::SIGN_EXTEND:
18220 case ISD::ZERO_EXTEND:
18221 case ISD::ANY_EXTEND:
18222 return PerformExtendCombine(N, DCI.DAG, Subtarget);
18223 case ISD::FP_EXTEND:
18224 return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
18225 case ISD::SMIN:
18226 case ISD::UMIN:
18227 case ISD::SMAX:
18228 case ISD::UMAX:
18229 return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
18230 case ARMISD::CMOV:
18231 return PerformCMOVCombine(N, DCI.DAG);
18232 case ARMISD::BRCOND:
18233 return PerformBRCONDCombine(N, DCI.DAG);
18234 case ISD::LOAD:
18235 return PerformLOADCombine(N, DCI, Subtarget);
18236 case ARMISD::VLD1DUP:
18237 case ARMISD::VLD2DUP:
18238 case ARMISD::VLD3DUP:
18239 case ARMISD::VLD4DUP:
18240 return PerformVLDCombine(N, DCI);
18241 case ARMISD::BUILD_VECTOR:
18242 return PerformARMBUILD_VECTORCombine(N, DCI);
18243 case ISD::BITCAST:
18244 return PerformBITCASTCombine(N, DCI, Subtarget);
18245 case ARMISD::PREDICATE_CAST:
18246 return PerformPREDICATE_CASTCombine(N, DCI);
18247 case ARMISD::VECTOR_REG_CAST:
18248 return PerformVECTOR_REG_CASTCombine(N, DCI.DAG, Subtarget);
18249 case ARMISD::MVETRUNC:
18250 return PerformMVETruncCombine(N, DCI);
18251 case ARMISD::MVESEXT:
18252 case ARMISD::MVEZEXT:
18253 return PerformMVEExtCombine(N, DCI);
18254 case ARMISD::VCMP:
18255 return PerformVCMPCombine(N, DCI.DAG, Subtarget);
18256 case ISD::VECREDUCE_ADD:
18257 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
18258 case ARMISD::VMOVN:
18259 return PerformVMOVNCombine(N, DCI);
18260 case ARMISD::VQMOVNs:
18261 case ARMISD::VQMOVNu:
18262 return PerformVQMOVNCombine(N, DCI);
18263 case ARMISD::ASRL:
18264 case ARMISD::LSRL:
18265 case ARMISD::LSLL:
18266 return PerformLongShiftCombine(N, DCI.DAG);
18267 case ARMISD::SMULWB: {
18268 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18269 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
18270 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
18271 return SDValue();
18272 break;
18273 }
18274 case ARMISD::SMULWT: {
18275 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18276 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
18277 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
18278 return SDValue();
18279 break;
18280 }
18281 case ARMISD::SMLALBB:
18282 case ARMISD::QADD16b:
18283 case ARMISD::QSUB16b:
18284 case ARMISD::UQADD16b:
18285 case ARMISD::UQSUB16b: {
18286 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18287 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
18288 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
18289 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
18290 return SDValue();
18291 break;
18292 }
18293 case ARMISD::SMLALBT: {
18294 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
18295 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
18296 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
18297 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
18298 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
18299 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
18300 return SDValue();
18301 break;
18302 }
18303 case ARMISD::SMLALTB: {
18304 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
18305 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
18306 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
18307 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
18308 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
18309 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
18310 return SDValue();
18311 break;
18312 }
18313 case ARMISD::SMLALTT: {
18314 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18315 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
18316 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
18317 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
18318 return SDValue();
18319 break;
18320 }
18321 case ARMISD::QADD8b:
18322 case ARMISD::QSUB8b:
18323 case ARMISD::UQADD8b:
18324 case ARMISD::UQSUB8b: {
18325 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18326 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
18327 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
18328 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
18329 return SDValue();
18330 break;
18331 }
18332 case ISD::INTRINSIC_VOID:
18333 case ISD::INTRINSIC_W_CHAIN:
18334 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
18335 case Intrinsic::arm_neon_vld1:
18336 case Intrinsic::arm_neon_vld1x2:
18337 case Intrinsic::arm_neon_vld1x3:
18338 case Intrinsic::arm_neon_vld1x4:
18339 case Intrinsic::arm_neon_vld2:
18340 case Intrinsic::arm_neon_vld3:
18341 case Intrinsic::arm_neon_vld4:
18342 case Intrinsic::arm_neon_vld2lane:
18343 case Intrinsic::arm_neon_vld3lane:
18344 case Intrinsic::arm_neon_vld4lane:
18345 case Intrinsic::arm_neon_vld2dup:
18346 case Intrinsic::arm_neon_vld3dup:
18347 case Intrinsic::arm_neon_vld4dup:
18348 case Intrinsic::arm_neon_vst1:
18349 case Intrinsic::arm_neon_vst1x2:
18350 case Intrinsic::arm_neon_vst1x3:
18351 case Intrinsic::arm_neon_vst1x4:
18352 case Intrinsic::arm_neon_vst2:
18353 case Intrinsic::arm_neon_vst3:
18354 case Intrinsic::arm_neon_vst4:
18355 case Intrinsic::arm_neon_vst2lane:
18356 case Intrinsic::arm_neon_vst3lane:
18357 case Intrinsic::arm_neon_vst4lane:
18358 return PerformVLDCombine(N, DCI);
18359 case Intrinsic::arm_mve_vld2q:
18360 case Intrinsic::arm_mve_vld4q:
18361 case Intrinsic::arm_mve_vst2q:
18362 case Intrinsic::arm_mve_vst4q:
18363 return PerformMVEVLDCombine(N, DCI);
18364 default: break;
18365 }
18366 break;
18367 }
18368 return SDValue();
18369}
18370
18371bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
18372 EVT VT) const {
18373 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
18374}
18375
18376bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
18377 Align Alignment,
18378 MachineMemOperand::Flags,
18379 bool *Fast) const {
18380 // Depends what it gets converted into if the type is weird.
18381 if (!VT.isSimple())
18382 return false;
18383
18384 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
18385 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
18386 auto Ty = VT.getSimpleVT().SimpleTy;
18387
18388 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
18389 // Unaligned access can use (for example) LRDB, LRDH, LDR
18390 if (AllowsUnaligned) {
18391 if (Fast)
18392 *Fast = Subtarget->hasV7Ops();
18393 return true;
18394 }
18395 }
18396
18397 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
18398 // For any little-endian targets with neon, we can support unaligned ld/st
18399 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
18400 // A big-endian target may also explicitly support unaligned accesses
18401 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
18402 if (Fast)
18403 *Fast = true;
18404 return true;
18405 }
18406 }
18407
18408 if (!Subtarget->hasMVEIntegerOps())
18409 return false;
18410
18411 // These are for predicates
18412 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
18413 if (Fast)
18414 *Fast = true;
18415 return true;
18416 }
18417
18418 // These are for truncated stores/narrowing loads. They are fine so long as
18419 // the alignment is at least the size of the item being loaded
18420 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
18421 Alignment >= VT.getScalarSizeInBits() / 8) {
18422 if (Fast)
18423 *Fast = true;
18424 return true;
18425 }
18426
18427 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
18428 // VSTRW.U32 all store the vector register in exactly the same format, and
18429 // differ only in the range of their immediate offset field and the required
18430 // alignment. So there is always a store that can be used, regardless of
18431 // actual type.
18432 //
18433 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
18434 // VREV64.8) pair and get the same effect. This will likely be better than
18435 // aligning the vector through the stack.
18436 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
18437 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
18438 Ty == MVT::v2f64) {
18439 if (Fast)
18440 *Fast = true;
18441 return true;
18442 }
18443
18444 return false;
18445}
18446
18447
18448EVT ARMTargetLowering::getOptimalMemOpType(
18449 const MemOp &Op, const AttributeList &FuncAttributes) const {
18450 // See if we can use NEON instructions for this...
18451 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
18452 !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat)) {
18453 bool Fast;
18454 if (Op.size() >= 16 &&
18455 (Op.isAligned(Align(16)) ||
18456 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, Align(1),
18457 MachineMemOperand::MONone, &Fast) &&
18458 Fast))) {
18459 return MVT::v2f64;
18460 } else if (Op.size() >= 8 &&
18461 (Op.isAligned(Align(8)) ||
18462 (allowsMisalignedMemoryAccesses(
18463 MVT::f64, 0, Align(1), MachineMemOperand::MONone, &Fast) &&
18464 Fast))) {
18465 return MVT::f64;
18466 }
18467 }
18468
18469 // Let the target-independent logic figure it out.
18470 return MVT::Other;
18471}
18472
18473// 64-bit integers are split into their high and low parts and held in two
18474// different registers, so the trunc is free since the low register can just
18475// be used.
18476bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
18477 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
18478 return false;
18479 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
18480 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
18481 return (SrcBits == 64 && DestBits == 32);
18482}
18483
18484bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
18485 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
18486 !DstVT.isInteger())
18487 return false;
18488 unsigned SrcBits = SrcVT.getSizeInBits();
18489 unsigned DestBits = DstVT.getSizeInBits();
18490 return (SrcBits == 64 && DestBits == 32);
18491}
18492
18493bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18494 if (Val.getOpcode() != ISD::LOAD)
18495 return false;
18496
18497 EVT VT1 = Val.getValueType();
18498 if (!VT1.isSimple() || !VT1.isInteger() ||
18499 !VT2.isSimple() || !VT2.isInteger())
18500 return false;
18501
18502 switch (VT1.getSimpleVT().SimpleTy) {
18503 default: break;
18504 case MVT::i1:
18505 case MVT::i8:
18506 case MVT::i16:
18507 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
18508 return true;
18509 }
18510
18511 return false;
18512}
18513
18514bool ARMTargetLowering::isFNegFree(EVT VT) const {
18515 if (!VT.isSimple())
18516 return false;
18517
18518 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
18519 // negate values directly (fneg is free). So, we don't want to let the DAG
18520 // combiner rewrite fneg into xors and some other instructions. For f16 and
18521 // FullFP16 argument passing, some bitcast nodes may be introduced,
18522 // triggering this DAG combine rewrite, so we are avoiding that with this.
18523 switch (VT.getSimpleVT().SimpleTy) {
18524 default: break;
18525 case MVT::f16:
18526 return Subtarget->hasFullFP16();
18527 }
18528
18529 return false;
18530}
18531
18532/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
18533/// of the vector elements.
18534static bool areExtractExts(Value *Ext1, Value *Ext2) {
18535 auto areExtDoubled = [](Instruction *Ext) {
18536 return Ext->getType()->getScalarSizeInBits() ==
18537 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
18538 };
18539
18540 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
18541 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
18542 !areExtDoubled(cast<Instruction>(Ext1)) ||
18543 !areExtDoubled(cast<Instruction>(Ext2)))
18544 return false;
18545
18546 return true;
18547}
18548
18549/// Check if sinking \p I's operands to I's basic block is profitable, because
18550/// the operands can be folded into a target instruction, e.g.
18551/// sext/zext can be folded into vsubl.
18552bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
18553 SmallVectorImpl<Use *> &Ops) const {
18554 if (!I->getType()->isVectorTy())
18555 return false;
18556
18557 if (Subtarget->hasNEON()) {
18558 switch (I->getOpcode()) {
18559 case Instruction::Sub:
18560 case Instruction::Add: {
18561 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
18562 return false;
18563 Ops.push_back(&I->getOperandUse(0));
18564 Ops.push_back(&I->getOperandUse(1));
18565 return true;
18566 }
18567 default:
18568 return false;
18569 }
18570 }
18571
18572 if (!Subtarget->hasMVEIntegerOps())
18573 return false;
18574
18575 auto IsFMSMul = [&](Instruction *I) {
18576 if (!I->hasOneUse())
18577 return false;
18578 auto *Sub = cast<Instruction>(*I->users().begin());
18579 return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
18580 };
18581 auto IsFMS = [&](Instruction *I) {
18582 if (match(I->getOperand(0), m_FNeg(m_Value())) ||
18583 match(I->getOperand(1), m_FNeg(m_Value())))
18584 return true;
18585 return false;
18586 };
18587
18588 auto IsSinker = [&](Instruction *I, int Operand) {
18589 switch (I->getOpcode()) {
18590 case Instruction::Add:
18591 case Instruction::Mul:
18592 case Instruction::FAdd:
18593 case Instruction::ICmp:
18594 case Instruction::FCmp:
18595 return true;
18596 case Instruction::FMul:
18597 return !IsFMSMul(I);
18598 case Instruction::Sub:
18599 case Instruction::FSub:
18600 case Instruction::Shl:
18601 case Instruction::LShr:
18602 case Instruction::AShr:
18603 return Operand == 1;
18604 case Instruction::Call:
18605 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
18606 switch (II->getIntrinsicID()) {
18607 case Intrinsic::fma:
18608 return !IsFMS(I);
18609 case Intrinsic::sadd_sat:
18610 case Intrinsic::uadd_sat:
18611 case Intrinsic::arm_mve_add_predicated:
18612 case Intrinsic::arm_mve_mul_predicated:
18613 case Intrinsic::arm_mve_qadd_predicated:
18614 case Intrinsic::arm_mve_vhadd:
18615 case Intrinsic::arm_mve_hadd_predicated:
18616 case Intrinsic::arm_mve_vqdmull:
18617 case Intrinsic::arm_mve_vqdmull_predicated:
18618 case Intrinsic::arm_mve_vqdmulh:
18619 case Intrinsic::arm_mve_qdmulh_predicated:
18620 case Intrinsic::arm_mve_vqrdmulh:
18621 case Intrinsic::arm_mve_qrdmulh_predicated:
18622 case Intrinsic::arm_mve_fma_predicated:
18623 return true;
18624 case Intrinsic::ssub_sat:
18625 case Intrinsic::usub_sat:
18626 case Intrinsic::arm_mve_sub_predicated:
18627 case Intrinsic::arm_mve_qsub_predicated:
18628 case Intrinsic::arm_mve_hsub_predicated:
18629 case Intrinsic::arm_mve_vhsub:
18630 return Operand == 1;
18631 default:
18632 return false;
18633 }
18634 }
18635 return false;
18636 default:
18637 return false;
18638 }
18639 };
18640
18641 for (auto OpIdx : enumerate(I->operands())) {
18642 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
18643 // Make sure we are not already sinking this operand
18644 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
18645 continue;
18646
18647 Instruction *Shuffle = Op;
18648 if (Shuffle->getOpcode() == Instruction::BitCast)
18649 Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0));
18650 // We are looking for a splat that can be sunk.
18651 if (!Shuffle ||
18652 !match(Shuffle, m_Shuffle(
18653 m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
18654 m_Undef(), m_ZeroMask())))
18655 continue;
18656 if (!IsSinker(I, OpIdx.index()))
18657 continue;
18658
18659 // All uses of the shuffle should be sunk to avoid duplicating it across gpr
18660 // and vector registers
18661 for (Use &U : Op->uses()) {
18662 Instruction *Insn = cast<Instruction>(U.getUser());
18663 if (!IsSinker(Insn, U.getOperandNo()))
18664 return false;
18665 }
18666
18667 Ops.push_back(&Shuffle->getOperandUse(0));
18668 if (Shuffle != Op)
18669 Ops.push_back(&Op->getOperandUse(0));
18670 Ops.push_back(&OpIdx.value());
18671 }
18672 return true;
18673}
18674
18675Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
18676 if (!Subtarget->hasMVEIntegerOps())
18677 return nullptr;
18678 Type *SVIType = SVI->getType();
18679 Type *ScalarType = SVIType->getScalarType();
18680
18681 if (ScalarType->isFloatTy())
18682 return Type::getInt32Ty(SVIType->getContext());
18683 if (ScalarType->isHalfTy())
18684 return Type::getInt16Ty(SVIType->getContext());
18685 return nullptr;
18686}
18687
18688bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
18689 EVT VT = ExtVal.getValueType();
18690
18691 if (!isTypeLegal(VT))
18692 return false;
18693
18694 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
18695 if (Ld->isExpandingLoad())
18696 return false;
18697 }
18698
18699 if (Subtarget->hasMVEIntegerOps())
18700 return true;
18701
18702 // Don't create a loadext if we can fold the extension into a wide/long
18703 // instruction.
18704 // If there's more than one user instruction, the loadext is desirable no
18705 // matter what. There can be two uses by the same instruction.
18706 if (ExtVal->use_empty() ||
18707 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
18708 return true;
18709
18710 SDNode *U = *ExtVal->use_begin();
18711 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
18712 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
18713 return false;
18714
18715 return true;
18716}
18717
18718bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18719 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18720 return false;
18721
18722 if (!isTypeLegal(EVT::getEVT(Ty1)))
18723 return false;
18724
18725 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18725, __extension__ __PRETTY_FUNCTION__))
;
18726
18727 // Assuming the caller doesn't have a zeroext or signext return parameter,
18728 // truncation all the way down to i1 is valid.
18729 return true;
18730}
18731
18732InstructionCost ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
18733 const AddrMode &AM,
18734 Type *Ty,
18735 unsigned AS) const {
18736 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
18737 if (Subtarget->hasFPAO())
18738 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
18739 return 0;
18740 }
18741 return -1;
18742}
18743
18744/// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
18745/// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
18746/// expanded to FMAs when this method returns true, otherwise fmuladd is
18747/// expanded to fmul + fadd.
18748///
18749/// ARM supports both fused and unfused multiply-add operations; we already
18750/// lower a pair of fmul and fadd to the latter so it's not clear that there
18751/// would be a gain or that the gain would be worthwhile enough to risk
18752/// correctness bugs.
18753///
18754/// For MVE, we set this to true as it helps simplify the need for some
18755/// patterns (and we don't have the non-fused floating point instruction).
18756bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
18757 EVT VT) const {
18758 if (!VT.isSimple())
18759 return false;
18760
18761 switch (VT.getSimpleVT().SimpleTy) {
18762 case MVT::v4f32:
18763 case MVT::v8f16:
18764 return Subtarget->hasMVEFloatOps();
18765 case MVT::f16:
18766 return Subtarget->useFPVFMx16();
18767 case MVT::f32:
18768 return Subtarget->useFPVFMx();
18769 case MVT::f64:
18770 return Subtarget->useFPVFMx64();
18771 default:
18772 break;
18773 }
18774
18775 return false;
18776}
18777
18778static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
18779 if (V < 0)
18780 return false;
18781
18782 unsigned Scale = 1;
18783 switch (VT.getSimpleVT().SimpleTy) {
18784 case MVT::i1:
18785 case MVT::i8:
18786 // Scale == 1;
18787 break;
18788 case MVT::i16:
18789 // Scale == 2;
18790 Scale = 2;
18791 break;
18792 default:
18793 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
18794 // Scale == 4;
18795 Scale = 4;
18796 break;
18797 }
18798
18799 if ((V & (Scale - 1)) != 0)
18800 return false;
18801 return isUInt<5>(V / Scale);
18802}
18803
18804static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
18805 const ARMSubtarget *Subtarget) {
18806 if (!VT.isInteger() && !VT.isFloatingPoint())
18807 return false;
18808 if (VT.isVector() && Subtarget->hasNEON())
18809 return false;
18810 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
18811 !Subtarget->hasMVEFloatOps())
18812 return false;
18813
18814 bool IsNeg = false;
18815 if (V < 0) {
18816 IsNeg = true;
18817 V = -V;
18818 }
18819
18820 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
18821
18822 // MVE: size * imm7
18823 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
18824 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
18825 case MVT::i32:
18826 case MVT::f32:
18827 return isShiftedUInt<7,2>(V);
18828 case MVT::i16:
18829 case MVT::f16:
18830 return isShiftedUInt<7,1>(V);
18831 case MVT::i8:
18832 return isUInt<7>(V);
18833 default:
18834 return false;
18835 }
18836 }
18837
18838 // half VLDR: 2 * imm8
18839 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
18840 return isShiftedUInt<8, 1>(V);
18841 // VLDR and LDRD: 4 * imm8
18842 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
18843 return isShiftedUInt<8, 2>(V);
18844
18845 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
18846 // + imm12 or - imm8
18847 if (IsNeg)
18848 return isUInt<8>(V);
18849 return isUInt<12>(V);
18850 }
18851
18852 return false;
18853}
18854
18855/// isLegalAddressImmediate - Return true if the integer value can be used
18856/// as the offset of the target addressing mode for load / store of the
18857/// given type.
18858static bool isLegalAddressImmediate(int64_t V, EVT VT,
18859 const ARMSubtarget *Subtarget) {
18860 if (V == 0)
18861 return true;
18862
18863 if (!VT.isSimple())
18864 return false;
18865
18866 if (Subtarget->isThumb1Only())
18867 return isLegalT1AddressImmediate(V, VT);
18868 else if (Subtarget->isThumb2())
18869 return isLegalT2AddressImmediate(V, VT, Subtarget);
18870
18871 // ARM mode.
18872 if (V < 0)
18873 V = - V;
18874 switch (VT.getSimpleVT().SimpleTy) {
18875 default: return false;
18876 case MVT::i1:
18877 case MVT::i8:
18878 case MVT::i32:
18879 // +- imm12
18880 return isUInt<12>(V);
18881 case MVT::i16:
18882 // +- imm8
18883 return isUInt<8>(V);
18884 case MVT::f32:
18885 case MVT::f64:
18886 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
18887 return false;
18888 return isShiftedUInt<8, 2>(V);
18889 }
18890}
18891
18892bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
18893 EVT VT) const {
18894 int Scale = AM.Scale;
18895 if (Scale < 0)
18896 return false;
18897
18898 switch (VT.getSimpleVT().SimpleTy) {
18899 default: return false;
18900 case MVT::i1:
18901 case MVT::i8:
18902 case MVT::i16:
18903 case MVT::i32:
18904 if (Scale == 1)
18905 return true;
18906 // r + r << imm
18907 Scale = Scale & ~1;
18908 return Scale == 2 || Scale == 4 || Scale == 8;
18909 case MVT::i64:
18910 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
18911 // version in Thumb mode.
18912 // r + r
18913 if (Scale == 1)
18914 return true;
18915 // r * 2 (this can be lowered to r + r).
18916 if (!AM.HasBaseReg && Scale == 2)
18917 return true;
18918 return false;
18919 case MVT::isVoid:
18920 // Note, we allow "void" uses (basically, uses that aren't loads or
18921 // stores), because arm allows folding a scale into many arithmetic
18922 // operations. This should be made more precise and revisited later.
18923
18924 // Allow r << imm, but the imm has to be a multiple of two.
18925 if (Scale & 1) return false;
18926 return isPowerOf2_32(Scale);
18927 }
18928}
18929
18930bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
18931 EVT VT) const {
18932 const int Scale = AM.Scale;
18933
18934 // Negative scales are not supported in Thumb1.
18935 if (Scale < 0)
18936 return false;
18937
18938 // Thumb1 addressing modes do not support register scaling excepting the
18939 // following cases:
18940 // 1. Scale == 1 means no scaling.
18941 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
18942 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
18943}
18944
18945/// isLegalAddressingMode - Return true if the addressing mode represented
18946/// by AM is legal for this target, for a load/store of the specified type.
18947bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
18948 const AddrMode &AM, Type *Ty,
18949 unsigned AS, Instruction *I) const {
18950 EVT VT = getValueType(DL, Ty, true);
18951 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
18952 return false;
18953
18954 // Can never fold addr of global into load/store.
18955 if (AM.BaseGV)
18956 return false;
18957
18958 switch (AM.Scale) {
18959 case 0: // no scale reg, must be "r+i" or "r", or "i".
18960 break;
18961 default:
18962 // ARM doesn't support any R+R*scale+imm addr modes.
18963 if (AM.BaseOffs)
18964 return false;
18965
18966 if (!VT.isSimple())
18967 return false;
18968
18969 if (Subtarget->isThumb1Only())
18970 return isLegalT1ScaledAddressingMode(AM, VT);
18971
18972 if (Subtarget->isThumb2())
18973 return isLegalT2ScaledAddressingMode(AM, VT);
18974
18975 int Scale = AM.Scale;
18976 switch (VT.getSimpleVT().SimpleTy) {
18977 default: return false;
18978 case MVT::i1:
18979 case MVT::i8:
18980 case MVT::i32:
18981 if (Scale < 0) Scale = -Scale;
18982 if (Scale == 1)
18983 return true;
18984 // r + r << imm
18985 return isPowerOf2_32(Scale & ~1);
18986 case MVT::i16:
18987 case MVT::i64:
18988 // r +/- r
18989 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
18990 return true;
18991 // r * 2 (this can be lowered to r + r).
18992 if (!AM.HasBaseReg && Scale == 2)
18993 return true;
18994 return false;
18995
18996 case MVT::isVoid:
18997 // Note, we allow "void" uses (basically, uses that aren't loads or
18998 // stores), because arm allows folding a scale into many arithmetic
18999 // operations. This should be made more precise and revisited later.
19000
19001 // Allow r << imm, but the imm has to be a multiple of two.
19002 if (Scale & 1) return false;
19003 return isPowerOf2_32(Scale);
19004 }
19005 }
19006 return true;
19007}
19008
19009/// isLegalICmpImmediate - Return true if the specified immediate is legal
19010/// icmp immediate, that is the target has icmp instructions which can compare
19011/// a register against the immediate without having to materialize the
19012/// immediate into a register.
19013bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19014 // Thumb2 and ARM modes can use cmn for negative immediates.
19015 if (!Subtarget->isThumb())
19016 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
19017 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
19018 if (Subtarget->isThumb2())
19019 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
19020 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
19021 // Thumb1 doesn't have cmn, and only 8-bit immediates.
19022 return Imm >= 0 && Imm <= 255;
19023}
19024
19025/// isLegalAddImmediate - Return true if the specified immediate is a legal add
19026/// *or sub* immediate, that is the target has add or sub instructions which can
19027/// add a register with the immediate without having to materialize the
19028/// immediate into a register.
19029bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
19030 // Same encoding for add/sub, just flip the sign.
19031 int64_t AbsImm = std::abs(Imm);
19032 if (!Subtarget->isThumb())
19033 return ARM_AM::getSOImmVal(AbsImm) != -1;
19034 if (Subtarget->isThumb2())
19035 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
19036 // Thumb1 only has 8-bit unsigned immediate.
19037 return AbsImm >= 0 && AbsImm <= 255;
19038}
19039
19040// Return false to prevent folding
19041// (mul (add r, c0), c1) -> (add (mul r, c1), c0*c1) in DAGCombine,
19042// if the folding leads to worse code.
19043bool ARMTargetLowering::isMulAddWithConstProfitable(
19044 const SDValue &AddNode, const SDValue &ConstNode) const {
19045 // Let the DAGCombiner decide for vector types and large types.
19046 const EVT VT = AddNode.getValueType();
19047 if (VT.isVector() || VT.getScalarSizeInBits() > 32)
19048 return true;
19049
19050 // It is worse if c0 is legal add immediate, while c1*c0 is not
19051 // and has to be composed by at least two instructions.
19052 const ConstantSDNode *C0Node = cast<ConstantSDNode>(AddNode.getOperand(1));
19053 const ConstantSDNode *C1Node = cast<ConstantSDNode>(ConstNode);
19054 const int64_t C0 = C0Node->getSExtValue();
19055 APInt CA = C0Node->getAPIntValue() * C1Node->getAPIntValue();
19056 if (!isLegalAddImmediate(C0) || isLegalAddImmediate(CA.getSExtValue()))
19057 return true;
19058 if (ConstantMaterializationCost((unsigned)CA.getZExtValue(), Subtarget) > 1)
19059 return false;
19060
19061 // Default to true and let the DAGCombiner decide.
19062 return true;
19063}
19064
19065static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
19066 bool isSEXTLoad, SDValue &Base,
19067 SDValue &Offset, bool &isInc,
19068 SelectionDAG &DAG) {
19069 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19070 return false;
19071
19072 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
19073 // AddressingMode 3
19074 Base = Ptr->getOperand(0);
19075 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19076 int RHSC = (int)RHS->getZExtValue();
19077 if (RHSC < 0 && RHSC > -256) {
19078 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19078, __extension__ __PRETTY_FUNCTION__))
;
19079 isInc = false;
19080 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19081 return true;
19082 }
19083 }
19084 isInc = (Ptr->getOpcode() == ISD::ADD);
19085 Offset = Ptr->getOperand(1);
19086 return true;
19087 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
19088 // AddressingMode 2
19089 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19090 int RHSC = (int)RHS->getZExtValue();
19091 if (RHSC < 0 && RHSC > -0x1000) {
19092 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19092, __extension__ __PRETTY_FUNCTION__))
;
19093 isInc = false;
19094 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19095 Base = Ptr->getOperand(0);
19096 return true;
19097 }
19098 }
19099
19100 if (Ptr->getOpcode() == ISD::ADD) {
19101 isInc = true;
19102 ARM_AM::ShiftOpc ShOpcVal=
19103 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
19104 if (ShOpcVal != ARM_AM::no_shift) {
19105 Base = Ptr->getOperand(1);
19106 Offset = Ptr->getOperand(0);
19107 } else {
19108 Base = Ptr->getOperand(0);
19109 Offset = Ptr->getOperand(1);
19110 }
19111 return true;
19112 }
19113
19114 isInc = (Ptr->getOpcode() == ISD::ADD);
19115 Base = Ptr->getOperand(0);
19116 Offset = Ptr->getOperand(1);
19117 return true;
19118 }
19119
19120 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
19121 return false;
19122}
19123
19124static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
19125 bool isSEXTLoad, SDValue &Base,
19126 SDValue &Offset, bool &isInc,
19127 SelectionDAG &DAG) {
19128 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19129 return false;
19130
19131 Base = Ptr->getOperand(0);
19132 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19133 int RHSC = (int)RHS->getZExtValue();
19134 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
19135 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19135, __extension__ __PRETTY_FUNCTION__))
;
19136 isInc = false;
19137 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19138 return true;
19139 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
19140 isInc = Ptr->getOpcode() == ISD::ADD;
19141 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
19142 return true;
19143 }
19144 }
19145
19146 return false;
19147}
19148
19149static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
19150 bool isSEXTLoad, bool IsMasked, bool isLE,
19151 SDValue &Base, SDValue &Offset,
19152 bool &isInc, SelectionDAG &DAG) {
19153 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19154 return false;
19155 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
19156 return false;
19157
19158 // We allow LE non-masked loads to change the type (for example use a vldrb.8
19159 // as opposed to a vldrw.32). This can allow extra addressing modes or
19160 // alignments for what is otherwise an equivalent instruction.
19161 bool CanChangeType = isLE && !IsMasked;
19162
19163 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
19164 int RHSC = (int)RHS->getZExtValue();
19165
19166 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
19167 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
19168 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19168, __extension__ __PRETTY_FUNCTION__))
;
19169 isInc = false;
19170 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19171 return true;
19172 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
19173 isInc = Ptr->getOpcode() == ISD::ADD;
19174 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
19175 return true;
19176 }
19177 return false;
19178 };
19179
19180 // Try to find a matching instruction based on s/zext, Alignment, Offset and
19181 // (in BE/masked) type.
19182 Base = Ptr->getOperand(0);
19183 if (VT == MVT::v4i16) {
19184 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
19185 return true;
19186 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
19187 if (IsInRange(RHSC, 0x80, 1))
19188 return true;
19189 } else if (Alignment >= 4 &&
19190 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
19191 IsInRange(RHSC, 0x80, 4))
19192 return true;
19193 else if (Alignment >= 2 &&
19194 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
19195 IsInRange(RHSC, 0x80, 2))
19196 return true;
19197 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
19198 return true;
19199 return false;
19200}
19201
19202/// getPreIndexedAddressParts - returns true by value, base pointer and
19203/// offset pointer and addressing mode by reference if the node's address
19204/// can be legally represented as pre-indexed load / store address.
19205bool
19206ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
19207 SDValue &Offset,
19208 ISD::MemIndexedMode &AM,
19209 SelectionDAG &DAG) const {
19210 if (Subtarget->isThumb1Only())
19211 return false;
19212
19213 EVT VT;
19214 SDValue Ptr;
19215 Align Alignment;
19216 bool isSEXTLoad = false;
19217 bool IsMasked = false;
19218 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
19219 Ptr = LD->getBasePtr();
19220 VT = LD->getMemoryVT();
19221 Alignment = LD->getAlign();
19222 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19223 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
19224 Ptr = ST->getBasePtr();
19225 VT = ST->getMemoryVT();
19226 Alignment = ST->getAlign();
19227 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
19228 Ptr = LD->getBasePtr();
19229 VT = LD->getMemoryVT();
19230 Alignment = LD->getAlign();
19231 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19232 IsMasked = true;
19233 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
19234 Ptr = ST->getBasePtr();
19235 VT = ST->getMemoryVT();
19236 Alignment = ST->getAlign();
19237 IsMasked = true;
19238 } else
19239 return false;
19240
19241 bool isInc;
19242 bool isLegal = false;
19243 if (VT.isVector())
19244 isLegal = Subtarget->hasMVEIntegerOps() &&
19245 getMVEIndexedAddressParts(
19246 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
19247 Subtarget->isLittle(), Base, Offset, isInc, DAG);
19248 else {
19249 if (Subtarget->isThumb2())
19250 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
19251 Offset, isInc, DAG);
19252 else
19253 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
19254 Offset, isInc, DAG);
19255 }
19256 if (!isLegal)
19257 return false;
19258
19259 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
19260 return true;
19261}
19262
19263/// getPostIndexedAddressParts - returns true by value, base pointer and
19264/// offset pointer and addressing mode by reference if this node can be
19265/// combined with a load / store to form a post-indexed load / store.
19266bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
19267 SDValue &Base,
19268 SDValue &Offset,
19269 ISD::MemIndexedMode &AM,
19270 SelectionDAG &DAG) const {
19271 EVT VT;
19272 SDValue Ptr;
19273 Align Alignment;
19274 bool isSEXTLoad = false, isNonExt;
19275 bool IsMasked = false;
19276 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
19277 VT = LD->getMemoryVT();
19278 Ptr = LD->getBasePtr();
19279 Alignment = LD->getAlign();
19280 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19281 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19282 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
19283 VT = ST->getMemoryVT();
19284 Ptr = ST->getBasePtr();
19285 Alignment = ST->getAlign();
19286 isNonExt = !ST->isTruncatingStore();
19287 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
19288 VT = LD->getMemoryVT();
19289 Ptr = LD->getBasePtr();
19290 Alignment = LD->getAlign();
19291 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19292 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19293 IsMasked = true;
19294 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
19295 VT = ST->getMemoryVT();
19296 Ptr = ST->getBasePtr();
19297 Alignment = ST->getAlign();
19298 isNonExt = !ST->isTruncatingStore();
19299 IsMasked = true;
19300 } else
19301 return false;
19302
19303 if (Subtarget->isThumb1Only()) {
19304 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
19305 // must be non-extending/truncating, i32, with an offset of 4.
19306 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?!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19306, __extension__ __PRETTY_FUNCTION__))
;
19307 if (Op->getOpcode() != ISD::ADD || !isNonExt)
19308 return false;
19309 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
19310 if (!RHS || RHS->getZExtValue() != 4)
19311 return false;
19312 if (Alignment < Align(4))
19313 return false;
19314
19315 Offset = Op->getOperand(1);
19316 Base = Op->getOperand(0);
19317 AM = ISD::POST_INC;
19318 return true;
19319 }
19320
19321 bool isInc;
19322 bool isLegal = false;
19323 if (VT.isVector())
19324 isLegal = Subtarget->hasMVEIntegerOps() &&
19325 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
19326 Subtarget->isLittle(), Base, Offset,
19327 isInc, DAG);
19328 else {
19329 if (Subtarget->isThumb2())
19330 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
19331 isInc, DAG);
19332 else
19333 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
19334 isInc, DAG);
19335 }
19336 if (!isLegal)
19337 return false;
19338
19339 if (Ptr != Base) {
19340 // Swap base ptr and offset to catch more post-index load / store when
19341 // it's legal. In Thumb2 mode, offset must be an immediate.
19342 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
19343 !Subtarget->isThumb2())
19344 std::swap(Base, Offset);
19345
19346 // Post-indexed load / store update the base pointer.
19347 if (Ptr != Base)
19348 return false;
19349 }
19350
19351 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
19352 return true;
19353}
19354
19355void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19356 KnownBits &Known,
19357 const APInt &DemandedElts,
19358 const SelectionDAG &DAG,
19359 unsigned Depth) const {
19360 unsigned BitWidth = Known.getBitWidth();
19361 Known.resetAll();
19362 switch (Op.getOpcode()) {
19363 default: break;
19364 case ARMISD::ADDC:
19365 case ARMISD::ADDE:
19366 case ARMISD::SUBC:
19367 case ARMISD::SUBE:
19368 // Special cases when we convert a carry to a boolean.
19369 if (Op.getResNo() == 0) {
19370 SDValue LHS = Op.getOperand(0);
19371 SDValue RHS = Op.getOperand(1);
19372 // (ADDE 0, 0, C) will give us a single bit.
19373 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
19374 isNullConstant(RHS)) {
19375 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19376 return;
19377 }
19378 }
19379 break;
19380 case ARMISD::CMOV: {
19381 // Bits are known zero/one if known on the LHS and RHS.
19382 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
19383 if (Known.isUnknown())
19384 return;
19385
19386 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
19387 Known = KnownBits::commonBits(Known, KnownRHS);
19388 return;
19389 }
19390 case ISD::INTRINSIC_W_CHAIN: {
19391 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
19392 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
19393 switch (IntID) {
19394 default: return;
19395 case Intrinsic::arm_ldaex:
19396 case Intrinsic::arm_ldrex: {
19397 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
19398 unsigned MemBits = VT.getScalarSizeInBits();
19399 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
19400 return;
19401 }
19402 }
19403 }
19404 case ARMISD::BFI: {
19405 // Conservatively, we can recurse down the first operand
19406 // and just mask out all affected bits.
19407 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
19408
19409 // The operand to BFI is already a mask suitable for removing the bits it
19410 // sets.
19411 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
19412 const APInt &Mask = CI->getAPIntValue();
19413 Known.Zero &= Mask;
19414 Known.One &= Mask;
19415 return;
19416 }
19417 case ARMISD::VGETLANEs:
19418 case ARMISD::VGETLANEu: {
19419 const SDValue &SrcSV = Op.getOperand(0);
19420 EVT VecVT = SrcSV.getValueType();
19421 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19421, __extension__ __PRETTY_FUNCTION__))
;
19422 const unsigned NumSrcElts = VecVT.getVectorNumElements();
19423 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
19424 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19425, __extension__ __PRETTY_FUNCTION__))
19425 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19425, __extension__ __PRETTY_FUNCTION__))
;
19426 unsigned Idx = Pos->getZExtValue();
19427 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
19428 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
19429
19430 EVT VT = Op.getValueType();
19431 const unsigned DstSz = VT.getScalarSizeInBits();
19432 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
19433 (void)SrcSz;
19434 assert(SrcSz == Known.getBitWidth())(static_cast <bool> (SrcSz == Known.getBitWidth()) ? void
(0) : __assert_fail ("SrcSz == Known.getBitWidth()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19434, __extension__ __PRETTY_FUNCTION__))
;
19435 assert(DstSz > SrcSz)(static_cast <bool> (DstSz > SrcSz) ? void (0) : __assert_fail
("DstSz > SrcSz", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19435, __extension__ __PRETTY_FUNCTION__))
;
19436 if (Op.getOpcode() == ARMISD::VGETLANEs)
19437 Known = Known.sext(DstSz);
19438 else {
19439 Known = Known.zext(DstSz);
19440 }
19441 assert(DstSz == Known.getBitWidth())(static_cast <bool> (DstSz == Known.getBitWidth()) ? void
(0) : __assert_fail ("DstSz == Known.getBitWidth()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19441, __extension__ __PRETTY_FUNCTION__))
;
19442 break;
19443 }
19444 case ARMISD::VMOVrh: {
19445 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
19446 assert(KnownOp.getBitWidth() == 16)(static_cast <bool> (KnownOp.getBitWidth() == 16) ? void
(0) : __assert_fail ("KnownOp.getBitWidth() == 16", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19446, __extension__ __PRETTY_FUNCTION__))
;
19447 Known = KnownOp.zext(32);
19448 break;
19449 }
19450 case ARMISD::CSINC:
19451 case ARMISD::CSINV:
19452 case ARMISD::CSNEG: {
19453 KnownBits KnownOp0 = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
19454 KnownBits KnownOp1 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
19455
19456 // The result is either:
19457 // CSINC: KnownOp0 or KnownOp1 + 1
19458 // CSINV: KnownOp0 or ~KnownOp1
19459 // CSNEG: KnownOp0 or KnownOp1 * -1
19460 if (Op.getOpcode() == ARMISD::CSINC)
19461 KnownOp1 = KnownBits::computeForAddSub(
19462 true, false, KnownOp1, KnownBits::makeConstant(APInt(32, 1)));
19463 else if (Op.getOpcode() == ARMISD::CSINV)
19464 std::swap(KnownOp1.Zero, KnownOp1.One);
19465 else if (Op.getOpcode() == ARMISD::CSNEG)
19466 KnownOp1 = KnownBits::mul(
19467 KnownOp1, KnownBits::makeConstant(APInt(32, -1)));
19468
19469 Known = KnownBits::commonBits(KnownOp0, KnownOp1);
19470 break;
19471 }
19472 }
19473}
19474
19475bool ARMTargetLowering::targetShrinkDemandedConstant(
19476 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
19477 TargetLoweringOpt &TLO) const {
19478 // Delay optimization, so we don't have to deal with illegal types, or block
19479 // optimizations.
19480 if (!TLO.LegalOps)
19481 return false;
19482
19483 // Only optimize AND for now.
19484 if (Op.getOpcode() != ISD::AND)
19485 return false;
19486
19487 EVT VT = Op.getValueType();
19488
19489 // Ignore vectors.
19490 if (VT.isVector())
19491 return false;
19492
19493 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19493, __extension__ __PRETTY_FUNCTION__))
;
19494
19495 // Make sure the RHS really is a constant.
19496 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
19497 if (!C)
19498 return false;
19499
19500 unsigned Mask = C->getZExtValue();
19501
19502 unsigned Demanded = DemandedBits.getZExtValue();
19503 unsigned ShrunkMask = Mask & Demanded;
19504 unsigned ExpandedMask = Mask | ~Demanded;
19505
19506 // If the mask is all zeros, let the target-independent code replace the
19507 // result with zero.
19508 if (ShrunkMask == 0)
19509 return false;
19510
19511 // If the mask is all ones, erase the AND. (Currently, the target-independent
19512 // code won't do this, so we have to do it explicitly to avoid an infinite
19513 // loop in obscure cases.)
19514 if (ExpandedMask == ~0U)
19515 return TLO.CombineTo(Op, Op.getOperand(0));
19516
19517 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
19518 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
19519 };
19520 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
19521 if (NewMask == Mask)
19522 return true;
19523 SDLoc DL(Op);
19524 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
19525 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
19526 return TLO.CombineTo(Op, NewOp);
19527 };
19528
19529 // Prefer uxtb mask.
19530 if (IsLegalMask(0xFF))
19531 return UseMask(0xFF);
19532
19533 // Prefer uxth mask.
19534 if (IsLegalMask(0xFFFF))
19535 return UseMask(0xFFFF);
19536
19537 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
19538 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
19539 if (ShrunkMask < 256)
19540 return UseMask(ShrunkMask);
19541
19542 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
19543 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
19544 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
19545 return UseMask(ExpandedMask);
19546
19547 // Potential improvements:
19548 //
19549 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
19550 // We could try to prefer Thumb1 immediates which can be lowered to a
19551 // two-instruction sequence.
19552 // We could try to recognize more legal ARM/Thumb2 immediates here.
19553
19554 return false;
19555}
19556
19557bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
19558 SDValue Op, const APInt &OriginalDemandedBits,
19559 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
19560 unsigned Depth) const {
19561 unsigned Opc = Op.getOpcode();
19562
19563 switch (Opc) {
19564 case ARMISD::ASRL:
19565 case ARMISD::LSRL: {
19566 // If this is result 0 and the other result is unused, see if the demand
19567 // bits allow us to shrink this long shift into a standard small shift in
19568 // the opposite direction.
19569 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
19570 isa<ConstantSDNode>(Op->getOperand(2))) {
19571 unsigned ShAmt = Op->getConstantOperandVal(2);
19572 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(APInt::getAllOnes(32)
19573 << (32 - ShAmt)))
19574 return TLO.CombineTo(
19575 Op, TLO.DAG.getNode(
19576 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
19577 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
19578 }
19579 break;
19580 }
19581 }
19582
19583 return TargetLowering::SimplifyDemandedBitsForTargetNode(
19584 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
19585}
19586
19587//===----------------------------------------------------------------------===//
19588// ARM Inline Assembly Support
19589//===----------------------------------------------------------------------===//
19590
19591bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
19592 // Looking for "rev" which is V6+.
19593 if (!Subtarget->hasV6Ops())
19594 return false;
19595
19596 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
19597 std::string AsmStr = IA->getAsmString();
19598 SmallVector<StringRef, 4> AsmPieces;
19599 SplitString(AsmStr, AsmPieces, ";\n");
19600
19601 switch (AsmPieces.size()) {
19602 default: return false;
19603 case 1:
19604 AsmStr = std::string(AsmPieces[0]);
19605 AsmPieces.clear();
19606 SplitString(AsmStr, AsmPieces, " \t,");
19607
19608 // rev $0, $1
19609 if (AsmPieces.size() == 3 &&
19610 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
19611 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
19612 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19613 if (Ty && Ty->getBitWidth() == 32)
19614 return IntrinsicLowering::LowerToByteSwap(CI);
19615 }
19616 break;
19617 }
19618
19619 return false;
19620}
19621
19622const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
19623 // At this point, we have to lower this constraint to something else, so we
19624 // lower it to an "r" or "w". However, by doing this we will force the result
19625 // to be in register, while the X constraint is much more permissive.
19626 //
19627 // Although we are correct (we are free to emit anything, without
19628 // constraints), we might break use cases that would expect us to be more
19629 // efficient and emit something else.
19630 if (!Subtarget->hasVFP2Base())
19631 return "r";
19632 if (ConstraintVT.isFloatingPoint())
19633 return "w";
19634 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
19635 (ConstraintVT.getSizeInBits() == 64 ||
19636 ConstraintVT.getSizeInBits() == 128))
19637 return "w";
19638
19639 return "r";
19640}
19641
19642/// getConstraintType - Given a constraint letter, return the type of
19643/// constraint it is for this target.
19644ARMTargetLowering::ConstraintType
19645ARMTargetLowering::getConstraintType(StringRef Constraint) const {
19646 unsigned S = Constraint.size();
19647 if (S == 1) {
19648 switch (Constraint[0]) {
19649 default: break;
19650 case 'l': return C_RegisterClass;
19651 case 'w': return C_RegisterClass;
19652 case 'h': return C_RegisterClass;
19653 case 'x': return C_RegisterClass;
19654 case 't': return C_RegisterClass;
19655 case 'j': return C_Immediate; // Constant for movw.
19656 // An address with a single base register. Due to the way we
19657 // currently handle addresses it is the same as an 'r' memory constraint.
19658 case 'Q': return C_Memory;
19659 }
19660 } else if (S == 2) {
19661 switch (Constraint[0]) {
19662 default: break;
19663 case 'T': return C_RegisterClass;
19664 // All 'U+' constraints are addresses.
19665 case 'U': return C_Memory;
19666 }
19667 }
19668 return TargetLowering::getConstraintType(Constraint);
19669}
19670
19671/// Examine constraint type and operand type and determine a weight value.
19672/// This object must already have been set up with the operand type
19673/// and the current alternative constraint selected.
19674TargetLowering::ConstraintWeight
19675ARMTargetLowering::getSingleConstraintMatchWeight(
19676 AsmOperandInfo &info, const char *constraint) const {
19677 ConstraintWeight weight = CW_Invalid;
19678 Value *CallOperandVal = info.CallOperandVal;
19679 // If we don't have a value, we can't do a match,
19680 // but allow it at the lowest weight.
19681 if (!CallOperandVal)
19682 return CW_Default;
19683 Type *type = CallOperandVal->getType();
19684 // Look at the constraint type.
19685 switch (*constraint) {
19686 default:
19687 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19688 break;
19689 case 'l':
19690 if (type->isIntegerTy()) {
19691 if (Subtarget->isThumb())
19692 weight = CW_SpecificReg;
19693 else
19694 weight = CW_Register;
19695 }
19696 break;
19697 case 'w':
19698 if (type->isFloatingPointTy())
19699 weight = CW_Register;
19700 break;
19701 }
19702 return weight;
19703}
19704
19705using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
19706
19707RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
19708 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
19709 switch (Constraint.size()) {
19710 case 1:
19711 // GCC ARM Constraint Letters
19712 switch (Constraint[0]) {
19713 case 'l': // Low regs or general regs.
19714 if (Subtarget->isThumb())
19715 return RCPair(0U, &ARM::tGPRRegClass);
19716 return RCPair(0U, &ARM::GPRRegClass);
19717 case 'h': // High regs or no regs.
19718 if (Subtarget->isThumb())
19719 return RCPair(0U, &ARM::hGPRRegClass);
19720 break;
19721 case 'r':
19722 if (Subtarget->isThumb1Only())
19723 return RCPair(0U, &ARM::tGPRRegClass);
19724 return RCPair(0U, &ARM::GPRRegClass);
19725 case 'w':
19726 if (VT == MVT::Other)
19727 break;
19728 if (VT == MVT::f32)
19729 return RCPair(0U, &ARM::SPRRegClass);
19730 if (VT.getSizeInBits() == 64)
19731 return RCPair(0U, &ARM::DPRRegClass);
19732 if (VT.getSizeInBits() == 128)
19733 return RCPair(0U, &ARM::QPRRegClass);
19734 break;
19735 case 'x':
19736 if (VT == MVT::Other)
19737 break;
19738 if (VT == MVT::f32)
19739 return RCPair(0U, &ARM::SPR_8RegClass);
19740 if (VT.getSizeInBits() == 64)
19741 return RCPair(0U, &ARM::DPR_8RegClass);
19742 if (VT.getSizeInBits() == 128)
19743 return RCPair(0U, &ARM::QPR_8RegClass);
19744 break;
19745 case 't':
19746 if (VT == MVT::Other)
19747 break;
19748 if (VT == MVT::f32 || VT == MVT::i32)
19749 return RCPair(0U, &ARM::SPRRegClass);
19750 if (VT.getSizeInBits() == 64)
19751 return RCPair(0U, &ARM::DPR_VFP2RegClass);
19752 if (VT.getSizeInBits() == 128)
19753 return RCPair(0U, &ARM::QPR_VFP2RegClass);
19754 break;
19755 }
19756 break;
19757
19758 case 2:
19759 if (Constraint[0] == 'T') {
19760 switch (Constraint[1]) {
19761 default:
19762 break;
19763 case 'e':
19764 return RCPair(0U, &ARM::tGPREvenRegClass);
19765 case 'o':
19766 return RCPair(0U, &ARM::tGPROddRegClass);
19767 }
19768 }
19769 break;
19770
19771 default:
19772 break;
19773 }
19774
19775 if (StringRef("{cc}").equals_insensitive(Constraint))
19776 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
19777
19778 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
19779}
19780
19781/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19782/// vector. If it is invalid, don't add anything to Ops.
19783void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19784 std::string &Constraint,
19785 std::vector<SDValue>&Ops,
19786 SelectionDAG &DAG) const {
19787 SDValue Result;
19788
19789 // Currently only support length 1 constraints.
19790 if (Constraint.length() != 1) return;
19791
19792 char ConstraintLetter = Constraint[0];
19793 switch (ConstraintLetter) {
19794 default: break;
19795 case 'j':
19796 case 'I': case 'J': case 'K': case 'L':
19797 case 'M': case 'N': case 'O':
19798 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
19799 if (!C)
19800 return;
19801
19802 int64_t CVal64 = C->getSExtValue();
19803 int CVal = (int) CVal64;
19804 // None of these constraints allow values larger than 32 bits. Check
19805 // that the value fits in an int.
19806 if (CVal != CVal64)
19807 return;
19808
19809 switch (ConstraintLetter) {
19810 case 'j':
19811 // Constant suitable for movw, must be between 0 and
19812 // 65535.
19813 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
19814 if (CVal >= 0 && CVal <= 65535)
19815 break;
19816 return;
19817 case 'I':
19818 if (Subtarget->isThumb1Only()) {
19819 // This must be a constant between 0 and 255, for ADD
19820 // immediates.
19821 if (CVal >= 0 && CVal <= 255)
19822 break;
19823 } else if (Subtarget->isThumb2()) {
19824 // A constant that can be used as an immediate value in a
19825 // data-processing instruction.
19826 if (ARM_AM::getT2SOImmVal(CVal) != -1)
19827 break;
19828 } else {
19829 // A constant that can be used as an immediate value in a
19830 // data-processing instruction.
19831 if (ARM_AM::getSOImmVal(CVal) != -1)
19832 break;
19833 }
19834 return;
19835
19836 case 'J':
19837 if (Subtarget->isThumb1Only()) {
19838 // This must be a constant between -255 and -1, for negated ADD
19839 // immediates. This can be used in GCC with an "n" modifier that
19840 // prints the negated value, for use with SUB instructions. It is
19841 // not useful otherwise but is implemented for compatibility.
19842 if (CVal >= -255 && CVal <= -1)
19843 break;
19844 } else {
19845 // This must be a constant between -4095 and 4095. It is not clear
19846 // what this constraint is intended for. Implemented for
19847 // compatibility with GCC.
19848 if (CVal >= -4095 && CVal <= 4095)
19849 break;
19850 }
19851 return;
19852
19853 case 'K':
19854 if (Subtarget->isThumb1Only()) {
19855 // A 32-bit value where only one byte has a nonzero value. Exclude
19856 // zero to match GCC. This constraint is used by GCC internally for
19857 // constants that can be loaded with a move/shift combination.
19858 // It is not useful otherwise but is implemented for compatibility.
19859 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
19860 break;
19861 } else if (Subtarget->isThumb2()) {
19862 // A constant whose bitwise inverse can be used as an immediate
19863 // value in a data-processing instruction. This can be used in GCC
19864 // with a "B" modifier that prints the inverted value, for use with
19865 // BIC and MVN instructions. It is not useful otherwise but is
19866 // implemented for compatibility.
19867 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
19868 break;
19869 } else {
19870 // A constant whose bitwise inverse can be used as an immediate
19871 // value in a data-processing instruction. This can be used in GCC
19872 // with a "B" modifier that prints the inverted value, for use with
19873 // BIC and MVN instructions. It is not useful otherwise but is
19874 // implemented for compatibility.
19875 if (ARM_AM::getSOImmVal(~CVal) != -1)
19876 break;
19877 }
19878 return;
19879
19880 case 'L':
19881 if (Subtarget->isThumb1Only()) {
19882 // This must be a constant between -7 and 7,
19883 // for 3-operand ADD/SUB immediate instructions.
19884 if (CVal >= -7 && CVal < 7)
19885 break;
19886 } else if (Subtarget->isThumb2()) {
19887 // A constant whose negation can be used as an immediate value in a
19888 // data-processing instruction. This can be used in GCC with an "n"
19889 // modifier that prints the negated value, for use with SUB
19890 // instructions. It is not useful otherwise but is implemented for
19891 // compatibility.
19892 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
19893 break;
19894 } else {
19895 // A constant whose negation can be used as an immediate value in a
19896 // data-processing instruction. This can be used in GCC with an "n"
19897 // modifier that prints the negated value, for use with SUB
19898 // instructions. It is not useful otherwise but is implemented for
19899 // compatibility.
19900 if (ARM_AM::getSOImmVal(-CVal) != -1)
19901 break;
19902 }
19903 return;
19904
19905 case 'M':
19906 if (Subtarget->isThumb1Only()) {
19907 // This must be a multiple of 4 between 0 and 1020, for
19908 // ADD sp + immediate.
19909 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
19910 break;
19911 } else {
19912 // A power of two or a constant between 0 and 32. This is used in
19913 // GCC for the shift amount on shifted register operands, but it is
19914 // useful in general for any shift amounts.
19915 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
19916 break;
19917 }
19918 return;
19919
19920 case 'N':
19921 if (Subtarget->isThumb1Only()) {
19922 // This must be a constant between 0 and 31, for shift amounts.
19923 if (CVal >= 0 && CVal <= 31)
19924 break;
19925 }
19926 return;
19927
19928 case 'O':
19929 if (Subtarget->isThumb1Only()) {
19930 // This must be a multiple of 4 between -508 and 508, for
19931 // ADD/SUB sp = sp + immediate.
19932 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
19933 break;
19934 }
19935 return;
19936 }
19937 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
19938 break;
19939 }
19940
19941 if (Result.getNode()) {
19942 Ops.push_back(Result);
19943 return;
19944 }
19945 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19946}
19947
19948static RTLIB::Libcall getDivRemLibcall(
19949 const SDNode *N, MVT::SimpleValueType SVT) {
19950 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19952, __extension__ __PRETTY_FUNCTION__))
19951 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19952, __extension__ __PRETTY_FUNCTION__))
19952 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19952, __extension__ __PRETTY_FUNCTION__))
;
19953 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
19954 N->getOpcode() == ISD::SREM;
19955 RTLIB::Libcall LC;
19956 switch (SVT) {
19957 default: llvm_unreachable("Unexpected request for libcall!")::llvm::llvm_unreachable_internal("Unexpected request for libcall!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19957)
;
19958 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
19959 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
19960 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
19961 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
19962 }
19963 return LC;
19964}
19965
19966static TargetLowering::ArgListTy getDivRemArgList(
19967 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
19968 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19970, __extension__ __PRETTY_FUNCTION__))
19969 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19970, __extension__ __PRETTY_FUNCTION__))
19970 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19970, __extension__ __PRETTY_FUNCTION__))
;
19971 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
19972 N->getOpcode() == ISD::SREM;
19973 TargetLowering::ArgListTy Args;
19974 TargetLowering::ArgListEntry Entry;
19975 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
19976 EVT ArgVT = N->getOperand(i).getValueType();
19977 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
19978 Entry.Node = N->getOperand(i);
19979 Entry.Ty = ArgTy;
19980 Entry.IsSExt = isSigned;
19981 Entry.IsZExt = !isSigned;
19982 Args.push_back(Entry);
19983 }
19984 if (Subtarget->isTargetWindows() && Args.size() >= 2)
19985 std::swap(Args[0], Args[1]);
19986 return Args;
19987}
19988
19989SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
19990 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19993, __extension__ __PRETTY_FUNCTION__))
19991 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19993, __extension__ __PRETTY_FUNCTION__))
19992 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19993, __extension__ __PRETTY_FUNCTION__))
19993 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19993, __extension__ __PRETTY_FUNCTION__))
;
19994 unsigned Opcode = Op->getOpcode();
19995 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19996, __extension__ __PRETTY_FUNCTION__))
19996 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19996, __extension__ __PRETTY_FUNCTION__))
;
19997 bool isSigned = (Opcode == ISD::SDIVREM);
19998 EVT VT = Op->getValueType(0);
19999 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
20000 SDLoc dl(Op);
20001
20002 // If the target has hardware divide, use divide + multiply + subtract:
20003 // div = a / b
20004 // rem = a - b * div
20005 // return {div, rem}
20006 // This should be lowered into UDIV/SDIV + MLS later on.
20007 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
20008 : Subtarget->hasDivideInARMMode();
20009 if (hasDivide && Op->getValueType(0).isSimple() &&
20010 Op->getSimpleValueType(0) == MVT::i32) {
20011 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
20012 const SDValue Dividend = Op->getOperand(0);
20013 const SDValue Divisor = Op->getOperand(1);
20014 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
20015 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
20016 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
20017
20018 SDValue Values[2] = {Div, Rem};
20019 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
20020 }
20021
20022 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
20023 VT.getSimpleVT().SimpleTy);
20024 SDValue InChain = DAG.getEntryNode();
20025
20026 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
20027 DAG.getContext(),
20028 Subtarget);
20029
20030 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
20031 getPointerTy(DAG.getDataLayout()));
20032
20033 Type *RetTy = StructType::get(Ty, Ty);
20034
20035 if (Subtarget->isTargetWindows())
20036 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
20037
20038 TargetLowering::CallLoweringInfo CLI(DAG);
20039 CLI.setDebugLoc(dl).setChain(InChain)
20040 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
20041 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
20042
20043 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
20044 return CallInfo.first;
20045}
20046
20047// Lowers REM using divmod helpers
20048// see RTABI section 4.2/4.3
20049SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
20050 // Build return types (div and rem)
20051 std::vector<Type*> RetTyParams;
20052 Type *RetTyElement;
20053
20054 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
20055 default: llvm_unreachable("Unexpected request for libcall!")::llvm::llvm_unreachable_internal("Unexpected request for libcall!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20055)
;
20056 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
20057 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
20058 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
20059 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
20060 }
20061
20062 RetTyParams.push_back(RetTyElement);
20063 RetTyParams.push_back(RetTyElement);
20064 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
20065 Type *RetTy = StructType::get(*DAG.getContext(), ret);
20066
20067 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
20068 SimpleTy);
20069 SDValue InChain = DAG.getEntryNode();
20070 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
20071 Subtarget);
20072 bool isSigned = N->getOpcode() == ISD::SREM;
20073 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
20074 getPointerTy(DAG.getDataLayout()));
20075
20076 if (Subtarget->isTargetWindows())
20077 InChain = WinDBZCheckDenominator(DAG, N, InChain);
20078
20079 // Lower call
20080 CallLoweringInfo CLI(DAG);
20081 CLI.setChain(InChain)
20082 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
20083 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
20084 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
20085
20086 // Return second (rem) result operand (first contains div)
20087 SDNode *ResNode = CallResult.first.getNode();
20088 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20088, __extension__ __PRETTY_FUNCTION__))
;
20089 return ResNode->getOperand(1);
20090}
20091
20092SDValue
20093ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
20094 assert(Subtarget->isTargetWindows() && "unsupported target platform")(static_cast <bool> (Subtarget->isTargetWindows() &&
"unsupported target platform") ? void (0) : __assert_fail ("Subtarget->isTargetWindows() && \"unsupported target platform\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20094, __extension__ __PRETTY_FUNCTION__))
;
20095 SDLoc DL(Op);
20096
20097 // Get the inputs.
20098 SDValue Chain = Op.getOperand(0);
20099 SDValue Size = Op.getOperand(1);
20100
20101 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
20102 "no-stack-arg-probe")) {
20103 MaybeAlign Align =
20104 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
20105 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
20106 Chain = SP.getValue(1);
20107 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
20108 if (Align)
20109 SP =
20110 DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
20111 DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32));
20112 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
20113 SDValue Ops[2] = { SP, Chain };
20114 return DAG.getMergeValues(Ops, DL);
20115 }
20116
20117 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
20118 DAG.getConstant(2, DL, MVT::i32));
20119
20120 SDValue Flag;
20121 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
20122 Flag = Chain.getValue(1);
20123
20124 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
20125 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
20126
20127 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
20128 Chain = NewSP.getValue(1);
20129
20130 SDValue Ops[2] = { NewSP, Chain };
20131 return DAG.getMergeValues(Ops, DL);
20132}
20133
20134SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
20135 bool IsStrict = Op->isStrictFPOpcode();
20136 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
20137 const unsigned DstSz = Op.getValueType().getSizeInBits();
20138 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
20139 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20140, __extension__ __PRETTY_FUNCTION__))
20140 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20140, __extension__ __PRETTY_FUNCTION__))
;
20141
20142 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20143, __extension__ __PRETTY_FUNCTION__))
20143 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20143, __extension__ __PRETTY_FUNCTION__))
;
20144
20145 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20146, __extension__ __PRETTY_FUNCTION__))
20146 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20146, __extension__ __PRETTY_FUNCTION__))
;
20147
20148 // Converting from 32 -> 64 is valid if we have FP64.
20149 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
20150 // FIXME: Remove this when we have strict fp instruction selection patterns
20151 if (IsStrict) {
20152 SDLoc Loc(Op);
20153 SDValue Result = DAG.getNode(ISD::FP_EXTEND,
20154 Loc, Op.getValueType(), SrcVal);
20155 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
20156 }
20157 return Op;
20158 }
20159
20160 // Either we are converting from 16 -> 64, without FP16 and/or
20161 // FP.double-precision or without Armv8-fp. So we must do it in two
20162 // steps.
20163 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
20164 // without FP16. So we must do a function call.
20165 SDLoc Loc(Op);
20166 RTLIB::Libcall LC;
20167 MakeLibCallOptions CallOptions;
20168 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20169 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
20170 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
20171 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
20172 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
20173 if (Supported) {
20174 if (IsStrict) {
20175 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
20176 {DstVT, MVT::Other}, {Chain, SrcVal});
20177 Chain = SrcVal.getValue(1);
20178 } else {
20179 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
20180 }
20181 } else {
20182 LC = RTLIB::getFPEXT(SrcVT, DstVT);
20183 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20184, __extension__ __PRETTY_FUNCTION__))
20184 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20184, __extension__ __PRETTY_FUNCTION__))
;
20185 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
20186 Loc, Chain);
20187 }
20188 }
20189
20190 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
20191}
20192
20193SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
20194 bool IsStrict = Op->isStrictFPOpcode();
20195
20196 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
20197 EVT SrcVT = SrcVal.getValueType();
20198 EVT DstVT = Op.getValueType();
20199 const unsigned DstSz = Op.getValueType().getSizeInBits();
20200 const unsigned SrcSz = SrcVT.getSizeInBits();
20201 (void)DstSz;
20202 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20203, __extension__ __PRETTY_FUNCTION__))
20203 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20203, __extension__ __PRETTY_FUNCTION__))
;
20204
20205 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20206, __extension__ __PRETTY_FUNCTION__))
20206 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20206, __extension__ __PRETTY_FUNCTION__))
;
20207
20208 SDLoc Loc(Op);
20209
20210 // Instruction from 32 -> 16 if hasFP16 is valid
20211 if (SrcSz == 32 && Subtarget->hasFP16())
20212 return Op;
20213
20214 // Lib call from 32 -> 16 / 64 -> [32, 16]
20215 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
20216 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20217, __extension__ __PRETTY_FUNCTION__))
20217 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20217, __extension__ __PRETTY_FUNCTION__))
;
20218 MakeLibCallOptions CallOptions;
20219 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20220 SDValue Result;
20221 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
20222 Loc, Chain);
20223 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
20224}
20225
20226void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
20227 SelectionDAG &DAG) const {
20228 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.")(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"Unexpected type (!= i64) on ABS.") ? void (0) : __assert_fail
("N->getValueType(0) == MVT::i64 && \"Unexpected type (!= i64) on ABS.\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20228, __extension__ __PRETTY_FUNCTION__))
;
20229 MVT HalfT = MVT::i32;
20230 SDLoc dl(N);
20231 SDValue Hi, Lo, Tmp;
20232
20233 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
20234 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
20235 return ;
20236
20237 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
20238 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
20239
20240 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
20241 DAG.getConstant(0, dl, HalfT));
20242 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
20243 DAG.getConstant(1, dl, HalfT));
20244
20245 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
20246 DAG.getConstant(OpTypeBits - 1, dl,
20247 getShiftAmountTy(HalfT, DAG.getDataLayout())));
20248 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
20249 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
20250 SDValue(Lo.getNode(), 1));
20251 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
20252 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
20253
20254 Results.push_back(Lo);
20255 Results.push_back(Hi);
20256}
20257
20258bool
20259ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
20260 // The ARM target isn't yet aware of offsets.
20261 return false;
20262}
20263
20264bool ARM::isBitFieldInvertedMask(unsigned v) {
20265 if (v == 0xffffffff)
20266 return false;
20267
20268 // there can be 1's on either or both "outsides", all the "inside"
20269 // bits must be 0's
20270 return isShiftedMask_32(~v);
20271}
20272
20273/// isFPImmLegal - Returns true if the target can instruction select the
20274/// specified FP immediate natively. If false, the legalizer will
20275/// materialize the FP immediate as a load from a constant pool.
20276bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
20277 bool ForCodeSize) const {
20278 if (!Subtarget->hasVFP3Base())
20279 return false;
20280 if (VT == MVT::f16 && Subtarget->hasFullFP16())
20281 return ARM_AM::getFP16Imm(Imm) != -1;
20282 if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
20283 ARM_AM::getFP32FP16Imm(Imm) != -1)
20284 return true;
20285 if (VT == MVT::f32)
20286 return ARM_AM::getFP32Imm(Imm) != -1;
20287 if (VT == MVT::f64 && Subtarget->hasFP64())
20288 return ARM_AM::getFP64Imm(Imm) != -1;
20289 return false;
20290}
20291
20292/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
20293/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
20294/// specified in the intrinsic calls.
20295bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
20296 const CallInst &I,
20297 MachineFunction &MF,
20298 unsigned Intrinsic) const {
20299 switch (Intrinsic) {
20300 case Intrinsic::arm_neon_vld1:
20301 case Intrinsic::arm_neon_vld2:
20302 case Intrinsic::arm_neon_vld3:
20303 case Intrinsic::arm_neon_vld4:
20304 case Intrinsic::arm_neon_vld2lane:
20305 case Intrinsic::arm_neon_vld3lane:
20306 case Intrinsic::arm_neon_vld4lane:
20307 case Intrinsic::arm_neon_vld2dup:
20308 case Intrinsic::arm_neon_vld3dup:
20309 case Intrinsic::arm_neon_vld4dup: {
20310 Info.opc = ISD::INTRINSIC_W_CHAIN;
20311 // Conservatively set memVT to the entire set of vectors loaded.
20312 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20313 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
20314 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20315 Info.ptrVal = I.getArgOperand(0);
20316 Info.offset = 0;
20317 Value *AlignArg = I.getArgOperand(I.arg_size() - 1);
20318 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
20319 // volatile loads with NEON intrinsics not supported
20320 Info.flags = MachineMemOperand::MOLoad;
20321 return true;
20322 }
20323 case Intrinsic::arm_neon_vld1x2:
20324 case Intrinsic::arm_neon_vld1x3:
20325 case Intrinsic::arm_neon_vld1x4: {
20326 Info.opc = ISD::INTRINSIC_W_CHAIN;
20327 // Conservatively set memVT to the entire set of vectors loaded.
20328 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20329 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
20330 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20331 Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
20332 Info.offset = 0;
20333 Info.align.reset();
20334 // volatile loads with NEON intrinsics not supported
20335 Info.flags = MachineMemOperand::MOLoad;
20336 return true;
20337 }
20338 case Intrinsic::arm_neon_vst1:
20339 case Intrinsic::arm_neon_vst2:
20340 case Intrinsic::arm_neon_vst3:
20341 case Intrinsic::arm_neon_vst4:
20342 case Intrinsic::arm_neon_vst2lane:
20343 case Intrinsic::arm_neon_vst3lane:
20344 case Intrinsic::arm_neon_vst4lane: {
20345 Info.opc = ISD::INTRINSIC_VOID;
20346 // Conservatively set memVT to the entire set of vectors stored.
20347 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20348 unsigned NumElts = 0;
20349 for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
20350 Type *ArgTy = I.getArgOperand(ArgI)->getType();
20351 if (!ArgTy->isVectorTy())
20352 break;
20353 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
20354 }
20355 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20356 Info.ptrVal = I.getArgOperand(0);
20357 Info.offset = 0;
20358 Value *AlignArg = I.getArgOperand(I.arg_size() - 1);
20359 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
20360 // volatile stores with NEON intrinsics not supported
20361 Info.flags = MachineMemOperand::MOStore;
20362 return true;
20363 }
20364 case Intrinsic::arm_neon_vst1x2:
20365 case Intrinsic::arm_neon_vst1x3:
20366 case Intrinsic::arm_neon_vst1x4: {
20367 Info.opc = ISD::INTRINSIC_VOID;
20368 // Conservatively set memVT to the entire set of vectors stored.
20369 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20370 unsigned NumElts = 0;
20371 for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
20372 Type *ArgTy = I.getArgOperand(ArgI)->getType();
20373 if (!ArgTy->isVectorTy())
20374 break;
20375 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
20376 }
20377 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20378 Info.ptrVal = I.getArgOperand(0);
20379 Info.offset = 0;
20380 Info.align.reset();
20381 // volatile stores with NEON intrinsics not supported
20382 Info.flags = MachineMemOperand::MOStore;
20383 return true;
20384 }
20385 case Intrinsic::arm_mve_vld2q:
20386 case Intrinsic::arm_mve_vld4q: {
20387 Info.opc = ISD::INTRINSIC_W_CHAIN;
20388 // Conservatively set memVT to the entire set of vectors loaded.
20389 Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
20390 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
20391 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
20392 Info.ptrVal = I.getArgOperand(0);
20393 Info.offset = 0;
20394 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
20395 // volatile loads with MVE intrinsics not supported
20396 Info.flags = MachineMemOperand::MOLoad;
20397 return true;
20398 }
20399 case Intrinsic::arm_mve_vst2q:
20400 case Intrinsic::arm_mve_vst4q: {
20401 Info.opc = ISD::INTRINSIC_VOID;
20402 // Conservatively set memVT to the entire set of vectors stored.
20403 Type *VecTy = I.getArgOperand(1)->getType();
20404 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
20405 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
20406 Info.ptrVal = I.getArgOperand(0);
20407 Info.offset = 0;
20408 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
20409 // volatile stores with MVE intrinsics not supported
20410 Info.flags = MachineMemOperand::MOStore;
20411 return true;
20412 }
20413 case Intrinsic::arm_mve_vldr_gather_base:
20414 case Intrinsic::arm_mve_vldr_gather_base_predicated: {
20415 Info.opc = ISD::INTRINSIC_W_CHAIN;
20416 Info.ptrVal = nullptr;
20417 Info.memVT = MVT::getVT(I.getType());
20418 Info.align = Align(1);
20419 Info.flags |= MachineMemOperand::MOLoad;
20420 return true;
20421 }
20422 case Intrinsic::arm_mve_vldr_gather_base_wb:
20423 case Intrinsic::arm_mve_vldr_gather_base_wb_predicated: {
20424 Info.opc = ISD::INTRINSIC_W_CHAIN;
20425 Info.ptrVal = nullptr;
20426 Info.memVT = MVT::getVT(I.getType()->getContainedType(0));
20427 Info.align = Align(1);
20428 Info.flags |= MachineMemOperand::MOLoad;
20429 return true;
20430 }
20431 case Intrinsic::arm_mve_vldr_gather_offset:
20432 case Intrinsic::arm_mve_vldr_gather_offset_predicated: {
20433 Info.opc = ISD::INTRINSIC_W_CHAIN;
20434 Info.ptrVal = nullptr;
20435 MVT DataVT = MVT::getVT(I.getType());
20436 unsigned MemSize = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
20437 Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
20438 DataVT.getVectorNumElements());
20439 Info.align = Align(1);
20440 Info.flags |= MachineMemOperand::MOLoad;
20441 return true;
20442 }
20443 case Intrinsic::arm_mve_vstr_scatter_base:
20444 case Intrinsic::arm_mve_vstr_scatter_base_predicated: {
20445 Info.opc = ISD::INTRINSIC_VOID;
20446 Info.ptrVal = nullptr;
20447 Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
20448 Info.align = Align(1);
20449 Info.flags |= MachineMemOperand::MOStore;
20450 return true;
20451 }
20452 case Intrinsic::arm_mve_vstr_scatter_base_wb:
20453 case Intrinsic::arm_mve_vstr_scatter_base_wb_predicated: {
20454 Info.opc = ISD::INTRINSIC_W_CHAIN;
20455 Info.ptrVal = nullptr;
20456 Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
20457 Info.align = Align(1);
20458 Info.flags |= MachineMemOperand::MOStore;
20459 return true;
20460 }
20461 case Intrinsic::arm_mve_vstr_scatter_offset:
20462 case Intrinsic::arm_mve_vstr_scatter_offset_predicated: {
20463 Info.opc = ISD::INTRINSIC_VOID;
20464 Info.ptrVal = nullptr;
20465 MVT DataVT = MVT::getVT(I.getArgOperand(2)->getType());
20466 unsigned MemSize = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
20467 Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
20468 DataVT.getVectorNumElements());
20469 Info.align = Align(1);
20470 Info.flags |= MachineMemOperand::MOStore;
20471 return true;
20472 }
20473 case Intrinsic::arm_ldaex:
20474 case Intrinsic::arm_ldrex: {
20475 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20476 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
20477 Info.opc = ISD::INTRINSIC_W_CHAIN;
20478 Info.memVT = MVT::getVT(PtrTy->getElementType());
20479 Info.ptrVal = I.getArgOperand(0);
20480 Info.offset = 0;
20481 Info.align = DL.getABITypeAlign(PtrTy->getElementType());
20482 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
20483 return true;
20484 }
20485 case Intrinsic::arm_stlex:
20486 case Intrinsic::arm_strex: {
20487 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20488 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
20489 Info.opc = ISD::INTRINSIC_W_CHAIN;
20490 Info.memVT = MVT::getVT(PtrTy->getElementType());
20491 Info.ptrVal = I.getArgOperand(1);
20492 Info.offset = 0;
20493 Info.align = DL.getABITypeAlign(PtrTy->getElementType());
20494 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
20495 return true;
20496 }
20497 case Intrinsic::arm_stlexd:
20498 case Intrinsic::arm_strexd:
20499 Info.opc = ISD::INTRINSIC_W_CHAIN;
20500 Info.memVT = MVT::i64;
20501 Info.ptrVal = I.getArgOperand(2);
20502 Info.offset = 0;
20503 Info.align = Align(8);
20504 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
20505 return true;
20506
20507 case Intrinsic::arm_ldaexd:
20508 case Intrinsic::arm_ldrexd:
20509 Info.opc = ISD::INTRINSIC_W_CHAIN;
20510 Info.memVT = MVT::i64;
20511 Info.ptrVal = I.getArgOperand(0);
20512 Info.offset = 0;
20513 Info.align = Align(8);
20514 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
20515 return true;
20516
20517 default:
20518 break;
20519 }
20520
20521 return false;
20522}
20523
20524/// Returns true if it is beneficial to convert a load of a constant
20525/// to just the constant itself.
20526bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
20527 Type *Ty) const {
20528 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20528, __extension__ __PRETTY_FUNCTION__))
;
20529
20530 unsigned Bits = Ty->getPrimitiveSizeInBits();
20531 if (Bits == 0 || Bits > 32)
20532 return false;
20533 return true;
20534}
20535
20536bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
20537 unsigned Index) const {
20538 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
20539 return false;
20540
20541 return (Index == 0 || Index == ResVT.getVectorNumElements());
20542}
20543
20544Instruction *ARMTargetLowering::makeDMB(IRBuilderBase &Builder,
20545 ARM_MB::MemBOpt Domain) const {
20546 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20547
20548 // First, if the target has no DMB, see what fallback we can use.
20549 if (!Subtarget->hasDataBarrier()) {
20550 // Some ARMv6 cpus can support data barriers with an mcr instruction.
20551 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
20552 // here.
20553 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
20554 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
20555 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
20556 Builder.getInt32(0), Builder.getInt32(7),
20557 Builder.getInt32(10), Builder.getInt32(5)};
20558 return Builder.CreateCall(MCR, args);
20559 } else {
20560 // Instead of using barriers, atomic accesses on these subtargets use
20561 // libcalls.
20562 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"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20562)
;
20563 }
20564 } else {
20565 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
20566 // Only a full system barrier exists in the M-class architectures.
20567 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
20568 Constant *CDomain = Builder.getInt32(Domain);
20569 return Builder.CreateCall(DMB, CDomain);
20570 }
20571}
20572
20573// Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
20574Instruction *ARMTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
20575 Instruction *Inst,
20576 AtomicOrdering Ord) const {
20577 switch (Ord) {
20578 case AtomicOrdering::NotAtomic:
20579 case AtomicOrdering::Unordered:
20580 llvm_unreachable("Invalid fence: unordered/non-atomic")::llvm::llvm_unreachable_internal("Invalid fence: unordered/non-atomic"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20580)
;
20581 case AtomicOrdering::Monotonic:
20582 case AtomicOrdering::Acquire:
20583 return nullptr; // Nothing to do
20584 case AtomicOrdering::SequentiallyConsistent:
20585 if (!Inst->hasAtomicStore())
20586 return nullptr; // Nothing to do
20587 LLVM_FALLTHROUGH[[gnu::fallthrough]];
20588 case AtomicOrdering::Release:
20589 case AtomicOrdering::AcquireRelease:
20590 if (Subtarget->preferISHSTBarriers())
20591 return makeDMB(Builder, ARM_MB::ISHST);
20592 // FIXME: add a comment with a link to documentation justifying this.
20593 else
20594 return makeDMB(Builder, ARM_MB::ISH);
20595 }
20596 llvm_unreachable("Unknown fence ordering in emitLeadingFence")::llvm::llvm_unreachable_internal("Unknown fence ordering in emitLeadingFence"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20596)
;
20597}
20598
20599Instruction *ARMTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
20600 Instruction *Inst,
20601 AtomicOrdering Ord) const {
20602 switch (Ord) {
20603 case AtomicOrdering::NotAtomic:
20604 case AtomicOrdering::Unordered:
20605 llvm_unreachable("Invalid fence: unordered/not-atomic")::llvm::llvm_unreachable_internal("Invalid fence: unordered/not-atomic"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20605)
;
20606 case AtomicOrdering::Monotonic:
20607 case AtomicOrdering::Release:
20608 return nullptr; // Nothing to do
20609 case AtomicOrdering::Acquire:
20610 case AtomicOrdering::AcquireRelease:
20611 case AtomicOrdering::SequentiallyConsistent:
20612 return makeDMB(Builder, ARM_MB::ISH);
20613 }
20614 llvm_unreachable("Unknown fence ordering in emitTrailingFence")::llvm::llvm_unreachable_internal("Unknown fence ordering in emitTrailingFence"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20614)
;
20615}
20616
20617// Loads and stores less than 64-bits are already atomic; ones above that
20618// are doomed anyway, so defer to the default libcall and blame the OS when
20619// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
20620// anything for those.
20621bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
20622 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
20623 return (Size == 64) && !Subtarget->isMClass();
20624}
20625
20626// Loads and stores less than 64-bits are already atomic; ones above that
20627// are doomed anyway, so defer to the default libcall and blame the OS when
20628// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
20629// anything for those.
20630// FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
20631// guarantee, see DDI0406C ARM architecture reference manual,
20632// sections A8.8.72-74 LDRD)
20633TargetLowering::AtomicExpansionKind
20634ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
20635 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
20636 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
20637 : AtomicExpansionKind::None;
20638}
20639
20640// For the real atomic operations, we have ldrex/strex up to 32 bits,
20641// and up to 64 bits on the non-M profiles
20642TargetLowering::AtomicExpansionKind
20643ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
20644 if (AI->isFloatingPointOperation())
20645 return AtomicExpansionKind::CmpXChg;
20646
20647 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
20648 // implement atomicrmw without spilling. If the target address is also on the
20649 // stack and close enough to the spill slot, this can lead to a situation
20650 // where the monitor always gets cleared and the atomic operation can never
20651 // succeed. So at -O0 lower this operation to a CAS loop.
20652 if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
20653 return AtomicExpansionKind::CmpXChg;
20654
20655 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
20656 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
20657 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
20658 ? AtomicExpansionKind::LLSC
20659 : AtomicExpansionKind::None;
20660}
20661
20662// Similar to shouldExpandAtomicRMWInIR, ldrex/strex can be used up to 32
20663// bits, and up to 64 bits on the non-M profiles.
20664TargetLowering::AtomicExpansionKind
20665ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
20666 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
20667 // implement cmpxchg without spilling. If the address being exchanged is also
20668 // on the stack and close enough to the spill slot, this can lead to a
20669 // situation where the monitor always gets cleared and the atomic operation
20670 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
20671 unsigned Size = AI->getOperand(1)->getType()->getPrimitiveSizeInBits();
20672 bool HasAtomicCmpXchg =
20673 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
20674 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg &&
20675 Size <= (Subtarget->isMClass() ? 32U : 64U))
20676 return AtomicExpansionKind::LLSC;
20677 return AtomicExpansionKind::None;
20678}
20679
20680bool ARMTargetLowering::shouldInsertFencesForAtomic(
20681 const Instruction *I) const {
20682 return InsertFencesForAtomic;
20683}
20684
20685bool ARMTargetLowering::useLoadStackGuardNode() const { return true; }
20686
20687void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
20688 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
20689 return TargetLowering::insertSSPDeclarations(M);
20690
20691 // MSVC CRT has a global variable holding security cookie.
20692 M.getOrInsertGlobal("__security_cookie",
20693 Type::getInt8PtrTy(M.getContext()));
20694
20695 // MSVC CRT has a function to validate security cookie.
20696 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
20697 "__security_check_cookie", Type::getVoidTy(M.getContext()),
20698 Type::getInt8PtrTy(M.getContext()));
20699 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
20700 F->addParamAttr(0, Attribute::AttrKind::InReg);
20701}
20702
20703Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
20704 // MSVC CRT has a global variable holding security cookie.
20705 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
20706 return M.getGlobalVariable("__security_cookie");
20707 return TargetLowering::getSDagStackGuard(M);
20708}
20709
20710Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
20711 // MSVC CRT has a function to validate security cookie.
20712 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
20713 return M.getFunction("__security_check_cookie");
20714 return TargetLowering::getSSPStackGuardCheck(M);
20715}
20716
20717bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
20718 unsigned &Cost) const {
20719 // If we do not have NEON, vector types are not natively supported.
20720 if (!Subtarget->hasNEON())
20721 return false;
20722
20723 // Floating point values and vector values map to the same register file.
20724 // Therefore, although we could do a store extract of a vector type, this is
20725 // better to leave at float as we have more freedom in the addressing mode for
20726 // those.
20727 if (VectorTy->isFPOrFPVectorTy())
20728 return false;
20729
20730 // If the index is unknown at compile time, this is very expensive to lower
20731 // and it is not possible to combine the store with the extract.
20732 if (!isa<ConstantInt>(Idx))
20733 return false;
20734
20735 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20735, __extension__ __PRETTY_FUNCTION__))
;
20736 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize();
20737 // We can do a store + vector extract on any vector that fits perfectly in a D
20738 // or Q register.
20739 if (BitWidth == 64 || BitWidth == 128) {
20740 Cost = 0;
20741 return true;
20742 }
20743 return false;
20744}
20745
20746bool ARMTargetLowering::isCheapToSpeculateCttz() const {
20747 return Subtarget->hasV6T2Ops();
20748}
20749
20750bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
20751 return Subtarget->hasV6T2Ops();
20752}
20753
20754bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
20755 return !Subtarget->hasMinSize() || Subtarget->isTargetWindows();
20756}
20757
20758Value *ARMTargetLowering::emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
20759 Value *Addr,
20760 AtomicOrdering Ord) const {
20761 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20762 bool IsAcquire = isAcquireOrStronger(Ord);
20763
20764 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
20765 // intrinsic must return {i32, i32} and we have to recombine them into a
20766 // single i64 here.
20767 if (ValueTy->getPrimitiveSizeInBits() == 64) {
20768 Intrinsic::ID Int =
20769 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
20770 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
20771
20772 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
20773 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
20774
20775 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
20776 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
20777 if (!Subtarget->isLittle())
20778 std::swap (Lo, Hi);
20779 Lo = Builder.CreateZExt(Lo, ValueTy, "lo64");
20780 Hi = Builder.CreateZExt(Hi, ValueTy, "hi64");
20781 return Builder.CreateOr(
20782 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValueTy, 32)), "val64");
20783 }
20784
20785 Type *Tys[] = { Addr->getType() };
20786 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
20787 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
20788
20789 return Builder.CreateTruncOrBitCast(Builder.CreateCall(Ldrex, Addr), ValueTy);
20790}
20791
20792void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
20793 IRBuilderBase &Builder) const {
20794 if (!Subtarget->hasV7Ops())
20795 return;
20796 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20797 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
20798}
20799
20800Value *ARMTargetLowering::emitStoreConditional(IRBuilderBase &Builder,
20801 Value *Val, Value *Addr,
20802 AtomicOrdering Ord) const {
20803 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20804 bool IsRelease = isReleaseOrStronger(Ord);
20805
20806 // Since the intrinsics must have legal type, the i64 intrinsics take two
20807 // parameters: "i32, i32". We must marshal Val into the appropriate form
20808 // before the call.
20809 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
20810 Intrinsic::ID Int =
20811 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
20812 Function *Strex = Intrinsic::getDeclaration(M, Int);
20813 Type *Int32Ty = Type::getInt32Ty(M->getContext());
20814
20815 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
20816 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
20817 if (!Subtarget->isLittle())
20818 std::swap(Lo, Hi);
20819 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
20820 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
20821 }
20822
20823 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
20824 Type *Tys[] = { Addr->getType() };
20825 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
20826
20827 return Builder.CreateCall(
20828 Strex, {Builder.CreateZExtOrBitCast(
20829 Val, Strex->getFunctionType()->getParamType(0)),
20830 Addr});
20831}
20832
20833
20834bool ARMTargetLowering::alignLoopsWithOptSize() const {
20835 return Subtarget->isMClass();
20836}
20837
20838/// A helper function for determining the number of interleaved accesses we
20839/// will generate when lowering accesses of the given type.
20840unsigned
20841ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
20842 const DataLayout &DL) const {
20843 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
20844}
20845
20846bool ARMTargetLowering::isLegalInterleavedAccessType(
20847 unsigned Factor, FixedVectorType *VecTy, Align Alignment,
20848 const DataLayout &DL) const {
20849
20850 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
20851 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
20852
20853 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
20854 return false;
20855
20856 // Ensure the vector doesn't have f16 elements. Even though we could do an
20857 // i16 vldN, we can't hold the f16 vectors and will end up converting via
20858 // f32.
20859 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
20860 return false;
20861 if (Subtarget->hasMVEIntegerOps() && Factor == 3)
20862 return false;
20863
20864 // Ensure the number of vector elements is greater than 1.
20865 if (VecTy->getNumElements() < 2)
20866 return false;
20867
20868 // Ensure the element type is legal.
20869 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
20870 return false;
20871 // And the alignment if high enough under MVE.
20872 if (Subtarget->hasMVEIntegerOps() && Alignment < ElSize / 8)
20873 return false;
20874
20875 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
20876 // 128 will be split into multiple interleaved accesses.
20877 if (Subtarget->hasNEON() && VecSize == 64)
20878 return true;
20879 return VecSize % 128 == 0;
20880}
20881
20882unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
20883 if (Subtarget->hasNEON())
20884 return 4;
20885 if (Subtarget->hasMVEIntegerOps())
20886 return MVEMaxSupportedInterleaveFactor;
20887 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
20888}
20889
20890/// Lower an interleaved load into a vldN intrinsic.
20891///
20892/// E.g. Lower an interleaved load (Factor = 2):
20893/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
20894/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
20895/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
20896///
20897/// Into:
20898/// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
20899/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
20900/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
20901bool ARMTargetLowering::lowerInterleavedLoad(
20902 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
20903 ArrayRef<unsigned> Indices, unsigned Factor) const {
20904 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20905, __extension__ __PRETTY_FUNCTION__))
20905 "Invalid interleave factor")(static_cast <bool> (Factor >= 2 && Factor <=
getMaxSupportedInterleaveFactor() && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20905, __extension__ __PRETTY_FUNCTION__))
;
20906 assert(!Shuffles.empty() && "Empty shufflevector input")(static_cast <bool> (!Shuffles.empty() && "Empty shufflevector input"
) ? void (0) : __assert_fail ("!Shuffles.empty() && \"Empty shufflevector input\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20906, __extension__ __PRETTY_FUNCTION__))
;
20907 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20908, __extension__ __PRETTY_FUNCTION__))
20908 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20908, __extension__ __PRETTY_FUNCTION__))
;
20909
20910 auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType());
20911 Type *EltTy = VecTy->getElementType();
20912
20913 const DataLayout &DL = LI->getModule()->getDataLayout();
20914 Align Alignment = LI->getAlign();
20915
20916 // Skip if we do not have NEON and skip illegal vector types. We can
20917 // "legalize" wide vector types into multiple interleaved accesses as long as
20918 // the vector types are divisible by 128.
20919 if (!isLegalInterleavedAccessType(Factor, VecTy, Alignment, DL))
20920 return false;
20921
20922 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
20923
20924 // A pointer vector can not be the return type of the ldN intrinsics. Need to
20925 // load integer vectors first and then convert to pointer vectors.
20926 if (EltTy->isPointerTy())
20927 VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy);
20928
20929 IRBuilder<> Builder(LI);
20930
20931 // The base address of the load.
20932 Value *BaseAddr = LI->getPointerOperand();
20933
20934 if (NumLoads > 1) {
20935 // If we're going to generate more than one load, reset the sub-vector type
20936 // to something legal.
20937 VecTy = FixedVectorType::get(VecTy->getElementType(),
20938 VecTy->getNumElements() / NumLoads);
20939
20940 // We will compute the pointer operand of each load from the original base
20941 // address using GEPs. Cast the base address to a pointer to the scalar
20942 // element type.
20943 BaseAddr = Builder.CreateBitCast(
20944 BaseAddr,
20945 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
20946 }
20947
20948 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20948, __extension__ __PRETTY_FUNCTION__))
;
20949
20950 auto createLoadIntrinsic = [&](Value *BaseAddr) {
20951 if (Subtarget->hasNEON()) {
20952 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
20953 Type *Tys[] = {VecTy, Int8Ptr};
20954 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
20955 Intrinsic::arm_neon_vld3,
20956 Intrinsic::arm_neon_vld4};
20957 Function *VldnFunc =
20958 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
20959
20960 SmallVector<Value *, 2> Ops;
20961 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
20962 Ops.push_back(Builder.getInt32(LI->getAlignment()));
20963
20964 return Builder.CreateCall(VldnFunc, Ops, "vldN");
20965 } else {
20966 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20967, __extension__ __PRETTY_FUNCTION__))
20967 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20967, __extension__ __PRETTY_FUNCTION__))
;
20968 Intrinsic::ID LoadInts =
20969 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
20970 Type *VecEltTy =
20971 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace());
20972 Type *Tys[] = {VecTy, VecEltTy};
20973 Function *VldnFunc =
20974 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
20975
20976 SmallVector<Value *, 2> Ops;
20977 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy));
20978 return Builder.CreateCall(VldnFunc, Ops, "vldN");
20979 }
20980 };
20981
20982 // Holds sub-vectors extracted from the load intrinsic return values. The
20983 // sub-vectors are associated with the shufflevector instructions they will
20984 // replace.
20985 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
20986
20987 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
20988 // If we're generating more than one load, compute the base address of
20989 // subsequent loads as an offset from the previous.
20990 if (LoadCount > 0)
20991 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
20992 VecTy->getNumElements() * Factor);
20993
20994 CallInst *VldN = createLoadIntrinsic(BaseAddr);
20995
20996 // Replace uses of each shufflevector with the corresponding vector loaded
20997 // by ldN.
20998 for (unsigned i = 0; i < Shuffles.size(); i++) {
20999 ShuffleVectorInst *SV = Shuffles[i];
21000 unsigned Index = Indices[i];
21001
21002 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
21003
21004 // Convert the integer vector to pointer vector if the element is pointer.
21005 if (EltTy->isPointerTy())
21006 SubVec = Builder.CreateIntToPtr(
21007 SubVec,
21008 FixedVectorType::get(SV->getType()->getElementType(), VecTy));
21009
21010 SubVecs[SV].push_back(SubVec);
21011 }
21012 }
21013
21014 // Replace uses of the shufflevector instructions with the sub-vectors
21015 // returned by the load intrinsic. If a shufflevector instruction is
21016 // associated with more than one sub-vector, those sub-vectors will be
21017 // concatenated into a single wide vector.
21018 for (ShuffleVectorInst *SVI : Shuffles) {
21019 auto &SubVec = SubVecs[SVI];
21020 auto *WideVec =
21021 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
21022 SVI->replaceAllUsesWith(WideVec);
21023 }
21024
21025 return true;
21026}
21027
21028/// Lower an interleaved store into a vstN intrinsic.
21029///
21030/// E.g. Lower an interleaved store (Factor = 3):
21031/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
21032/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
21033/// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
21034///
21035/// Into:
21036/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
21037/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
21038/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
21039/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
21040///
21041/// Note that the new shufflevectors will be removed and we'll only generate one
21042/// vst3 instruction in CodeGen.
21043///
21044/// Example for a more general valid mask (Factor 3). Lower:
21045/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
21046/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
21047/// store <12 x i32> %i.vec, <12 x i32>* %ptr
21048///
21049/// Into:
21050/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
21051/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
21052/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
21053/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
21054bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
21055 ShuffleVectorInst *SVI,
21056 unsigned Factor) const {
21057 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21058, __extension__ __PRETTY_FUNCTION__))
21058 "Invalid interleave factor")(static_cast <bool> (Factor >= 2 && Factor <=
getMaxSupportedInterleaveFactor() && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21058, __extension__ __PRETTY_FUNCTION__))
;
21059
21060 auto *VecTy = cast<FixedVectorType>(SVI->getType());
21061 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21061, __extension__ __PRETTY_FUNCTION__))
;
21062
21063 unsigned LaneLen = VecTy->getNumElements() / Factor;
21064 Type *EltTy = VecTy->getElementType();
21065 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
21066
21067 const DataLayout &DL = SI->getModule()->getDataLayout();
21068 Align Alignment = SI->getAlign();
21069
21070 // Skip if we do not have NEON and skip illegal vector types. We can
21071 // "legalize" wide vector types into multiple interleaved accesses as long as
21072 // the vector types are divisible by 128.
21073 if (!isLegalInterleavedAccessType(Factor, SubVecTy, Alignment, DL))
21074 return false;
21075
21076 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
21077
21078 Value *Op0 = SVI->getOperand(0);
21079 Value *Op1 = SVI->getOperand(1);
21080 IRBuilder<> Builder(SI);
21081
21082 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
21083 // vectors to integer vectors.
21084 if (EltTy->isPointerTy()) {
21085 Type *IntTy = DL.getIntPtrType(EltTy);
21086
21087 // Convert to the corresponding integer vector.
21088 auto *IntVecTy =
21089 FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType()));
21090 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
21091 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
21092
21093 SubVecTy = FixedVectorType::get(IntTy, LaneLen);
21094 }
21095
21096 // The base address of the store.
21097 Value *BaseAddr = SI->getPointerOperand();
21098
21099 if (NumStores > 1) {
21100 // If we're going to generate more than one store, reset the lane length
21101 // and sub-vector type to something legal.
21102 LaneLen /= NumStores;
21103 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
21104
21105 // We will compute the pointer operand of each store from the original base
21106 // address using GEPs. Cast the base address to a pointer to the scalar
21107 // element type.
21108 BaseAddr = Builder.CreateBitCast(
21109 BaseAddr,
21110 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
21111 }
21112
21113 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21113, __extension__ __PRETTY_FUNCTION__))
;
21114
21115 auto Mask = SVI->getShuffleMask();
21116
21117 auto createStoreIntrinsic = [&](Value *BaseAddr,
21118 SmallVectorImpl<Value *> &Shuffles) {
21119 if (Subtarget->hasNEON()) {
21120 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
21121 Intrinsic::arm_neon_vst3,
21122 Intrinsic::arm_neon_vst4};
21123 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
21124 Type *Tys[] = {Int8Ptr, SubVecTy};
21125
21126 Function *VstNFunc = Intrinsic::getDeclaration(
21127 SI->getModule(), StoreInts[Factor - 2], Tys);
21128
21129 SmallVector<Value *, 6> Ops;
21130 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
21131 append_range(Ops, Shuffles);
21132 Ops.push_back(Builder.getInt32(SI->getAlignment()));
21133 Builder.CreateCall(VstNFunc, Ops);
21134 } else {
21135 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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21136, __extension__ __PRETTY_FUNCTION__))
21136 "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\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21136, __extension__ __PRETTY_FUNCTION__))
;
21137 Intrinsic::ID StoreInts =
21138 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
21139 Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo(
21140 SI->getPointerAddressSpace());
21141 Type *Tys[] = {EltPtrTy, SubVecTy};
21142 Function *VstNFunc =
21143 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
21144
21145 SmallVector<Value *, 6> Ops;
21146 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy));
21147 append_range(Ops, Shuffles);
21148 for (unsigned F = 0; F < Factor; F++) {
21149 Ops.push_back(Builder.getInt32(F));
21150 Builder.CreateCall(VstNFunc, Ops);
21151 Ops.pop_back();
21152 }
21153 }
21154 };
21155
21156 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
21157 // If we generating more than one store, we compute the base address of
21158 // subsequent stores as an offset from the previous.
21159 if (StoreCount > 0)
21160 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
21161 BaseAddr, LaneLen * Factor);
21162
21163 SmallVector<Value *, 4> Shuffles;
21164
21165 // Split the shufflevector operands into sub vectors for the new vstN call.
21166 for (unsigned i = 0; i < Factor; i++) {
21167 unsigned IdxI = StoreCount * LaneLen * Factor + i;
21168 if (Mask[IdxI] >= 0) {
21169 Shuffles.push_back(Builder.CreateShuffleVector(
21170 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
21171 } else {
21172 unsigned StartMask = 0;
21173 for (unsigned j = 1; j < LaneLen; j++) {
21174 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
21175 if (Mask[IdxJ * Factor + IdxI] >= 0) {
21176 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
21177 break;
21178 }
21179 }
21180 // Note: If all elements in a chunk are undefs, StartMask=0!
21181 // Note: Filling undef gaps with random elements is ok, since
21182 // those elements were being written anyway (with undefs).
21183 // In the case of all undefs we're defaulting to using elems from 0
21184 // Note: StartMask cannot be negative, it's checked in
21185 // isReInterleaveMask
21186 Shuffles.push_back(Builder.CreateShuffleVector(
21187 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
21188 }
21189 }
21190
21191 createStoreIntrinsic(BaseAddr, Shuffles);
21192 }
21193 return true;
21194}
21195
21196enum HABaseType {
21197 HA_UNKNOWN = 0,
21198 HA_FLOAT,
21199 HA_DOUBLE,
21200 HA_VECT64,
21201 HA_VECT128
21202};
21203
21204static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
21205 uint64_t &Members) {
21206 if (auto *ST = dyn_cast<StructType>(Ty)) {
21207 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
21208 uint64_t SubMembers = 0;
21209 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
21210 return false;
21211 Members += SubMembers;
21212 }
21213 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
21214 uint64_t SubMembers = 0;
21215 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
21216 return false;
21217 Members += SubMembers * AT->getNumElements();
21218 } else if (Ty->isFloatTy()) {
21219 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
21220 return false;
21221 Members = 1;
21222 Base = HA_FLOAT;
21223 } else if (Ty->isDoubleTy()) {
21224 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
21225 return false;
21226 Members = 1;
21227 Base = HA_DOUBLE;
21228 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
21229 Members = 1;
21230 switch (Base) {
21231 case HA_FLOAT:
21232 case HA_DOUBLE:
21233 return false;
21234 case HA_VECT64:
21235 return VT->getPrimitiveSizeInBits().getFixedSize() == 64;
21236 case HA_VECT128:
21237 return VT->getPrimitiveSizeInBits().getFixedSize() == 128;
21238 case HA_UNKNOWN:
21239 switch (VT->getPrimitiveSizeInBits().getFixedSize()) {
21240 case 64:
21241 Base = HA_VECT64;
21242 return true;
21243 case 128:
21244 Base = HA_VECT128;
21245 return true;
21246 default:
21247 return false;
21248 }
21249 }
21250 }
21251
21252 return (Members > 0 && Members <= 4);
21253}
21254
21255/// Return the correct alignment for the current calling convention.
21256Align ARMTargetLowering::getABIAlignmentForCallingConv(
21257 Type *ArgTy, const DataLayout &DL) const {
21258 const Align ABITypeAlign = DL.getABITypeAlign(ArgTy);
21259 if (!ArgTy->isVectorTy())
21260 return ABITypeAlign;
21261
21262 // Avoid over-aligning vector parameters. It would require realigning the
21263 // stack and waste space for no real benefit.
21264 return std::min(ABITypeAlign, DL.getStackAlignment());
21265}
21266
21267/// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
21268/// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
21269/// passing according to AAPCS rules.
21270bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
21271 Type *Ty, CallingConv::ID CallConv, bool isVarArg,
21272 const DataLayout &DL) const {
21273 if (getEffectiveCallingConv(CallConv, isVarArg) !=
21274 CallingConv::ARM_AAPCS_VFP)
21275 return false;
21276
21277 HABaseType Base = HA_UNKNOWN;
21278 uint64_t Members = 0;
21279 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
21280 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "isHA: " << IsHA <<
" "; Ty->dump(); } } while (false)
;
21281
21282 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
21283 return IsHA || IsIntArray;
21284}
21285
21286Register ARMTargetLowering::getExceptionPointerRegister(
21287 const Constant *PersonalityFn) const {
21288 // Platforms which do not use SjLj EH may return values in these registers
21289 // via the personality function.
21290 return Subtarget->useSjLjEH() ? Register() : ARM::R0;
21291}
21292
21293Register ARMTargetLowering::getExceptionSelectorRegister(
21294 const Constant *PersonalityFn) const {
21295 // Platforms which do not use SjLj EH may return values in these registers
21296 // via the personality function.
21297 return Subtarget->useSjLjEH() ? Register() : ARM::R1;
21298}
21299
21300void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
21301 // Update IsSplitCSR in ARMFunctionInfo.
21302 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
21303 AFI->setIsSplitCSR(true);
21304}
21305
21306void ARMTargetLowering::insertCopiesSplitCSR(
21307 MachineBasicBlock *Entry,
21308 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
21309 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
21310 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
21311 if (!IStart)
21312 return;
21313
21314 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21315 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
21316 MachineBasicBlock::iterator MBBI = Entry->begin();
21317 for (const MCPhysReg *I = IStart; *I; ++I) {
21318 const TargetRegisterClass *RC = nullptr;
21319 if (ARM::GPRRegClass.contains(*I))
21320 RC = &ARM::GPRRegClass;
21321 else if (ARM::DPRRegClass.contains(*I))
21322 RC = &ARM::DPRRegClass;
21323 else
21324 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21324)
;
21325
21326 Register NewVR = MRI->createVirtualRegister(RC);
21327 // Create copy from CSR to a virtual register.
21328 // FIXME: this currently does not emit CFI pseudo-instructions, it works
21329 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
21330 // nounwind. If we want to generalize this later, we may need to emit
21331 // CFI pseudo-instructions.
21332 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21334, __extension__ __PRETTY_FUNCTION__))
21333 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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21334, __extension__ __PRETTY_FUNCTION__))
21334 "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!\""
, "/build/llvm-toolchain-snapshot-14~++20211110111138+cffbfd01e37b/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21334, __extension__ __PRETTY_FUNCTION__))
;
21335 Entry->addLiveIn(*I);
21336 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
21337 .addReg(*I);
21338
21339 // Insert the copy-back instructions right before the terminator.
21340 for (auto *Exit : Exits)
21341 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
21342 TII->get(TargetOpcode::COPY), *I)
21343 .addReg(NewVR);
21344 }
21345}
21346
21347void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
21348 MF.getFrameInfo().computeMaxCallFrameSize(MF);
21349 TargetLoweringBase::finalizeLowering(MF);
21350}