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/Twine.h"
41#include "llvm/Analysis/VectorUtils.h"
42#include "llvm/CodeGen/CallingConvLower.h"
43#include "llvm/CodeGen/ComplexDeinterleavingPass.h"
44#include "llvm/CodeGen/ISDOpcodes.h"
45#include "llvm/CodeGen/MachineBasicBlock.h"
46#include "llvm/CodeGen/MachineConstantPool.h"
47#include "llvm/CodeGen/MachineFrameInfo.h"
48#include "llvm/CodeGen/MachineFunction.h"
49#include "llvm/CodeGen/MachineInstr.h"
50#include "llvm/CodeGen/MachineInstrBuilder.h"
51#include "llvm/CodeGen/MachineJumpTableInfo.h"
52#include "llvm/CodeGen/MachineMemOperand.h"
53#include "llvm/CodeGen/MachineOperand.h"
54#include "llvm/CodeGen/MachineRegisterInfo.h"
55#include "llvm/CodeGen/RuntimeLibcallUtil.h"
56#include "llvm/CodeGen/SelectionDAG.h"
57#include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
58#include "llvm/CodeGen/SelectionDAGNodes.h"
59#include "llvm/CodeGen/TargetInstrInfo.h"
60#include "llvm/CodeGen/TargetLowering.h"
61#include "llvm/CodeGen/TargetOpcodes.h"
62#include "llvm/CodeGen/TargetRegisterInfo.h"
63#include "llvm/CodeGen/TargetSubtargetInfo.h"
64#include "llvm/CodeGen/ValueTypes.h"
65#include "llvm/CodeGenTypes/MachineValueType.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/Type.h"
86#include "llvm/IR/User.h"
87#include "llvm/IR/Value.h"
88#include "llvm/MC/MCInstrDesc.h"
89#include "llvm/MC/MCInstrItineraries.h"
90#include "llvm/MC/MCSchedule.h"
91#include "llvm/Support/AtomicOrdering.h"
92#include "llvm/Support/BranchProbability.h"
93#include "llvm/Support/Casting.h"
94#include "llvm/Support/CodeGen.h"
95#include "llvm/Support/CommandLine.h"
96#include "llvm/Support/Compiler.h"
97#include "llvm/Support/Debug.h"
98#include "llvm/Support/ErrorHandling.h"
99#include "llvm/Support/KnownBits.h"
100#include "llvm/Support/MathExtras.h"
101#include "llvm/Support/raw_ostream.h"
102#include "llvm/Target/TargetMachine.h"
103#include "llvm/Target/TargetOptions.h"
104#include "llvm/TargetParser/Triple.h"
105#include <algorithm>
106#include <cassert>
107#include <cstdint>
108#include <cstdlib>
109#include <iterator>
110#include <limits>
111#include <optional>
112#include <tuple>
113#include <utility>
114#include <vector>
115
116using namespace llvm;
117
118#define DEBUG_TYPE "arm-isel"
119
120STATISTIC(NumTailCalls, "Number of tail calls");
121STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
122STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
123STATISTIC(NumConstpoolPromoted,
124 "Number of constants with their storage promoted into constant pools");
125
126static cl::opt<bool>
127ARMInterworking("arm-interworking", cl::Hidden,
128 cl::desc("Enable / disable ARM interworking (for debugging only)"),
129 cl::init(Val: true));
130
131static cl::opt<bool> EnableConstpoolPromotion(
132 "arm-promote-constant", cl::Hidden,
133 cl::desc("Enable / disable promotion of unnamed_addr constants into "
134 "constant pools"),
135 cl::init(Val: false)); // FIXME: set to true by default once PR32780 is fixed
136static cl::opt<unsigned> ConstpoolPromotionMaxSize(
137 "arm-promote-constant-max-size", cl::Hidden,
138 cl::desc("Maximum size of constant to promote into a constant pool"),
139 cl::init(Val: 64));
140static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
141 "arm-promote-constant-max-total", cl::Hidden,
142 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
143 cl::init(Val: 128));
144
145cl::opt<unsigned>
146MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
147 cl::desc("Maximum interleave factor for MVE VLDn to generate."),
148 cl::init(Val: 2));
149
150cl::opt<unsigned> ArmMaxBaseUpdatesToCheck(
151 "arm-max-base-updates-to-check", cl::Hidden,
152 cl::desc("Maximum number of base-updates to check generating postindex."),
153 cl::init(Val: 64));
154
155/// Value type used for "flags" operands / results (either CPSR or FPSCR_NZCV).
156constexpr MVT FlagsVT = MVT::i32;
157
158// The APCS parameter registers.
159static const MCPhysReg GPRArgRegs[] = {
160 ARM::R0, ARM::R1, ARM::R2, ARM::R3
161};
162
163static SDValue handleCMSEValue(const SDValue &Value, const ISD::InputArg &Arg,
164 SelectionDAG &DAG, const SDLoc &DL) {
165 assert(Arg.ArgVT.isScalarInteger());
166 assert(Arg.ArgVT.bitsLT(MVT::i32));
167 SDValue Trunc = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: Arg.ArgVT, Operand: Value);
168 SDValue Ext =
169 DAG.getNode(Opcode: Arg.Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
170 VT: MVT::i32, Operand: Trunc);
171 return Ext;
172}
173
174void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT) {
175 if (VT != PromotedLdStVT) {
176 setOperationAction(Op: ISD::LOAD, VT, Action: Promote);
177 AddPromotedToType (Opc: ISD::LOAD, OrigVT: VT, DestVT: PromotedLdStVT);
178
179 setOperationAction(Op: ISD::STORE, VT, Action: Promote);
180 AddPromotedToType (Opc: ISD::STORE, OrigVT: VT, DestVT: PromotedLdStVT);
181 }
182
183 MVT ElemTy = VT.getVectorElementType();
184 if (ElemTy != MVT::f64)
185 setOperationAction(Op: ISD::SETCC, VT, Action: Custom);
186 setOperationAction(Op: ISD::INSERT_VECTOR_ELT, VT, Action: Custom);
187 setOperationAction(Op: ISD::EXTRACT_VECTOR_ELT, VT, Action: Custom);
188 if (ElemTy == MVT::i32) {
189 setOperationAction(Op: ISD::SINT_TO_FP, VT, Action: Custom);
190 setOperationAction(Op: ISD::UINT_TO_FP, VT, Action: Custom);
191 setOperationAction(Op: ISD::FP_TO_SINT, VT, Action: Custom);
192 setOperationAction(Op: ISD::FP_TO_UINT, VT, Action: Custom);
193 } else {
194 setOperationAction(Op: ISD::SINT_TO_FP, VT, Action: Expand);
195 setOperationAction(Op: ISD::UINT_TO_FP, VT, Action: Expand);
196 setOperationAction(Op: ISD::FP_TO_SINT, VT, Action: Expand);
197 setOperationAction(Op: ISD::FP_TO_UINT, VT, Action: Expand);
198 }
199 setOperationAction(Op: ISD::BUILD_VECTOR, VT, Action: Custom);
200 setOperationAction(Op: ISD::VECTOR_SHUFFLE, VT, Action: Custom);
201 setOperationAction(Op: ISD::CONCAT_VECTORS, VT, Action: Legal);
202 setOperationAction(Op: ISD::EXTRACT_SUBVECTOR, VT, Action: Legal);
203 setOperationAction(Op: ISD::SELECT, VT, Action: Expand);
204 setOperationAction(Op: ISD::SELECT_CC, VT, Action: Expand);
205 setOperationAction(Op: ISD::VSELECT, VT, Action: Expand);
206 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT, Action: Expand);
207 if (VT.isInteger()) {
208 setOperationAction(Op: ISD::SHL, VT, Action: Custom);
209 setOperationAction(Op: ISD::SRA, VT, Action: Custom);
210 setOperationAction(Op: ISD::SRL, VT, Action: Custom);
211 }
212
213 // Neon does not support vector divide/remainder operations.
214 setOperationAction(Op: ISD::SDIV, VT, Action: Expand);
215 setOperationAction(Op: ISD::UDIV, VT, Action: Expand);
216 setOperationAction(Op: ISD::FDIV, VT, Action: Expand);
217 setOperationAction(Op: ISD::SREM, VT, Action: Expand);
218 setOperationAction(Op: ISD::UREM, VT, Action: Expand);
219 setOperationAction(Op: ISD::FREM, VT, Action: Expand);
220 setOperationAction(Op: ISD::SDIVREM, VT, Action: Expand);
221 setOperationAction(Op: ISD::UDIVREM, VT, Action: Expand);
222
223 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
224 for (auto Opcode : {ISD::ABS, ISD::ABDS, ISD::ABDU, ISD::SMIN, ISD::SMAX,
225 ISD::UMIN, ISD::UMAX, ISD::CTLS})
226 setOperationAction(Op: Opcode, VT, Action: Legal);
227 if (!VT.isFloatingPoint())
228 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
229 setOperationAction(Op: Opcode, VT, Action: Legal);
230}
231
232void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
233 addRegisterClass(VT, RC: &ARM::DPRRegClass);
234 addTypeForNEON(VT, PromotedLdStVT: MVT::f64);
235}
236
237void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
238 addRegisterClass(VT, RC: &ARM::DPairRegClass);
239 addTypeForNEON(VT, PromotedLdStVT: MVT::v2f64);
240}
241
242void ARMTargetLowering::setAllExpand(MVT VT) {
243 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
244 setOperationAction(Op: Opc, VT, Action: Expand);
245
246 // We support these really simple operations even on types where all
247 // the actual arithmetic has to be broken down into simpler
248 // operations or turned into library calls.
249 setOperationAction(Op: ISD::BITCAST, VT, Action: Legal);
250 setOperationAction(Op: ISD::LOAD, VT, Action: Legal);
251 setOperationAction(Op: ISD::STORE, VT, Action: Legal);
252 setOperationAction(Op: ISD::UNDEF, VT, Action: Legal);
253}
254
255void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
256 LegalizeAction Action) {
257 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT: From, MemVT: To, Action);
258 setLoadExtAction(ExtType: ISD::ZEXTLOAD, ValVT: From, MemVT: To, Action);
259 setLoadExtAction(ExtType: ISD::SEXTLOAD, ValVT: From, MemVT: To, Action);
260}
261
262void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
263 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
264
265 for (auto VT : IntTypes) {
266 addRegisterClass(VT, RC: &ARM::MQPRRegClass);
267 setOperationAction(Op: ISD::VECTOR_SHUFFLE, VT, Action: Custom);
268 setOperationAction(Op: ISD::INSERT_VECTOR_ELT, VT, Action: Custom);
269 setOperationAction(Op: ISD::EXTRACT_VECTOR_ELT, VT, Action: Custom);
270 setOperationAction(Op: ISD::BUILD_VECTOR, VT, Action: Custom);
271 setOperationAction(Op: ISD::SHL, VT, Action: Custom);
272 setOperationAction(Op: ISD::SRA, VT, Action: Custom);
273 setOperationAction(Op: ISD::SRL, VT, Action: Custom);
274 setOperationAction(Op: ISD::SMIN, VT, Action: Legal);
275 setOperationAction(Op: ISD::SMAX, VT, Action: Legal);
276 setOperationAction(Op: ISD::UMIN, VT, Action: Legal);
277 setOperationAction(Op: ISD::UMAX, VT, Action: Legal);
278 setOperationAction(Op: ISD::ABS, VT, Action: Legal);
279 setOperationAction(Op: ISD::CTLS, VT, Action: Legal);
280 setOperationAction(Op: ISD::SETCC, VT, Action: Custom);
281 setOperationAction(Op: ISD::MLOAD, VT, Action: Custom);
282 setOperationAction(Op: ISD::MSTORE, VT, Action: Legal);
283 setOperationAction(Op: ISD::CTLZ, VT, Action: Legal);
284 setOperationAction(Op: ISD::CTTZ, VT, Action: Custom);
285 setOperationAction(Op: ISD::BITREVERSE, VT, Action: Legal);
286 setOperationAction(Op: ISD::BSWAP, VT, Action: Legal);
287 setOperationAction(Op: ISD::SADDSAT, VT, Action: Legal);
288 setOperationAction(Op: ISD::UADDSAT, VT, Action: Legal);
289 setOperationAction(Op: ISD::SSUBSAT, VT, Action: Legal);
290 setOperationAction(Op: ISD::USUBSAT, VT, Action: Legal);
291 setOperationAction(Op: ISD::ABDS, VT, Action: Legal);
292 setOperationAction(Op: ISD::ABDU, VT, Action: Legal);
293 setOperationAction(Op: ISD::AVGFLOORS, VT, Action: Legal);
294 setOperationAction(Op: ISD::AVGFLOORU, VT, Action: Legal);
295 setOperationAction(Op: ISD::AVGCEILS, VT, Action: Legal);
296 setOperationAction(Op: ISD::AVGCEILU, VT, Action: Legal);
297
298 // No native support for these.
299 setOperationAction(Op: ISD::UDIV, VT, Action: Expand);
300 setOperationAction(Op: ISD::SDIV, VT, Action: Expand);
301 setOperationAction(Op: ISD::UREM, VT, Action: Expand);
302 setOperationAction(Op: ISD::SREM, VT, Action: Expand);
303 setOperationAction(Op: ISD::UDIVREM, VT, Action: Expand);
304 setOperationAction(Op: ISD::SDIVREM, VT, Action: Expand);
305 setOperationAction(Op: ISD::CTPOP, VT, Action: Expand);
306 setOperationAction(Op: ISD::SELECT, VT, Action: Expand);
307 setOperationAction(Op: ISD::SELECT_CC, VT, Action: Expand);
308
309 // Vector reductions
310 setOperationAction(Op: ISD::VECREDUCE_ADD, VT, Action: Legal);
311 setOperationAction(Op: ISD::VECREDUCE_SMAX, VT, Action: Legal);
312 setOperationAction(Op: ISD::VECREDUCE_UMAX, VT, Action: Legal);
313 setOperationAction(Op: ISD::VECREDUCE_SMIN, VT, Action: Legal);
314 setOperationAction(Op: ISD::VECREDUCE_UMIN, VT, Action: Legal);
315 setOperationAction(Op: ISD::VECREDUCE_MUL, VT, Action: Custom);
316 setOperationAction(Op: ISD::VECREDUCE_AND, VT, Action: Custom);
317 setOperationAction(Op: ISD::VECREDUCE_OR, VT, Action: Custom);
318 setOperationAction(Op: ISD::VECREDUCE_XOR, VT, Action: Custom);
319
320 if (!HasMVEFP) {
321 setOperationAction(Op: ISD::SINT_TO_FP, VT, Action: Expand);
322 setOperationAction(Op: ISD::UINT_TO_FP, VT, Action: Expand);
323 setOperationAction(Op: ISD::FP_TO_SINT, VT, Action: Expand);
324 setOperationAction(Op: ISD::FP_TO_UINT, VT, Action: Expand);
325 } else {
326 setOperationAction(Op: ISD::FP_TO_SINT_SAT, VT, Action: Custom);
327 setOperationAction(Op: ISD::FP_TO_UINT_SAT, VT, Action: Custom);
328 }
329
330 // Pre and Post inc are supported on loads and stores
331 for (unsigned im = (unsigned)ISD::PRE_INC;
332 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
333 setIndexedLoadAction(IdxModes: im, VT, Action: Legal);
334 setIndexedStoreAction(IdxModes: im, VT, Action: Legal);
335 setIndexedMaskedLoadAction(IdxMode: im, VT, Action: Legal);
336 setIndexedMaskedStoreAction(IdxMode: im, VT, Action: Legal);
337 }
338 }
339
340 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
341 for (auto VT : FloatTypes) {
342 addRegisterClass(VT, RC: &ARM::MQPRRegClass);
343 if (!HasMVEFP)
344 setAllExpand(VT);
345
346 // These are legal or custom whether we have MVE.fp or not
347 setOperationAction(Op: ISD::VECTOR_SHUFFLE, VT, Action: Custom);
348 setOperationAction(Op: ISD::INSERT_VECTOR_ELT, VT, Action: Custom);
349 setOperationAction(Op: ISD::INSERT_VECTOR_ELT, VT: VT.getVectorElementType(), Action: Custom);
350 setOperationAction(Op: ISD::EXTRACT_VECTOR_ELT, VT, Action: Custom);
351 setOperationAction(Op: ISD::BUILD_VECTOR, VT, Action: Custom);
352 setOperationAction(Op: ISD::BUILD_VECTOR, VT: VT.getVectorElementType(), Action: Custom);
353 setOperationAction(Op: ISD::SCALAR_TO_VECTOR, VT, Action: Legal);
354 setOperationAction(Op: ISD::SETCC, VT, Action: Custom);
355 setOperationAction(Op: ISD::MLOAD, VT, Action: Custom);
356 setOperationAction(Op: ISD::MSTORE, VT, Action: Legal);
357 setOperationAction(Op: ISD::SELECT, VT, Action: Expand);
358 setOperationAction(Op: ISD::SELECT_CC, VT, Action: Expand);
359
360 // Pre and Post inc are supported on loads and stores
361 for (unsigned im = (unsigned)ISD::PRE_INC;
362 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
363 setIndexedLoadAction(IdxModes: im, VT, Action: Legal);
364 setIndexedStoreAction(IdxModes: im, VT, Action: Legal);
365 setIndexedMaskedLoadAction(IdxMode: im, VT, Action: Legal);
366 setIndexedMaskedStoreAction(IdxMode: im, VT, Action: Legal);
367 }
368
369 if (HasMVEFP) {
370 setOperationAction(Op: ISD::FMINNUM, VT, Action: Legal);
371 setOperationAction(Op: ISD::FMAXNUM, VT, Action: Legal);
372 for (auto Op : {ISD::FROUND, ISD::STRICT_FROUND, ISD::FROUNDEVEN,
373 ISD::STRICT_FROUNDEVEN, ISD::FTRUNC, ISD::STRICT_FTRUNC,
374 ISD::FRINT, ISD::STRICT_FRINT, ISD::FFLOOR,
375 ISD::STRICT_FFLOOR, ISD::FCEIL, ISD::STRICT_FCEIL}) {
376 setOperationAction(Op, VT, Action: Legal);
377 }
378 setOperationAction(Op: ISD::VECREDUCE_FADD, VT, Action: Custom);
379 setOperationAction(Op: ISD::VECREDUCE_FMUL, VT, Action: Custom);
380 setOperationAction(Op: ISD::VECREDUCE_FMIN, VT, Action: Custom);
381 setOperationAction(Op: ISD::VECREDUCE_FMAX, VT, Action: Custom);
382
383 // No native support for these.
384 setOperationAction(Op: ISD::FDIV, VT, Action: Expand);
385 setOperationAction(Op: ISD::FREM, VT, Action: Expand);
386 setOperationAction(Op: ISD::FSQRT, VT, Action: Expand);
387 setOperationAction(Op: ISD::FSIN, VT, Action: Expand);
388 setOperationAction(Op: ISD::FCOS, VT, Action: Expand);
389 setOperationAction(Op: ISD::FTAN, VT, Action: Expand);
390 setOperationAction(Op: ISD::FPOW, VT, Action: Expand);
391 setOperationAction(Op: ISD::FLOG, VT, Action: Expand);
392 setOperationAction(Op: ISD::FLOG2, VT, Action: Expand);
393 setOperationAction(Op: ISD::FLOG10, VT, Action: Expand);
394 setOperationAction(Op: ISD::FEXP, VT, Action: Expand);
395 setOperationAction(Op: ISD::FEXP2, VT, Action: Expand);
396 setOperationAction(Op: ISD::FEXP10, VT, Action: Expand);
397 setOperationAction(Op: ISD::FNEARBYINT, VT, Action: Expand);
398 }
399 }
400
401 // Custom Expand smaller than legal vector reductions to prevent false zero
402 // items being added.
403 setOperationAction(Op: ISD::VECREDUCE_FADD, VT: MVT::v4f16, Action: Custom);
404 setOperationAction(Op: ISD::VECREDUCE_FMUL, VT: MVT::v4f16, Action: Custom);
405 setOperationAction(Op: ISD::VECREDUCE_FMIN, VT: MVT::v4f16, Action: Custom);
406 setOperationAction(Op: ISD::VECREDUCE_FMAX, VT: MVT::v4f16, Action: Custom);
407 setOperationAction(Op: ISD::VECREDUCE_FADD, VT: MVT::v2f16, Action: Custom);
408 setOperationAction(Op: ISD::VECREDUCE_FMUL, VT: MVT::v2f16, Action: Custom);
409 setOperationAction(Op: ISD::VECREDUCE_FMIN, VT: MVT::v2f16, Action: Custom);
410 setOperationAction(Op: ISD::VECREDUCE_FMAX, VT: MVT::v2f16, Action: Custom);
411
412 // We 'support' these types up to bitcast/load/store level, regardless of
413 // MVE integer-only / float support. Only doing FP data processing on the FP
414 // vector types is inhibited at integer-only level.
415 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
416 for (auto VT : LongTypes) {
417 addRegisterClass(VT, RC: &ARM::MQPRRegClass);
418 setAllExpand(VT);
419 setOperationAction(Op: ISD::INSERT_VECTOR_ELT, VT, Action: Custom);
420 setOperationAction(Op: ISD::EXTRACT_VECTOR_ELT, VT, Action: Custom);
421 setOperationAction(Op: ISD::BUILD_VECTOR, VT, Action: Custom);
422 setOperationAction(Op: ISD::VSELECT, VT, Action: Legal);
423 setOperationAction(Op: ISD::VECTOR_SHUFFLE, VT, Action: Custom);
424 }
425 setOperationAction(Op: ISD::SCALAR_TO_VECTOR, VT: MVT::v2f64, Action: Legal);
426
427 // We can do bitwise operations on v2i64 vectors
428 setOperationAction(Op: ISD::AND, VT: MVT::v2i64, Action: Legal);
429 setOperationAction(Op: ISD::OR, VT: MVT::v2i64, Action: Legal);
430 setOperationAction(Op: ISD::XOR, VT: MVT::v2i64, Action: Legal);
431
432 // It is legal to extload from v4i8 to v4i16 or v4i32.
433 addAllExtLoads(From: MVT::v8i16, To: MVT::v8i8, Action: Legal);
434 addAllExtLoads(From: MVT::v4i32, To: MVT::v4i16, Action: Legal);
435 addAllExtLoads(From: MVT::v4i32, To: MVT::v4i8, Action: Legal);
436
437 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
438 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::v4i8, Action: Legal);
439 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::v4i16, Action: Legal);
440 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::v4i32, Action: Legal);
441 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::v8i8, Action: Legal);
442 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::v8i16, Action: Legal);
443
444 // Some truncating stores are legal too.
445 setTruncStoreAction(ValVT: MVT::v4i32, MemVT: MVT::v4i16, Action: Legal);
446 setTruncStoreAction(ValVT: MVT::v4i32, MemVT: MVT::v4i8, Action: Legal);
447 setTruncStoreAction(ValVT: MVT::v8i16, MemVT: MVT::v8i8, Action: Legal);
448
449 // Pre and Post inc on these are legal, given the correct extends
450 for (unsigned im = (unsigned)ISD::PRE_INC;
451 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
452 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
453 setIndexedLoadAction(IdxModes: im, VT, Action: Legal);
454 setIndexedStoreAction(IdxModes: im, VT, Action: Legal);
455 setIndexedMaskedLoadAction(IdxMode: im, VT, Action: Legal);
456 setIndexedMaskedStoreAction(IdxMode: im, VT, Action: Legal);
457 }
458 }
459
460 // Predicate types
461 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1, MVT::v2i1};
462 for (auto VT : pTypes) {
463 addRegisterClass(VT, RC: &ARM::VCCRRegClass);
464 setOperationAction(Op: ISD::BUILD_VECTOR, VT, Action: Custom);
465 setOperationAction(Op: ISD::VECTOR_SHUFFLE, VT, Action: Custom);
466 setOperationAction(Op: ISD::EXTRACT_SUBVECTOR, VT, Action: Custom);
467 setOperationAction(Op: ISD::CONCAT_VECTORS, VT, Action: Custom);
468 setOperationAction(Op: ISD::INSERT_VECTOR_ELT, VT, Action: Custom);
469 setOperationAction(Op: ISD::EXTRACT_VECTOR_ELT, VT, Action: Custom);
470 setOperationAction(Op: ISD::SETCC, VT, Action: Custom);
471 setOperationAction(Op: ISD::SCALAR_TO_VECTOR, VT, Action: Expand);
472 setOperationAction(Op: ISD::LOAD, VT, Action: Custom);
473 setOperationAction(Op: ISD::STORE, VT, Action: Custom);
474 setOperationAction(Op: ISD::TRUNCATE, VT, Action: Custom);
475 setOperationAction(Op: ISD::VSELECT, VT, Action: Expand);
476 setOperationAction(Op: ISD::SELECT, VT, Action: Expand);
477 setOperationAction(Op: ISD::SELECT_CC, VT, Action: Expand);
478
479 if (!HasMVEFP) {
480 setOperationAction(Op: ISD::SINT_TO_FP, VT, Action: Expand);
481 setOperationAction(Op: ISD::UINT_TO_FP, VT, Action: Expand);
482 setOperationAction(Op: ISD::FP_TO_SINT, VT, Action: Expand);
483 setOperationAction(Op: ISD::FP_TO_UINT, VT, Action: Expand);
484 }
485 }
486 setOperationAction(Op: ISD::SETCC, VT: MVT::v2i1, Action: Expand);
487 setOperationAction(Op: ISD::TRUNCATE, VT: MVT::v2i1, Action: Expand);
488 setOperationAction(Op: ISD::AND, VT: MVT::v2i1, Action: Expand);
489 setOperationAction(Op: ISD::OR, VT: MVT::v2i1, Action: Expand);
490 setOperationAction(Op: ISD::XOR, VT: MVT::v2i1, Action: Expand);
491 setOperationAction(Op: ISD::SINT_TO_FP, VT: MVT::v2i1, Action: Expand);
492 setOperationAction(Op: ISD::UINT_TO_FP, VT: MVT::v2i1, Action: Expand);
493 setOperationAction(Op: ISD::FP_TO_SINT, VT: MVT::v2i1, Action: Expand);
494 setOperationAction(Op: ISD::FP_TO_UINT, VT: MVT::v2i1, Action: Expand);
495
496 setOperationAction(Op: ISD::SIGN_EXTEND, VT: MVT::v8i32, Action: Custom);
497 setOperationAction(Op: ISD::SIGN_EXTEND, VT: MVT::v16i16, Action: Custom);
498 setOperationAction(Op: ISD::SIGN_EXTEND, VT: MVT::v16i32, Action: Custom);
499 setOperationAction(Op: ISD::ZERO_EXTEND, VT: MVT::v8i32, Action: Custom);
500 setOperationAction(Op: ISD::ZERO_EXTEND, VT: MVT::v16i16, Action: Custom);
501 setOperationAction(Op: ISD::ZERO_EXTEND, VT: MVT::v16i32, Action: Custom);
502 setOperationAction(Op: ISD::TRUNCATE, VT: MVT::v8i32, Action: Custom);
503 setOperationAction(Op: ISD::TRUNCATE, VT: MVT::v16i16, Action: Custom);
504}
505
506const ARMBaseTargetMachine &ARMTargetLowering::getTM() const {
507 return static_cast<const ARMBaseTargetMachine &>(getTargetMachine());
508}
509
510ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM_,
511 const ARMSubtarget &STI)
512 : TargetLowering(TM_, STI), Subtarget(&STI),
513 RegInfo(Subtarget->getRegisterInfo()),
514 Itins(Subtarget->getInstrItineraryData()) {
515 const auto &TM = static_cast<const ARMBaseTargetMachine &>(TM_);
516
517 setBooleanContents(ZeroOrOneBooleanContent);
518 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
519
520 const Triple &TT = TM.getTargetTriple();
521
522 if (Subtarget->isThumb1Only())
523 addRegisterClass(VT: MVT::i32, RC: &ARM::tGPRRegClass);
524 else
525 addRegisterClass(VT: MVT::i32, RC: &ARM::GPRRegClass);
526
527 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
528 Subtarget->hasFPRegs()) {
529 addRegisterClass(VT: MVT::f32, RC: &ARM::SPRRegClass);
530 addRegisterClass(VT: MVT::f64, RC: &ARM::DPRRegClass);
531
532 setOperationAction(Op: ISD::FP_TO_SINT_SAT, VT: MVT::i32, Action: Custom);
533 setOperationAction(Op: ISD::FP_TO_UINT_SAT, VT: MVT::i32, Action: Custom);
534 setOperationAction(Op: ISD::FP_TO_SINT_SAT, VT: MVT::i64, Action: Custom);
535 setOperationAction(Op: ISD::FP_TO_UINT_SAT, VT: MVT::i64, Action: Custom);
536
537 if (!Subtarget->hasVFP2Base()) {
538 setAllExpand(MVT::f32);
539 } else {
540 for (auto Op : {ISD::STRICT_FADD, ISD::STRICT_FSUB, ISD::STRICT_FMUL,
541 ISD::STRICT_FDIV, ISD::STRICT_FMA, ISD::STRICT_FSQRT})
542 setOperationAction(Op, VT: MVT::f32, Action: Legal);
543 }
544 if (!Subtarget->hasFP64()) {
545 setAllExpand(MVT::f64);
546 } else {
547 for (auto Op : {ISD::STRICT_FADD, ISD::STRICT_FSUB, ISD::STRICT_FMUL,
548 ISD::STRICT_FDIV, ISD::STRICT_FMA, ISD::STRICT_FSQRT})
549 setOperationAction(Op, VT: MVT::f64, Action: Legal);
550
551 setOperationAction(Op: ISD::STRICT_FP_ROUND, VT: MVT::f32, Action: Legal);
552 }
553 }
554
555 if (Subtarget->hasFullFP16()) {
556 for (auto Op : {ISD::STRICT_FADD, ISD::STRICT_FSUB, ISD::STRICT_FMUL,
557 ISD::STRICT_FDIV, ISD::STRICT_FMA, ISD::STRICT_FSQRT})
558 setOperationAction(Op, VT: MVT::f16, Action: Legal);
559
560 addRegisterClass(VT: MVT::f16, RC: &ARM::HPRRegClass);
561 setOperationAction(Op: ISD::BITCAST, VT: MVT::i16, Action: Custom);
562 setOperationAction(Op: ISD::BITCAST, VT: MVT::f16, Action: Custom);
563
564 setOperationAction(Op: ISD::FMINNUM, VT: MVT::f16, Action: Legal);
565 setOperationAction(Op: ISD::FMAXNUM, VT: MVT::f16, Action: Legal);
566 setOperationAction(Op: ISD::STRICT_FMINNUM, VT: MVT::f16, Action: Legal);
567 setOperationAction(Op: ISD::STRICT_FMAXNUM, VT: MVT::f16, Action: Legal);
568 }
569
570 if (Subtarget->hasBF16()) {
571 addRegisterClass(VT: MVT::bf16, RC: &ARM::HPRRegClass);
572 setAllExpand(MVT::bf16);
573 if (!Subtarget->hasFullFP16())
574 setOperationAction(Op: ISD::BITCAST, VT: MVT::bf16, Action: Custom);
575 } else {
576 setOperationAction(Op: ISD::BF16_TO_FP, VT: MVT::f32, Action: Expand);
577 setOperationAction(Op: ISD::BF16_TO_FP, VT: MVT::f64, Action: Expand);
578 setOperationAction(Op: ISD::FP_TO_BF16, VT: MVT::f32, Action: Custom);
579 setOperationAction(Op: ISD::FP_TO_BF16, VT: MVT::f64, Action: Custom);
580 }
581
582 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
583 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
584 setTruncStoreAction(ValVT: VT, MemVT: InnerVT, Action: Expand);
585 addAllExtLoads(From: VT, To: InnerVT, Action: Expand);
586 }
587
588 setOperationAction(Op: ISD::SMUL_LOHI, VT, Action: Expand);
589 setOperationAction(Op: ISD::UMUL_LOHI, VT, Action: Expand);
590
591 setOperationAction(Op: ISD::BSWAP, VT, Action: Expand);
592 }
593
594 if (!Subtarget->isThumb1Only() && !Subtarget->hasV8_1MMainlineOps())
595 setOperationAction(Op: ISD::SCMP, VT: MVT::i32, Action: Custom);
596
597 if (!Subtarget->hasV8_1MMainlineOps())
598 setOperationAction(Op: ISD::UCMP, VT: MVT::i32, Action: Custom);
599
600 if (!Subtarget->isThumb1Only())
601 setOperationAction(Op: ISD::ABS, VT: MVT::i32, Action: Custom);
602
603 setOperationAction(Op: ISD::ConstantFP, VT: MVT::f32, Action: Custom);
604 setOperationAction(Op: ISD::ConstantFP, VT: MVT::f64, Action: Custom);
605
606 setOperationAction(Op: ISD::READ_REGISTER, VT: MVT::i64, Action: Custom);
607 setOperationAction(Op: ISD::WRITE_REGISTER, VT: MVT::i64, Action: Custom);
608
609 if (Subtarget->hasMVEIntegerOps())
610 addMVEVectorTypes(HasMVEFP: Subtarget->hasMVEFloatOps());
611
612 // Combine low-overhead loop intrinsics so that we can lower i1 types.
613 if (Subtarget->hasLOB()) {
614 setTargetDAGCombine({ISD::BRCOND, ISD::BR_CC});
615 }
616
617 if (Subtarget->hasNEON()) {
618 addDRTypeForNEON(VT: MVT::v2f32);
619 addDRTypeForNEON(VT: MVT::v8i8);
620 addDRTypeForNEON(VT: MVT::v4i16);
621 addDRTypeForNEON(VT: MVT::v2i32);
622 addDRTypeForNEON(VT: MVT::v1i64);
623
624 addQRTypeForNEON(VT: MVT::v4f32);
625 addQRTypeForNEON(VT: MVT::v2f64);
626 addQRTypeForNEON(VT: MVT::v16i8);
627 addQRTypeForNEON(VT: MVT::v8i16);
628 addQRTypeForNEON(VT: MVT::v4i32);
629 addQRTypeForNEON(VT: MVT::v2i64);
630
631 if (Subtarget->hasFullFP16()) {
632 addQRTypeForNEON(VT: MVT::v8f16);
633 addDRTypeForNEON(VT: MVT::v4f16);
634 }
635
636 if (Subtarget->hasBF16()) {
637 addQRTypeForNEON(VT: MVT::v8bf16);
638 addDRTypeForNEON(VT: MVT::v4bf16);
639 }
640 }
641
642 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
643 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
644 // none of Neon, MVE or VFP supports any arithmetic operations on it.
645 setOperationAction(Op: ISD::FADD, VT: MVT::v2f64, Action: Expand);
646 setOperationAction(Op: ISD::FSUB, VT: MVT::v2f64, Action: Expand);
647 setOperationAction(Op: ISD::FMUL, VT: MVT::v2f64, Action: Expand);
648 // FIXME: Code duplication: FDIV and FREM are expanded always, see
649 // ARMTargetLowering::addTypeForNEON method for details.
650 setOperationAction(Op: ISD::FDIV, VT: MVT::v2f64, Action: Expand);
651 setOperationAction(Op: ISD::FREM, VT: MVT::v2f64, Action: Expand);
652 // FIXME: Create unittest.
653 // In another words, find a way when "copysign" appears in DAG with vector
654 // operands.
655 setOperationAction(Op: ISD::FCOPYSIGN, VT: MVT::v2f64, Action: Expand);
656 // FIXME: Code duplication: SETCC has custom operation action, see
657 // ARMTargetLowering::addTypeForNEON method for details.
658 setOperationAction(Op: ISD::SETCC, VT: MVT::v2f64, Action: Expand);
659 // FIXME: Create unittest for FNEG and for FABS.
660 setOperationAction(Op: ISD::FNEG, VT: MVT::v2f64, Action: Expand);
661 setOperationAction(Op: ISD::FABS, VT: MVT::v2f64, Action: Expand);
662 setOperationAction(Op: ISD::FSQRT, VT: MVT::v2f64, Action: Expand);
663 setOperationAction(Op: ISD::FSIN, VT: MVT::v2f64, Action: Expand);
664 setOperationAction(Op: ISD::FCOS, VT: MVT::v2f64, Action: Expand);
665 setOperationAction(Op: ISD::FTAN, VT: MVT::v2f64, Action: Expand);
666 setOperationAction(Op: ISD::FPOW, VT: MVT::v2f64, Action: Expand);
667 setOperationAction(Op: ISD::FLOG, VT: MVT::v2f64, Action: Expand);
668 setOperationAction(Op: ISD::FLOG2, VT: MVT::v2f64, Action: Expand);
669 setOperationAction(Op: ISD::FLOG10, VT: MVT::v2f64, Action: Expand);
670 setOperationAction(Op: ISD::FEXP, VT: MVT::v2f64, Action: Expand);
671 setOperationAction(Op: ISD::FEXP2, VT: MVT::v2f64, Action: Expand);
672 setOperationAction(Op: ISD::FEXP10, VT: MVT::v2f64, Action: Expand);
673 setOperationAction(Op: ISD::FCEIL, VT: MVT::v2f64, Action: Expand);
674 setOperationAction(Op: ISD::FTRUNC, VT: MVT::v2f64, Action: Expand);
675 setOperationAction(Op: ISD::FRINT, VT: MVT::v2f64, Action: Expand);
676 setOperationAction(Op: ISD::FROUNDEVEN, VT: MVT::v2f64, Action: Expand);
677 setOperationAction(Op: ISD::FNEARBYINT, VT: MVT::v2f64, Action: Expand);
678 setOperationAction(Op: ISD::FFLOOR, VT: MVT::v2f64, Action: Expand);
679 setOperationAction(Op: ISD::FMA, VT: MVT::v2f64, Action: Expand);
680 }
681
682 if (Subtarget->hasNEON()) {
683 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
684 // supported for v4f32.
685 setOperationAction(Op: ISD::FSQRT, VT: MVT::v4f32, Action: Expand);
686 setOperationAction(Op: ISD::FSIN, VT: MVT::v4f32, Action: Expand);
687 setOperationAction(Op: ISD::FCOS, VT: MVT::v4f32, Action: Expand);
688 setOperationAction(Op: ISD::FTAN, VT: MVT::v4f32, Action: Expand);
689 setOperationAction(Op: ISD::FPOW, VT: MVT::v4f32, Action: Expand);
690 setOperationAction(Op: ISD::FLOG, VT: MVT::v4f32, Action: Expand);
691 setOperationAction(Op: ISD::FLOG2, VT: MVT::v4f32, Action: Expand);
692 setOperationAction(Op: ISD::FLOG10, VT: MVT::v4f32, Action: Expand);
693 setOperationAction(Op: ISD::FEXP, VT: MVT::v4f32, Action: Expand);
694 setOperationAction(Op: ISD::FEXP2, VT: MVT::v4f32, Action: Expand);
695 setOperationAction(Op: ISD::FEXP10, VT: MVT::v4f32, Action: Expand);
696 setOperationAction(Op: ISD::FCEIL, VT: MVT::v4f32, Action: Expand);
697 setOperationAction(Op: ISD::FTRUNC, VT: MVT::v4f32, Action: Expand);
698 setOperationAction(Op: ISD::FRINT, VT: MVT::v4f32, Action: Expand);
699 setOperationAction(Op: ISD::FROUNDEVEN, VT: MVT::v4f32, Action: Expand);
700 setOperationAction(Op: ISD::FNEARBYINT, VT: MVT::v4f32, Action: Expand);
701 setOperationAction(Op: ISD::FFLOOR, VT: MVT::v4f32, Action: Expand);
702
703 // Mark v2f32 intrinsics.
704 setOperationAction(Op: ISD::FSQRT, VT: MVT::v2f32, Action: Expand);
705 setOperationAction(Op: ISD::FSIN, VT: MVT::v2f32, Action: Expand);
706 setOperationAction(Op: ISD::FCOS, VT: MVT::v2f32, Action: Expand);
707 setOperationAction(Op: ISD::FTAN, VT: MVT::v2f32, Action: Expand);
708 setOperationAction(Op: ISD::FPOW, VT: MVT::v2f32, Action: Expand);
709 setOperationAction(Op: ISD::FLOG, VT: MVT::v2f32, Action: Expand);
710 setOperationAction(Op: ISD::FLOG2, VT: MVT::v2f32, Action: Expand);
711 setOperationAction(Op: ISD::FLOG10, VT: MVT::v2f32, Action: Expand);
712 setOperationAction(Op: ISD::FEXP, VT: MVT::v2f32, Action: Expand);
713 setOperationAction(Op: ISD::FEXP2, VT: MVT::v2f32, Action: Expand);
714 setOperationAction(Op: ISD::FEXP10, VT: MVT::v2f32, Action: Expand);
715 setOperationAction(Op: ISD::FCEIL, VT: MVT::v2f32, Action: Expand);
716 setOperationAction(Op: ISD::FTRUNC, VT: MVT::v2f32, Action: Expand);
717 setOperationAction(Op: ISD::FRINT, VT: MVT::v2f32, Action: Expand);
718 setOperationAction(Op: ISD::FROUNDEVEN, VT: MVT::v2f32, Action: Expand);
719 setOperationAction(Op: ISD::FNEARBYINT, VT: MVT::v2f32, Action: Expand);
720 setOperationAction(Op: ISD::FFLOOR, VT: MVT::v2f32, Action: Expand);
721
722 for (ISD::NodeType Op : {ISD::FFLOOR, ISD::FNEARBYINT, ISD::FCEIL,
723 ISD::FRINT, ISD::FTRUNC, ISD::FROUNDEVEN}) {
724 setOperationAction(Op, VT: MVT::v4f16, Action: Expand);
725 setOperationAction(Op, VT: MVT::v8f16, Action: Expand);
726 }
727
728 // Neon does not support some operations on v1i64 and v2i64 types.
729 setOperationAction(Op: ISD::MUL, VT: MVT::v1i64, Action: Expand);
730 // Custom handling for some quad-vector types to detect VMULL.
731 setOperationAction(Op: ISD::MUL, VT: MVT::v8i16, Action: Custom);
732 setOperationAction(Op: ISD::MUL, VT: MVT::v4i32, Action: Custom);
733 setOperationAction(Op: ISD::MUL, VT: MVT::v2i64, Action: Custom);
734 // Custom handling for some vector types to avoid expensive expansions
735 setOperationAction(Op: ISD::SDIV, VT: MVT::v4i16, Action: Custom);
736 setOperationAction(Op: ISD::SDIV, VT: MVT::v8i8, Action: Custom);
737 setOperationAction(Op: ISD::UDIV, VT: MVT::v4i16, Action: Custom);
738 setOperationAction(Op: ISD::UDIV, VT: MVT::v8i8, Action: Custom);
739 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
740 // a destination type that is wider than the source, and nor does
741 // it have a FP_TO_[SU]INT instruction with a narrower destination than
742 // source.
743 setOperationAction(Op: ISD::SINT_TO_FP, VT: MVT::v4i16, Action: Custom);
744 setOperationAction(Op: ISD::SINT_TO_FP, VT: MVT::v8i16, Action: Custom);
745 setOperationAction(Op: ISD::UINT_TO_FP, VT: MVT::v4i16, Action: Custom);
746 setOperationAction(Op: ISD::UINT_TO_FP, VT: MVT::v8i16, Action: Custom);
747 setOperationAction(Op: ISD::FP_TO_UINT, VT: MVT::v4i16, Action: Custom);
748 setOperationAction(Op: ISD::FP_TO_UINT, VT: MVT::v8i16, Action: Custom);
749 setOperationAction(Op: ISD::FP_TO_SINT, VT: MVT::v4i16, Action: Custom);
750 setOperationAction(Op: ISD::FP_TO_SINT, VT: MVT::v8i16, Action: Custom);
751
752 setOperationAction(Op: ISD::FP_ROUND, VT: MVT::v2f32, Action: Expand);
753 setOperationAction(Op: ISD::FP_EXTEND, VT: MVT::v2f64, Action: Expand);
754
755 // NEON does not have single instruction CTPOP for vectors with element
756 // types wider than 8-bits. However, custom lowering can leverage the
757 // v8i8/v16i8 vcnt instruction.
758 setOperationAction(Op: ISD::CTPOP, VT: MVT::v2i32, Action: Custom);
759 setOperationAction(Op: ISD::CTPOP, VT: MVT::v4i32, Action: Custom);
760 setOperationAction(Op: ISD::CTPOP, VT: MVT::v4i16, Action: Custom);
761 setOperationAction(Op: ISD::CTPOP, VT: MVT::v8i16, Action: Custom);
762 setOperationAction(Op: ISD::CTPOP, VT: MVT::v1i64, Action: Custom);
763 setOperationAction(Op: ISD::CTPOP, VT: MVT::v2i64, Action: Custom);
764
765 setOperationAction(Op: ISD::CTLZ, VT: MVT::v1i64, Action: Expand);
766 setOperationAction(Op: ISD::CTLZ, VT: MVT::v2i64, Action: Expand);
767
768 // NEON does not have single instruction CTTZ for vectors.
769 setOperationAction(Op: ISD::CTTZ, VT: MVT::v8i8, Action: Custom);
770 setOperationAction(Op: ISD::CTTZ, VT: MVT::v4i16, Action: Custom);
771 setOperationAction(Op: ISD::CTTZ, VT: MVT::v2i32, Action: Custom);
772 setOperationAction(Op: ISD::CTTZ, VT: MVT::v1i64, Action: Custom);
773
774 setOperationAction(Op: ISD::CTTZ, VT: MVT::v16i8, Action: Custom);
775 setOperationAction(Op: ISD::CTTZ, VT: MVT::v8i16, Action: Custom);
776 setOperationAction(Op: ISD::CTTZ, VT: MVT::v4i32, Action: Custom);
777 setOperationAction(Op: ISD::CTTZ, VT: MVT::v2i64, Action: Custom);
778
779 setOperationAction(Op: ISD::CTTZ_ZERO_UNDEF, VT: MVT::v8i8, Action: Custom);
780 setOperationAction(Op: ISD::CTTZ_ZERO_UNDEF, VT: MVT::v4i16, Action: Custom);
781 setOperationAction(Op: ISD::CTTZ_ZERO_UNDEF, VT: MVT::v2i32, Action: Custom);
782 setOperationAction(Op: ISD::CTTZ_ZERO_UNDEF, VT: MVT::v1i64, Action: Custom);
783
784 setOperationAction(Op: ISD::CTTZ_ZERO_UNDEF, VT: MVT::v16i8, Action: Custom);
785 setOperationAction(Op: ISD::CTTZ_ZERO_UNDEF, VT: MVT::v8i16, Action: Custom);
786 setOperationAction(Op: ISD::CTTZ_ZERO_UNDEF, VT: MVT::v4i32, Action: Custom);
787 setOperationAction(Op: ISD::CTTZ_ZERO_UNDEF, VT: MVT::v2i64, Action: Custom);
788
789 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
790 setOperationAction(Op: ISD::MULHS, VT, Action: Expand);
791 setOperationAction(Op: ISD::MULHU, VT, Action: Expand);
792 }
793
794 // NEON only has FMA instructions as of VFP4.
795 if (!Subtarget->hasVFP4Base()) {
796 setOperationAction(Op: ISD::FMA, VT: MVT::v2f32, Action: Expand);
797 setOperationAction(Op: ISD::FMA, VT: MVT::v4f32, Action: Expand);
798 }
799
800 setTargetDAGCombine({ISD::SHL, ISD::SRL, ISD::SRA, ISD::FP_TO_SINT,
801 ISD::FP_TO_UINT, ISD::FMUL, ISD::LOAD});
802
803 // It is legal to extload from v4i8 to v4i16 or v4i32.
804 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
805 MVT::v2i32}) {
806 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
807 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT: VT, MemVT: Ty, Action: Legal);
808 setLoadExtAction(ExtType: ISD::ZEXTLOAD, ValVT: VT, MemVT: Ty, Action: Legal);
809 setLoadExtAction(ExtType: ISD::SEXTLOAD, ValVT: VT, MemVT: Ty, Action: Legal);
810 }
811 }
812
813 for (auto VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
814 MVT::v4i32}) {
815 setOperationAction(Op: ISD::VECREDUCE_SMAX, VT, Action: Custom);
816 setOperationAction(Op: ISD::VECREDUCE_UMAX, VT, Action: Custom);
817 setOperationAction(Op: ISD::VECREDUCE_SMIN, VT, Action: Custom);
818 setOperationAction(Op: ISD::VECREDUCE_UMIN, VT, Action: Custom);
819 }
820 }
821
822 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
823 setTargetDAGCombine(
824 {ISD::BUILD_VECTOR, ISD::VECTOR_SHUFFLE, ISD::INSERT_SUBVECTOR,
825 ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
826 ISD::SIGN_EXTEND_INREG, ISD::STORE, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND,
827 ISD::ANY_EXTEND, ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN,
828 ISD::INTRINSIC_VOID, ISD::VECREDUCE_ADD, ISD::ADD, ISD::BITCAST});
829 }
830 if (Subtarget->hasMVEIntegerOps()) {
831 setTargetDAGCombine({ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX,
832 ISD::FP_EXTEND, ISD::SELECT, ISD::SELECT_CC,
833 ISD::SETCC});
834 }
835 if (Subtarget->hasMVEFloatOps()) {
836 setTargetDAGCombine(ISD::FADD);
837 }
838
839 if (!Subtarget->hasFP64()) {
840 // When targeting a floating-point unit with only single-precision
841 // operations, f64 is legal for the few double-precision instructions which
842 // are present However, no double-precision operations other than moves,
843 // loads and stores are provided by the hardware.
844 setOperationAction(Op: ISD::FADD, VT: MVT::f64, Action: Expand);
845 setOperationAction(Op: ISD::FSUB, VT: MVT::f64, Action: Expand);
846 setOperationAction(Op: ISD::FMUL, VT: MVT::f64, Action: Expand);
847 setOperationAction(Op: ISD::FMA, VT: MVT::f64, Action: Expand);
848 setOperationAction(Op: ISD::FDIV, VT: MVT::f64, Action: Expand);
849 setOperationAction(Op: ISD::FREM, VT: MVT::f64, Action: LibCall);
850 setOperationAction(Op: ISD::FCOPYSIGN, VT: MVT::f64, Action: Expand);
851 setOperationAction(Op: ISD::FGETSIGN, VT: MVT::f64, Action: Expand);
852 setOperationAction(Op: ISD::FNEG, VT: MVT::f64, Action: Expand);
853 setOperationAction(Op: ISD::FABS, VT: MVT::f64, Action: Expand);
854 setOperationAction(Op: ISD::FSQRT, VT: MVT::f64, Action: Expand);
855 setOperationAction(Op: ISD::FSIN, VT: MVT::f64, Action: Expand);
856 setOperationAction(Op: ISD::FCOS, VT: MVT::f64, Action: Expand);
857 setOperationAction(Op: ISD::FPOW, VT: MVT::f64, Action: Expand);
858 setOperationAction(Op: ISD::FLOG, VT: MVT::f64, Action: Expand);
859 setOperationAction(Op: ISD::FLOG2, VT: MVT::f64, Action: Expand);
860 setOperationAction(Op: ISD::FLOG10, VT: MVT::f64, Action: Expand);
861 setOperationAction(Op: ISD::FEXP, VT: MVT::f64, Action: Expand);
862 setOperationAction(Op: ISD::FEXP2, VT: MVT::f64, Action: Expand);
863 setOperationAction(Op: ISD::FEXP10, VT: MVT::f64, Action: Expand);
864 setOperationAction(Op: ISD::FCEIL, VT: MVT::f64, Action: Expand);
865 setOperationAction(Op: ISD::FTRUNC, VT: MVT::f64, Action: Expand);
866 setOperationAction(Op: ISD::FRINT, VT: MVT::f64, Action: Expand);
867 setOperationAction(Op: ISD::FROUNDEVEN, VT: MVT::f64, Action: Expand);
868 setOperationAction(Op: ISD::FNEARBYINT, VT: MVT::f64, Action: Expand);
869 setOperationAction(Op: ISD::FFLOOR, VT: MVT::f64, Action: Expand);
870 setOperationAction(Op: ISD::SINT_TO_FP, VT: MVT::i32, Action: Custom);
871 setOperationAction(Op: ISD::UINT_TO_FP, VT: MVT::i32, Action: Custom);
872 setOperationAction(Op: ISD::FP_TO_SINT, VT: MVT::i32, Action: Custom);
873 setOperationAction(Op: ISD::FP_TO_UINT, VT: MVT::i32, Action: Custom);
874 setOperationAction(Op: ISD::FP_TO_SINT, VT: MVT::f64, Action: Custom);
875 setOperationAction(Op: ISD::FP_TO_UINT, VT: MVT::f64, Action: Custom);
876 setOperationAction(Op: ISD::FP_ROUND, VT: MVT::f32, Action: Custom);
877 setOperationAction(Op: ISD::STRICT_FP_TO_SINT, VT: MVT::f64, Action: Custom);
878 setOperationAction(Op: ISD::STRICT_FP_TO_UINT, VT: MVT::f64, Action: Custom);
879 setOperationAction(Op: ISD::STRICT_FP_ROUND, VT: MVT::f32, Action: Custom);
880 }
881
882 setOperationAction(Op: ISD::STRICT_FP_TO_SINT, VT: MVT::i32, Action: Custom);
883 setOperationAction(Op: ISD::STRICT_FP_TO_UINT, VT: MVT::i32, Action: Custom);
884
885 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
886 setOperationAction(Op: ISD::FP_EXTEND, VT: MVT::f64, Action: Custom);
887 setOperationAction(Op: ISD::STRICT_FP_EXTEND, VT: MVT::f64, Action: Custom);
888 if (Subtarget->hasFullFP16()) {
889 setOperationAction(Op: ISD::FP_ROUND, VT: MVT::f16, Action: Custom);
890 setOperationAction(Op: ISD::STRICT_FP_ROUND, VT: MVT::f16, Action: Custom);
891 }
892 } else {
893 setOperationAction(Op: ISD::STRICT_FP_EXTEND, VT: MVT::f64, Action: Legal);
894 }
895
896 if (!Subtarget->hasFP16()) {
897 setOperationAction(Op: ISD::FP_EXTEND, VT: MVT::f32, Action: Custom);
898 setOperationAction(Op: ISD::STRICT_FP_EXTEND, VT: MVT::f32, Action: Custom);
899 } else {
900 setOperationAction(Op: ISD::STRICT_FP_EXTEND, VT: MVT::f32, Action: Legal);
901 setOperationAction(Op: ISD::STRICT_FP_ROUND, VT: MVT::f16, Action: Legal);
902 }
903
904 computeRegisterProperties(TRI: Subtarget->getRegisterInfo());
905
906 // ARM does not have floating-point extending loads.
907 for (MVT VT : MVT::fp_valuetypes()) {
908 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT: VT, MemVT: MVT::f32, Action: Expand);
909 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT: VT, MemVT: MVT::f16, Action: Expand);
910 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT: VT, MemVT: MVT::bf16, Action: Expand);
911 }
912
913 // ... or truncating stores
914 setTruncStoreAction(ValVT: MVT::f64, MemVT: MVT::f32, Action: Expand);
915 setTruncStoreAction(ValVT: MVT::f32, MemVT: MVT::f16, Action: Expand);
916 setTruncStoreAction(ValVT: MVT::f64, MemVT: MVT::f16, Action: Expand);
917 setTruncStoreAction(ValVT: MVT::f32, MemVT: MVT::bf16, Action: Expand);
918 setTruncStoreAction(ValVT: MVT::f64, MemVT: MVT::bf16, Action: Expand);
919
920 // ARM does not have i1 sign extending load.
921 for (MVT VT : MVT::integer_valuetypes())
922 setLoadExtAction(ExtType: ISD::SEXTLOAD, ValVT: VT, MemVT: MVT::i1, Action: Promote);
923
924 // ARM supports all 4 flavors of integer indexed load / store.
925 if (!Subtarget->isThumb1Only()) {
926 for (unsigned im = (unsigned)ISD::PRE_INC;
927 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
928 setIndexedLoadAction(IdxModes: im, VT: MVT::i1, Action: Legal);
929 setIndexedLoadAction(IdxModes: im, VT: MVT::i8, Action: Legal);
930 setIndexedLoadAction(IdxModes: im, VT: MVT::i16, Action: Legal);
931 setIndexedLoadAction(IdxModes: im, VT: MVT::i32, Action: Legal);
932 setIndexedStoreAction(IdxModes: im, VT: MVT::i1, Action: Legal);
933 setIndexedStoreAction(IdxModes: im, VT: MVT::i8, Action: Legal);
934 setIndexedStoreAction(IdxModes: im, VT: MVT::i16, Action: Legal);
935 setIndexedStoreAction(IdxModes: im, VT: MVT::i32, Action: Legal);
936 }
937 } else {
938 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
939 setIndexedLoadAction(IdxModes: ISD::POST_INC, VT: MVT::i32, Action: Legal);
940 setIndexedStoreAction(IdxModes: ISD::POST_INC, VT: MVT::i32, Action: Legal);
941 }
942
943 // Custom loads/stores to possible use __aeabi_uread/write*
944 if (TT.isTargetAEABI() && !Subtarget->allowsUnalignedMem()) {
945 setOperationAction(Op: ISD::STORE, VT: MVT::i32, Action: Custom);
946 setOperationAction(Op: ISD::STORE, VT: MVT::i64, Action: Custom);
947 setOperationAction(Op: ISD::LOAD, VT: MVT::i32, Action: Custom);
948 setOperationAction(Op: ISD::LOAD, VT: MVT::i64, Action: Custom);
949 }
950
951 setOperationAction(Op: ISD::SADDO, VT: MVT::i32, Action: Custom);
952 setOperationAction(Op: ISD::UADDO, VT: MVT::i32, Action: Custom);
953 setOperationAction(Op: ISD::SSUBO, VT: MVT::i32, Action: Custom);
954 setOperationAction(Op: ISD::USUBO, VT: MVT::i32, Action: Custom);
955
956 if (!Subtarget->isThumb1Only()) {
957 setOperationAction(Op: ISD::UMULO, VT: MVT::i32, Action: Custom);
958 setOperationAction(Op: ISD::SMULO, VT: MVT::i32, Action: Custom);
959 }
960
961 setOperationAction(Op: ISD::UADDO_CARRY, VT: MVT::i32, Action: Custom);
962 setOperationAction(Op: ISD::USUBO_CARRY, VT: MVT::i32, Action: Custom);
963 if (Subtarget->hasDSP()) {
964 setOperationAction(Op: ISD::SADDSAT, VT: MVT::i8, Action: Custom);
965 setOperationAction(Op: ISD::SSUBSAT, VT: MVT::i8, Action: Custom);
966 setOperationAction(Op: ISD::SADDSAT, VT: MVT::i16, Action: Custom);
967 setOperationAction(Op: ISD::SSUBSAT, VT: MVT::i16, Action: Custom);
968 setOperationAction(Op: ISD::UADDSAT, VT: MVT::i8, Action: Custom);
969 setOperationAction(Op: ISD::USUBSAT, VT: MVT::i8, Action: Custom);
970 setOperationAction(Op: ISD::UADDSAT, VT: MVT::i16, Action: Custom);
971 setOperationAction(Op: ISD::USUBSAT, VT: MVT::i16, Action: Custom);
972 }
973 if (Subtarget->hasBaseDSP()) {
974 setOperationAction(Op: ISD::SADDSAT, VT: MVT::i32, Action: Legal);
975 setOperationAction(Op: ISD::SSUBSAT, VT: MVT::i32, Action: Legal);
976 }
977
978 // i64 operation support.
979 setOperationAction(Op: ISD::MUL, VT: MVT::i64, Action: Expand);
980 setOperationAction(Op: ISD::MULHU, VT: MVT::i32, Action: Expand);
981 if (Subtarget->isThumb1Only()) {
982 setOperationAction(Op: ISD::UMUL_LOHI, VT: MVT::i32, Action: Expand);
983 setOperationAction(Op: ISD::SMUL_LOHI, VT: MVT::i32, Action: Expand);
984 }
985 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
986 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
987 setOperationAction(Op: ISD::MULHS, VT: MVT::i32, Action: Expand);
988
989 setOperationAction(Op: ISD::SHL_PARTS, VT: MVT::i32, Action: Custom);
990 setOperationAction(Op: ISD::SRA_PARTS, VT: MVT::i32, Action: Custom);
991 setOperationAction(Op: ISD::SRL_PARTS, VT: MVT::i32, Action: Custom);
992 setOperationAction(Op: ISD::SRL, VT: MVT::i64, Action: Custom);
993 setOperationAction(Op: ISD::SRA, VT: MVT::i64, Action: Custom);
994 setOperationAction(Op: ISD::INTRINSIC_VOID, VT: MVT::Other, Action: Custom);
995 setOperationAction(Op: ISD::INTRINSIC_WO_CHAIN, VT: MVT::i64, Action: Custom);
996 setOperationAction(Op: ISD::LOAD, VT: MVT::i64, Action: Custom);
997 setOperationAction(Op: ISD::STORE, VT: MVT::i64, Action: Custom);
998
999 // MVE lowers 64 bit shifts to lsll and lsrl
1000 // assuming that ISD::SRL and SRA of i64 are already marked custom
1001 if (Subtarget->hasMVEIntegerOps())
1002 setOperationAction(Op: ISD::SHL, VT: MVT::i64, Action: Custom);
1003
1004 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1005 if (Subtarget->isThumb1Only()) {
1006 setOperationAction(Op: ISD::SHL_PARTS, VT: MVT::i32, Action: Expand);
1007 setOperationAction(Op: ISD::SRA_PARTS, VT: MVT::i32, Action: Expand);
1008 setOperationAction(Op: ISD::SRL_PARTS, VT: MVT::i32, Action: Expand);
1009 }
1010
1011 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1012 setOperationAction(Op: ISD::BITREVERSE, VT: MVT::i32, Action: Legal);
1013
1014 // ARM does not have ROTL.
1015 setOperationAction(Op: ISD::ROTL, VT: MVT::i32, Action: Expand);
1016 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1017 setOperationAction(Op: ISD::ROTL, VT, Action: Expand);
1018 setOperationAction(Op: ISD::ROTR, VT, Action: Expand);
1019 }
1020 setOperationAction(Op: ISD::CTTZ, VT: MVT::i32, Action: Custom);
1021 // TODO: These two should be set to LibCall, but this currently breaks
1022 // the Linux kernel build. See #101786.
1023 setOperationAction(Op: ISD::CTPOP, VT: MVT::i32, Action: Expand);
1024 setOperationAction(Op: ISD::CTPOP, VT: MVT::i64, Action: Expand);
1025 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1026 setOperationAction(Op: ISD::CTLZ, VT: MVT::i32, Action: Expand);
1027 setOperationAction(Op: ISD::CTLZ_ZERO_UNDEF, VT: MVT::i32, Action: LibCall);
1028 }
1029
1030 // @llvm.readcyclecounter requires the Performance Monitors extension.
1031 // Default to the 0 expansion on unsupported platforms.
1032 // FIXME: Technically there are older ARM CPUs that have
1033 // implementation-specific ways of obtaining this information.
1034 if (Subtarget->hasPerfMon())
1035 setOperationAction(Op: ISD::READCYCLECOUNTER, VT: MVT::i64, Action: Custom);
1036
1037 // Only ARMv6 has BSWAP.
1038 if (!Subtarget->hasV6Ops())
1039 setOperationAction(Op: ISD::BSWAP, VT: MVT::i32, Action: Expand);
1040
1041 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1042 : Subtarget->hasDivideInARMMode();
1043 if (!hasDivide) {
1044 // These are expanded into libcalls if the cpu doesn't have HW divider.
1045 setOperationAction(Op: ISD::SDIV, VT: MVT::i32, Action: LibCall);
1046 setOperationAction(Op: ISD::UDIV, VT: MVT::i32, Action: LibCall);
1047 }
1048
1049 if (TT.isOSWindows() && !Subtarget->hasDivideInThumbMode()) {
1050 setOperationAction(Op: ISD::SDIV, VT: MVT::i32, Action: Custom);
1051 setOperationAction(Op: ISD::UDIV, VT: MVT::i32, Action: Custom);
1052
1053 setOperationAction(Op: ISD::SDIV, VT: MVT::i64, Action: Custom);
1054 setOperationAction(Op: ISD::UDIV, VT: MVT::i64, Action: Custom);
1055 }
1056
1057 setOperationAction(Op: ISD::SREM, VT: MVT::i32, Action: Expand);
1058 setOperationAction(Op: ISD::UREM, VT: MVT::i32, Action: Expand);
1059
1060 // Register based DivRem for AEABI (RTABI 4.2)
1061 if (TT.isTargetAEABI() || TT.isAndroid() || TT.isTargetGNUAEABI() ||
1062 TT.isTargetMuslAEABI() || TT.isOSFuchsia() || TT.isOSWindows()) {
1063 setOperationAction(Op: ISD::SREM, VT: MVT::i64, Action: Custom);
1064 setOperationAction(Op: ISD::UREM, VT: MVT::i64, Action: Custom);
1065 HasStandaloneRem = false;
1066
1067 setOperationAction(Op: ISD::SDIVREM, VT: MVT::i32, Action: Custom);
1068 setOperationAction(Op: ISD::UDIVREM, VT: MVT::i32, Action: Custom);
1069 setOperationAction(Op: ISD::SDIVREM, VT: MVT::i64, Action: Custom);
1070 setOperationAction(Op: ISD::UDIVREM, VT: MVT::i64, Action: Custom);
1071 } else {
1072 setOperationAction(Op: ISD::SDIVREM, VT: MVT::i32, Action: Expand);
1073 setOperationAction(Op: ISD::UDIVREM, VT: MVT::i32, Action: Expand);
1074 }
1075
1076 setOperationAction(Op: ISD::GlobalAddress, VT: MVT::i32, Action: Custom);
1077 setOperationAction(Op: ISD::ConstantPool, VT: MVT::i32, Action: Custom);
1078 setOperationAction(Op: ISD::GlobalTLSAddress, VT: MVT::i32, Action: Custom);
1079 setOperationAction(Op: ISD::BlockAddress, VT: MVT::i32, Action: Custom);
1080
1081 setOperationAction(Op: ISD::TRAP, VT: MVT::Other, Action: Legal);
1082 setOperationAction(Op: ISD::DEBUGTRAP, VT: MVT::Other, Action: Legal);
1083
1084 // Use the default implementation.
1085 setOperationAction(Op: ISD::VASTART, VT: MVT::Other, Action: Custom);
1086 setOperationAction(Op: ISD::VAARG, VT: MVT::Other, Action: Expand);
1087 setOperationAction(Op: ISD::VACOPY, VT: MVT::Other, Action: Expand);
1088 setOperationAction(Op: ISD::VAEND, VT: MVT::Other, Action: Expand);
1089 setOperationAction(Op: ISD::STACKSAVE, VT: MVT::Other, Action: Expand);
1090 setOperationAction(Op: ISD::STACKRESTORE, VT: MVT::Other, Action: Expand);
1091
1092 if (TT.isOSWindows())
1093 setOperationAction(Op: ISD::DYNAMIC_STACKALLOC, VT: MVT::i32, Action: Custom);
1094 else
1095 setOperationAction(Op: ISD::DYNAMIC_STACKALLOC, VT: MVT::i32, Action: Expand);
1096
1097 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1098 // the default expansion.
1099 InsertFencesForAtomic = false;
1100 if (Subtarget->hasAnyDataBarrier() &&
1101 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1102 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1103 // to ldrex/strex loops already.
1104 setOperationAction(Op: ISD::ATOMIC_FENCE, VT: MVT::Other, Action: Custom);
1105 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1106 setOperationAction(Op: ISD::ATOMIC_CMP_SWAP, VT: MVT::i64, Action: Custom);
1107
1108 // On v8, we have particularly efficient implementations of atomic fences
1109 // if they can be combined with nearby atomic loads and stores.
1110 if (!Subtarget->hasAcquireRelease() ||
1111 getTargetMachine().getOptLevel() == CodeGenOptLevel::None) {
1112 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1113 InsertFencesForAtomic = true;
1114 }
1115 } else {
1116 // If there's anything we can use as a barrier, go through custom lowering
1117 // for ATOMIC_FENCE.
1118 // If target has DMB in thumb, Fences can be inserted.
1119 if (Subtarget->hasDataBarrier())
1120 InsertFencesForAtomic = true;
1121
1122 setOperationAction(Op: ISD::ATOMIC_FENCE, VT: MVT::Other,
1123 Action: Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1124
1125 // Set them all for libcall, which will force libcalls.
1126 setOperationAction(Op: ISD::ATOMIC_CMP_SWAP, VT: MVT::i32, Action: LibCall);
1127 setOperationAction(Op: ISD::ATOMIC_SWAP, VT: MVT::i32, Action: LibCall);
1128 setOperationAction(Op: ISD::ATOMIC_LOAD_ADD, VT: MVT::i32, Action: LibCall);
1129 setOperationAction(Op: ISD::ATOMIC_LOAD_SUB, VT: MVT::i32, Action: LibCall);
1130 setOperationAction(Op: ISD::ATOMIC_LOAD_AND, VT: MVT::i32, Action: LibCall);
1131 setOperationAction(Op: ISD::ATOMIC_LOAD_OR, VT: MVT::i32, Action: LibCall);
1132 setOperationAction(Op: ISD::ATOMIC_LOAD_XOR, VT: MVT::i32, Action: LibCall);
1133 setOperationAction(Op: ISD::ATOMIC_LOAD_NAND, VT: MVT::i32, Action: LibCall);
1134 setOperationAction(Op: ISD::ATOMIC_LOAD_MIN, VT: MVT::i32, Action: LibCall);
1135 setOperationAction(Op: ISD::ATOMIC_LOAD_MAX, VT: MVT::i32, Action: LibCall);
1136 setOperationAction(Op: ISD::ATOMIC_LOAD_UMIN, VT: MVT::i32, Action: LibCall);
1137 setOperationAction(Op: ISD::ATOMIC_LOAD_UMAX, VT: MVT::i32, Action: LibCall);
1138 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1139 // Unordered/Monotonic case.
1140 if (!InsertFencesForAtomic) {
1141 setOperationAction(Op: ISD::ATOMIC_LOAD, VT: MVT::i32, Action: Custom);
1142 setOperationAction(Op: ISD::ATOMIC_STORE, VT: MVT::i32, Action: Custom);
1143 }
1144 }
1145
1146 // Compute supported atomic widths.
1147 if (TT.isOSLinux() || (!Subtarget->isMClass() && Subtarget->hasV6Ops())) {
1148 // For targets where __sync_* routines are reliably available, we use them
1149 // if necessary.
1150 //
1151 // ARM Linux always supports 64-bit atomics through kernel-assisted atomic
1152 // routines (kernel 3.1 or later). FIXME: Not with compiler-rt?
1153 //
1154 // ARMv6 targets have native instructions in ARM mode. For Thumb mode,
1155 // such targets should provide __sync_* routines, which use the ARM mode
1156 // instructions. (ARMv6 doesn't have dmb, but it has an equivalent
1157 // encoding; see ARMISD::MEMBARRIER_MCR.)
1158 setMaxAtomicSizeInBitsSupported(64);
1159 } else if ((Subtarget->isMClass() && Subtarget->hasV8MBaselineOps()) ||
1160 Subtarget->hasForced32BitAtomics()) {
1161 // Cortex-M (besides Cortex-M0) have 32-bit atomics.
1162 setMaxAtomicSizeInBitsSupported(32);
1163 } else {
1164 // We can't assume anything about other targets; just use libatomic
1165 // routines.
1166 setMaxAtomicSizeInBitsSupported(0);
1167 }
1168
1169 setMaxDivRemBitWidthSupported(64);
1170
1171 setOperationAction(Op: ISD::PREFETCH, VT: MVT::Other, Action: Custom);
1172
1173 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1174 if (!Subtarget->hasV6Ops()) {
1175 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i16, Action: Expand);
1176 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i8, Action: Expand);
1177 }
1178 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i1, Action: Expand);
1179
1180 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1181 !Subtarget->isThumb1Only()) {
1182 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1183 // iff target supports vfp2.
1184 setOperationAction(Op: ISD::BITCAST, VT: MVT::i64, Action: Custom);
1185 setOperationAction(Op: ISD::GET_ROUNDING, VT: MVT::i32, Action: Custom);
1186 setOperationAction(Op: ISD::SET_ROUNDING, VT: MVT::Other, Action: Custom);
1187 setOperationAction(Op: ISD::GET_FPENV, VT: MVT::i32, Action: Legal);
1188 setOperationAction(Op: ISD::SET_FPENV, VT: MVT::i32, Action: Legal);
1189 setOperationAction(Op: ISD::RESET_FPENV, VT: MVT::Other, Action: Legal);
1190 setOperationAction(Op: ISD::GET_FPMODE, VT: MVT::i32, Action: Legal);
1191 setOperationAction(Op: ISD::SET_FPMODE, VT: MVT::i32, Action: Custom);
1192 setOperationAction(Op: ISD::RESET_FPMODE, VT: MVT::Other, Action: Custom);
1193 }
1194
1195 // We want to custom lower some of our intrinsics.
1196 setOperationAction(Op: ISD::INTRINSIC_WO_CHAIN, VT: MVT::Other, Action: Custom);
1197 setOperationAction(Op: ISD::EH_SJLJ_SETJMP, VT: MVT::i32, Action: Custom);
1198 setOperationAction(Op: ISD::EH_SJLJ_LONGJMP, VT: MVT::Other, Action: Custom);
1199 setOperationAction(Op: ISD::EH_SJLJ_SETUP_DISPATCH, VT: MVT::Other, Action: Custom);
1200
1201 setOperationAction(Op: ISD::SETCC, VT: MVT::i32, Action: Expand);
1202 setOperationAction(Op: ISD::SETCC, VT: MVT::f32, Action: Expand);
1203 setOperationAction(Op: ISD::SETCC, VT: MVT::f64, Action: Expand);
1204 setOperationAction(Op: ISD::SELECT, VT: MVT::i32, Action: Custom);
1205 setOperationAction(Op: ISD::SELECT, VT: MVT::f32, Action: Custom);
1206 setOperationAction(Op: ISD::SELECT, VT: MVT::f64, Action: Custom);
1207 setOperationAction(Op: ISD::SELECT_CC, VT: MVT::i32, Action: Custom);
1208 setOperationAction(Op: ISD::SELECT_CC, VT: MVT::f32, Action: Custom);
1209 setOperationAction(Op: ISD::SELECT_CC, VT: MVT::f64, Action: Custom);
1210 if (Subtarget->hasFullFP16()) {
1211 setOperationAction(Op: ISD::SETCC, VT: MVT::f16, Action: Expand);
1212 setOperationAction(Op: ISD::SELECT, VT: MVT::f16, Action: Custom);
1213 setOperationAction(Op: ISD::SELECT_CC, VT: MVT::f16, Action: Custom);
1214 }
1215
1216 setOperationAction(Op: ISD::SETCCCARRY, VT: MVT::i32, Action: Custom);
1217
1218 setOperationAction(Op: ISD::BRCOND, VT: MVT::Other, Action: Custom);
1219 setOperationAction(Op: ISD::BR_CC, VT: MVT::i32, Action: Custom);
1220 if (Subtarget->hasFullFP16())
1221 setOperationAction(Op: ISD::BR_CC, VT: MVT::f16, Action: Custom);
1222 setOperationAction(Op: ISD::BR_CC, VT: MVT::f32, Action: Custom);
1223 setOperationAction(Op: ISD::BR_CC, VT: MVT::f64, Action: Custom);
1224 setOperationAction(Op: ISD::BR_JT, VT: MVT::Other, Action: Custom);
1225
1226 // We don't support sin/cos/fmod/copysign/pow
1227 setOperationAction(Op: ISD::FSIN, VT: MVT::f64, Action: Expand);
1228 setOperationAction(Op: ISD::FSIN, VT: MVT::f32, Action: Expand);
1229 setOperationAction(Op: ISD::FCOS, VT: MVT::f32, Action: Expand);
1230 setOperationAction(Op: ISD::FCOS, VT: MVT::f64, Action: Expand);
1231 setOperationAction(Op: ISD::FSINCOS, VT: MVT::f64, Action: Expand);
1232 setOperationAction(Op: ISD::FSINCOS, VT: MVT::f32, Action: Expand);
1233 setOperationAction(Op: ISD::FREM, VT: MVT::f64, Action: LibCall);
1234 setOperationAction(Op: ISD::FREM, VT: MVT::f32, Action: LibCall);
1235 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1236 !Subtarget->isThumb1Only()) {
1237 setOperationAction(Op: ISD::FCOPYSIGN, VT: MVT::f64, Action: Custom);
1238 setOperationAction(Op: ISD::FCOPYSIGN, VT: MVT::f32, Action: Custom);
1239 }
1240 setOperationAction(Op: ISD::FPOW, VT: MVT::f64, Action: Expand);
1241 setOperationAction(Op: ISD::FPOW, VT: MVT::f32, Action: Expand);
1242
1243 if (!Subtarget->hasVFP4Base()) {
1244 setOperationAction(Op: ISD::FMA, VT: MVT::f64, Action: Expand);
1245 setOperationAction(Op: ISD::FMA, VT: MVT::f32, Action: Expand);
1246 }
1247
1248 // Various VFP goodness
1249 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1250 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1251 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1252 setOperationAction(Op: ISD::FP16_TO_FP, VT: MVT::f64, Action: Expand);
1253 setOperationAction(Op: ISD::FP_TO_FP16, VT: MVT::f64, Action: Expand);
1254 setOperationAction(Op: ISD::STRICT_FP16_TO_FP, VT: MVT::f64, Action: Expand);
1255 setOperationAction(Op: ISD::STRICT_FP_TO_FP16, VT: MVT::f64, Action: Expand);
1256 }
1257
1258 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1259 if (!Subtarget->hasFP16()) {
1260 setOperationAction(Op: ISD::FP16_TO_FP, VT: MVT::f32, Action: Expand);
1261 setOperationAction(Op: ISD::FP_TO_FP16, VT: MVT::f32, Action: Expand);
1262 setOperationAction(Op: ISD::STRICT_FP16_TO_FP, VT: MVT::f32, Action: Expand);
1263 setOperationAction(Op: ISD::STRICT_FP_TO_FP16, VT: MVT::f32, Action: Expand);
1264 }
1265
1266 // Strict floating-point comparisons need custom lowering.
1267 setOperationAction(Op: ISD::STRICT_FSETCC, VT: MVT::f16, Action: Custom);
1268 setOperationAction(Op: ISD::STRICT_FSETCCS, VT: MVT::f16, Action: Custom);
1269 setOperationAction(Op: ISD::STRICT_FSETCC, VT: MVT::f32, Action: Custom);
1270 setOperationAction(Op: ISD::STRICT_FSETCCS, VT: MVT::f32, Action: Custom);
1271 setOperationAction(Op: ISD::STRICT_FSETCC, VT: MVT::f64, Action: Custom);
1272 setOperationAction(Op: ISD::STRICT_FSETCCS, VT: MVT::f64, Action: Custom);
1273 }
1274
1275 setOperationAction(Op: ISD::FSINCOS, VT: MVT::f64, Action: Expand);
1276 setOperationAction(Op: ISD::FSINCOS, VT: MVT::f32, Action: Expand);
1277
1278 // FP-ARMv8 implements a lot of rounding-like FP operations.
1279 if (Subtarget->hasFPARMv8Base()) {
1280 for (auto Op :
1281 {ISD::FFLOOR, ISD::FCEIL, ISD::FROUND,
1282 ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT,
1283 ISD::FROUNDEVEN, ISD::FMINNUM, ISD::FMAXNUM,
1284 ISD::STRICT_FFLOOR, ISD::STRICT_FCEIL, ISD::STRICT_FROUND,
1285 ISD::STRICT_FTRUNC, ISD::STRICT_FNEARBYINT, ISD::STRICT_FRINT,
1286 ISD::STRICT_FROUNDEVEN, ISD::STRICT_FMINNUM, ISD::STRICT_FMAXNUM}) {
1287 setOperationAction(Op, VT: MVT::f32, Action: Legal);
1288
1289 if (Subtarget->hasFP64())
1290 setOperationAction(Op, VT: MVT::f64, Action: Legal);
1291 }
1292
1293 if (Subtarget->hasNEON()) {
1294 setOperationAction(Op: ISD::FMINNUM, VT: MVT::v2f32, Action: Legal);
1295 setOperationAction(Op: ISD::FMAXNUM, VT: MVT::v2f32, Action: Legal);
1296 setOperationAction(Op: ISD::FMINNUM, VT: MVT::v4f32, Action: Legal);
1297 setOperationAction(Op: ISD::FMAXNUM, VT: MVT::v4f32, Action: Legal);
1298 }
1299 }
1300
1301 // FP16 often need to be promoted to call lib functions
1302 // clang-format off
1303 if (Subtarget->hasFullFP16()) {
1304 setOperationAction(Op: ISD::LRINT, VT: MVT::f16, Action: Expand);
1305 setOperationAction(Op: ISD::LROUND, VT: MVT::f16, Action: Expand);
1306 setOperationAction(Op: ISD::FCOPYSIGN, VT: MVT::f16, Action: Expand);
1307
1308 for (auto Op : {ISD::FREM, ISD::FPOW, ISD::FPOWI,
1309 ISD::FCOS, ISD::FSIN, ISD::FSINCOS,
1310 ISD::FSINCOSPI, ISD::FMODF, ISD::FACOS,
1311 ISD::FASIN, ISD::FATAN, ISD::FATAN2,
1312 ISD::FCOSH, ISD::FSINH, ISD::FTANH,
1313 ISD::FTAN, ISD::FEXP, ISD::FEXP2,
1314 ISD::FEXP10, ISD::FLOG, ISD::FLOG2,
1315 ISD::FLOG10, ISD::STRICT_FREM, ISD::STRICT_FPOW,
1316 ISD::STRICT_FPOWI, ISD::STRICT_FCOS, ISD::STRICT_FSIN,
1317 ISD::STRICT_FACOS, ISD::STRICT_FASIN, ISD::STRICT_FATAN,
1318 ISD::STRICT_FATAN2, ISD::STRICT_FCOSH, ISD::STRICT_FSINH,
1319 ISD::STRICT_FTANH, ISD::STRICT_FEXP, ISD::STRICT_FEXP2,
1320 ISD::STRICT_FLOG, ISD::STRICT_FLOG2, ISD::STRICT_FLOG10,
1321 ISD::STRICT_FTAN}) {
1322 setOperationAction(Op, VT: MVT::f16, Action: Promote);
1323 }
1324
1325 // Round-to-integer need custom lowering for fp16, as Promote doesn't work
1326 // because the result type is integer.
1327 for (auto Op : {ISD::STRICT_LROUND, ISD::STRICT_LLROUND, ISD::STRICT_LRINT, ISD::STRICT_LLRINT})
1328 setOperationAction(Op, VT: MVT::f16, Action: Custom);
1329
1330 for (auto Op : {ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
1331 ISD::FNEARBYINT, ISD::FRINT, ISD::FFLOOR,
1332 ISD::FCEIL, ISD::STRICT_FROUND, ISD::STRICT_FROUNDEVEN,
1333 ISD::STRICT_FTRUNC, ISD::STRICT_FNEARBYINT, ISD::STRICT_FRINT,
1334 ISD::STRICT_FFLOOR, ISD::STRICT_FCEIL}) {
1335 setOperationAction(Op, VT: MVT::f16, Action: Legal);
1336 }
1337 // clang-format on
1338 }
1339
1340 if (Subtarget->hasNEON()) {
1341 // vmin and vmax aren't available in a scalar form, so we can use
1342 // a NEON instruction with an undef lane instead.
1343 setOperationAction(Op: ISD::FMINIMUM, VT: MVT::f32, Action: Legal);
1344 setOperationAction(Op: ISD::FMAXIMUM, VT: MVT::f32, Action: Legal);
1345 setOperationAction(Op: ISD::FMINIMUM, VT: MVT::f16, Action: Legal);
1346 setOperationAction(Op: ISD::FMAXIMUM, VT: MVT::f16, Action: Legal);
1347 setOperationAction(Op: ISD::FMINIMUM, VT: MVT::v2f32, Action: Legal);
1348 setOperationAction(Op: ISD::FMAXIMUM, VT: MVT::v2f32, Action: Legal);
1349 setOperationAction(Op: ISD::FMINIMUM, VT: MVT::v4f32, Action: Legal);
1350 setOperationAction(Op: ISD::FMAXIMUM, VT: MVT::v4f32, Action: Legal);
1351
1352 if (Subtarget->hasV8Ops()) {
1353 for (auto Op : {ISD::FROUND, ISD::STRICT_FROUND, ISD::FROUNDEVEN,
1354 ISD::STRICT_FROUNDEVEN, ISD::FTRUNC, ISD::STRICT_FTRUNC,
1355 ISD::FRINT, ISD::STRICT_FRINT, ISD::FFLOOR,
1356 ISD::STRICT_FFLOOR, ISD::FCEIL, ISD::STRICT_FCEIL}) {
1357 setOperationAction(Op, VT: MVT::v2f32, Action: Legal);
1358 setOperationAction(Op, VT: MVT::v4f32, Action: Legal);
1359 }
1360 }
1361
1362 if (Subtarget->hasFullFP16()) {
1363 setOperationAction(Op: ISD::FMINNUM, VT: MVT::v4f16, Action: Legal);
1364 setOperationAction(Op: ISD::FMAXNUM, VT: MVT::v4f16, Action: Legal);
1365 setOperationAction(Op: ISD::FMINNUM, VT: MVT::v8f16, Action: Legal);
1366 setOperationAction(Op: ISD::FMAXNUM, VT: MVT::v8f16, Action: Legal);
1367
1368 setOperationAction(Op: ISD::FMINIMUM, VT: MVT::v4f16, Action: Legal);
1369 setOperationAction(Op: ISD::FMAXIMUM, VT: MVT::v4f16, Action: Legal);
1370 setOperationAction(Op: ISD::FMINIMUM, VT: MVT::v8f16, Action: Legal);
1371 setOperationAction(Op: ISD::FMAXIMUM, VT: MVT::v8f16, Action: Legal);
1372
1373 for (auto Op : {ISD::FROUND, ISD::STRICT_FROUND, ISD::FROUNDEVEN,
1374 ISD::STRICT_FROUNDEVEN, ISD::FTRUNC, ISD::STRICT_FTRUNC,
1375 ISD::FRINT, ISD::STRICT_FRINT, ISD::FFLOOR,
1376 ISD::STRICT_FFLOOR, ISD::FCEIL, ISD::STRICT_FCEIL}) {
1377 setOperationAction(Op, VT: MVT::v4f16, Action: Legal);
1378 setOperationAction(Op, VT: MVT::v8f16, Action: Legal);
1379 }
1380 }
1381 }
1382
1383 // On MSVC, both 32-bit and 64-bit, ldexpf(f32) is not defined. MinGW has
1384 // it, but it's just a wrapper around ldexp.
1385 if (TT.isOSWindows()) {
1386 for (ISD::NodeType Op : {ISD::FLDEXP, ISD::STRICT_FLDEXP, ISD::FFREXP})
1387 if (isOperationExpand(Op, VT: MVT::f32))
1388 setOperationAction(Op, VT: MVT::f32, Action: Promote);
1389 }
1390
1391 // LegalizeDAG currently can't expand fp16 LDEXP/FREXP on targets where i16
1392 // isn't legal.
1393 for (ISD::NodeType Op : {ISD::FLDEXP, ISD::STRICT_FLDEXP, ISD::FFREXP})
1394 if (isOperationExpand(Op, VT: MVT::f16))
1395 setOperationAction(Op, VT: MVT::f16, Action: Promote);
1396
1397 // We have target-specific dag combine patterns for the following nodes:
1398 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1399 setTargetDAGCombine(
1400 {ISD::ADD, ISD::SUB, ISD::MUL, ISD::AND, ISD::OR, ISD::XOR});
1401
1402 if (Subtarget->hasMVEIntegerOps())
1403 setTargetDAGCombine(ISD::VSELECT);
1404
1405 if (Subtarget->hasV6Ops())
1406 setTargetDAGCombine(ISD::SRL);
1407 if (Subtarget->isThumb1Only())
1408 setTargetDAGCombine(ISD::SHL);
1409 // Attempt to lower smin/smax to ssat/usat
1410 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) ||
1411 Subtarget->isThumb2()) {
1412 setTargetDAGCombine({ISD::SMIN, ISD::SMAX});
1413 }
1414
1415 setStackPointerRegisterToSaveRestore(ARM::SP);
1416
1417 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1418 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1419 setSchedulingPreference(Sched::RegPressure);
1420 else
1421 setSchedulingPreference(Sched::Hybrid);
1422
1423 //// temporary - rewrite interface to use type
1424 MaxStoresPerMemset = 8;
1425 MaxStoresPerMemsetOptSize = 4;
1426 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1427 MaxStoresPerMemcpyOptSize = 2;
1428 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1429 MaxStoresPerMemmoveOptSize = 2;
1430
1431 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1432 // are at least 4 bytes aligned.
1433 setMinStackArgumentAlignment(Align(4));
1434
1435 // Prefer likely predicted branches to selects on out-of-order cores.
1436 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1437
1438 setPrefLoopAlignment(Align(1ULL << Subtarget->getPreferBranchLogAlignment()));
1439 setPrefFunctionAlignment(
1440 Align(1ULL << Subtarget->getPreferBranchLogAlignment()));
1441
1442 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1443
1444 IsStrictFPEnabled = true;
1445}
1446
1447bool ARMTargetLowering::useSoftFloat() const {
1448 return Subtarget->useSoftFloat();
1449}
1450
1451bool ARMTargetLowering::preferSelectsOverBooleanArithmetic(EVT VT) const {
1452 return !Subtarget->isThumb1Only() && VT.getSizeInBits() <= 32;
1453}
1454
1455// FIXME: It might make sense to define the representative register class as the
1456// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1457// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1458// SPR's representative would be DPR_VFP2. This should work well if register
1459// pressure tracking were modified such that a register use would increment the
1460// pressure of the register class's representative and all of it's super
1461// classes' representatives transitively. We have not implemented this because
1462// of the difficulty prior to coalescing of modeling operand register classes
1463// due to the common occurrence of cross class copies and subregister insertions
1464// and extractions.
1465std::pair<const TargetRegisterClass *, uint8_t>
1466ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1467 MVT VT) const {
1468 const TargetRegisterClass *RRC = nullptr;
1469 uint8_t Cost = 1;
1470 switch (VT.SimpleTy) {
1471 default:
1472 return TargetLowering::findRepresentativeClass(TRI, VT);
1473 // Use DPR as representative register class for all floating point
1474 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1475 // the cost is 1 for both f32 and f64.
1476 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1477 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1478 RRC = &ARM::DPRRegClass;
1479 // When NEON is used for SP, only half of the register file is available
1480 // because operations that define both SP and DP results will be constrained
1481 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1482 // coalescing by double-counting the SP regs. See the FIXME above.
1483 if (Subtarget->useNEONForSinglePrecisionFP())
1484 Cost = 2;
1485 break;
1486 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1487 case MVT::v4f32: case MVT::v2f64:
1488 RRC = &ARM::DPRRegClass;
1489 Cost = 2;
1490 break;
1491 case MVT::v4i64:
1492 RRC = &ARM::DPRRegClass;
1493 Cost = 4;
1494 break;
1495 case MVT::v8i64:
1496 RRC = &ARM::DPRRegClass;
1497 Cost = 8;
1498 break;
1499 }
1500 return std::make_pair(x&: RRC, y&: Cost);
1501}
1502
1503EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1504 EVT VT) const {
1505 if (!VT.isVector())
1506 return getPointerTy(DL);
1507
1508 // MVE has a predicate register.
1509 if ((Subtarget->hasMVEIntegerOps() &&
1510 (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
1511 VT == MVT::v16i8)) ||
1512 (Subtarget->hasMVEFloatOps() &&
1513 (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16)))
1514 return MVT::getVectorVT(VT: MVT::i1, EC: VT.getVectorElementCount());
1515 return VT.changeVectorElementTypeToInteger();
1516}
1517
1518/// getRegClassFor - Return the register class that should be used for the
1519/// specified value type.
1520const TargetRegisterClass *
1521ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1522 (void)isDivergent;
1523 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1524 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1525 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1526 // MVE Q registers.
1527 if (Subtarget->hasNEON()) {
1528 if (VT == MVT::v4i64)
1529 return &ARM::QQPRRegClass;
1530 if (VT == MVT::v8i64)
1531 return &ARM::QQQQPRRegClass;
1532 }
1533 if (Subtarget->hasMVEIntegerOps()) {
1534 if (VT == MVT::v4i64)
1535 return &ARM::MQQPRRegClass;
1536 if (VT == MVT::v8i64)
1537 return &ARM::MQQQQPRRegClass;
1538 }
1539 return TargetLowering::getRegClassFor(VT);
1540}
1541
1542// memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1543// source/dest is aligned and the copy size is large enough. We therefore want
1544// to align such objects passed to memory intrinsics.
1545bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1546 Align &PrefAlign) const {
1547 if (!isa<MemIntrinsic>(Val: CI))
1548 return false;
1549 MinSize = 8;
1550 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1551 // cycle faster than 4-byte aligned LDM.
1552 PrefAlign =
1553 (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? Align(8) : Align(4));
1554 return true;
1555}
1556
1557// Create a fast isel object.
1558FastISel *ARMTargetLowering::createFastISel(
1559 FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo,
1560 const LibcallLoweringInfo *libcallLowering) const {
1561 return ARM::createFastISel(funcInfo, libInfo, libcallLowering);
1562}
1563
1564Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1565 unsigned NumVals = N->getNumValues();
1566 if (!NumVals)
1567 return Sched::RegPressure;
1568
1569 for (unsigned i = 0; i != NumVals; ++i) {
1570 EVT VT = N->getValueType(ResNo: i);
1571 if (VT == MVT::Glue || VT == MVT::Other)
1572 continue;
1573 if (VT.isFloatingPoint() || VT.isVector())
1574 return Sched::ILP;
1575 }
1576
1577 if (!N->isMachineOpcode())
1578 return Sched::RegPressure;
1579
1580 // Load are scheduled for latency even if there instruction itinerary
1581 // is not available.
1582 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1583 const MCInstrDesc &MCID = TII->get(Opcode: N->getMachineOpcode());
1584
1585 if (MCID.getNumDefs() == 0)
1586 return Sched::RegPressure;
1587 if (!Itins->isEmpty() &&
1588 Itins->getOperandCycle(ItinClassIndx: MCID.getSchedClass(), OperandIdx: 0) > 2U)
1589 return Sched::ILP;
1590
1591 return Sched::RegPressure;
1592}
1593
1594//===----------------------------------------------------------------------===//
1595// Lowering Code
1596//===----------------------------------------------------------------------===//
1597
1598static bool isSRL16(const SDValue &Op) {
1599 if (Op.getOpcode() != ISD::SRL)
1600 return false;
1601 if (auto Const = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 1)))
1602 return Const->getZExtValue() == 16;
1603 return false;
1604}
1605
1606static bool isSRA16(const SDValue &Op) {
1607 if (Op.getOpcode() != ISD::SRA)
1608 return false;
1609 if (auto Const = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 1)))
1610 return Const->getZExtValue() == 16;
1611 return false;
1612}
1613
1614static bool isSHL16(const SDValue &Op) {
1615 if (Op.getOpcode() != ISD::SHL)
1616 return false;
1617 if (auto Const = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 1)))
1618 return Const->getZExtValue() == 16;
1619 return false;
1620}
1621
1622// Check for a signed 16-bit value. We special case SRA because it makes it
1623// more simple when also looking for SRAs that aren't sign extending a
1624// smaller value. Without the check, we'd need to take extra care with
1625// checking order for some operations.
1626static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1627 if (isSRA16(Op))
1628 return isSHL16(Op: Op.getOperand(i: 0));
1629 return DAG.ComputeNumSignBits(Op) == 17;
1630}
1631
1632/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1633static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1634 switch (CC) {
1635 default: llvm_unreachable("Unknown condition code!");
1636 case ISD::SETNE: return ARMCC::NE;
1637 case ISD::SETEQ: return ARMCC::EQ;
1638 case ISD::SETGT: return ARMCC::GT;
1639 case ISD::SETGE: return ARMCC::GE;
1640 case ISD::SETLT: return ARMCC::LT;
1641 case ISD::SETLE: return ARMCC::LE;
1642 case ISD::SETUGT: return ARMCC::HI;
1643 case ISD::SETUGE: return ARMCC::HS;
1644 case ISD::SETULT: return ARMCC::LO;
1645 case ISD::SETULE: return ARMCC::LS;
1646 }
1647}
1648
1649/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1650static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1651 ARMCC::CondCodes &CondCode2) {
1652 CondCode2 = ARMCC::AL;
1653 switch (CC) {
1654 default: llvm_unreachable("Unknown FP condition!");
1655 case ISD::SETEQ:
1656 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1657 case ISD::SETGT:
1658 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1659 case ISD::SETGE:
1660 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1661 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1662 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1663 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1664 case ISD::SETO: CondCode = ARMCC::VC; break;
1665 case ISD::SETUO: CondCode = ARMCC::VS; break;
1666 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1667 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1668 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1669 case ISD::SETLT:
1670 case ISD::SETULT: CondCode = ARMCC::LT; break;
1671 case ISD::SETLE:
1672 case ISD::SETULE: CondCode = ARMCC::LE; break;
1673 case ISD::SETNE:
1674 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1675 }
1676}
1677
1678//===----------------------------------------------------------------------===//
1679// Calling Convention Implementation
1680//===----------------------------------------------------------------------===//
1681
1682/// getEffectiveCallingConv - Get the effective calling convention, taking into
1683/// account presence of floating point hardware and calling convention
1684/// limitations, such as support for variadic functions.
1685CallingConv::ID
1686ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1687 bool isVarArg) const {
1688 switch (CC) {
1689 default:
1690 report_fatal_error(reason: "Unsupported calling convention");
1691 case CallingConv::ARM_AAPCS:
1692 case CallingConv::ARM_APCS:
1693 case CallingConv::GHC:
1694 case CallingConv::CFGuard_Check:
1695 return CC;
1696 case CallingConv::PreserveMost:
1697 return CallingConv::PreserveMost;
1698 case CallingConv::PreserveAll:
1699 return CallingConv::PreserveAll;
1700 case CallingConv::ARM_AAPCS_VFP:
1701 case CallingConv::Swift:
1702 case CallingConv::SwiftTail:
1703 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1704 case CallingConv::C:
1705 case CallingConv::Tail:
1706 if (!getTM().isAAPCS_ABI())
1707 return CallingConv::ARM_APCS;
1708 else if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() &&
1709 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1710 !isVarArg)
1711 return CallingConv::ARM_AAPCS_VFP;
1712 else
1713 return CallingConv::ARM_AAPCS;
1714 case CallingConv::Fast:
1715 case CallingConv::CXX_FAST_TLS:
1716 if (!getTM().isAAPCS_ABI()) {
1717 if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() && !isVarArg)
1718 return CallingConv::Fast;
1719 return CallingConv::ARM_APCS;
1720 } else if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() &&
1721 !isVarArg)
1722 return CallingConv::ARM_AAPCS_VFP;
1723 else
1724 return CallingConv::ARM_AAPCS;
1725 }
1726}
1727
1728CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1729 bool isVarArg) const {
1730 return CCAssignFnForNode(CC, Return: false, isVarArg);
1731}
1732
1733CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1734 bool isVarArg) const {
1735 return CCAssignFnForNode(CC, Return: true, isVarArg);
1736}
1737
1738/// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1739/// CallingConvention.
1740CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1741 bool Return,
1742 bool isVarArg) const {
1743 switch (getEffectiveCallingConv(CC, isVarArg)) {
1744 default:
1745 report_fatal_error(reason: "Unsupported calling convention");
1746 case CallingConv::ARM_APCS:
1747 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1748 case CallingConv::ARM_AAPCS:
1749 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1750 case CallingConv::ARM_AAPCS_VFP:
1751 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1752 case CallingConv::Fast:
1753 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1754 case CallingConv::GHC:
1755 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1756 case CallingConv::PreserveMost:
1757 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1758 case CallingConv::PreserveAll:
1759 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1760 case CallingConv::CFGuard_Check:
1761 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
1762 }
1763}
1764
1765SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
1766 MVT LocVT, MVT ValVT, SDValue Val) const {
1767 Val = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::getIntegerVT(BitWidth: LocVT.getSizeInBits()),
1768 Operand: Val);
1769 if (Subtarget->hasFullFP16()) {
1770 Val = DAG.getNode(Opcode: ARMISD::VMOVhr, DL: dl, VT: ValVT, Operand: Val);
1771 } else {
1772 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl,
1773 VT: MVT::getIntegerVT(BitWidth: ValVT.getSizeInBits()), Operand: Val);
1774 Val = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: ValVT, Operand: Val);
1775 }
1776 return Val;
1777}
1778
1779SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
1780 MVT LocVT, MVT ValVT,
1781 SDValue Val) const {
1782 if (Subtarget->hasFullFP16()) {
1783 Val = DAG.getNode(Opcode: ARMISD::VMOVrh, DL: dl,
1784 VT: MVT::getIntegerVT(BitWidth: LocVT.getSizeInBits()), Operand: Val);
1785 } else {
1786 Val = DAG.getNode(Opcode: ISD::BITCAST, DL: dl,
1787 VT: MVT::getIntegerVT(BitWidth: ValVT.getSizeInBits()), Operand: Val);
1788 Val = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl,
1789 VT: MVT::getIntegerVT(BitWidth: LocVT.getSizeInBits()), Operand: Val);
1790 }
1791 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: LocVT, Operand: Val);
1792}
1793
1794/// LowerCallResult - Lower the result values of a call into the
1795/// appropriate copies out of appropriate physical registers.
1796SDValue ARMTargetLowering::LowerCallResult(
1797 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
1798 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1799 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1800 SDValue ThisVal, bool isCmseNSCall) const {
1801 // Assign locations to each value returned by this call.
1802 SmallVector<CCValAssign, 16> RVLocs;
1803 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1804 *DAG.getContext());
1805 CCInfo.AnalyzeCallResult(Ins, Fn: CCAssignFnForReturn(CC: CallConv, isVarArg));
1806
1807 // Copy all of the result registers out of their specified physreg.
1808 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1809 CCValAssign VA = RVLocs[i];
1810
1811 // Pass 'this' value directly from the argument to return value, to avoid
1812 // reg unit interference
1813 if (i == 0 && isThisReturn) {
1814 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1815 "unexpected return calling convention register assignment");
1816 InVals.push_back(Elt: ThisVal);
1817 continue;
1818 }
1819
1820 SDValue Val;
1821 if (VA.needsCustom() &&
1822 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
1823 // Handle f64 or half of a v2f64.
1824 SDValue Lo = DAG.getCopyFromReg(Chain, dl, Reg: VA.getLocReg(), VT: MVT::i32,
1825 Glue: InGlue);
1826 Chain = Lo.getValue(R: 1);
1827 InGlue = Lo.getValue(R: 2);
1828 VA = RVLocs[++i]; // skip ahead to next loc
1829 SDValue Hi = DAG.getCopyFromReg(Chain, dl, Reg: VA.getLocReg(), VT: MVT::i32,
1830 Glue: InGlue);
1831 Chain = Hi.getValue(R: 1);
1832 InGlue = Hi.getValue(R: 2);
1833 if (!Subtarget->isLittle())
1834 std::swap (a&: Lo, b&: Hi);
1835 Val = DAG.getNode(Opcode: ARMISD::VMOVDRR, DL: dl, VT: MVT::f64, N1: Lo, N2: Hi);
1836
1837 if (VA.getLocVT() == MVT::v2f64) {
1838 SDValue Vec = DAG.getNode(Opcode: ISD::UNDEF, DL: dl, VT: MVT::v2f64);
1839 Vec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: MVT::v2f64, N1: Vec, N2: Val,
1840 N3: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
1841
1842 VA = RVLocs[++i]; // skip ahead to next loc
1843 Lo = DAG.getCopyFromReg(Chain, dl, Reg: VA.getLocReg(), VT: MVT::i32, Glue: InGlue);
1844 Chain = Lo.getValue(R: 1);
1845 InGlue = Lo.getValue(R: 2);
1846 VA = RVLocs[++i]; // skip ahead to next loc
1847 Hi = DAG.getCopyFromReg(Chain, dl, Reg: VA.getLocReg(), VT: MVT::i32, Glue: InGlue);
1848 Chain = Hi.getValue(R: 1);
1849 InGlue = Hi.getValue(R: 2);
1850 if (!Subtarget->isLittle())
1851 std::swap (a&: Lo, b&: Hi);
1852 Val = DAG.getNode(Opcode: ARMISD::VMOVDRR, DL: dl, VT: MVT::f64, N1: Lo, N2: Hi);
1853 Val = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: MVT::v2f64, N1: Vec, N2: Val,
1854 N3: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
1855 }
1856 } else {
1857 Val = DAG.getCopyFromReg(Chain, dl, Reg: VA.getLocReg(), VT: VA.getLocVT(),
1858 Glue: InGlue);
1859 Chain = Val.getValue(R: 1);
1860 InGlue = Val.getValue(R: 2);
1861 }
1862
1863 switch (VA.getLocInfo()) {
1864 default: llvm_unreachable("Unknown loc info!");
1865 case CCValAssign::Full: break;
1866 case CCValAssign::BCvt:
1867 Val = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VA.getValVT(), Operand: Val);
1868 break;
1869 }
1870
1871 // f16 arguments have their size extended to 4 bytes and passed as if they
1872 // had been copied to the LSBs of a 32-bit register.
1873 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
1874 if (VA.needsCustom() &&
1875 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
1876 Val = MoveToHPR(dl, DAG, LocVT: VA.getLocVT(), ValVT: VA.getValVT(), Val);
1877
1878 // On CMSE Non-secure Calls, call results (returned values) whose bitwidth
1879 // is less than 32 bits must be sign- or zero-extended after the call for
1880 // security reasons. Although the ABI mandates an extension done by the
1881 // callee, the latter cannot be trusted to follow the rules of the ABI.
1882 const ISD::InputArg &Arg = Ins[VA.getValNo()];
1883 if (isCmseNSCall && Arg.ArgVT.isScalarInteger() &&
1884 VA.getLocVT().isScalarInteger() && Arg.ArgVT.bitsLT(VT: MVT::i32))
1885 Val = handleCMSEValue(Value: Val, Arg, DAG, DL: dl);
1886
1887 InVals.push_back(Elt: Val);
1888 }
1889
1890 return Chain;
1891}
1892
1893std::pair<SDValue, MachinePointerInfo> ARMTargetLowering::computeAddrForCallArg(
1894 const SDLoc &dl, SelectionDAG &DAG, const CCValAssign &VA, SDValue StackPtr,
1895 bool IsTailCall, int SPDiff) const {
1896 SDValue DstAddr;
1897 MachinePointerInfo DstInfo;
1898 int32_t Offset = VA.getLocMemOffset();
1899 MachineFunction &MF = DAG.getMachineFunction();
1900
1901 if (IsTailCall) {
1902 Offset += SPDiff;
1903 auto PtrVT = getPointerTy(DL: DAG.getDataLayout());
1904 int Size = VA.getLocVT().getFixedSizeInBits() / 8;
1905 int FI = MF.getFrameInfo().CreateFixedObject(Size, SPOffset: Offset, IsImmutable: true);
1906 DstAddr = DAG.getFrameIndex(FI, VT: PtrVT);
1907 DstInfo =
1908 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI);
1909 } else {
1910 SDValue PtrOff = DAG.getIntPtrConstant(Val: Offset, DL: dl);
1911 DstAddr = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: getPointerTy(DL: DAG.getDataLayout()),
1912 N1: StackPtr, N2: PtrOff);
1913 DstInfo =
1914 MachinePointerInfo::getStack(MF&: DAG.getMachineFunction(), Offset);
1915 }
1916
1917 return std::make_pair(x&: DstAddr, y&: DstInfo);
1918}
1919
1920// Returns the type of copying which is required to set up a byval argument to
1921// a tail-called function. This isn't needed for non-tail calls, because they
1922// always need the equivalent of CopyOnce, but tail-calls sometimes need two to
1923// avoid clobbering another argument (CopyViaTemp), and sometimes can be
1924// optimised to zero copies when forwarding an argument from the caller's
1925// caller (NoCopy).
1926ARMTargetLowering::ByValCopyKind ARMTargetLowering::ByValNeedsCopyForTailCall(
1927 SelectionDAG &DAG, SDValue Src, SDValue Dst, ISD::ArgFlagsTy Flags) const {
1928 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1929 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1930
1931 // Globals are always safe to copy from.
1932 if (isa<GlobalAddressSDNode>(Val: Src) || isa<ExternalSymbolSDNode>(Val: Src))
1933 return CopyOnce;
1934
1935 // Can only analyse frame index nodes, conservatively assume we need a
1936 // temporary.
1937 auto *SrcFrameIdxNode = dyn_cast<FrameIndexSDNode>(Val&: Src);
1938 auto *DstFrameIdxNode = dyn_cast<FrameIndexSDNode>(Val&: Dst);
1939 if (!SrcFrameIdxNode || !DstFrameIdxNode)
1940 return CopyViaTemp;
1941
1942 int SrcFI = SrcFrameIdxNode->getIndex();
1943 int DstFI = DstFrameIdxNode->getIndex();
1944 assert(MFI.isFixedObjectIndex(DstFI) &&
1945 "byval passed in non-fixed stack slot");
1946
1947 int64_t SrcOffset = MFI.getObjectOffset(ObjectIdx: SrcFI);
1948 int64_t DstOffset = MFI.getObjectOffset(ObjectIdx: DstFI);
1949
1950 // If the source is in the local frame, then the copy to the argument memory
1951 // is always valid.
1952 bool FixedSrc = MFI.isFixedObjectIndex(ObjectIdx: SrcFI);
1953 if (!FixedSrc ||
1954 (FixedSrc && SrcOffset < -(int64_t)AFI->getArgRegsSaveSize()))
1955 return CopyOnce;
1956
1957 // In the case of byval arguments split between registers and the stack,
1958 // computeAddrForCallArg returns a FrameIndex which corresponds only to the
1959 // stack portion, but the Src SDValue will refer to the full value, including
1960 // the local stack memory that the register portion gets stored into. We only
1961 // need to compare them for equality, so normalise on the full value version.
1962 uint64_t RegSize = Flags.getByValSize() - MFI.getObjectSize(ObjectIdx: DstFI);
1963 DstOffset -= RegSize;
1964
1965 // If the value is already in the correct location, then no copying is
1966 // needed. If not, then we need to copy via a temporary.
1967 if (SrcOffset == DstOffset)
1968 return NoCopy;
1969 else
1970 return CopyViaTemp;
1971}
1972
1973void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1974 SDValue Chain, SDValue &Arg,
1975 RegsToPassVector &RegsToPass,
1976 CCValAssign &VA, CCValAssign &NextVA,
1977 SDValue &StackPtr,
1978 SmallVectorImpl<SDValue> &MemOpChains,
1979 bool IsTailCall,
1980 int SPDiff) const {
1981 SDValue fmrrd = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl,
1982 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N: Arg);
1983 unsigned id = Subtarget->isLittle() ? 0 : 1;
1984 RegsToPass.push_back(Elt: std::make_pair(x: VA.getLocReg(), y: fmrrd.getValue(R: id)));
1985
1986 if (NextVA.isRegLoc())
1987 RegsToPass.push_back(Elt: std::make_pair(x: NextVA.getLocReg(), y: fmrrd.getValue(R: 1-id)));
1988 else {
1989 assert(NextVA.isMemLoc());
1990 if (!StackPtr.getNode())
1991 StackPtr = DAG.getCopyFromReg(Chain, dl, Reg: ARM::SP,
1992 VT: getPointerTy(DL: DAG.getDataLayout()));
1993
1994 SDValue DstAddr;
1995 MachinePointerInfo DstInfo;
1996 std::tie(args&: DstAddr, args&: DstInfo) =
1997 computeAddrForCallArg(dl, DAG, VA: NextVA, StackPtr, IsTailCall, SPDiff);
1998 MemOpChains.push_back(
1999 Elt: DAG.getStore(Chain, dl, Val: fmrrd.getValue(R: 1 - id), Ptr: DstAddr, PtrInfo: DstInfo));
2000 }
2001}
2002
2003static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
2004 return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
2005 CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
2006}
2007
2008/// LowerCall - Lowering a call into a callseq_start <-
2009/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2010/// nodes.
2011SDValue
2012ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2013 SmallVectorImpl<SDValue> &InVals) const {
2014 SelectionDAG &DAG = CLI.DAG;
2015 SDLoc &dl = CLI.DL;
2016 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2017 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2018 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2019 SDValue Chain = CLI.Chain;
2020 SDValue Callee = CLI.Callee;
2021 bool &isTailCall = CLI.IsTailCall;
2022 CallingConv::ID CallConv = CLI.CallConv;
2023 bool doesNotRet = CLI.DoesNotReturn;
2024 bool isVarArg = CLI.IsVarArg;
2025 const CallBase *CB = CLI.CB;
2026
2027 MachineFunction &MF = DAG.getMachineFunction();
2028 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2029 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2030 MachineFunction::CallSiteInfo CSInfo;
2031 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2032 bool isThisReturn = false;
2033 bool isCmseNSCall = false;
2034 bool isSibCall = false;
2035 bool PreferIndirect = false;
2036 bool GuardWithBTI = false;
2037
2038 // Analyze operands of the call, assigning locations to each operand.
2039 SmallVector<CCValAssign, 16> ArgLocs;
2040 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2041 *DAG.getContext());
2042 CCInfo.AnalyzeCallOperands(Outs, Fn: CCAssignFnForCall(CC: CallConv, isVarArg));
2043
2044 // Lower 'returns_twice' calls to a pseudo-instruction.
2045 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr(Kind: Attribute::ReturnsTwice) &&
2046 !Subtarget->noBTIAtReturnTwice())
2047 GuardWithBTI = AFI->branchTargetEnforcement();
2048
2049 // Set type id for call site info.
2050 setTypeIdForCallsiteInfo(CB, MF, CSInfo);
2051
2052 // Determine whether this is a non-secure function call.
2053 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr(Kind: "cmse_nonsecure_call"))
2054 isCmseNSCall = true;
2055
2056 // Disable tail calls if they're not supported.
2057 if (!Subtarget->supportsTailCall())
2058 isTailCall = false;
2059
2060 // For both the non-secure calls and the returns from a CMSE entry function,
2061 // the function needs to do some extra work after the call, or before the
2062 // return, respectively, thus it cannot end with a tail call
2063 if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2064 isTailCall = false;
2065
2066 if (isa<GlobalAddressSDNode>(Val: Callee)) {
2067 // If we're optimizing for minimum size and the function is called three or
2068 // more times in this block, we can improve codesize by calling indirectly
2069 // as BLXr has a 16-bit encoding.
2070 auto *GV = cast<GlobalAddressSDNode>(Val&: Callee)->getGlobal();
2071 if (CLI.CB) {
2072 auto *BB = CLI.CB->getParent();
2073 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2074 count_if(Range: GV->users(), P: [&BB](const User *U) {
2075 return isa<Instruction>(Val: U) &&
2076 cast<Instruction>(Val: U)->getParent() == BB;
2077 }) > 2;
2078 }
2079 }
2080 if (isTailCall) {
2081 // Check if it's really possible to do a tail call.
2082 isTailCall =
2083 IsEligibleForTailCallOptimization(CLI, CCInfo, ArgLocs, isIndirect: PreferIndirect);
2084
2085 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt &&
2086 CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
2087 isSibCall = true;
2088
2089 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2090 // detected sibcalls.
2091 if (isTailCall)
2092 ++NumTailCalls;
2093 }
2094
2095 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2096 report_fatal_error(reason: "failed to perform tail call elimination on a call "
2097 "site marked musttail");
2098
2099 // Get a count of how many bytes are to be pushed on the stack.
2100 unsigned NumBytes = CCInfo.getStackSize();
2101
2102 // SPDiff is the byte offset of the call's argument area from the callee's.
2103 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2104 // by this amount for a tail call. In a sibling call it must be 0 because the
2105 // caller will deallocate the entire stack and the callee still expects its
2106 // arguments to begin at SP+0. Completely unused for non-tail calls.
2107 int SPDiff = 0;
2108
2109 if (isTailCall && !isSibCall) {
2110 auto FuncInfo = MF.getInfo<ARMFunctionInfo>();
2111 unsigned NumReusableBytes = FuncInfo->getArgumentStackSize();
2112
2113 // Since callee will pop argument stack as a tail call, we must keep the
2114 // popped size 16-byte aligned.
2115 MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
2116 assert(StackAlign && "data layout string is missing stack alignment");
2117 NumBytes = alignTo(Size: NumBytes, A: *StackAlign);
2118
2119 // SPDiff will be negative if this tail call requires more space than we
2120 // would automatically have in our incoming argument space. Positive if we
2121 // can actually shrink the stack.
2122 SPDiff = NumReusableBytes - NumBytes;
2123
2124 // If this call requires more stack than we have available from
2125 // LowerFormalArguments, tell FrameLowering to reserve space for it.
2126 if (SPDiff < 0 && AFI->getArgRegsSaveSize() < (unsigned)-SPDiff)
2127 AFI->setArgRegsSaveSize(-SPDiff);
2128 }
2129
2130 if (isSibCall) {
2131 // For sibling tail calls, memory operands are available in our caller's stack.
2132 NumBytes = 0;
2133 } else {
2134 // Adjust the stack pointer for the new arguments...
2135 // These operations are automatically eliminated by the prolog/epilog pass
2136 Chain = DAG.getCALLSEQ_START(Chain, InSize: isTailCall ? 0 : NumBytes, OutSize: 0, DL: dl);
2137 }
2138
2139 SDValue StackPtr =
2140 DAG.getCopyFromReg(Chain, dl, Reg: ARM::SP, VT: getPointerTy(DL: DAG.getDataLayout()));
2141
2142 RegsToPassVector RegsToPass;
2143 SmallVector<SDValue, 8> MemOpChains;
2144
2145 // If we are doing a tail-call, any byval arguments will be written to stack
2146 // space which was used for incoming arguments. If any the values being used
2147 // are incoming byval arguments to this function, then they might be
2148 // overwritten by the stores of the outgoing arguments. To avoid this, we
2149 // need to make a temporary copy of them in local stack space, then copy back
2150 // to the argument area.
2151 DenseMap<unsigned, SDValue> ByValTemporaries;
2152 SDValue ByValTempChain;
2153 if (isTailCall) {
2154 SmallVector<SDValue, 8> ByValCopyChains;
2155 for (const CCValAssign &VA : ArgLocs) {
2156 unsigned ArgIdx = VA.getValNo();
2157 SDValue Src = OutVals[ArgIdx];
2158 ISD::ArgFlagsTy Flags = Outs[ArgIdx].Flags;
2159
2160 if (!Flags.isByVal())
2161 continue;
2162
2163 SDValue Dst;
2164 MachinePointerInfo DstInfo;
2165 std::tie(args&: Dst, args&: DstInfo) =
2166 computeAddrForCallArg(dl, DAG, VA, StackPtr: SDValue(), IsTailCall: true, SPDiff);
2167 ByValCopyKind Copy = ByValNeedsCopyForTailCall(DAG, Src, Dst, Flags);
2168
2169 if (Copy == NoCopy) {
2170 // If the argument is already at the correct offset on the stack
2171 // (because we are forwarding a byval argument from our caller), we
2172 // don't need any copying.
2173 continue;
2174 } else if (Copy == CopyOnce) {
2175 // If the argument is in our local stack frame, no other argument
2176 // preparation can clobber it, so we can copy it to the final location
2177 // later.
2178 ByValTemporaries[ArgIdx] = Src;
2179 } else {
2180 assert(Copy == CopyViaTemp && "unexpected enum value");
2181 // If we might be copying this argument from the outgoing argument
2182 // stack area, we need to copy via a temporary in the local stack
2183 // frame.
2184 int TempFrameIdx = MFI.CreateStackObject(
2185 Size: Flags.getByValSize(), Alignment: Flags.getNonZeroByValAlign(), isSpillSlot: false);
2186 SDValue Temp =
2187 DAG.getFrameIndex(FI: TempFrameIdx, VT: getPointerTy(DL: DAG.getDataLayout()));
2188
2189 SDValue SizeNode = DAG.getConstant(Val: Flags.getByValSize(), DL: dl, VT: MVT::i32);
2190 SDValue AlignNode =
2191 DAG.getConstant(Val: Flags.getNonZeroByValAlign().value(), DL: dl, VT: MVT::i32);
2192
2193 SDVTList VTs = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
2194 SDValue Ops[] = {Chain, Temp, Src, SizeNode, AlignNode};
2195 ByValCopyChains.push_back(
2196 Elt: DAG.getNode(Opcode: ARMISD::COPY_STRUCT_BYVAL, DL: dl, VTList: VTs, Ops));
2197 ByValTemporaries[ArgIdx] = Temp;
2198 }
2199 }
2200 if (!ByValCopyChains.empty())
2201 ByValTempChain =
2202 DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: ByValCopyChains);
2203 }
2204
2205 // During a tail call, stores to the argument area must happen after all of
2206 // the function's incoming arguments have been loaded because they may alias.
2207 // This is done by folding in a TokenFactor from LowerFormalArguments, but
2208 // there's no point in doing so repeatedly so this tracks whether that's
2209 // happened yet.
2210 bool AfterFormalArgLoads = false;
2211
2212 // Walk the register/memloc assignments, inserting copies/loads. In the case
2213 // of tail call optimization, arguments are handled later.
2214 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2215 i != e;
2216 ++i, ++realArgIdx) {
2217 CCValAssign &VA = ArgLocs[i];
2218 SDValue Arg = OutVals[realArgIdx];
2219 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2220 bool isByVal = Flags.isByVal();
2221
2222 // Promote the value if needed.
2223 switch (VA.getLocInfo()) {
2224 default: llvm_unreachable("Unknown loc info!");
2225 case CCValAssign::Full: break;
2226 case CCValAssign::SExt:
2227 Arg = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: VA.getLocVT(), Operand: Arg);
2228 break;
2229 case CCValAssign::ZExt:
2230 Arg = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: VA.getLocVT(), Operand: Arg);
2231 break;
2232 case CCValAssign::AExt:
2233 Arg = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL: dl, VT: VA.getLocVT(), Operand: Arg);
2234 break;
2235 case CCValAssign::BCvt:
2236 Arg = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VA.getLocVT(), Operand: Arg);
2237 break;
2238 }
2239
2240 if (isTailCall && VA.isMemLoc() && !AfterFormalArgLoads) {
2241 Chain = DAG.getStackArgumentTokenFactor(Chain);
2242 if (ByValTempChain) {
2243 // In case of large byval copies, re-using the stackframe for tail-calls
2244 // can lead to overwriting incoming arguments on the stack. Force
2245 // loading these stack arguments before the copy to avoid that.
2246 SmallVector<SDValue, 8> IncomingLoad;
2247 for (unsigned I = 0; I < OutVals.size(); ++I) {
2248 if (Outs[I].Flags.isByVal())
2249 continue;
2250
2251 SDValue OutVal = OutVals[I];
2252 LoadSDNode *OutLN = dyn_cast_or_null<LoadSDNode>(Val&: OutVal);
2253 if (!OutLN)
2254 continue;
2255
2256 FrameIndexSDNode *FIN =
2257 dyn_cast_or_null<FrameIndexSDNode>(Val: OutLN->getBasePtr());
2258 if (!FIN)
2259 continue;
2260
2261 if (!MFI.isFixedObjectIndex(ObjectIdx: FIN->getIndex()))
2262 continue;
2263
2264 for (const CCValAssign &VA : ArgLocs) {
2265 if (VA.isMemLoc())
2266 IncomingLoad.push_back(Elt: OutVal.getValue(R: 1));
2267 }
2268 }
2269
2270 // Update the chain to force loads for potentially clobbered argument
2271 // loads to happen before the byval copy.
2272 if (!IncomingLoad.empty()) {
2273 IncomingLoad.push_back(Elt: Chain);
2274 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: IncomingLoad);
2275 }
2276
2277 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, N1: Chain,
2278 N2: ByValTempChain);
2279 }
2280 AfterFormalArgLoads = true;
2281 }
2282
2283 // f16 arguments have their size extended to 4 bytes and passed as if they
2284 // had been copied to the LSBs of a 32-bit register.
2285 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2286 if (VA.needsCustom() &&
2287 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2288 Arg = MoveFromHPR(dl, DAG, LocVT: VA.getLocVT(), ValVT: VA.getValVT(), Val: Arg);
2289 } else {
2290 // f16 arguments could have been extended prior to argument lowering.
2291 // Mask them arguments if this is a CMSE nonsecure call.
2292 auto ArgVT = Outs[realArgIdx].ArgVT;
2293 if (isCmseNSCall && (ArgVT == MVT::f16)) {
2294 auto LocBits = VA.getLocVT().getSizeInBits();
2295 auto MaskValue = APInt::getLowBitsSet(numBits: LocBits, loBitsSet: ArgVT.getSizeInBits());
2296 SDValue Mask =
2297 DAG.getConstant(Val: MaskValue, DL: dl, VT: MVT::getIntegerVT(BitWidth: LocBits));
2298 Arg = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::getIntegerVT(BitWidth: LocBits), Operand: Arg);
2299 Arg = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::getIntegerVT(BitWidth: LocBits), N1: Arg, N2: Mask);
2300 Arg = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VA.getLocVT(), Operand: Arg);
2301 }
2302 }
2303
2304 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2305 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2306 SDValue Op0 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f64, N1: Arg,
2307 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
2308 SDValue Op1 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f64, N1: Arg,
2309 N2: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
2310
2311 PassF64ArgInRegs(dl, DAG, Chain, Arg&: Op0, RegsToPass, VA, NextVA&: ArgLocs[++i],
2312 StackPtr, MemOpChains, IsTailCall: isTailCall, SPDiff);
2313
2314 VA = ArgLocs[++i]; // skip ahead to next loc
2315 if (VA.isRegLoc()) {
2316 PassF64ArgInRegs(dl, DAG, Chain, Arg&: Op1, RegsToPass, VA, NextVA&: ArgLocs[++i],
2317 StackPtr, MemOpChains, IsTailCall: isTailCall, SPDiff);
2318 } else {
2319 assert(VA.isMemLoc());
2320 SDValue DstAddr;
2321 MachinePointerInfo DstInfo;
2322 std::tie(args&: DstAddr, args&: DstInfo) =
2323 computeAddrForCallArg(dl, DAG, VA, StackPtr, IsTailCall: isTailCall, SPDiff);
2324 MemOpChains.push_back(Elt: DAG.getStore(Chain, dl, Val: Op1, Ptr: DstAddr, PtrInfo: DstInfo));
2325 }
2326 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2327 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, NextVA&: ArgLocs[++i],
2328 StackPtr, MemOpChains, IsTailCall: isTailCall, SPDiff);
2329 } else if (VA.isRegLoc()) {
2330 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2331 Outs[0].VT == MVT::i32) {
2332 assert(VA.getLocVT() == MVT::i32 &&
2333 "unexpected calling convention register assignment");
2334 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2335 "unexpected use of 'returned'");
2336 isThisReturn = true;
2337 }
2338 const TargetOptions &Options = DAG.getTarget().Options;
2339 if (Options.EmitCallSiteInfo)
2340 CSInfo.ArgRegPairs.emplace_back(Args: VA.getLocReg(), Args&: i);
2341 RegsToPass.push_back(Elt: std::make_pair(x: VA.getLocReg(), y&: Arg));
2342 } else if (isByVal) {
2343 assert(VA.isMemLoc());
2344 unsigned offset = 0;
2345
2346 // True if this byval aggregate will be split between registers
2347 // and memory.
2348 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2349 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2350
2351 SDValue ByValSrc;
2352 bool NeedsStackCopy;
2353 if (auto It = ByValTemporaries.find(Val: realArgIdx);
2354 It != ByValTemporaries.end()) {
2355 ByValSrc = It->second;
2356 NeedsStackCopy = true;
2357 } else {
2358 ByValSrc = Arg;
2359 NeedsStackCopy = !isTailCall;
2360 }
2361
2362 // If part of the argument is in registers, load them.
2363 if (CurByValIdx < ByValArgsCount) {
2364 unsigned RegBegin, RegEnd;
2365 CCInfo.getInRegsParamInfo(InRegsParamRecordIndex: CurByValIdx, BeginReg&: RegBegin, EndReg&: RegEnd);
2366
2367 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
2368 unsigned int i, j;
2369 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2370 SDValue Const = DAG.getConstant(Val: 4*i, DL: dl, VT: MVT::i32);
2371 SDValue AddArg = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PtrVT, N1: ByValSrc, N2: Const);
2372 SDValue Load =
2373 DAG.getLoad(VT: PtrVT, dl, Chain, Ptr: AddArg, PtrInfo: MachinePointerInfo(),
2374 Alignment: DAG.InferPtrAlign(Ptr: AddArg));
2375 MemOpChains.push_back(Elt: Load.getValue(R: 1));
2376 RegsToPass.push_back(Elt: std::make_pair(x&: j, y&: Load));
2377 }
2378
2379 // If parameter size outsides register area, "offset" value
2380 // helps us to calculate stack slot for remained part properly.
2381 offset = RegEnd - RegBegin;
2382
2383 CCInfo.nextInRegsParam();
2384 }
2385
2386 // If the memory part of the argument isn't already in the correct place
2387 // (which can happen with tail calls), copy it into the argument area.
2388 if (NeedsStackCopy && Flags.getByValSize() > 4 * offset) {
2389 auto PtrVT = getPointerTy(DL: DAG.getDataLayout());
2390 SDValue Dst;
2391 MachinePointerInfo DstInfo;
2392 std::tie(args&: Dst, args&: DstInfo) =
2393 computeAddrForCallArg(dl, DAG, VA, StackPtr, IsTailCall: isTailCall, SPDiff);
2394 SDValue SrcOffset = DAG.getIntPtrConstant(Val: 4*offset, DL: dl);
2395 SDValue Src = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PtrVT, N1: ByValSrc, N2: SrcOffset);
2396 SDValue SizeNode = DAG.getConstant(Val: Flags.getByValSize() - 4*offset, DL: dl,
2397 VT: MVT::i32);
2398 SDValue AlignNode =
2399 DAG.getConstant(Val: Flags.getNonZeroByValAlign().value(), DL: dl, VT: MVT::i32);
2400
2401 SDVTList VTs = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
2402 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2403 MemOpChains.push_back(Elt: DAG.getNode(Opcode: ARMISD::COPY_STRUCT_BYVAL, DL: dl, VTList: VTs,
2404 Ops));
2405 }
2406 } else {
2407 assert(VA.isMemLoc());
2408 SDValue DstAddr;
2409 MachinePointerInfo DstInfo;
2410 std::tie(args&: DstAddr, args&: DstInfo) =
2411 computeAddrForCallArg(dl, DAG, VA, StackPtr, IsTailCall: isTailCall, SPDiff);
2412
2413 SDValue Store = DAG.getStore(Chain, dl, Val: Arg, Ptr: DstAddr, PtrInfo: DstInfo);
2414 MemOpChains.push_back(Elt: Store);
2415 }
2416 }
2417
2418 if (!MemOpChains.empty())
2419 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: MemOpChains);
2420
2421 // Build a sequence of copy-to-reg nodes chained together with token chain
2422 // and flag operands which copy the outgoing args into the appropriate regs.
2423 SDValue InGlue;
2424 for (const auto &[Reg, N] : RegsToPass) {
2425 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, Glue: InGlue);
2426 InGlue = Chain.getValue(R: 1);
2427 }
2428
2429 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2430 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2431 // node so that legalize doesn't hack it.
2432 bool isDirect = false;
2433
2434 const TargetMachine &TM = getTargetMachine();
2435 const Triple &TT = TM.getTargetTriple();
2436 const GlobalValue *GVal = nullptr;
2437 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Val&: Callee))
2438 GVal = G->getGlobal();
2439 bool isStub = !TM.shouldAssumeDSOLocal(GV: GVal) && TT.isOSBinFormatMachO();
2440
2441 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2442 bool isLocalARMFunc = false;
2443 auto PtrVt = getPointerTy(DL: DAG.getDataLayout());
2444
2445 if (Subtarget->genLongCalls()) {
2446 assert((!isPositionIndependent() || TT.isOSWindows()) &&
2447 "long-calls codegen is not position independent!");
2448 // Handle a global address or an external symbol. If it's not one of
2449 // those, the target's already in a register, so we don't need to do
2450 // anything extra.
2451 if (isa<GlobalAddressSDNode>(Val: Callee)) {
2452 if (Subtarget->genExecuteOnly()) {
2453 if (Subtarget->useMovt())
2454 ++NumMovwMovt;
2455 Callee = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: PtrVt,
2456 Operand: DAG.getTargetGlobalAddress(GV: GVal, DL: dl, VT: PtrVt));
2457 } else {
2458 // Create a constant pool entry for the callee address
2459 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2460 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2461 C: GVal, ID: ARMPCLabelIndex, Kind: ARMCP::CPValue, PCAdj: 0);
2462
2463 // Get the address of the callee into a register
2464 SDValue Addr = DAG.getTargetConstantPool(C: CPV, VT: PtrVt, Align: Align(4));
2465 Addr = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: Addr);
2466 Callee = DAG.getLoad(
2467 VT: PtrVt, dl, Chain: DAG.getEntryNode(), Ptr: Addr,
2468 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
2469 }
2470 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Val&: Callee)) {
2471 const char *Sym = S->getSymbol();
2472
2473 if (Subtarget->genExecuteOnly()) {
2474 if (Subtarget->useMovt())
2475 ++NumMovwMovt;
2476 Callee = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: PtrVt,
2477 Operand: DAG.getTargetGlobalAddress(GV: GVal, DL: dl, VT: PtrVt));
2478 } else {
2479 // Create a constant pool entry for the callee address
2480 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2481 ARMConstantPoolValue *CPV = ARMConstantPoolSymbol::Create(
2482 C&: *DAG.getContext(), s: Sym, ID: ARMPCLabelIndex, PCAdj: 0);
2483
2484 // Get the address of the callee into a register
2485 SDValue Addr = DAG.getTargetConstantPool(C: CPV, VT: PtrVt, Align: Align(4));
2486 Addr = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: Addr);
2487 Callee = DAG.getLoad(
2488 VT: PtrVt, dl, Chain: DAG.getEntryNode(), Ptr: Addr,
2489 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
2490 }
2491 }
2492 } else if (isa<GlobalAddressSDNode>(Val: Callee)) {
2493 if (!PreferIndirect) {
2494 isDirect = true;
2495 bool isDef = GVal->isStrongDefinitionForLinker();
2496
2497 // ARM call to a local ARM function is predicable.
2498 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2499 // tBX takes a register source operand.
2500 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2501 assert(TT.isOSBinFormatMachO() && "WrapperPIC use on non-MachO?");
2502 Callee = DAG.getNode(
2503 Opcode: ARMISD::WrapperPIC, DL: dl, VT: PtrVt,
2504 Operand: DAG.getTargetGlobalAddress(GV: GVal, DL: dl, VT: PtrVt, offset: 0, TargetFlags: ARMII::MO_NONLAZY));
2505 Callee = DAG.getLoad(
2506 VT: PtrVt, dl, Chain: DAG.getEntryNode(), Ptr: Callee,
2507 PtrInfo: MachinePointerInfo::getGOT(MF&: DAG.getMachineFunction()), Alignment: MaybeAlign(),
2508 MMOFlags: MachineMemOperand::MODereferenceable |
2509 MachineMemOperand::MOInvariant);
2510 } else if (Subtarget->isTargetCOFF()) {
2511 assert(Subtarget->isTargetWindows() &&
2512 "Windows is the only supported COFF target");
2513 unsigned TargetFlags = ARMII::MO_NO_FLAG;
2514 if (GVal->hasDLLImportStorageClass())
2515 TargetFlags = ARMII::MO_DLLIMPORT;
2516 else if (!TM.shouldAssumeDSOLocal(GV: GVal))
2517 TargetFlags = ARMII::MO_COFFSTUB;
2518 Callee = DAG.getTargetGlobalAddress(GV: GVal, DL: dl, VT: PtrVt, /*offset=*/0,
2519 TargetFlags);
2520 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2521 Callee =
2522 DAG.getLoad(VT: PtrVt, dl, Chain: DAG.getEntryNode(),
2523 Ptr: DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: PtrVt, Operand: Callee),
2524 PtrInfo: MachinePointerInfo::getGOT(MF&: DAG.getMachineFunction()));
2525 } else {
2526 Callee = DAG.getTargetGlobalAddress(GV: GVal, DL: dl, VT: PtrVt, offset: 0, TargetFlags: 0);
2527 }
2528 }
2529 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Val&: Callee)) {
2530 isDirect = true;
2531 // tBX takes a register source operand.
2532 const char *Sym = S->getSymbol();
2533 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2534 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2535 ARMConstantPoolValue *CPV =
2536 ARMConstantPoolSymbol::Create(C&: *DAG.getContext(), s: Sym,
2537 ID: ARMPCLabelIndex, PCAdj: 4);
2538 SDValue CPAddr = DAG.getTargetConstantPool(C: CPV, VT: PtrVt, Align: Align(4));
2539 CPAddr = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: CPAddr);
2540 Callee = DAG.getLoad(
2541 VT: PtrVt, dl, Chain: DAG.getEntryNode(), Ptr: CPAddr,
2542 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
2543 SDValue PICLabel = DAG.getConstant(Val: ARMPCLabelIndex, DL: dl, VT: MVT::i32);
2544 Callee = DAG.getNode(Opcode: ARMISD::PIC_ADD, DL: dl, VT: PtrVt, N1: Callee, N2: PICLabel);
2545 } else {
2546 Callee = DAG.getTargetExternalSymbol(Sym, VT: PtrVt, TargetFlags: 0);
2547 }
2548 }
2549
2550 if (isCmseNSCall) {
2551 assert(!isARMFunc && !isDirect &&
2552 "Cannot handle call to ARM function or direct call");
2553 if (NumBytes > 0) {
2554 DAG.getContext()->diagnose(
2555 DI: DiagnosticInfoUnsupported(DAG.getMachineFunction().getFunction(),
2556 "call to non-secure function would require "
2557 "passing arguments on stack",
2558 dl.getDebugLoc()));
2559 }
2560 if (isStructRet) {
2561 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
2562 DAG.getMachineFunction().getFunction(),
2563 "call to non-secure function would return value through pointer",
2564 dl.getDebugLoc()));
2565 }
2566 }
2567
2568 // FIXME: handle tail calls differently.
2569 unsigned CallOpc;
2570 if (Subtarget->isThumb()) {
2571 if (GuardWithBTI)
2572 CallOpc = ARMISD::t2CALL_BTI;
2573 else if (isCmseNSCall)
2574 CallOpc = ARMISD::tSECALL;
2575 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2576 CallOpc = ARMISD::CALL_NOLINK;
2577 else
2578 CallOpc = ARMISD::CALL;
2579 } else {
2580 if (!isDirect && !Subtarget->hasV5TOps())
2581 CallOpc = ARMISD::CALL_NOLINK;
2582 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2583 // Emit regular call when code size is the priority
2584 !Subtarget->hasMinSize())
2585 // "mov lr, pc; b _foo" to avoid confusing the RSP
2586 CallOpc = ARMISD::CALL_NOLINK;
2587 else
2588 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2589 }
2590
2591 // We don't usually want to end the call-sequence here because we would tidy
2592 // the frame up *after* the call, however in the ABI-changing tail-call case
2593 // we've carefully laid out the parameters so that when sp is reset they'll be
2594 // in the correct location.
2595 if (isTailCall && !isSibCall) {
2596 Chain = DAG.getCALLSEQ_END(Chain, Size1: 0, Size2: 0, Glue: InGlue, DL: dl);
2597 InGlue = Chain.getValue(R: 1);
2598 }
2599
2600 std::vector<SDValue> Ops;
2601 Ops.push_back(x: Chain);
2602 Ops.push_back(x: Callee);
2603
2604 if (isTailCall) {
2605 Ops.push_back(x: DAG.getSignedTargetConstant(Val: SPDiff, DL: dl, VT: MVT::i32));
2606 }
2607
2608 // Add argument registers to the end of the list so that they are known live
2609 // into the call.
2610 for (const auto &[Reg, N] : RegsToPass)
2611 Ops.push_back(x: DAG.getRegister(Reg, VT: N.getValueType()));
2612
2613 // Add a register mask operand representing the call-preserved registers.
2614 const uint32_t *Mask;
2615 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2616 if (isThisReturn) {
2617 // For 'this' returns, use the R0-preserving mask if applicable
2618 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2619 if (!Mask) {
2620 // Set isThisReturn to false if the calling convention is not one that
2621 // allows 'returned' to be modeled in this way, so LowerCallResult does
2622 // not try to pass 'this' straight through
2623 isThisReturn = false;
2624 Mask = ARI->getCallPreservedMask(MF, CallConv);
2625 }
2626 } else
2627 Mask = ARI->getCallPreservedMask(MF, CallConv);
2628
2629 assert(Mask && "Missing call preserved mask for calling convention");
2630 Ops.push_back(x: DAG.getRegisterMask(RegMask: Mask));
2631
2632 if (InGlue.getNode())
2633 Ops.push_back(x: InGlue);
2634
2635 if (isTailCall) {
2636 MF.getFrameInfo().setHasTailCall();
2637 SDValue Ret = DAG.getNode(Opcode: ARMISD::TC_RETURN, DL: dl, VT: MVT::Other, Ops);
2638 if (CLI.CFIType)
2639 Ret.getNode()->setCFIType(CLI.CFIType->getZExtValue());
2640 DAG.addNoMergeSiteInfo(Node: Ret.getNode(), NoMerge: CLI.NoMerge);
2641 DAG.addCallSiteInfo(Node: Ret.getNode(), CallInfo: std::move(CSInfo));
2642 return Ret;
2643 }
2644
2645 // Returns a chain and a flag for retval copy to use.
2646 Chain = DAG.getNode(Opcode: CallOpc, DL: dl, ResultTys: {MVT::Other, MVT::Glue}, Ops);
2647 if (CLI.CFIType)
2648 Chain.getNode()->setCFIType(CLI.CFIType->getZExtValue());
2649 DAG.addNoMergeSiteInfo(Node: Chain.getNode(), NoMerge: CLI.NoMerge);
2650 InGlue = Chain.getValue(R: 1);
2651 DAG.addCallSiteInfo(Node: Chain.getNode(), CallInfo: std::move(CSInfo));
2652
2653 // If we're guaranteeing tail-calls will be honoured, the callee must
2654 // pop its own argument stack on return. But this call is *not* a tail call so
2655 // we need to undo that after it returns to restore the status-quo.
2656 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
2657 uint64_t CalleePopBytes =
2658 canGuaranteeTCO(CC: CallConv, GuaranteeTailCalls: TailCallOpt) ? alignTo(Value: NumBytes, Align: 16) : -1U;
2659
2660 Chain = DAG.getCALLSEQ_END(Chain, Size1: NumBytes, Size2: CalleePopBytes, Glue: InGlue, DL: dl);
2661 if (!Ins.empty())
2662 InGlue = Chain.getValue(R: 1);
2663
2664 // Handle result values, copying them out of physregs into vregs that we
2665 // return.
2666 return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, dl, DAG,
2667 InVals, isThisReturn,
2668 ThisVal: isThisReturn ? OutVals[0] : SDValue(), isCmseNSCall);
2669}
2670
2671/// HandleByVal - Every parameter *after* a byval parameter is passed
2672/// on the stack. Remember the next parameter register to allocate,
2673/// and then confiscate the rest of the parameter registers to insure
2674/// this.
2675void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2676 Align Alignment) const {
2677 // Byval (as with any stack) slots are always at least 4 byte aligned.
2678 Alignment = std::max(a: Alignment, b: Align(4));
2679
2680 MCRegister Reg = State->AllocateReg(Regs: GPRArgRegs);
2681 if (!Reg)
2682 return;
2683
2684 unsigned AlignInRegs = Alignment.value() / 4;
2685 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2686 for (unsigned i = 0; i < Waste; ++i)
2687 Reg = State->AllocateReg(Regs: GPRArgRegs);
2688
2689 if (!Reg)
2690 return;
2691
2692 unsigned Excess = 4 * (ARM::R4 - Reg);
2693
2694 // Special case when NSAA != SP and parameter size greater than size of
2695 // all remained GPR regs. In that case we can't split parameter, we must
2696 // send it to stack. We also must set NCRN to R4, so waste all
2697 // remained registers.
2698 const unsigned NSAAOffset = State->getStackSize();
2699 if (NSAAOffset != 0 && Size > Excess) {
2700 while (State->AllocateReg(Regs: GPRArgRegs))
2701 ;
2702 return;
2703 }
2704
2705 // First register for byval parameter is the first register that wasn't
2706 // allocated before this method call, so it would be "reg".
2707 // If parameter is small enough to be saved in range [reg, r4), then
2708 // the end (first after last) register would be reg + param-size-in-regs,
2709 // else parameter would be splitted between registers and stack,
2710 // end register would be r4 in this case.
2711 unsigned ByValRegBegin = Reg;
2712 unsigned ByValRegEnd = std::min<unsigned>(a: Reg + Size / 4, b: ARM::R4);
2713 State->addInRegsParamInfo(RegBegin: ByValRegBegin, RegEnd: ByValRegEnd);
2714 // Note, first register is allocated in the beginning of function already,
2715 // allocate remained amount of registers we need.
2716 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2717 State->AllocateReg(Regs: GPRArgRegs);
2718 // A byval parameter that is split between registers and memory needs its
2719 // size truncated here.
2720 // In the case where the entire structure fits in registers, we set the
2721 // size in memory to zero.
2722 Size = std::max<int>(a: Size - Excess, b: 0);
2723}
2724
2725/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2726/// for tail call optimization. Targets which want to do tail call
2727/// optimization should implement this function. Note that this function also
2728/// processes musttail calls, so when this function returns false on a valid
2729/// musttail call, a fatal backend error occurs.
2730bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2731 TargetLowering::CallLoweringInfo &CLI, CCState &CCInfo,
2732 SmallVectorImpl<CCValAssign> &ArgLocs, const bool isIndirect) const {
2733 CallingConv::ID CalleeCC = CLI.CallConv;
2734 SDValue Callee = CLI.Callee;
2735 bool isVarArg = CLI.IsVarArg;
2736 const SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2737 const SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2738 const SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2739 const SelectionDAG &DAG = CLI.DAG;
2740 MachineFunction &MF = DAG.getMachineFunction();
2741 const Function &CallerF = MF.getFunction();
2742 CallingConv::ID CallerCC = CallerF.getCallingConv();
2743
2744 assert(Subtarget->supportsTailCall());
2745
2746 // Indirect tail-calls require a register to hold the target address. That
2747 // register must be:
2748 // * Allocatable (i.e. r0-r7 if the target is Thumb1).
2749 // * Not callee-saved, so must be one of r0-r3 or r12.
2750 // * Not used to hold an argument to the tail-called function, which might be
2751 // in r0-r3.
2752 // * Not used to hold the return address authentication code, which is in r12
2753 // if enabled.
2754 // Sometimes, no register matches all of these conditions, so we can't do a
2755 // tail-call.
2756 if (!isa<GlobalAddressSDNode>(Val: Callee.getNode()) || isIndirect) {
2757 SmallSet<MCPhysReg, 5> AddressRegisters = {ARM::R0, ARM::R1, ARM::R2,
2758 ARM::R3};
2759 if (!(Subtarget->isThumb1Only() ||
2760 MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress(SpillsLR: true)))
2761 AddressRegisters.insert(V: ARM::R12);
2762 for (const CCValAssign &AL : ArgLocs)
2763 if (AL.isRegLoc())
2764 AddressRegisters.erase(V: AL.getLocReg());
2765 if (AddressRegisters.empty()) {
2766 LLVM_DEBUG(dbgs() << "false (no reg to hold function pointer)\n");
2767 return false;
2768 }
2769 }
2770
2771 // Look for obvious safe cases to perform tail call optimization that do not
2772 // require ABI changes. This is what gcc calls sibcall.
2773
2774 // Exception-handling functions need a special set of instructions to indicate
2775 // a return to the hardware. Tail-calling another function would probably
2776 // break this.
2777 if (CallerF.hasFnAttribute(Kind: "interrupt")) {
2778 LLVM_DEBUG(dbgs() << "false (interrupt attribute)\n");
2779 return false;
2780 }
2781
2782 if (canGuaranteeTCO(CC: CalleeCC,
2783 GuaranteeTailCalls: getTargetMachine().Options.GuaranteedTailCallOpt)) {
2784 LLVM_DEBUG(dbgs() << (CalleeCC == CallerCC ? "true" : "false")
2785 << " (guaranteed tail-call CC)\n");
2786 return CalleeCC == CallerCC;
2787 }
2788
2789 // Also avoid sibcall optimization if either caller or callee uses struct
2790 // return semantics.
2791 bool isCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
2792 bool isCallerStructRet = MF.getFunction().hasStructRetAttr();
2793 if (isCalleeStructRet != isCallerStructRet) {
2794 LLVM_DEBUG(dbgs() << "false (struct-ret)\n");
2795 return false;
2796 }
2797
2798 // Externally-defined functions with weak linkage should not be
2799 // tail-called on ARM when the OS does not support dynamic
2800 // pre-emption of symbols, as the AAELF spec requires normal calls
2801 // to undefined weak functions to be replaced with a NOP or jump to the
2802 // next instruction. The behaviour of branch instructions in this
2803 // situation (as used for tail calls) is implementation-defined, so we
2804 // cannot rely on the linker replacing the tail call with a return.
2805 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Val&: Callee)) {
2806 const GlobalValue *GV = G->getGlobal();
2807 const Triple &TT = getTargetMachine().getTargetTriple();
2808 if (GV->hasExternalWeakLinkage() &&
2809 (!TT.isOSWindows() || TT.isOSBinFormatELF() ||
2810 TT.isOSBinFormatMachO())) {
2811 LLVM_DEBUG(dbgs() << "false (external weak linkage)\n");
2812 return false;
2813 }
2814 }
2815
2816 // Check that the call results are passed in the same way.
2817 LLVMContext &C = *DAG.getContext();
2818 if (!CCState::resultsCompatible(
2819 CalleeCC: getEffectiveCallingConv(CC: CalleeCC, isVarArg),
2820 CallerCC: getEffectiveCallingConv(CC: CallerCC, isVarArg: CallerF.isVarArg()), MF, C, Ins,
2821 CalleeFn: CCAssignFnForReturn(CC: CalleeCC, isVarArg),
2822 CallerFn: CCAssignFnForReturn(CC: CallerCC, isVarArg: CallerF.isVarArg()))) {
2823 LLVM_DEBUG(dbgs() << "false (incompatible results)\n");
2824 return false;
2825 }
2826 // The callee has to preserve all registers the caller needs to preserve.
2827 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2828 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2829 if (CalleeCC != CallerCC) {
2830 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2831 if (!TRI->regmaskSubsetEqual(mask0: CallerPreserved, mask1: CalleePreserved)) {
2832 LLVM_DEBUG(dbgs() << "false (not all registers preserved)\n");
2833 return false;
2834 }
2835 }
2836
2837 // If Caller's vararg argument has been split between registers and stack, do
2838 // not perform tail call, since part of the argument is in caller's local
2839 // frame.
2840 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2841 if (CLI.IsVarArg && AFI_Caller->getArgRegsSaveSize()) {
2842 LLVM_DEBUG(dbgs() << "false (arg reg save area)\n");
2843 return false;
2844 }
2845
2846 // If the callee takes no arguments then go on to check the results of the
2847 // call.
2848 const MachineRegisterInfo &MRI = MF.getRegInfo();
2849 if (!parametersInCSRMatch(MRI, CallerPreservedMask: CallerPreserved, ArgLocs, OutVals)) {
2850 LLVM_DEBUG(dbgs() << "false (parameters in CSRs do not match)\n");
2851 return false;
2852 }
2853
2854 // If the stack arguments for this call do not fit into our own save area then
2855 // the call cannot be made tail.
2856 if (CCInfo.getStackSize() > AFI_Caller->getArgumentStackSize())
2857 return false;
2858
2859 LLVM_DEBUG(dbgs() << "true\n");
2860 return true;
2861}
2862
2863bool
2864ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2865 MachineFunction &MF, bool isVarArg,
2866 const SmallVectorImpl<ISD::OutputArg> &Outs,
2867 LLVMContext &Context, const Type *RetTy) const {
2868 SmallVector<CCValAssign, 16> RVLocs;
2869 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2870 return CCInfo.CheckReturn(Outs, Fn: CCAssignFnForReturn(CC: CallConv, isVarArg));
2871}
2872
2873static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2874 const SDLoc &DL, SelectionDAG &DAG) {
2875 const MachineFunction &MF = DAG.getMachineFunction();
2876 const Function &F = MF.getFunction();
2877
2878 StringRef IntKind = F.getFnAttribute(Kind: "interrupt").getValueAsString();
2879
2880 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2881 // version of the "preferred return address". These offsets affect the return
2882 // instruction if this is a return from PL1 without hypervisor extensions.
2883 // IRQ/FIQ: +4 "subs pc, lr, #4"
2884 // SWI: 0 "subs pc, lr, #0"
2885 // ABORT: +4 "subs pc, lr, #4"
2886 // UNDEF: +4/+2 "subs pc, lr, #0"
2887 // UNDEF varies depending on where the exception came from ARM or Thumb
2888 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2889
2890 int64_t LROffset;
2891 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2892 IntKind == "ABORT")
2893 LROffset = 4;
2894 else if (IntKind == "SWI" || IntKind == "UNDEF")
2895 LROffset = 0;
2896 else
2897 report_fatal_error(reason: "Unsupported interrupt attribute. If present, value "
2898 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2899
2900 RetOps.insert(I: RetOps.begin() + 1,
2901 Elt: DAG.getConstant(Val: LROffset, DL, VT: MVT::i32, isTarget: false));
2902
2903 return DAG.getNode(Opcode: ARMISD::INTRET_GLUE, DL, VT: MVT::Other, Ops: RetOps);
2904}
2905
2906SDValue
2907ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2908 bool isVarArg,
2909 const SmallVectorImpl<ISD::OutputArg> &Outs,
2910 const SmallVectorImpl<SDValue> &OutVals,
2911 const SDLoc &dl, SelectionDAG &DAG) const {
2912 // CCValAssign - represent the assignment of the return value to a location.
2913 SmallVector<CCValAssign, 16> RVLocs;
2914
2915 // CCState - Info about the registers and stack slots.
2916 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2917 *DAG.getContext());
2918
2919 // Analyze outgoing return values.
2920 CCInfo.AnalyzeReturn(Outs, Fn: CCAssignFnForReturn(CC: CallConv, isVarArg));
2921
2922 SDValue Glue;
2923 SmallVector<SDValue, 4> RetOps;
2924 RetOps.push_back(Elt: Chain); // Operand #0 = Chain (updated below)
2925 bool isLittleEndian = Subtarget->isLittle();
2926
2927 MachineFunction &MF = DAG.getMachineFunction();
2928 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2929 AFI->setReturnRegsCount(RVLocs.size());
2930
2931 // Report error if cmse entry function returns structure through first ptr arg.
2932 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
2933 // Note: using an empty SDLoc(), as the first line of the function is a
2934 // better place to report than the last line.
2935 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
2936 DAG.getMachineFunction().getFunction(),
2937 "secure entry function would return value through pointer",
2938 SDLoc().getDebugLoc()));
2939 }
2940
2941 // Copy the result values into the output registers.
2942 for (unsigned i = 0, realRVLocIdx = 0;
2943 i != RVLocs.size();
2944 ++i, ++realRVLocIdx) {
2945 CCValAssign &VA = RVLocs[i];
2946 assert(VA.isRegLoc() && "Can only return in registers!");
2947
2948 SDValue Arg = OutVals[realRVLocIdx];
2949 bool ReturnF16 = false;
2950
2951 if (Subtarget->hasFullFP16() && getTM().isTargetHardFloat()) {
2952 // Half-precision return values can be returned like this:
2953 //
2954 // t11 f16 = fadd ...
2955 // t12: i16 = bitcast t11
2956 // t13: i32 = zero_extend t12
2957 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2958 //
2959 // to avoid code generation for bitcasts, we simply set Arg to the node
2960 // that produces the f16 value, t11 in this case.
2961 //
2962 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2963 SDValue ZE = Arg.getOperand(i: 0);
2964 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2965 SDValue BC = ZE.getOperand(i: 0);
2966 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2967 Arg = BC.getOperand(i: 0);
2968 ReturnF16 = true;
2969 }
2970 }
2971 }
2972 }
2973
2974 switch (VA.getLocInfo()) {
2975 default: llvm_unreachable("Unknown loc info!");
2976 case CCValAssign::Full: break;
2977 case CCValAssign::BCvt:
2978 if (!ReturnF16)
2979 Arg = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VA.getLocVT(), Operand: Arg);
2980 break;
2981 }
2982
2983 // Mask f16 arguments if this is a CMSE nonsecure entry.
2984 auto RetVT = Outs[realRVLocIdx].ArgVT;
2985 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
2986 if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
2987 Arg = MoveFromHPR(dl, DAG, LocVT: VA.getLocVT(), ValVT: VA.getValVT(), Val: Arg);
2988 } else {
2989 auto LocBits = VA.getLocVT().getSizeInBits();
2990 auto MaskValue = APInt::getLowBitsSet(numBits: LocBits, loBitsSet: RetVT.getSizeInBits());
2991 SDValue Mask =
2992 DAG.getConstant(Val: MaskValue, DL: dl, VT: MVT::getIntegerVT(BitWidth: LocBits));
2993 Arg = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::getIntegerVT(BitWidth: LocBits), Operand: Arg);
2994 Arg = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::getIntegerVT(BitWidth: LocBits), N1: Arg, N2: Mask);
2995 Arg = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VA.getLocVT(), Operand: Arg);
2996 }
2997 }
2998
2999 if (VA.needsCustom() &&
3000 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3001 if (VA.getLocVT() == MVT::v2f64) {
3002 // Extract the first half and return it in two registers.
3003 SDValue Half = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f64, N1: Arg,
3004 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
3005 SDValue HalfGPRs = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl,
3006 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N: Half);
3007
3008 Chain =
3009 DAG.getCopyToReg(Chain, dl, Reg: VA.getLocReg(),
3010 N: HalfGPRs.getValue(R: isLittleEndian ? 0 : 1), Glue);
3011 Glue = Chain.getValue(R: 1);
3012 RetOps.push_back(Elt: DAG.getRegister(Reg: VA.getLocReg(), VT: VA.getLocVT()));
3013 VA = RVLocs[++i]; // skip ahead to next loc
3014 Chain =
3015 DAG.getCopyToReg(Chain, dl, Reg: VA.getLocReg(),
3016 N: HalfGPRs.getValue(R: isLittleEndian ? 1 : 0), Glue);
3017 Glue = Chain.getValue(R: 1);
3018 RetOps.push_back(Elt: DAG.getRegister(Reg: VA.getLocReg(), VT: VA.getLocVT()));
3019 VA = RVLocs[++i]; // skip ahead to next loc
3020
3021 // Extract the 2nd half and fall through to handle it as an f64 value.
3022 Arg = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f64, N1: Arg,
3023 N2: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
3024 }
3025 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
3026 // available.
3027 SDValue fmrrd = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl,
3028 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N: Arg);
3029 Chain = DAG.getCopyToReg(Chain, dl, Reg: VA.getLocReg(),
3030 N: fmrrd.getValue(R: isLittleEndian ? 0 : 1), Glue);
3031 Glue = Chain.getValue(R: 1);
3032 RetOps.push_back(Elt: DAG.getRegister(Reg: VA.getLocReg(), VT: VA.getLocVT()));
3033 VA = RVLocs[++i]; // skip ahead to next loc
3034 Chain = DAG.getCopyToReg(Chain, dl, Reg: VA.getLocReg(),
3035 N: fmrrd.getValue(R: isLittleEndian ? 1 : 0), Glue);
3036 } else
3037 Chain = DAG.getCopyToReg(Chain, dl, Reg: VA.getLocReg(), N: Arg, Glue);
3038
3039 // Guarantee that all emitted copies are
3040 // stuck together, avoiding something bad.
3041 Glue = Chain.getValue(R: 1);
3042 RetOps.push_back(Elt: DAG.getRegister(
3043 Reg: VA.getLocReg(), VT: ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3044 }
3045 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3046 const MCPhysReg *I =
3047 TRI->getCalleeSavedRegsViaCopy(MF: &DAG.getMachineFunction());
3048 if (I) {
3049 for (; *I; ++I) {
3050 if (ARM::GPRRegClass.contains(Reg: *I))
3051 RetOps.push_back(Elt: DAG.getRegister(Reg: *I, VT: MVT::i32));
3052 else if (ARM::DPRRegClass.contains(Reg: *I))
3053 RetOps.push_back(Elt: DAG.getRegister(Reg: *I, VT: MVT::getFloatingPointVT(BitWidth: 64)));
3054 else
3055 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3056 }
3057 }
3058
3059 // Update chain and glue.
3060 RetOps[0] = Chain;
3061 if (Glue.getNode())
3062 RetOps.push_back(Elt: Glue);
3063
3064 // CPUs which aren't M-class use a special sequence to return from
3065 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3066 // though we use "subs pc, lr, #N").
3067 //
3068 // M-class CPUs actually use a normal return sequence with a special
3069 // (hardware-provided) value in LR, so the normal code path works.
3070 if (DAG.getMachineFunction().getFunction().hasFnAttribute(Kind: "interrupt") &&
3071 !Subtarget->isMClass()) {
3072 if (Subtarget->isThumb1Only())
3073 report_fatal_error(reason: "interrupt attribute is not supported in Thumb1");
3074 return LowerInterruptReturn(RetOps, DL: dl, DAG);
3075 }
3076
3077 unsigned RetNode =
3078 AFI->isCmseNSEntryFunction() ? ARMISD::SERET_GLUE : ARMISD::RET_GLUE;
3079 return DAG.getNode(Opcode: RetNode, DL: dl, VT: MVT::Other, Ops: RetOps);
3080}
3081
3082bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3083 if (N->getNumValues() != 1)
3084 return false;
3085 if (!N->hasNUsesOfValue(NUses: 1, Value: 0))
3086 return false;
3087
3088 SDValue TCChain = Chain;
3089 SDNode *Copy = *N->user_begin();
3090 if (Copy->getOpcode() == ISD::CopyToReg) {
3091 // If the copy has a glue operand, we conservatively assume it isn't safe to
3092 // perform a tail call.
3093 if (Copy->getOperand(Num: Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3094 return false;
3095 TCChain = Copy->getOperand(Num: 0);
3096 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3097 SDNode *VMov = Copy;
3098 // f64 returned in a pair of GPRs.
3099 SmallPtrSet<SDNode*, 2> Copies;
3100 for (SDNode *U : VMov->users()) {
3101 if (U->getOpcode() != ISD::CopyToReg)
3102 return false;
3103 Copies.insert(Ptr: U);
3104 }
3105 if (Copies.size() > 2)
3106 return false;
3107
3108 for (SDNode *U : VMov->users()) {
3109 SDValue UseChain = U->getOperand(Num: 0);
3110 if (Copies.count(Ptr: UseChain.getNode()))
3111 // Second CopyToReg
3112 Copy = U;
3113 else {
3114 // We are at the top of this chain.
3115 // If the copy has a glue operand, we conservatively assume it
3116 // isn't safe to perform a tail call.
3117 if (U->getOperand(Num: U->getNumOperands() - 1).getValueType() == MVT::Glue)
3118 return false;
3119 // First CopyToReg
3120 TCChain = UseChain;
3121 }
3122 }
3123 } else if (Copy->getOpcode() == ISD::BITCAST) {
3124 // f32 returned in a single GPR.
3125 if (!Copy->hasOneUse())
3126 return false;
3127 Copy = *Copy->user_begin();
3128 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(NUses: 1, Value: 0))
3129 return false;
3130 // If the copy has a glue operand, we conservatively assume it isn't safe to
3131 // perform a tail call.
3132 if (Copy->getOperand(Num: Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3133 return false;
3134 TCChain = Copy->getOperand(Num: 0);
3135 } else {
3136 return false;
3137 }
3138
3139 bool HasRet = false;
3140 for (const SDNode *U : Copy->users()) {
3141 if (U->getOpcode() != ARMISD::RET_GLUE &&
3142 U->getOpcode() != ARMISD::INTRET_GLUE)
3143 return false;
3144 HasRet = true;
3145 }
3146
3147 if (!HasRet)
3148 return false;
3149
3150 Chain = TCChain;
3151 return true;
3152}
3153
3154bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3155 if (!Subtarget->supportsTailCall())
3156 return false;
3157
3158 if (!CI->isTailCall())
3159 return false;
3160
3161 return true;
3162}
3163
3164// Trying to write a 64 bit value so need to split into two 32 bit values first,
3165// and pass the lower and high parts through.
3166static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3167 SDLoc DL(Op);
3168 SDValue WriteValue = Op->getOperand(Num: 2);
3169
3170 // This function is only supposed to be called for i64 type argument.
3171 assert(WriteValue.getValueType() == MVT::i64
3172 && "LowerWRITE_REGISTER called for non-i64 type argument.");
3173
3174 SDValue Lo, Hi;
3175 std::tie(args&: Lo, args&: Hi) = DAG.SplitScalar(N: WriteValue, DL, LoVT: MVT::i32, HiVT: MVT::i32);
3176 SDValue Ops[] = { Op->getOperand(Num: 0), Op->getOperand(Num: 1), Lo, Hi };
3177 return DAG.getNode(Opcode: ISD::WRITE_REGISTER, DL, VT: MVT::Other, Ops);
3178}
3179
3180// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3181// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3182// one of the above mentioned nodes. It has to be wrapped because otherwise
3183// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3184// be used to form addressing mode. These wrapped nodes will be selected
3185// into MOVi.
3186SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3187 SelectionDAG &DAG) const {
3188 EVT PtrVT = Op.getValueType();
3189 // FIXME there is no actual debug info here
3190 SDLoc dl(Op);
3191 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Val&: Op);
3192 SDValue Res;
3193
3194 // When generating execute-only code Constant Pools must be promoted to the
3195 // global data section. It's a bit ugly that we can't share them across basic
3196 // blocks, but this way we guarantee that execute-only behaves correct with
3197 // position-independent addressing modes.
3198 if (Subtarget->genExecuteOnly()) {
3199 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3200 auto *T = CP->getType();
3201 auto C = const_cast<Constant*>(CP->getConstVal());
3202 auto M = DAG.getMachineFunction().getFunction().getParent();
3203 auto GV = new GlobalVariable(
3204 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3205 Twine(DAG.getDataLayout().getInternalSymbolPrefix()) + "CP" +
3206 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3207 Twine(AFI->createPICLabelUId()));
3208 SDValue GA = DAG.getTargetGlobalAddress(GV, DL: dl, VT: PtrVT);
3209 return LowerGlobalAddress(Op: GA, DAG);
3210 }
3211
3212 // The 16-bit ADR instruction can only encode offsets that are multiples of 4,
3213 // so we need to align to at least 4 bytes when we don't have 32-bit ADR.
3214 Align CPAlign = CP->getAlign();
3215 if (Subtarget->isThumb1Only())
3216 CPAlign = std::max(a: CPAlign, b: Align(4));
3217 if (CP->isMachineConstantPoolEntry())
3218 Res =
3219 DAG.getTargetConstantPool(C: CP->getMachineCPVal(), VT: PtrVT, Align: CPAlign);
3220 else
3221 Res = DAG.getTargetConstantPool(C: CP->getConstVal(), VT: PtrVT, Align: CPAlign);
3222 return DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: Res);
3223}
3224
3225unsigned ARMTargetLowering::getJumpTableEncoding() const {
3226 // If we don't have a 32-bit pc-relative branch instruction then the jump
3227 // table consists of block addresses. Usually this is inline, but for
3228 // execute-only it must be placed out-of-line.
3229 if (Subtarget->genExecuteOnly() && !Subtarget->hasV8MBaselineOps())
3230 return MachineJumpTableInfo::EK_BlockAddress;
3231 return MachineJumpTableInfo::EK_Inline;
3232}
3233
3234SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3235 SelectionDAG &DAG) const {
3236 MachineFunction &MF = DAG.getMachineFunction();
3237 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3238 unsigned ARMPCLabelIndex = 0;
3239 SDLoc DL(Op);
3240 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3241 const BlockAddress *BA = cast<BlockAddressSDNode>(Val&: Op)->getBlockAddress();
3242 SDValue CPAddr;
3243 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3244 if (!IsPositionIndependent) {
3245 CPAddr = DAG.getTargetConstantPool(C: BA, VT: PtrVT, Align: Align(4));
3246 } else {
3247 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3248 ARMPCLabelIndex = AFI->createPICLabelUId();
3249 ARMConstantPoolValue *CPV =
3250 ARMConstantPoolConstant::Create(C: BA, ID: ARMPCLabelIndex,
3251 Kind: ARMCP::CPBlockAddress, PCAdj);
3252 CPAddr = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3253 }
3254 CPAddr = DAG.getNode(Opcode: ARMISD::Wrapper, DL, VT: PtrVT, Operand: CPAddr);
3255 SDValue Result = DAG.getLoad(
3256 VT: PtrVT, dl: DL, Chain: DAG.getEntryNode(), Ptr: CPAddr,
3257 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3258 if (!IsPositionIndependent)
3259 return Result;
3260 SDValue PICLabel = DAG.getConstant(Val: ARMPCLabelIndex, DL, VT: MVT::i32);
3261 return DAG.getNode(Opcode: ARMISD::PIC_ADD, DL, VT: PtrVT, N1: Result, N2: PICLabel);
3262}
3263
3264/// Convert a TLS address reference into the correct sequence of loads
3265/// and calls to compute the variable's address for Darwin, and return an
3266/// SDValue containing the final node.
3267
3268/// Darwin only has one TLS scheme which must be capable of dealing with the
3269/// fully general situation, in the worst case. This means:
3270/// + "extern __thread" declaration.
3271/// + Defined in a possibly unknown dynamic library.
3272///
3273/// The general system is that each __thread variable has a [3 x i32] descriptor
3274/// which contains information used by the runtime to calculate the address. The
3275/// only part of this the compiler needs to know about is the first word, which
3276/// contains a function pointer that must be called with the address of the
3277/// entire descriptor in "r0".
3278///
3279/// Since this descriptor may be in a different unit, in general access must
3280/// proceed along the usual ARM rules. A common sequence to produce is:
3281///
3282/// movw rT1, :lower16:_var$non_lazy_ptr
3283/// movt rT1, :upper16:_var$non_lazy_ptr
3284/// ldr r0, [rT1]
3285/// ldr rT2, [r0]
3286/// blx rT2
3287/// [...address now in r0...]
3288SDValue
3289ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3290 SelectionDAG &DAG) const {
3291 assert(getTargetMachine().getTargetTriple().isOSDarwin() &&
3292 "This function expects a Darwin target");
3293 SDLoc DL(Op);
3294
3295 // First step is to get the address of the actua global symbol. This is where
3296 // the TLS descriptor lives.
3297 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3298
3299 // The first entry in the descriptor is a function pointer that we must call
3300 // to obtain the address of the variable.
3301 SDValue Chain = DAG.getEntryNode();
3302 SDValue FuncTLVGet = DAG.getLoad(
3303 VT: MVT::i32, dl: DL, Chain, Ptr: DescAddr,
3304 PtrInfo: MachinePointerInfo::getGOT(MF&: DAG.getMachineFunction()), Alignment: Align(4),
3305 MMOFlags: MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3306 MachineMemOperand::MOInvariant);
3307 Chain = FuncTLVGet.getValue(R: 1);
3308
3309 MachineFunction &F = DAG.getMachineFunction();
3310 MachineFrameInfo &MFI = F.getFrameInfo();
3311 MFI.setAdjustsStack(true);
3312
3313 // TLS calls preserve all registers except those that absolutely must be
3314 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3315 // silly).
3316 auto TRI =
3317 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3318 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3319 const uint32_t *Mask = ARI->getTLSCallPreservedMask(MF: DAG.getMachineFunction());
3320
3321 // Finally, we can make the call. This is just a degenerate version of a
3322 // normal AArch64 call node: r0 takes the address of the descriptor, and
3323 // returns the address of the variable in this thread.
3324 Chain = DAG.getCopyToReg(Chain, dl: DL, Reg: ARM::R0, N: DescAddr, Glue: SDValue());
3325 Chain =
3326 DAG.getNode(Opcode: ARMISD::CALL, DL, VTList: DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue),
3327 N1: Chain, N2: FuncTLVGet, N3: DAG.getRegister(Reg: ARM::R0, VT: MVT::i32),
3328 N4: DAG.getRegisterMask(RegMask: Mask), N5: Chain.getValue(R: 1));
3329 return DAG.getCopyFromReg(Chain, dl: DL, Reg: ARM::R0, VT: MVT::i32, Glue: Chain.getValue(R: 1));
3330}
3331
3332SDValue
3333ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3334 SelectionDAG &DAG) const {
3335 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3336 "Windows specific TLS lowering");
3337
3338 SDValue Chain = DAG.getEntryNode();
3339 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3340 SDLoc DL(Op);
3341
3342 // Load the current TEB (thread environment block)
3343 SDValue Ops[] = {Chain,
3344 DAG.getTargetConstant(Val: Intrinsic::arm_mrc, DL, VT: MVT::i32),
3345 DAG.getTargetConstant(Val: 15, DL, VT: MVT::i32),
3346 DAG.getTargetConstant(Val: 0, DL, VT: MVT::i32),
3347 DAG.getTargetConstant(Val: 13, DL, VT: MVT::i32),
3348 DAG.getTargetConstant(Val: 0, DL, VT: MVT::i32),
3349 DAG.getTargetConstant(Val: 2, DL, VT: MVT::i32)};
3350 SDValue CurrentTEB = DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL,
3351 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), Ops);
3352
3353 SDValue TEB = CurrentTEB.getValue(R: 0);
3354 Chain = CurrentTEB.getValue(R: 1);
3355
3356 // Load the ThreadLocalStoragePointer from the TEB
3357 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3358 SDValue TLSArray =
3359 DAG.getNode(Opcode: ISD::ADD, DL, VT: PtrVT, N1: TEB, N2: DAG.getIntPtrConstant(Val: 0x2c, DL));
3360 TLSArray = DAG.getLoad(VT: PtrVT, dl: DL, Chain, Ptr: TLSArray, PtrInfo: MachinePointerInfo());
3361
3362 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3363 // offset into the TLSArray.
3364
3365 // Load the TLS index from the C runtime
3366 SDValue TLSIndex =
3367 DAG.getTargetExternalSymbol(Sym: "_tls_index", VT: PtrVT, TargetFlags: ARMII::MO_NO_FLAG);
3368 TLSIndex = DAG.getNode(Opcode: ARMISD::Wrapper, DL, VT: PtrVT, Operand: TLSIndex);
3369 TLSIndex = DAG.getLoad(VT: PtrVT, dl: DL, Chain, Ptr: TLSIndex, PtrInfo: MachinePointerInfo());
3370
3371 SDValue Slot = DAG.getNode(Opcode: ISD::SHL, DL, VT: PtrVT, N1: TLSIndex,
3372 N2: DAG.getConstant(Val: 2, DL, VT: MVT::i32));
3373 SDValue TLS = DAG.getLoad(VT: PtrVT, dl: DL, Chain,
3374 Ptr: DAG.getNode(Opcode: ISD::ADD, DL, VT: PtrVT, N1: TLSArray, N2: Slot),
3375 PtrInfo: MachinePointerInfo());
3376
3377 // Get the offset of the start of the .tls section (section base)
3378 const auto *GA = cast<GlobalAddressSDNode>(Val&: Op);
3379 auto *CPV = ARMConstantPoolConstant::Create(GV: GA->getGlobal(), Modifier: ARMCP::SECREL);
3380 SDValue Offset = DAG.getLoad(
3381 VT: PtrVT, dl: DL, Chain,
3382 Ptr: DAG.getNode(Opcode: ARMISD::Wrapper, DL, VT: MVT::i32,
3383 Operand: DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4))),
3384 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3385
3386 return DAG.getNode(Opcode: ISD::ADD, DL, VT: PtrVT, N1: TLS, N2: Offset);
3387}
3388
3389// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3390SDValue
3391ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3392 SelectionDAG &DAG) const {
3393 SDLoc dl(GA);
3394 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3395 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3396 MachineFunction &MF = DAG.getMachineFunction();
3397 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3398 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3399 ARMConstantPoolValue *CPV =
3400 ARMConstantPoolConstant::Create(C: GA->getGlobal(), ID: ARMPCLabelIndex,
3401 Kind: ARMCP::CPValue, PCAdj, Modifier: ARMCP::TLSGD, AddCurrentAddress: true);
3402 SDValue Argument = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3403 Argument = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: Argument);
3404 Argument = DAG.getLoad(
3405 VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: Argument,
3406 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3407 SDValue Chain = Argument.getValue(R: 1);
3408
3409 SDValue PICLabel = DAG.getConstant(Val: ARMPCLabelIndex, DL: dl, VT: MVT::i32);
3410 Argument = DAG.getNode(Opcode: ARMISD::PIC_ADD, DL: dl, VT: PtrVT, N1: Argument, N2: PICLabel);
3411
3412 // call __tls_get_addr.
3413 ArgListTy Args;
3414 Args.emplace_back(args&: Argument, args: Type::getInt32Ty(C&: *DAG.getContext()));
3415
3416 // FIXME: is there useful debug info available here?
3417 TargetLowering::CallLoweringInfo CLI(DAG);
3418 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3419 CC: CallingConv::C, ResultType: Type::getInt32Ty(C&: *DAG.getContext()),
3420 Target: DAG.getExternalSymbol(Sym: "__tls_get_addr", VT: PtrVT), ArgsList: std::move(Args));
3421
3422 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3423 return CallResult.first;
3424}
3425
3426// Lower ISD::GlobalTLSAddress using the "initial exec" or
3427// "local exec" model.
3428SDValue
3429ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3430 SelectionDAG &DAG,
3431 TLSModel::Model model) const {
3432 const GlobalValue *GV = GA->getGlobal();
3433 SDLoc dl(GA);
3434 SDValue Offset;
3435 SDValue Chain = DAG.getEntryNode();
3436 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3437 // Get the Thread Pointer
3438 SDValue ThreadPointer = DAG.getNode(Opcode: ARMISD::THREAD_POINTER, DL: dl, VT: PtrVT);
3439
3440 if (model == TLSModel::InitialExec) {
3441 MachineFunction &MF = DAG.getMachineFunction();
3442 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3443 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3444 // Initial exec model.
3445 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3446 ARMConstantPoolValue *CPV =
3447 ARMConstantPoolConstant::Create(C: GA->getGlobal(), ID: ARMPCLabelIndex,
3448 Kind: ARMCP::CPValue, PCAdj, Modifier: ARMCP::GOTTPOFF,
3449 AddCurrentAddress: true);
3450 Offset = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3451 Offset = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: Offset);
3452 Offset = DAG.getLoad(
3453 VT: PtrVT, dl, Chain, Ptr: Offset,
3454 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3455 Chain = Offset.getValue(R: 1);
3456
3457 SDValue PICLabel = DAG.getConstant(Val: ARMPCLabelIndex, DL: dl, VT: MVT::i32);
3458 Offset = DAG.getNode(Opcode: ARMISD::PIC_ADD, DL: dl, VT: PtrVT, N1: Offset, N2: PICLabel);
3459
3460 Offset = DAG.getLoad(
3461 VT: PtrVT, dl, Chain, Ptr: Offset,
3462 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3463 } else {
3464 // local exec model
3465 assert(model == TLSModel::LocalExec);
3466 ARMConstantPoolValue *CPV =
3467 ARMConstantPoolConstant::Create(GV, Modifier: ARMCP::TPOFF);
3468 Offset = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3469 Offset = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: Offset);
3470 Offset = DAG.getLoad(
3471 VT: PtrVT, dl, Chain, Ptr: Offset,
3472 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3473 }
3474
3475 // The address of the thread local variable is the add of the thread
3476 // pointer with the offset of the variable.
3477 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PtrVT, N1: ThreadPointer, N2: Offset);
3478}
3479
3480SDValue
3481ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3482 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Val&: Op);
3483 if (DAG.getTarget().useEmulatedTLS())
3484 return LowerToTLSEmulatedModel(GA, DAG);
3485
3486 const Triple &TT = getTargetMachine().getTargetTriple();
3487 if (TT.isOSDarwin())
3488 return LowerGlobalTLSAddressDarwin(Op, DAG);
3489
3490 if (TT.isOSWindows())
3491 return LowerGlobalTLSAddressWindows(Op, DAG);
3492
3493 // TODO: implement the "local dynamic" model
3494 assert(TT.isOSBinFormatELF() && "Only ELF implemented here");
3495 TLSModel::Model model = getTargetMachine().getTLSModel(GV: GA->getGlobal());
3496
3497 switch (model) {
3498 case TLSModel::GeneralDynamic:
3499 case TLSModel::LocalDynamic:
3500 return LowerToTLSGeneralDynamicModel(GA, DAG);
3501 case TLSModel::InitialExec:
3502 case TLSModel::LocalExec:
3503 return LowerToTLSExecModels(GA, DAG, model);
3504 }
3505 llvm_unreachable("bogus TLS model");
3506}
3507
3508/// Return true if all users of V are within function F, looking through
3509/// ConstantExprs.
3510static bool allUsersAreInFunction(const Value *V, const Function *F) {
3511 SmallVector<const User*,4> Worklist(V->users());
3512 while (!Worklist.empty()) {
3513 auto *U = Worklist.pop_back_val();
3514 if (isa<ConstantExpr>(Val: U)) {
3515 append_range(C&: Worklist, R: U->users());
3516 continue;
3517 }
3518
3519 auto *I = dyn_cast<Instruction>(Val: U);
3520 if (!I || I->getParent()->getParent() != F)
3521 return false;
3522 }
3523 return true;
3524}
3525
3526static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3527 const GlobalValue *GV, SelectionDAG &DAG,
3528 EVT PtrVT, const SDLoc &dl) {
3529 // If we're creating a pool entry for a constant global with unnamed address,
3530 // and the global is small enough, we can emit it inline into the constant pool
3531 // to save ourselves an indirection.
3532 //
3533 // This is a win if the constant is only used in one function (so it doesn't
3534 // need to be duplicated) or duplicating the constant wouldn't increase code
3535 // size (implying the constant is no larger than 4 bytes).
3536 const Function &F = DAG.getMachineFunction().getFunction();
3537
3538 // We rely on this decision to inline being idempotent and unrelated to the
3539 // use-site. We know that if we inline a variable at one use site, we'll
3540 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3541 // doesn't know about this optimization, so bail out if it's enabled else
3542 // we could decide to inline here (and thus never emit the GV) but require
3543 // the GV from fast-isel generated code.
3544 if (!EnableConstpoolPromotion ||
3545 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3546 return SDValue();
3547
3548 auto *GVar = dyn_cast<GlobalVariable>(Val: GV);
3549 if (!GVar || !GVar->hasInitializer() ||
3550 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3551 !GVar->hasLocalLinkage())
3552 return SDValue();
3553
3554 // If we inline a value that contains relocations, we move the relocations
3555 // from .data to .text. This is not allowed in position-independent code.
3556 auto *Init = GVar->getInitializer();
3557 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3558 Init->needsDynamicRelocation())
3559 return SDValue();
3560
3561 // The constant islands pass can only really deal with alignment requests
3562 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3563 // any type wanting greater alignment requirements than 4 bytes. We also
3564 // can only promote constants that are multiples of 4 bytes in size or
3565 // are paddable to a multiple of 4. Currently we only try and pad constants
3566 // that are strings for simplicity.
3567 auto *CDAInit = dyn_cast<ConstantDataArray>(Val: Init);
3568 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Ty: Init->getType());
3569 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GV: GVar);
3570 unsigned RequiredPadding = 4 - (Size % 4);
3571 bool PaddingPossible =
3572 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3573 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3574 Size == 0)
3575 return SDValue();
3576
3577 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3578 MachineFunction &MF = DAG.getMachineFunction();
3579 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3580
3581 // We can't bloat the constant pool too much, else the ConstantIslands pass
3582 // may fail to converge. If we haven't promoted this global yet (it may have
3583 // multiple uses), and promoting it would increase the constant pool size (Sz
3584 // > 4), ensure we have space to do so up to MaxTotal.
3585 if (!AFI->getGlobalsPromotedToConstantPool().count(Ptr: GVar) && Size > 4)
3586 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3587 ConstpoolPromotionMaxTotal)
3588 return SDValue();
3589
3590 // This is only valid if all users are in a single function; we can't clone
3591 // the constant in general. The LLVM IR unnamed_addr allows merging
3592 // constants, but not cloning them.
3593 //
3594 // We could potentially allow cloning if we could prove all uses of the
3595 // constant in the current function don't care about the address, like
3596 // printf format strings. But that isn't implemented for now.
3597 if (!allUsersAreInFunction(V: GVar, F: &F))
3598 return SDValue();
3599
3600 // We're going to inline this global. Pad it out if needed.
3601 if (RequiredPadding != 4) {
3602 StringRef S = CDAInit->getAsString();
3603
3604 SmallVector<uint8_t,16> V(S.size());
3605 std::copy(first: S.bytes_begin(), last: S.bytes_end(), result: V.begin());
3606 while (RequiredPadding--)
3607 V.push_back(Elt: 0);
3608 Init = ConstantDataArray::get(Context&: *DAG.getContext(), Elts&: V);
3609 }
3610
3611 auto CPVal = ARMConstantPoolConstant::Create(GV: GVar, Initializer: Init);
3612 SDValue CPAddr = DAG.getTargetConstantPool(C: CPVal, VT: PtrVT, Align: Align(4));
3613 if (!AFI->getGlobalsPromotedToConstantPool().count(Ptr: GVar)) {
3614 AFI->markGlobalAsPromotedToConstantPool(GV: GVar);
3615 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3616 PaddedSize - 4);
3617 }
3618 ++NumConstpoolPromoted;
3619 return DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: CPAddr);
3620}
3621
3622bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3623 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Val: GV))
3624 if (!(GV = GA->getAliaseeObject()))
3625 return false;
3626 if (const auto *V = dyn_cast<GlobalVariable>(Val: GV))
3627 return V->isConstant();
3628 return isa<Function>(Val: GV);
3629}
3630
3631SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3632 SelectionDAG &DAG) const {
3633 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3634 default: llvm_unreachable("unknown object format");
3635 case Triple::COFF:
3636 return LowerGlobalAddressWindows(Op, DAG);
3637 case Triple::ELF:
3638 return LowerGlobalAddressELF(Op, DAG);
3639 case Triple::MachO:
3640 return LowerGlobalAddressDarwin(Op, DAG);
3641 }
3642}
3643
3644SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3645 SelectionDAG &DAG) const {
3646 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3647 SDLoc dl(Op);
3648 const GlobalValue *GV = cast<GlobalAddressSDNode>(Val&: Op)->getGlobal();
3649 bool IsRO = isReadOnly(GV);
3650
3651 // promoteToConstantPool only if not generating XO text section
3652 if (GV->isDSOLocal() && !Subtarget->genExecuteOnly())
3653 if (SDValue V = promoteToConstantPool(TLI: this, GV, DAG, PtrVT, dl))
3654 return V;
3655
3656 if (isPositionIndependent()) {
3657 SDValue G = DAG.getTargetGlobalAddress(
3658 GV, DL: dl, VT: PtrVT, offset: 0, TargetFlags: GV->isDSOLocal() ? 0 : ARMII::MO_GOT);
3659 SDValue Result = DAG.getNode(Opcode: ARMISD::WrapperPIC, DL: dl, VT: PtrVT, Operand: G);
3660 if (!GV->isDSOLocal())
3661 Result =
3662 DAG.getLoad(VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: Result,
3663 PtrInfo: MachinePointerInfo::getGOT(MF&: DAG.getMachineFunction()));
3664 return Result;
3665 } else if (Subtarget->isROPI() && IsRO) {
3666 // PC-relative.
3667 SDValue G = DAG.getTargetGlobalAddress(GV, DL: dl, VT: PtrVT);
3668 SDValue Result = DAG.getNode(Opcode: ARMISD::WrapperPIC, DL: dl, VT: PtrVT, Operand: G);
3669 return Result;
3670 } else if (Subtarget->isRWPI() && !IsRO) {
3671 // SB-relative.
3672 SDValue RelAddr;
3673 if (Subtarget->useMovt()) {
3674 ++NumMovwMovt;
3675 SDValue G = DAG.getTargetGlobalAddress(GV, DL: dl, VT: PtrVT, offset: 0, TargetFlags: ARMII::MO_SBREL);
3676 RelAddr = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: PtrVT, Operand: G);
3677 } else { // use literal pool for address constant
3678 ARMConstantPoolValue *CPV =
3679 ARMConstantPoolConstant::Create(GV, Modifier: ARMCP::SBREL);
3680 SDValue CPAddr = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3681 CPAddr = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: CPAddr);
3682 RelAddr = DAG.getLoad(
3683 VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: CPAddr,
3684 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3685 }
3686 SDValue SB = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl, Reg: ARM::R9, VT: PtrVT);
3687 SDValue Result = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PtrVT, N1: SB, N2: RelAddr);
3688 return Result;
3689 }
3690
3691 // If we have T2 ops, we can materialize the address directly via movt/movw
3692 // pair. This is always cheaper. If need to generate Execute Only code, and we
3693 // only have Thumb1 available, we can't use a constant pool and are forced to
3694 // use immediate relocations.
3695 if (Subtarget->useMovt() || Subtarget->genExecuteOnly()) {
3696 if (Subtarget->useMovt())
3697 ++NumMovwMovt;
3698 // FIXME: Once remat is capable of dealing with instructions with register
3699 // operands, expand this into two nodes.
3700 return DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: PtrVT,
3701 Operand: DAG.getTargetGlobalAddress(GV, DL: dl, VT: PtrVT));
3702 } else {
3703 SDValue CPAddr = DAG.getTargetConstantPool(C: GV, VT: PtrVT, Align: Align(4));
3704 CPAddr = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: CPAddr);
3705 return DAG.getLoad(
3706 VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: CPAddr,
3707 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3708 }
3709}
3710
3711SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3712 SelectionDAG &DAG) const {
3713 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3714 "ROPI/RWPI not currently supported for Darwin");
3715 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3716 SDLoc dl(Op);
3717 const GlobalValue *GV = cast<GlobalAddressSDNode>(Val&: Op)->getGlobal();
3718
3719 if (Subtarget->useMovt())
3720 ++NumMovwMovt;
3721
3722 // FIXME: Once remat is capable of dealing with instructions with register
3723 // operands, expand this into multiple nodes
3724 unsigned Wrapper =
3725 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3726
3727 SDValue G = DAG.getTargetGlobalAddress(GV, DL: dl, VT: PtrVT, offset: 0, TargetFlags: ARMII::MO_NONLAZY);
3728 SDValue Result = DAG.getNode(Opcode: Wrapper, DL: dl, VT: PtrVT, Operand: G);
3729
3730 if (Subtarget->isGVIndirectSymbol(GV))
3731 Result = DAG.getLoad(VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: Result,
3732 PtrInfo: MachinePointerInfo::getGOT(MF&: DAG.getMachineFunction()));
3733 return Result;
3734}
3735
3736SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3737 SelectionDAG &DAG) const {
3738 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3739 "non-Windows COFF is not supported");
3740 assert(Subtarget->useMovt() &&
3741 "Windows on ARM expects to use movw/movt");
3742 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3743 "ROPI/RWPI not currently supported for Windows");
3744
3745 const TargetMachine &TM = getTargetMachine();
3746 const GlobalValue *GV = cast<GlobalAddressSDNode>(Val&: Op)->getGlobal();
3747 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3748 if (GV->hasDLLImportStorageClass())
3749 TargetFlags = ARMII::MO_DLLIMPORT;
3750 else if (!TM.shouldAssumeDSOLocal(GV))
3751 TargetFlags = ARMII::MO_COFFSTUB;
3752 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3753 SDValue Result;
3754 SDLoc DL(Op);
3755
3756 ++NumMovwMovt;
3757
3758 // FIXME: Once remat is capable of dealing with instructions with register
3759 // operands, expand this into two nodes.
3760 Result = DAG.getNode(Opcode: ARMISD::Wrapper, DL, VT: PtrVT,
3761 Operand: DAG.getTargetGlobalAddress(GV, DL, VT: PtrVT, /*offset=*/0,
3762 TargetFlags));
3763 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3764 Result = DAG.getLoad(VT: PtrVT, dl: DL, Chain: DAG.getEntryNode(), Ptr: Result,
3765 PtrInfo: MachinePointerInfo::getGOT(MF&: DAG.getMachineFunction()));
3766 return Result;
3767}
3768
3769SDValue
3770ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3771 SDLoc dl(Op);
3772 SDValue Val = DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32);
3773 return DAG.getNode(Opcode: ARMISD::EH_SJLJ_SETJMP, DL: dl,
3774 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), N1: Op.getOperand(i: 0),
3775 N2: Op.getOperand(i: 1), N3: Val);
3776}
3777
3778SDValue
3779ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3780 SDLoc dl(Op);
3781 return DAG.getNode(Opcode: ARMISD::EH_SJLJ_LONGJMP, DL: dl, VT: MVT::Other, N1: Op.getOperand(i: 0),
3782 N2: Op.getOperand(i: 1), N3: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
3783}
3784
3785SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3786 SelectionDAG &DAG) const {
3787 SDLoc dl(Op);
3788 return DAG.getNode(Opcode: ARMISD::EH_SJLJ_SETUP_DISPATCH, DL: dl, VT: MVT::Other,
3789 Operand: Op.getOperand(i: 0));
3790}
3791
3792SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3793 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3794 unsigned IntNo =
3795 Op.getConstantOperandVal(i: Op.getOperand(i: 0).getValueType() == MVT::Other);
3796 switch (IntNo) {
3797 default:
3798 return SDValue(); // Don't custom lower most intrinsics.
3799 case Intrinsic::arm_gnu_eabi_mcount: {
3800 MachineFunction &MF = DAG.getMachineFunction();
3801 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3802 SDLoc dl(Op);
3803 SDValue Chain = Op.getOperand(i: 0);
3804 // call "\01__gnu_mcount_nc"
3805 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3806 const uint32_t *Mask =
3807 ARI->getCallPreservedMask(MF: DAG.getMachineFunction(), CallingConv::C);
3808 assert(Mask && "Missing call preserved mask for calling convention");
3809 // Mark LR an implicit live-in.
3810 Register Reg = MF.addLiveIn(PReg: ARM::LR, RC: getRegClassFor(VT: MVT::i32));
3811 SDValue ReturnAddress =
3812 DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl, Reg, VT: PtrVT);
3813 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3814 SDValue Callee =
3815 DAG.getTargetExternalSymbol(Sym: "\01__gnu_mcount_nc", VT: PtrVT, TargetFlags: 0);
3816 SDValue RegisterMask = DAG.getRegisterMask(RegMask: Mask);
3817 if (Subtarget->isThumb())
3818 return SDValue(
3819 DAG.getMachineNode(
3820 Opcode: ARM::tBL_PUSHLR, dl, ResultTys,
3821 Ops: {ReturnAddress, DAG.getTargetConstant(Val: ARMCC::AL, DL: dl, VT: PtrVT),
3822 DAG.getRegister(Reg: 0, VT: PtrVT), Callee, RegisterMask, Chain}),
3823 0);
3824 return SDValue(
3825 DAG.getMachineNode(Opcode: ARM::BL_PUSHLR, dl, ResultTys,
3826 Ops: {ReturnAddress, Callee, RegisterMask, Chain}),
3827 0);
3828 }
3829 }
3830}
3831
3832SDValue
3833ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3834 const ARMSubtarget *Subtarget) const {
3835 unsigned IntNo = Op.getConstantOperandVal(i: 0);
3836 SDLoc dl(Op);
3837 switch (IntNo) {
3838 default: return SDValue(); // Don't custom lower most intrinsics.
3839 case Intrinsic::thread_pointer: {
3840 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3841 return DAG.getNode(Opcode: ARMISD::THREAD_POINTER, DL: dl, VT: PtrVT);
3842 }
3843 case Intrinsic::arm_cls: {
3844 // Note: arm_cls and arm_cls64 intrinsics are expanded directly here
3845 // in LowerINTRINSIC_WO_CHAIN since there's no native scalar CLS
3846 // instruction.
3847 const SDValue &Operand = Op.getOperand(i: 1);
3848 const EVT VTy = Op.getValueType();
3849 return DAG.getNode(Opcode: ISD::CTLS, DL: dl, VT: VTy, Operand);
3850 }
3851 case Intrinsic::arm_cls64: {
3852 // arm_cls64 returns i32 but takes i64 input.
3853 // Use ISD::CTLS for i64 and truncate the result.
3854 SDValue CTLS64 = DAG.getNode(Opcode: ISD::CTLS, DL: dl, VT: MVT::i64, Operand: Op.getOperand(i: 1));
3855 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::i32, Operand: CTLS64);
3856 }
3857 case Intrinsic::arm_neon_vcls:
3858 case Intrinsic::arm_mve_vcls: {
3859 // Lower vector CLS intrinsics to ISD::CTLS.
3860 // Vector CTLS is Legal when NEON/MVE is available (set elsewhere).
3861 const EVT VTy = Op.getValueType();
3862 return DAG.getNode(Opcode: ISD::CTLS, DL: dl, VT: VTy, Operand: Op.getOperand(i: 1));
3863 }
3864 case Intrinsic::eh_sjlj_lsda: {
3865 MachineFunction &MF = DAG.getMachineFunction();
3866 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3867 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3868 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3869 SDValue CPAddr;
3870 bool IsPositionIndependent = isPositionIndependent();
3871 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3872 ARMConstantPoolValue *CPV =
3873 ARMConstantPoolConstant::Create(C: &MF.getFunction(), ID: ARMPCLabelIndex,
3874 Kind: ARMCP::CPLSDA, PCAdj);
3875 CPAddr = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3876 CPAddr = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: CPAddr);
3877 SDValue Result = DAG.getLoad(
3878 VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: CPAddr,
3879 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3880
3881 if (IsPositionIndependent) {
3882 SDValue PICLabel = DAG.getConstant(Val: ARMPCLabelIndex, DL: dl, VT: MVT::i32);
3883 Result = DAG.getNode(Opcode: ARMISD::PIC_ADD, DL: dl, VT: PtrVT, N1: Result, N2: PICLabel);
3884 }
3885 return Result;
3886 }
3887 case Intrinsic::arm_neon_vabs:
3888 return DAG.getNode(Opcode: ISD::ABS, DL: SDLoc(Op), VT: Op.getValueType(),
3889 Operand: Op.getOperand(i: 1));
3890 case Intrinsic::arm_neon_vabds:
3891 if (Op.getValueType().isInteger())
3892 return DAG.getNode(Opcode: ISD::ABDS, DL: SDLoc(Op), VT: Op.getValueType(),
3893 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3894 return SDValue();
3895 case Intrinsic::arm_neon_vabdu:
3896 return DAG.getNode(Opcode: ISD::ABDU, DL: SDLoc(Op), VT: Op.getValueType(),
3897 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3898 case Intrinsic::arm_neon_vmulls:
3899 case Intrinsic::arm_neon_vmullu: {
3900 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3901 ? ARMISD::VMULLs : ARMISD::VMULLu;
3902 return DAG.getNode(Opcode: NewOpc, DL: SDLoc(Op), VT: Op.getValueType(),
3903 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3904 }
3905 case Intrinsic::arm_neon_vminnm:
3906 case Intrinsic::arm_neon_vmaxnm: {
3907 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3908 ? ISD::FMINNUM : ISD::FMAXNUM;
3909 return DAG.getNode(Opcode: NewOpc, DL: SDLoc(Op), VT: Op.getValueType(),
3910 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3911 }
3912 case Intrinsic::arm_neon_vminu:
3913 case Intrinsic::arm_neon_vmaxu: {
3914 if (Op.getValueType().isFloatingPoint())
3915 return SDValue();
3916 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3917 ? ISD::UMIN : ISD::UMAX;
3918 return DAG.getNode(Opcode: NewOpc, DL: SDLoc(Op), VT: Op.getValueType(),
3919 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3920 }
3921 case Intrinsic::arm_neon_vmins:
3922 case Intrinsic::arm_neon_vmaxs: {
3923 // v{min,max}s is overloaded between signed integers and floats.
3924 if (!Op.getValueType().isFloatingPoint()) {
3925 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3926 ? ISD::SMIN : ISD::SMAX;
3927 return DAG.getNode(Opcode: NewOpc, DL: SDLoc(Op), VT: Op.getValueType(),
3928 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3929 }
3930 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3931 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3932 return DAG.getNode(Opcode: NewOpc, DL: SDLoc(Op), VT: Op.getValueType(),
3933 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3934 }
3935 case Intrinsic::arm_neon_vtbl1:
3936 return DAG.getNode(Opcode: ARMISD::VTBL1, DL: SDLoc(Op), VT: Op.getValueType(),
3937 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3938 case Intrinsic::arm_neon_vtbl2:
3939 return DAG.getNode(Opcode: ARMISD::VTBL2, DL: SDLoc(Op), VT: Op.getValueType(),
3940 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2), N3: Op.getOperand(i: 3));
3941 case Intrinsic::arm_mve_pred_i2v:
3942 case Intrinsic::arm_mve_pred_v2i:
3943 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: SDLoc(Op), VT: Op.getValueType(),
3944 Operand: Op.getOperand(i: 1));
3945 case Intrinsic::arm_mve_vreinterpretq:
3946 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: SDLoc(Op), VT: Op.getValueType(),
3947 Operand: Op.getOperand(i: 1));
3948 case Intrinsic::arm_mve_lsll:
3949 return DAG.getNode(Opcode: ARMISD::LSLL, DL: SDLoc(Op), VTList: Op->getVTList(),
3950 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2), N3: Op.getOperand(i: 3));
3951 case Intrinsic::arm_mve_asrl:
3952 return DAG.getNode(Opcode: ARMISD::ASRL, DL: SDLoc(Op), VTList: Op->getVTList(),
3953 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2), N3: Op.getOperand(i: 3));
3954 case Intrinsic::arm_mve_vsli:
3955 return DAG.getNode(Opcode: ARMISD::VSLIIMM, DL: SDLoc(Op), VTList: Op->getVTList(),
3956 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2), N3: Op.getOperand(i: 3));
3957 case Intrinsic::arm_mve_vsri:
3958 return DAG.getNode(Opcode: ARMISD::VSRIIMM, DL: SDLoc(Op), VTList: Op->getVTList(),
3959 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2), N3: Op.getOperand(i: 3));
3960 }
3961}
3962
3963static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3964 const ARMSubtarget *Subtarget) {
3965 SDLoc dl(Op);
3966 auto SSID = static_cast<SyncScope::ID>(Op.getConstantOperandVal(i: 2));
3967 if (SSID == SyncScope::SingleThread)
3968 return Op;
3969
3970 if (!Subtarget->hasDataBarrier()) {
3971 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3972 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3973 // here.
3974 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3975 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3976 return DAG.getNode(Opcode: ARMISD::MEMBARRIER_MCR, DL: dl, VT: MVT::Other, N1: Op.getOperand(i: 0),
3977 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
3978 }
3979
3980 AtomicOrdering Ord =
3981 static_cast<AtomicOrdering>(Op.getConstantOperandVal(i: 1));
3982 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3983 if (Subtarget->isMClass()) {
3984 // Only a full system barrier exists in the M-class architectures.
3985 Domain = ARM_MB::SY;
3986 } else if (Subtarget->preferISHSTBarriers() &&
3987 Ord == AtomicOrdering::Release) {
3988 // Swift happens to implement ISHST barriers in a way that's compatible with
3989 // Release semantics but weaker than ISH so we'd be fools not to use
3990 // it. Beware: other processors probably don't!
3991 Domain = ARM_MB::ISHST;
3992 }
3993
3994 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: dl, VT: MVT::Other, N1: Op.getOperand(i: 0),
3995 N2: DAG.getConstant(Val: Intrinsic::arm_dmb, DL: dl, VT: MVT::i32),
3996 N3: DAG.getConstant(Val: Domain, DL: dl, VT: MVT::i32));
3997}
3998
3999static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
4000 const ARMSubtarget *Subtarget) {
4001 // ARM pre v5TE and Thumb1 does not have preload instructions.
4002 if (!(Subtarget->isThumb2() ||
4003 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4004 // Just preserve the chain.
4005 return Op.getOperand(i: 0);
4006
4007 SDLoc dl(Op);
4008 unsigned isRead = ~Op.getConstantOperandVal(i: 2) & 1;
4009 if (!isRead &&
4010 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4011 // ARMv7 with MP extension has PLDW.
4012 return Op.getOperand(i: 0);
4013
4014 unsigned isData = Op.getConstantOperandVal(i: 4);
4015 if (Subtarget->isThumb()) {
4016 // Invert the bits.
4017 isRead = ~isRead & 1;
4018 isData = ~isData & 1;
4019 }
4020
4021 return DAG.getNode(Opcode: ARMISD::PRELOAD, DL: dl, VT: MVT::Other, N1: Op.getOperand(i: 0),
4022 N2: Op.getOperand(i: 1), N3: DAG.getConstant(Val: isRead, DL: dl, VT: MVT::i32),
4023 N4: DAG.getConstant(Val: isData, DL: dl, VT: MVT::i32));
4024}
4025
4026static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
4027 MachineFunction &MF = DAG.getMachineFunction();
4028 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4029
4030 // vastart just stores the address of the VarArgsFrameIndex slot into the
4031 // memory location argument.
4032 SDLoc dl(Op);
4033 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DL: DAG.getDataLayout());
4034 SDValue FR = DAG.getFrameIndex(FI: FuncInfo->getVarArgsFrameIndex(), VT: PtrVT);
4035 const Value *SV = cast<SrcValueSDNode>(Val: Op.getOperand(i: 2))->getValue();
4036 return DAG.getStore(Chain: Op.getOperand(i: 0), dl, Val: FR, Ptr: Op.getOperand(i: 1),
4037 PtrInfo: MachinePointerInfo(SV));
4038}
4039
4040SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4041 CCValAssign &NextVA,
4042 SDValue &Root,
4043 SelectionDAG &DAG,
4044 const SDLoc &dl) const {
4045 MachineFunction &MF = DAG.getMachineFunction();
4046 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4047
4048 const TargetRegisterClass *RC;
4049 if (AFI->isThumb1OnlyFunction())
4050 RC = &ARM::tGPRRegClass;
4051 else
4052 RC = &ARM::GPRRegClass;
4053
4054 // Transform the arguments stored in physical registers into virtual ones.
4055 Register Reg = MF.addLiveIn(PReg: VA.getLocReg(), RC);
4056 SDValue ArgValue = DAG.getCopyFromReg(Chain: Root, dl, Reg, VT: MVT::i32);
4057
4058 SDValue ArgValue2;
4059 if (NextVA.isMemLoc()) {
4060 MachineFrameInfo &MFI = MF.getFrameInfo();
4061 int FI = MFI.CreateFixedObject(Size: 4, SPOffset: NextVA.getLocMemOffset(), IsImmutable: true);
4062
4063 // Create load node to retrieve arguments from the stack.
4064 SDValue FIN = DAG.getFrameIndex(FI, VT: getPointerTy(DL: DAG.getDataLayout()));
4065 ArgValue2 = DAG.getLoad(
4066 VT: MVT::i32, dl, Chain: Root, Ptr: FIN,
4067 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI));
4068 } else {
4069 Reg = MF.addLiveIn(PReg: NextVA.getLocReg(), RC);
4070 ArgValue2 = DAG.getCopyFromReg(Chain: Root, dl, Reg, VT: MVT::i32);
4071 }
4072 if (!Subtarget->isLittle())
4073 std::swap (a&: ArgValue, b&: ArgValue2);
4074 return DAG.getNode(Opcode: ARMISD::VMOVDRR, DL: dl, VT: MVT::f64, N1: ArgValue, N2: ArgValue2);
4075}
4076
4077// The remaining GPRs hold either the beginning of variable-argument
4078// data, or the beginning of an aggregate passed by value (usually
4079// byval). Either way, we allocate stack slots adjacent to the data
4080// provided by our caller, and store the unallocated registers there.
4081// If this is a variadic function, the va_list pointer will begin with
4082// these values; otherwise, this reassembles a (byval) structure that
4083// was split between registers and memory.
4084// Return: The frame index registers were stored into.
4085int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4086 const SDLoc &dl, SDValue &Chain,
4087 const Value *OrigArg,
4088 unsigned InRegsParamRecordIdx,
4089 int ArgOffset, unsigned ArgSize) const {
4090 // Currently, two use-cases possible:
4091 // Case #1. Non-var-args function, and we meet first byval parameter.
4092 // Setup first unallocated register as first byval register;
4093 // eat all remained registers
4094 // (these two actions are performed by HandleByVal method).
4095 // Then, here, we initialize stack frame with
4096 // "store-reg" instructions.
4097 // Case #2. Var-args function, that doesn't contain byval parameters.
4098 // The same: eat all remained unallocated registers,
4099 // initialize stack frame.
4100
4101 MachineFunction &MF = DAG.getMachineFunction();
4102 MachineFrameInfo &MFI = MF.getFrameInfo();
4103 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4104 unsigned RBegin, REnd;
4105 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4106 CCInfo.getInRegsParamInfo(InRegsParamRecordIndex: InRegsParamRecordIdx, BeginReg&: RBegin, EndReg&: REnd);
4107 } else {
4108 unsigned RBeginIdx = CCInfo.getFirstUnallocated(Regs: GPRArgRegs);
4109 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4110 REnd = ARM::R4;
4111 }
4112
4113 if (REnd != RBegin)
4114 ArgOffset = -4 * (ARM::R4 - RBegin);
4115
4116 auto PtrVT = getPointerTy(DL: DAG.getDataLayout());
4117 int FrameIndex = MFI.CreateFixedObject(Size: ArgSize, SPOffset: ArgOffset, IsImmutable: false);
4118 SDValue FIN = DAG.getFrameIndex(FI: FrameIndex, VT: PtrVT);
4119
4120 SmallVector<SDValue, 4> MemOps;
4121 const TargetRegisterClass *RC =
4122 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4123
4124 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4125 Register VReg = MF.addLiveIn(PReg: Reg, RC);
4126 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg: VReg, VT: MVT::i32);
4127 SDValue Store = DAG.getStore(Chain: Val.getValue(R: 1), dl, Val, Ptr: FIN,
4128 PtrInfo: MachinePointerInfo(OrigArg, 4 * i));
4129 MemOps.push_back(Elt: Store);
4130 FIN = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PtrVT, N1: FIN, N2: DAG.getConstant(Val: 4, DL: dl, VT: PtrVT));
4131 }
4132
4133 if (!MemOps.empty())
4134 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: MemOps);
4135 return FrameIndex;
4136}
4137
4138// Setup stack frame, the va_list pointer will start from.
4139void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4140 const SDLoc &dl, SDValue &Chain,
4141 unsigned ArgOffset,
4142 unsigned TotalArgRegsSaveSize,
4143 bool ForceMutable) const {
4144 MachineFunction &MF = DAG.getMachineFunction();
4145 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4146
4147 // Try to store any remaining integer argument regs
4148 // to their spots on the stack so that they may be loaded by dereferencing
4149 // the result of va_next.
4150 // If there is no regs to be stored, just point address after last
4151 // argument passed via stack.
4152 int FrameIndex = StoreByValRegs(
4153 CCInfo, DAG, dl, Chain, OrigArg: nullptr, InRegsParamRecordIdx: CCInfo.getInRegsParamsCount(),
4154 ArgOffset: CCInfo.getStackSize(), ArgSize: std::max(a: 4U, b: TotalArgRegsSaveSize));
4155 AFI->setVarArgsFrameIndex(FrameIndex);
4156}
4157
4158bool ARMTargetLowering::splitValueIntoRegisterParts(
4159 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4160 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4161 EVT ValueVT = Val.getValueType();
4162 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4163 unsigned ValueBits = ValueVT.getSizeInBits();
4164 unsigned PartBits = PartVT.getSizeInBits();
4165 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::getIntegerVT(BitWidth: ValueBits), Operand: Val);
4166 Val = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: MVT::getIntegerVT(BitWidth: PartBits), Operand: Val);
4167 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
4168 Parts[0] = Val;
4169 return true;
4170 }
4171 return false;
4172}
4173
4174SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4175 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4176 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
4177 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4178 unsigned ValueBits = ValueVT.getSizeInBits();
4179 unsigned PartBits = PartVT.getSizeInBits();
4180 SDValue Val = Parts[0];
4181
4182 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::getIntegerVT(BitWidth: PartBits), Operand: Val);
4183 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: MVT::getIntegerVT(BitWidth: ValueBits), Operand: Val);
4184 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
4185 return Val;
4186 }
4187 return SDValue();
4188}
4189
4190SDValue ARMTargetLowering::LowerFormalArguments(
4191 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4192 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4193 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4194 MachineFunction &MF = DAG.getMachineFunction();
4195 MachineFrameInfo &MFI = MF.getFrameInfo();
4196
4197 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4198
4199 // Assign locations to all of the incoming arguments.
4200 SmallVector<CCValAssign, 16> ArgLocs;
4201 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4202 *DAG.getContext());
4203 CCInfo.AnalyzeFormalArguments(Ins, Fn: CCAssignFnForCall(CC: CallConv, isVarArg));
4204
4205 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4206 unsigned CurArgIdx = 0;
4207
4208 // Initially ArgRegsSaveSize is zero.
4209 // Then we increase this value each time we meet byval parameter.
4210 // We also increase this value in case of varargs function.
4211 AFI->setArgRegsSaveSize(0);
4212
4213 // Calculate the amount of stack space that we need to allocate to store
4214 // byval and variadic arguments that are passed in registers.
4215 // We need to know this before we allocate the first byval or variadic
4216 // argument, as they will be allocated a stack slot below the CFA (Canonical
4217 // Frame Address, the stack pointer at entry to the function).
4218 unsigned ArgRegBegin = ARM::R4;
4219 for (const CCValAssign &VA : ArgLocs) {
4220 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4221 break;
4222
4223 unsigned Index = VA.getValNo();
4224 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4225 if (!Flags.isByVal())
4226 continue;
4227
4228 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4229 unsigned RBegin, REnd;
4230 CCInfo.getInRegsParamInfo(InRegsParamRecordIndex: CCInfo.getInRegsParamsProcessed(), BeginReg&: RBegin, EndReg&: REnd);
4231 ArgRegBegin = std::min(a: ArgRegBegin, b: RBegin);
4232
4233 CCInfo.nextInRegsParam();
4234 }
4235 CCInfo.rewindByValRegsInfo();
4236
4237 int lastInsIndex = -1;
4238 if (isVarArg && MFI.hasVAStart()) {
4239 unsigned RegIdx = CCInfo.getFirstUnallocated(Regs: GPRArgRegs);
4240 if (RegIdx != std::size(GPRArgRegs))
4241 ArgRegBegin = std::min(a: ArgRegBegin, b: (unsigned)GPRArgRegs[RegIdx]);
4242 }
4243
4244 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4245 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4246 auto PtrVT = getPointerTy(DL: DAG.getDataLayout());
4247
4248 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4249 CCValAssign &VA = ArgLocs[i];
4250 if (Ins[VA.getValNo()].isOrigArg()) {
4251 std::advance(i&: CurOrigArg,
4252 n: Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4253 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4254 }
4255 // Arguments stored in registers.
4256 if (VA.isRegLoc()) {
4257 EVT RegVT = VA.getLocVT();
4258 SDValue ArgValue;
4259
4260 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4261 // f64 and vector types are split up into multiple registers or
4262 // combinations of registers and stack slots.
4263 SDValue ArgValue1 =
4264 GetF64FormalArgument(VA, NextVA&: ArgLocs[++i], Root&: Chain, DAG, dl);
4265 VA = ArgLocs[++i]; // skip ahead to next loc
4266 SDValue ArgValue2;
4267 if (VA.isMemLoc()) {
4268 int FI = MFI.CreateFixedObject(Size: 8, SPOffset: VA.getLocMemOffset(), IsImmutable: true);
4269 SDValue FIN = DAG.getFrameIndex(FI, VT: PtrVT);
4270 ArgValue2 = DAG.getLoad(
4271 VT: MVT::f64, dl, Chain, Ptr: FIN,
4272 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI));
4273 } else {
4274 ArgValue2 = GetF64FormalArgument(VA, NextVA&: ArgLocs[++i], Root&: Chain, DAG, dl);
4275 }
4276 ArgValue = DAG.getNode(Opcode: ISD::UNDEF, DL: dl, VT: MVT::v2f64);
4277 ArgValue = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: MVT::v2f64, N1: ArgValue,
4278 N2: ArgValue1, N3: DAG.getIntPtrConstant(Val: 0, DL: dl));
4279 ArgValue = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: MVT::v2f64, N1: ArgValue,
4280 N2: ArgValue2, N3: DAG.getIntPtrConstant(Val: 1, DL: dl));
4281 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4282 ArgValue = GetF64FormalArgument(VA, NextVA&: ArgLocs[++i], Root&: Chain, DAG, dl);
4283 } else {
4284 const TargetRegisterClass *RC;
4285
4286 if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4287 RC = &ARM::HPRRegClass;
4288 else if (RegVT == MVT::f32)
4289 RC = &ARM::SPRRegClass;
4290 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4291 RegVT == MVT::v4bf16)
4292 RC = &ARM::DPRRegClass;
4293 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4294 RegVT == MVT::v8bf16)
4295 RC = &ARM::QPRRegClass;
4296 else if (RegVT == MVT::i32)
4297 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4298 : &ARM::GPRRegClass;
4299 else
4300 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4301
4302 // Transform the arguments in physical registers into virtual ones.
4303 Register Reg = MF.addLiveIn(PReg: VA.getLocReg(), RC);
4304 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, VT: RegVT);
4305
4306 // If this value is passed in r0 and has the returned attribute (e.g.
4307 // C++ 'structors), record this fact for later use.
4308 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4309 AFI->setPreservesR0();
4310 }
4311 }
4312
4313 // If this is an 8 or 16-bit value, it is really passed promoted
4314 // to 32 bits. Insert an assert[sz]ext to capture this, then
4315 // truncate to the right size.
4316 switch (VA.getLocInfo()) {
4317 default: llvm_unreachable("Unknown loc info!");
4318 case CCValAssign::Full: break;
4319 case CCValAssign::BCvt:
4320 ArgValue = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VA.getValVT(), Operand: ArgValue);
4321 break;
4322 }
4323
4324 // f16 arguments have their size extended to 4 bytes and passed as if they
4325 // had been copied to the LSBs of a 32-bit register.
4326 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4327 if (VA.needsCustom() &&
4328 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4329 ArgValue = MoveToHPR(dl, DAG, LocVT: VA.getLocVT(), ValVT: VA.getValVT(), Val: ArgValue);
4330
4331 // On CMSE Entry Functions, formal integer arguments whose bitwidth is
4332 // less than 32 bits must be sign- or zero-extended in the callee for
4333 // security reasons. Although the ABI mandates an extension done by the
4334 // caller, the latter cannot be trusted to follow the rules of the ABI.
4335 const ISD::InputArg &Arg = Ins[VA.getValNo()];
4336 if (AFI->isCmseNSEntryFunction() && Arg.ArgVT.isScalarInteger() &&
4337 RegVT.isScalarInteger() && Arg.ArgVT.bitsLT(VT: MVT::i32))
4338 ArgValue = handleCMSEValue(Value: ArgValue, Arg, DAG, DL: dl);
4339
4340 InVals.push_back(Elt: ArgValue);
4341 } else { // VA.isRegLoc()
4342 // Only arguments passed on the stack should make it here.
4343 assert(VA.isMemLoc());
4344 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4345
4346 int index = VA.getValNo();
4347
4348 // Some Ins[] entries become multiple ArgLoc[] entries.
4349 // Process them only once.
4350 if (index != lastInsIndex)
4351 {
4352 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4353 // FIXME: For now, all byval parameter objects are marked mutable.
4354 // This can be changed with more analysis.
4355 // In case of tail call optimization mark all arguments mutable.
4356 // Since they could be overwritten by lowering of arguments in case of
4357 // a tail call.
4358 if (Flags.isByVal()) {
4359 assert(Ins[index].isOrigArg() &&
4360 "Byval arguments cannot be implicit");
4361 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4362
4363 int FrameIndex = StoreByValRegs(
4364 CCInfo, DAG, dl, Chain, OrigArg: &*CurOrigArg, InRegsParamRecordIdx: CurByValIndex,
4365 ArgOffset: VA.getLocMemOffset(), ArgSize: Flags.getByValSize());
4366 InVals.push_back(Elt: DAG.getFrameIndex(FI: FrameIndex, VT: PtrVT));
4367 CCInfo.nextInRegsParam();
4368 } else if (VA.needsCustom() && (VA.getValVT() == MVT::f16 ||
4369 VA.getValVT() == MVT::bf16)) {
4370 // f16 and bf16 values are passed in the least-significant half of
4371 // a 4 byte stack slot. This is done as-if the extension was done
4372 // in a 32-bit register, so the actual bytes used for the value
4373 // differ between little and big endian.
4374 assert(VA.getLocVT().getSizeInBits() == 32);
4375 unsigned FIOffset = VA.getLocMemOffset();
4376 int FI = MFI.CreateFixedObject(Size: VA.getLocVT().getSizeInBits() / 8,
4377 SPOffset: FIOffset, IsImmutable: true);
4378
4379 SDValue Addr = DAG.getFrameIndex(FI, VT: PtrVT);
4380 if (DAG.getDataLayout().isBigEndian())
4381 Addr = DAG.getObjectPtrOffset(SL: dl, Ptr: Addr, Offset: TypeSize::getFixed(ExactSize: 2));
4382
4383 InVals.push_back(Elt: DAG.getLoad(VT: VA.getValVT(), dl, Chain, Ptr: Addr,
4384 PtrInfo: MachinePointerInfo::getFixedStack(
4385 MF&: DAG.getMachineFunction(), FI)));
4386
4387 } else {
4388 unsigned FIOffset = VA.getLocMemOffset();
4389 int FI = MFI.CreateFixedObject(Size: VA.getLocVT().getSizeInBits()/8,
4390 SPOffset: FIOffset, IsImmutable: true);
4391
4392 // Create load nodes to retrieve arguments from the stack.
4393 SDValue FIN = DAG.getFrameIndex(FI, VT: PtrVT);
4394 InVals.push_back(Elt: DAG.getLoad(VT: VA.getValVT(), dl, Chain, Ptr: FIN,
4395 PtrInfo: MachinePointerInfo::getFixedStack(
4396 MF&: DAG.getMachineFunction(), FI)));
4397 }
4398 lastInsIndex = index;
4399 }
4400 }
4401 }
4402
4403 // varargs
4404 if (isVarArg && MFI.hasVAStart()) {
4405 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, ArgOffset: CCInfo.getStackSize(),
4406 TotalArgRegsSaveSize);
4407 if (AFI->isCmseNSEntryFunction()) {
4408 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
4409 DAG.getMachineFunction().getFunction(),
4410 "secure entry function must not be variadic", dl.getDebugLoc()));
4411 }
4412 }
4413
4414 unsigned StackArgSize = CCInfo.getStackSize();
4415 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4416 if (canGuaranteeTCO(CC: CallConv, GuaranteeTailCalls: TailCallOpt)) {
4417 // The only way to guarantee a tail call is if the callee restores its
4418 // argument area, but it must also keep the stack aligned when doing so.
4419 MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
4420 assert(StackAlign && "data layout string is missing stack alignment");
4421 StackArgSize = alignTo(Size: StackArgSize, A: *StackAlign);
4422
4423 AFI->setArgumentStackToRestore(StackArgSize);
4424 }
4425 AFI->setArgumentStackSize(StackArgSize);
4426
4427 if (CCInfo.getStackSize() > 0 && AFI->isCmseNSEntryFunction()) {
4428 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
4429 DAG.getMachineFunction().getFunction(),
4430 "secure entry function requires arguments on stack", dl.getDebugLoc()));
4431 }
4432
4433 return Chain;
4434}
4435
4436/// isFloatingPointZero - Return true if this is +0.0.
4437static bool isFloatingPointZero(SDValue Op) {
4438 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Val&: Op))
4439 return CFP->getValueAPF().isPosZero();
4440 else if (ISD::isEXTLoad(N: Op.getNode()) || ISD::isNON_EXTLoad(N: Op.getNode())) {
4441 // Maybe this has already been legalized into the constant pool?
4442 if (Op.getOperand(i: 1).getOpcode() == ARMISD::Wrapper) {
4443 SDValue WrapperOp = Op.getOperand(i: 1).getOperand(i: 0);
4444 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Val&: WrapperOp))
4445 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Val: CP->getConstVal()))
4446 return CFP->getValueAPF().isPosZero();
4447 }
4448 } else if (Op->getOpcode() == ISD::BITCAST &&
4449 Op->getValueType(ResNo: 0) == MVT::f64) {
4450 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4451 // created by LowerConstantFP().
4452 SDValue BitcastOp = Op->getOperand(Num: 0);
4453 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4454 isNullConstant(V: BitcastOp->getOperand(Num: 0)))
4455 return true;
4456 }
4457 return false;
4458}
4459
4460/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4461/// the given operands.
4462SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4463 SDValue &ARMcc, SelectionDAG &DAG,
4464 const SDLoc &dl) const {
4465 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Val: RHS.getNode())) {
4466 unsigned C = RHSC->getZExtValue();
4467 if (!isLegalICmpImmediate(Imm: (int32_t)C)) {
4468 // Constant does not fit, try adjusting it by one.
4469 switch (CC) {
4470 default: break;
4471 case ISD::SETLT:
4472 case ISD::SETGE:
4473 if (C != 0x80000000 && isLegalICmpImmediate(Imm: C-1)) {
4474 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4475 RHS = DAG.getConstant(Val: C - 1, DL: dl, VT: MVT::i32);
4476 }
4477 break;
4478 case ISD::SETULT:
4479 case ISD::SETUGE:
4480 if (C != 0 && isLegalICmpImmediate(Imm: C-1)) {
4481 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4482 RHS = DAG.getConstant(Val: C - 1, DL: dl, VT: MVT::i32);
4483 }
4484 break;
4485 case ISD::SETLE:
4486 case ISD::SETGT:
4487 if (C != 0x7fffffff && isLegalICmpImmediate(Imm: C+1)) {
4488 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4489 RHS = DAG.getConstant(Val: C + 1, DL: dl, VT: MVT::i32);
4490 }
4491 break;
4492 case ISD::SETULE:
4493 case ISD::SETUGT:
4494 if (C != 0xffffffff && isLegalICmpImmediate(Imm: C+1)) {
4495 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4496 RHS = DAG.getConstant(Val: C + 1, DL: dl, VT: MVT::i32);
4497 }
4498 break;
4499 }
4500 }
4501 } else if ((ARM_AM::getShiftOpcForNode(Opcode: LHS.getOpcode()) != ARM_AM::no_shift) &&
4502 (ARM_AM::getShiftOpcForNode(Opcode: RHS.getOpcode()) == ARM_AM::no_shift)) {
4503 // In ARM and Thumb-2, the compare instructions can shift their second
4504 // operand.
4505 CC = ISD::getSetCCSwappedOperands(Operation: CC);
4506 std::swap(a&: LHS, b&: RHS);
4507 }
4508
4509 // Thumb1 has very limited immediate modes, so turning an "and" into a
4510 // shift can save multiple instructions.
4511 //
4512 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4513 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4514 // own. If it's the operand to an unsigned comparison with an immediate,
4515 // we can eliminate one of the shifts: we transform
4516 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4517 //
4518 // We avoid transforming cases which aren't profitable due to encoding
4519 // details:
4520 //
4521 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4522 // would not; in that case, we're essentially trading one immediate load for
4523 // another.
4524 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4525 // 3. C2 is zero; we have other code for this special case.
4526 //
4527 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4528 // instruction, since the AND is always one instruction anyway, but we could
4529 // use narrow instructions in some cases.
4530 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4531 LHS->hasOneUse() && isa<ConstantSDNode>(Val: LHS.getOperand(i: 1)) &&
4532 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(Val: RHS) &&
4533 !isSignedIntSetCC(Code: CC)) {
4534 unsigned Mask = LHS.getConstantOperandVal(i: 1);
4535 auto *RHSC = cast<ConstantSDNode>(Val: RHS.getNode());
4536 uint64_t RHSV = RHSC->getZExtValue();
4537 if (isMask_32(Value: Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4538 unsigned ShiftBits = llvm::countl_zero(Val: Mask);
4539 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4540 SDValue ShiftAmt = DAG.getConstant(Val: ShiftBits, DL: dl, VT: MVT::i32);
4541 LHS = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT: MVT::i32, N1: LHS.getOperand(i: 0), N2: ShiftAmt);
4542 RHS = DAG.getConstant(Val: RHSV << ShiftBits, DL: dl, VT: MVT::i32);
4543 }
4544 }
4545 }
4546
4547 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4548 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4549 // way a cmp would.
4550 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4551 // some tweaks to the heuristics for the previous and->shift transform.
4552 // FIXME: Optimize cases where the LHS isn't a shift.
4553 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4554 isa<ConstantSDNode>(Val: RHS) && RHS->getAsZExtVal() == 0x80000000U &&
4555 CC == ISD::SETUGT && isa<ConstantSDNode>(Val: LHS.getOperand(i: 1)) &&
4556 LHS.getConstantOperandVal(i: 1) < 31) {
4557 unsigned ShiftAmt = LHS.getConstantOperandVal(i: 1) + 1;
4558 SDValue Shift =
4559 DAG.getNode(Opcode: ARMISD::LSLS, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT),
4560 N1: LHS.getOperand(i: 0), N2: DAG.getConstant(Val: ShiftAmt, DL: dl, VT: MVT::i32));
4561 ARMcc = DAG.getConstant(Val: ARMCC::HI, DL: dl, VT: MVT::i32);
4562 return Shift.getValue(R: 1);
4563 }
4564
4565 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4566
4567 // If the RHS is a constant zero then the V (overflow) flag will never be
4568 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4569 // simpler for other passes (like the peephole optimiser) to deal with.
4570 if (isNullConstant(V: RHS)) {
4571 switch (CondCode) {
4572 default: break;
4573 case ARMCC::GE:
4574 CondCode = ARMCC::PL;
4575 break;
4576 case ARMCC::LT:
4577 CondCode = ARMCC::MI;
4578 break;
4579 }
4580 }
4581
4582 unsigned CompareType;
4583 switch (CondCode) {
4584 default:
4585 CompareType = ARMISD::CMP;
4586 break;
4587 case ARMCC::EQ:
4588 case ARMCC::NE:
4589 // Uses only Z Flag
4590 CompareType = ARMISD::CMPZ;
4591 break;
4592 }
4593 ARMcc = DAG.getConstant(Val: CondCode, DL: dl, VT: MVT::i32);
4594 return DAG.getNode(Opcode: CompareType, DL: dl, VT: FlagsVT, N1: LHS, N2: RHS);
4595}
4596
4597/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4598SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4599 SelectionDAG &DAG, const SDLoc &dl,
4600 bool Signaling) const {
4601 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4602 SDValue Flags;
4603 if (!isFloatingPointZero(Op: RHS))
4604 Flags = DAG.getNode(Opcode: Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, DL: dl, VT: FlagsVT,
4605 N1: LHS, N2: RHS);
4606 else
4607 Flags = DAG.getNode(Opcode: Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, DL: dl,
4608 VT: FlagsVT, Operand: LHS);
4609 return DAG.getNode(Opcode: ARMISD::FMSTAT, DL: dl, VT: FlagsVT, Operand: Flags);
4610}
4611
4612// This function returns three things: the arithmetic computation itself
4613// (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4614// comparison and the condition code define the case in which the arithmetic
4615// computation *does not* overflow.
4616std::pair<SDValue, SDValue>
4617ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4618 SDValue &ARMcc) const {
4619 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4620
4621 SDValue Value, OverflowCmp;
4622 SDValue LHS = Op.getOperand(i: 0);
4623 SDValue RHS = Op.getOperand(i: 1);
4624 SDLoc dl(Op);
4625
4626 // FIXME: We are currently always generating CMPs because we don't support
4627 // generating CMN through the backend. This is not as good as the natural
4628 // CMP case because it causes a register dependency and cannot be folded
4629 // later.
4630
4631 switch (Op.getOpcode()) {
4632 default:
4633 llvm_unreachable("Unknown overflow instruction!");
4634 case ISD::SADDO:
4635 ARMcc = DAG.getConstant(Val: ARMCC::VC, DL: dl, VT: MVT::i32);
4636 Value = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: Op.getValueType(), N1: LHS, N2: RHS);
4637 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMP, DL: dl, VT: FlagsVT, N1: Value, N2: LHS);
4638 break;
4639 case ISD::UADDO:
4640 ARMcc = DAG.getConstant(Val: ARMCC::HS, DL: dl, VT: MVT::i32);
4641 // We use ADDC here to correspond to its use in LowerALUO.
4642 // We do not use it in the USUBO case as Value may not be used.
4643 Value = DAG.getNode(Opcode: ARMISD::ADDC, DL: dl,
4644 VTList: DAG.getVTList(VT1: Op.getValueType(), VT2: MVT::i32), N1: LHS, N2: RHS)
4645 .getValue(R: 0);
4646 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMP, DL: dl, VT: FlagsVT, N1: Value, N2: LHS);
4647 break;
4648 case ISD::SSUBO:
4649 ARMcc = DAG.getConstant(Val: ARMCC::VC, DL: dl, VT: MVT::i32);
4650 Value = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: Op.getValueType(), N1: LHS, N2: RHS);
4651 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMP, DL: dl, VT: FlagsVT, N1: LHS, N2: RHS);
4652 break;
4653 case ISD::USUBO:
4654 ARMcc = DAG.getConstant(Val: ARMCC::HS, DL: dl, VT: MVT::i32);
4655 Value = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: Op.getValueType(), N1: LHS, N2: RHS);
4656 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMP, DL: dl, VT: FlagsVT, N1: LHS, N2: RHS);
4657 break;
4658 case ISD::UMULO:
4659 // We generate a UMUL_LOHI and then check if the high word is 0.
4660 ARMcc = DAG.getConstant(Val: ARMCC::EQ, DL: dl, VT: MVT::i32);
4661 Value = DAG.getNode(Opcode: ISD::UMUL_LOHI, DL: dl,
4662 VTList: DAG.getVTList(VT1: Op.getValueType(), VT2: Op.getValueType()),
4663 N1: LHS, N2: RHS);
4664 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMPZ, DL: dl, VT: FlagsVT, N1: Value.getValue(R: 1),
4665 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
4666 Value = Value.getValue(R: 0); // We only want the low 32 bits for the result.
4667 break;
4668 case ISD::SMULO:
4669 // We generate a SMUL_LOHI and then check if all the bits of the high word
4670 // are the same as the sign bit of the low word.
4671 ARMcc = DAG.getConstant(Val: ARMCC::EQ, DL: dl, VT: MVT::i32);
4672 Value = DAG.getNode(Opcode: ISD::SMUL_LOHI, DL: dl,
4673 VTList: DAG.getVTList(VT1: Op.getValueType(), VT2: Op.getValueType()),
4674 N1: LHS, N2: RHS);
4675 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMPZ, DL: dl, VT: FlagsVT, N1: Value.getValue(R: 1),
4676 N2: DAG.getNode(Opcode: ISD::SRA, DL: dl, VT: Op.getValueType(),
4677 N1: Value.getValue(R: 0),
4678 N2: DAG.getConstant(Val: 31, DL: dl, VT: MVT::i32)));
4679 Value = Value.getValue(R: 0); // We only want the low 32 bits for the result.
4680 break;
4681 } // switch (...)
4682
4683 return std::make_pair(x&: Value, y&: OverflowCmp);
4684}
4685
4686static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4687 SelectionDAG &DAG) {
4688 SDLoc DL(BoolCarry);
4689 EVT CarryVT = BoolCarry.getValueType();
4690
4691 // This converts the boolean value carry into the carry flag by doing
4692 // ARMISD::SUBC Carry, 1
4693 SDValue Carry = DAG.getNode(Opcode: ARMISD::SUBC, DL,
4694 VTList: DAG.getVTList(VT1: CarryVT, VT2: MVT::i32),
4695 N1: BoolCarry, N2: DAG.getConstant(Val: 1, DL, VT: CarryVT));
4696 return Carry.getValue(R: 1);
4697}
4698
4699static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4700 SelectionDAG &DAG) {
4701 SDLoc DL(Flags);
4702
4703 // Now convert the carry flag into a boolean carry. We do this
4704 // using ARMISD:ADDE 0, 0, Carry
4705 return DAG.getNode(Opcode: ARMISD::ADDE, DL, VTList: DAG.getVTList(VT1: VT, VT2: MVT::i32),
4706 N1: DAG.getConstant(Val: 0, DL, VT: MVT::i32),
4707 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32), N3: Flags);
4708}
4709
4710SDValue ARMTargetLowering::LowerALUO(SDValue Op, SelectionDAG &DAG) const {
4711 // Let legalize expand this if it isn't a legal type yet.
4712 if (!isTypeLegal(VT: Op.getValueType()))
4713 return SDValue();
4714
4715 SDValue LHS = Op.getOperand(i: 0);
4716 SDValue RHS = Op.getOperand(i: 1);
4717 SDLoc dl(Op);
4718
4719 EVT VT = Op.getValueType();
4720 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::i32);
4721 SDValue Value;
4722 SDValue Overflow;
4723 switch (Op.getOpcode()) {
4724 case ISD::UADDO:
4725 Value = DAG.getNode(Opcode: ARMISD::ADDC, DL: dl, VTList: VTs, N1: LHS, N2: RHS);
4726 // Convert the carry flag into a boolean value.
4727 Overflow = ConvertCarryFlagToBooleanCarry(Flags: Value.getValue(R: 1), VT, DAG);
4728 break;
4729 case ISD::USUBO:
4730 Value = DAG.getNode(Opcode: ARMISD::SUBC, DL: dl, VTList: VTs, N1: LHS, N2: RHS);
4731 // Convert the carry flag into a boolean value.
4732 Overflow = ConvertCarryFlagToBooleanCarry(Flags: Value.getValue(R: 1), VT, DAG);
4733 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4734 // value. So compute 1 - C.
4735 Overflow = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
4736 N1: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32), N2: Overflow);
4737 break;
4738 default: {
4739 // Handle other operations with getARMXALUOOp
4740 SDValue OverflowCmp, ARMcc;
4741 std::tie(args&: Value, args&: OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4742 // We use 0 and 1 as false and true values.
4743 // ARMcc represents the "no overflow" condition (e.g., VC for signed ops).
4744 // CMOV operand order is (FalseVal, TrueVal), so we put 1 in FalseVal
4745 // position to get Overflow=1 when the "no overflow" condition is false.
4746 Overflow =
4747 DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT: MVT::i32,
4748 N1: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32), // FalseVal: overflow
4749 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32), // TrueVal: no overflow
4750 N3: ARMcc, N4: OverflowCmp);
4751 break;
4752 }
4753 }
4754
4755 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl, VTList: VTs, N1: Value, N2: Overflow);
4756}
4757
4758static SDValue LowerADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4759 const ARMSubtarget *Subtarget) {
4760 EVT VT = Op.getValueType();
4761 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() || Subtarget->isThumb1Only())
4762 return SDValue();
4763 if (!VT.isSimple())
4764 return SDValue();
4765
4766 unsigned NewOpcode;
4767 switch (VT.getSimpleVT().SimpleTy) {
4768 default:
4769 return SDValue();
4770 case MVT::i8:
4771 switch (Op->getOpcode()) {
4772 case ISD::UADDSAT:
4773 NewOpcode = ARMISD::UQADD8b;
4774 break;
4775 case ISD::SADDSAT:
4776 NewOpcode = ARMISD::QADD8b;
4777 break;
4778 case ISD::USUBSAT:
4779 NewOpcode = ARMISD::UQSUB8b;
4780 break;
4781 case ISD::SSUBSAT:
4782 NewOpcode = ARMISD::QSUB8b;
4783 break;
4784 }
4785 break;
4786 case MVT::i16:
4787 switch (Op->getOpcode()) {
4788 case ISD::UADDSAT:
4789 NewOpcode = ARMISD::UQADD16b;
4790 break;
4791 case ISD::SADDSAT:
4792 NewOpcode = ARMISD::QADD16b;
4793 break;
4794 case ISD::USUBSAT:
4795 NewOpcode = ARMISD::UQSUB16b;
4796 break;
4797 case ISD::SSUBSAT:
4798 NewOpcode = ARMISD::QSUB16b;
4799 break;
4800 }
4801 break;
4802 }
4803
4804 SDLoc dl(Op);
4805 SDValue Add =
4806 DAG.getNode(Opcode: NewOpcode, DL: dl, VT: MVT::i32,
4807 N1: DAG.getSExtOrTrunc(Op: Op->getOperand(Num: 0), DL: dl, VT: MVT::i32),
4808 N2: DAG.getSExtOrTrunc(Op: Op->getOperand(Num: 1), DL: dl, VT: MVT::i32));
4809 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT, Operand: Add);
4810}
4811
4812SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4813 SDValue Cond = Op.getOperand(i: 0);
4814 SDValue SelectTrue = Op.getOperand(i: 1);
4815 SDValue SelectFalse = Op.getOperand(i: 2);
4816 SDLoc dl(Op);
4817 unsigned Opc = Cond.getOpcode();
4818
4819 if (Cond.getResNo() == 1 &&
4820 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4821 Opc == ISD::USUBO)) {
4822 if (!isTypeLegal(VT: Cond->getValueType(ResNo: 0)))
4823 return SDValue();
4824
4825 SDValue Value, OverflowCmp;
4826 SDValue ARMcc;
4827 std::tie(args&: Value, args&: OverflowCmp) = getARMXALUOOp(Op: Cond, DAG, ARMcc);
4828 EVT VT = Op.getValueType();
4829
4830 return getCMOV(dl, VT, FalseVal: SelectTrue, TrueVal: SelectFalse, ARMcc, Flags: OverflowCmp, DAG);
4831 }
4832
4833 // Convert:
4834 //
4835 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4836 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4837 //
4838 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4839 const ConstantSDNode *CMOVTrue =
4840 dyn_cast<ConstantSDNode>(Val: Cond.getOperand(i: 0));
4841 const ConstantSDNode *CMOVFalse =
4842 dyn_cast<ConstantSDNode>(Val: Cond.getOperand(i: 1));
4843
4844 if (CMOVTrue && CMOVFalse) {
4845 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4846 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4847
4848 SDValue True;
4849 SDValue False;
4850 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4851 True = SelectTrue;
4852 False = SelectFalse;
4853 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4854 True = SelectFalse;
4855 False = SelectTrue;
4856 }
4857
4858 if (True.getNode() && False.getNode())
4859 return getCMOV(dl, VT: Op.getValueType(), FalseVal: True, TrueVal: False, ARMcc: Cond.getOperand(i: 2),
4860 Flags: Cond.getOperand(i: 3), DAG);
4861 }
4862 }
4863
4864 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4865 // undefined bits before doing a full-word comparison with zero.
4866 Cond = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: Cond.getValueType(), N1: Cond,
4867 N2: DAG.getConstant(Val: 1, DL: dl, VT: Cond.getValueType()));
4868
4869 return DAG.getSelectCC(DL: dl, LHS: Cond,
4870 RHS: DAG.getConstant(Val: 0, DL: dl, VT: Cond.getValueType()),
4871 True: SelectTrue, False: SelectFalse, Cond: ISD::SETNE);
4872}
4873
4874static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4875 bool &swpCmpOps, bool &swpVselOps) {
4876 // Start by selecting the GE condition code for opcodes that return true for
4877 // 'equality'
4878 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4879 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4880 CondCode = ARMCC::GE;
4881
4882 // and GT for opcodes that return false for 'equality'.
4883 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4884 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4885 CondCode = ARMCC::GT;
4886
4887 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4888 // to swap the compare operands.
4889 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4890 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4891 swpCmpOps = true;
4892
4893 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4894 // If we have an unordered opcode, we need to swap the operands to the VSEL
4895 // instruction (effectively negating the condition).
4896 //
4897 // This also has the effect of swapping which one of 'less' or 'greater'
4898 // returns true, so we also swap the compare operands. It also switches
4899 // whether we return true for 'equality', so we compensate by picking the
4900 // opposite condition code to our original choice.
4901 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4902 CC == ISD::SETUGT) {
4903 swpCmpOps = !swpCmpOps;
4904 swpVselOps = !swpVselOps;
4905 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4906 }
4907
4908 // 'ordered' is 'anything but unordered', so use the VS condition code and
4909 // swap the VSEL operands.
4910 if (CC == ISD::SETO) {
4911 CondCode = ARMCC::VS;
4912 swpVselOps = true;
4913 }
4914
4915 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4916 // code and swap the VSEL operands. Also do this if we don't care about the
4917 // unordered case.
4918 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4919 CondCode = ARMCC::EQ;
4920 swpVselOps = true;
4921 }
4922}
4923
4924SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4925 SDValue TrueVal, SDValue ARMcc,
4926 SDValue Flags, SelectionDAG &DAG) const {
4927 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4928 FalseVal = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl,
4929 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N: FalseVal);
4930 TrueVal = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl,
4931 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N: TrueVal);
4932
4933 SDValue TrueLow = TrueVal.getValue(R: 0);
4934 SDValue TrueHigh = TrueVal.getValue(R: 1);
4935 SDValue FalseLow = FalseVal.getValue(R: 0);
4936 SDValue FalseHigh = FalseVal.getValue(R: 1);
4937
4938 SDValue Low = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT: MVT::i32, N1: FalseLow, N2: TrueLow,
4939 N3: ARMcc, N4: Flags);
4940 SDValue High = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT: MVT::i32, N1: FalseHigh, N2: TrueHigh,
4941 N3: ARMcc, N4: Flags);
4942
4943 return DAG.getNode(Opcode: ARMISD::VMOVDRR, DL: dl, VT: MVT::f64, N1: Low, N2: High);
4944 }
4945 return DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: FalseVal, N2: TrueVal, N3: ARMcc, N4: Flags);
4946}
4947
4948static bool isGTorGE(ISD::CondCode CC) {
4949 return CC == ISD::SETGT || CC == ISD::SETGE;
4950}
4951
4952static bool isLTorLE(ISD::CondCode CC) {
4953 return CC == ISD::SETLT || CC == ISD::SETLE;
4954}
4955
4956// See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4957// All of these conditions (and their <= and >= counterparts) will do:
4958// x < k ? k : x
4959// x > k ? x : k
4960// k < x ? x : k
4961// k > x ? k : x
4962static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4963 const SDValue TrueVal, const SDValue FalseVal,
4964 const ISD::CondCode CC, const SDValue K) {
4965 return (isGTorGE(CC) &&
4966 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4967 (isLTorLE(CC) &&
4968 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4969}
4970
4971// Check if two chained conditionals could be converted into SSAT or USAT.
4972//
4973// SSAT can replace a set of two conditional selectors that bound a number to an
4974// interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4975//
4976// x < -k ? -k : (x > k ? k : x)
4977// x < -k ? -k : (x < k ? x : k)
4978// x > -k ? (x > k ? k : x) : -k
4979// x < k ? (x < -k ? -k : x) : k
4980// etc.
4981//
4982// LLVM canonicalizes these to either a min(max()) or a max(min())
4983// pattern. This function tries to match one of these and will return a SSAT
4984// node if successful.
4985//
4986// USAT works similarly to SSAT but bounds on the interval [0, k] where k + 1
4987// is a power of 2.
4988static SDValue LowerSaturatingConditional(SDValue Op, SelectionDAG &DAG) {
4989 EVT VT = Op.getValueType();
4990 SDValue V1 = Op.getOperand(i: 0);
4991 SDValue K1 = Op.getOperand(i: 1);
4992 SDValue TrueVal1 = Op.getOperand(i: 2);
4993 SDValue FalseVal1 = Op.getOperand(i: 3);
4994 ISD::CondCode CC1 = cast<CondCodeSDNode>(Val: Op.getOperand(i: 4))->get();
4995
4996 const SDValue Op2 = isa<ConstantSDNode>(Val: TrueVal1) ? FalseVal1 : TrueVal1;
4997 if (Op2.getOpcode() != ISD::SELECT_CC)
4998 return SDValue();
4999
5000 SDValue V2 = Op2.getOperand(i: 0);
5001 SDValue K2 = Op2.getOperand(i: 1);
5002 SDValue TrueVal2 = Op2.getOperand(i: 2);
5003 SDValue FalseVal2 = Op2.getOperand(i: 3);
5004 ISD::CondCode CC2 = cast<CondCodeSDNode>(Val: Op2.getOperand(i: 4))->get();
5005
5006 SDValue V1Tmp = V1;
5007 SDValue V2Tmp = V2;
5008
5009 // Check that the registers and the constants match a max(min()) or min(max())
5010 // pattern
5011 if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 ||
5012 K2 != FalseVal2 ||
5013 !((isGTorGE(CC: CC1) && isLTorLE(CC: CC2)) || (isLTorLE(CC: CC1) && isGTorGE(CC: CC2))))
5014 return SDValue();
5015
5016 // Check that the constant in the lower-bound check is
5017 // the opposite of the constant in the upper-bound check
5018 // in 1's complement.
5019 if (!isa<ConstantSDNode>(Val: K1) || !isa<ConstantSDNode>(Val: K2))
5020 return SDValue();
5021
5022 int64_t Val1 = cast<ConstantSDNode>(Val&: K1)->getSExtValue();
5023 int64_t Val2 = cast<ConstantSDNode>(Val&: K2)->getSExtValue();
5024 int64_t PosVal = std::max(a: Val1, b: Val2);
5025 int64_t NegVal = std::min(a: Val1, b: Val2);
5026
5027 if (!((Val1 > Val2 && isLTorLE(CC: CC1)) || (Val1 < Val2 && isLTorLE(CC: CC2))) ||
5028 !isPowerOf2_64(Value: PosVal + 1))
5029 return SDValue();
5030
5031 // Handle the difference between USAT (unsigned) and SSAT (signed)
5032 // saturation
5033 // At this point, PosVal is guaranteed to be positive
5034 uint64_t K = PosVal;
5035 SDLoc dl(Op);
5036 if (Val1 == ~Val2)
5037 return DAG.getNode(Opcode: ARMISD::SSAT, DL: dl, VT, N1: V2Tmp,
5038 N2: DAG.getConstant(Val: llvm::countr_one(Value: K), DL: dl, VT));
5039 if (NegVal == 0)
5040 return DAG.getNode(Opcode: ARMISD::USAT, DL: dl, VT, N1: V2Tmp,
5041 N2: DAG.getConstant(Val: llvm::countr_one(Value: K), DL: dl, VT));
5042
5043 return SDValue();
5044}
5045
5046// Check if a condition of the type x < k ? k : x can be converted into a
5047// bit operation instead of conditional moves.
5048// Currently this is allowed given:
5049// - The conditions and values match up
5050// - k is 0 or -1 (all ones)
5051// This function will not check the last condition, thats up to the caller
5052// It returns true if the transformation can be made, and in such case
5053// returns x in V, and k in SatK.
5054static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
5055 SDValue &SatK)
5056{
5057 SDValue LHS = Op.getOperand(i: 0);
5058 SDValue RHS = Op.getOperand(i: 1);
5059 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 4))->get();
5060 SDValue TrueVal = Op.getOperand(i: 2);
5061 SDValue FalseVal = Op.getOperand(i: 3);
5062
5063 SDValue *K = isa<ConstantSDNode>(Val: LHS) ? &LHS : isa<ConstantSDNode>(Val: RHS)
5064 ? &RHS
5065 : nullptr;
5066
5067 // No constant operation in comparison, early out
5068 if (!K)
5069 return false;
5070
5071 SDValue KTmp = isa<ConstantSDNode>(Val: TrueVal) ? TrueVal : FalseVal;
5072 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5073 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5074
5075 // If the constant on left and right side, or variable on left and right,
5076 // does not match, early out
5077 if (*K != KTmp || V != VTmp)
5078 return false;
5079
5080 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, K: *K)) {
5081 SatK = *K;
5082 return true;
5083 }
5084
5085 return false;
5086}
5087
5088bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5089 if (VT == MVT::f32)
5090 return !Subtarget->hasVFP2Base();
5091 if (VT == MVT::f64)
5092 return !Subtarget->hasFP64();
5093 if (VT == MVT::f16)
5094 return !Subtarget->hasFullFP16();
5095 return false;
5096}
5097
5098static SDValue matchCSET(unsigned &Opcode, bool &InvertCond, SDValue TrueVal,
5099 SDValue FalseVal, const ARMSubtarget *Subtarget) {
5100 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(Val&: FalseVal);
5101 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(Val&: TrueVal);
5102 if (!CFVal || !CTVal || !Subtarget->hasV8_1MMainlineOps())
5103 return SDValue();
5104
5105 unsigned TVal = CTVal->getZExtValue();
5106 unsigned FVal = CFVal->getZExtValue();
5107
5108 Opcode = 0;
5109 InvertCond = false;
5110 if (TVal == ~FVal) {
5111 Opcode = ARMISD::CSINV;
5112 } else if (TVal == ~FVal + 1) {
5113 Opcode = ARMISD::CSNEG;
5114 } else if (TVal + 1 == FVal) {
5115 Opcode = ARMISD::CSINC;
5116 } else if (TVal == FVal + 1) {
5117 Opcode = ARMISD::CSINC;
5118 std::swap(a&: TrueVal, b&: FalseVal);
5119 std::swap(a&: TVal, b&: FVal);
5120 InvertCond = !InvertCond;
5121 } else {
5122 return SDValue();
5123 }
5124
5125 // If one of the constants is cheaper than another, materialise the
5126 // cheaper one and let the csel generate the other.
5127 if (Opcode != ARMISD::CSINC &&
5128 HasLowerConstantMaterializationCost(Val1: FVal, Val2: TVal, Subtarget)) {
5129 std::swap(a&: TrueVal, b&: FalseVal);
5130 std::swap(a&: TVal, b&: FVal);
5131 InvertCond = !InvertCond;
5132 }
5133
5134 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5135 // to get there. CSINC not is invertable like the other two (~(~a) == a,
5136 // -(-a) == a, but (a+1)+1 != a).
5137 if (FVal == 0 && Opcode != ARMISD::CSINC) {
5138 std::swap(a&: TrueVal, b&: FalseVal);
5139 std::swap(a&: TVal, b&: FVal);
5140 InvertCond = !InvertCond;
5141 }
5142
5143 return TrueVal;
5144}
5145
5146SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5147 EVT VT = Op.getValueType();
5148 SDLoc dl(Op);
5149
5150 // Try to convert two saturating conditional selects into a single SSAT
5151 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2())
5152 if (SDValue SatValue = LowerSaturatingConditional(Op, DAG))
5153 return SatValue;
5154
5155 // Try to convert expressions of the form x < k ? k : x (and similar forms)
5156 // into more efficient bit operations, which is possible when k is 0 or -1
5157 // On ARM and Thumb-2 which have flexible operand 2 this will result in
5158 // single instructions. On Thumb the shift and the bit operation will be two
5159 // instructions.
5160 // Only allow this transformation on full-width (32-bit) operations
5161 SDValue LowerSatConstant;
5162 SDValue SatValue;
5163 if (VT == MVT::i32 &&
5164 isLowerSaturatingConditional(Op, V&: SatValue, SatK&: LowerSatConstant)) {
5165 SDValue ShiftV = DAG.getNode(Opcode: ISD::SRA, DL: dl, VT, N1: SatValue,
5166 N2: DAG.getConstant(Val: 31, DL: dl, VT));
5167 if (isNullConstant(V: LowerSatConstant)) {
5168 SDValue NotShiftV = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT, N1: ShiftV,
5169 N2: DAG.getAllOnesConstant(DL: dl, VT));
5170 return DAG.getNode(Opcode: ISD::AND, DL: dl, VT, N1: SatValue, N2: NotShiftV);
5171 } else if (isAllOnesConstant(V: LowerSatConstant))
5172 return DAG.getNode(Opcode: ISD::OR, DL: dl, VT, N1: SatValue, N2: ShiftV);
5173 }
5174
5175 SDValue LHS = Op.getOperand(i: 0);
5176 SDValue RHS = Op.getOperand(i: 1);
5177 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 4))->get();
5178 SDValue TrueVal = Op.getOperand(i: 2);
5179 SDValue FalseVal = Op.getOperand(i: 3);
5180 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(Val&: FalseVal);
5181 ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Val&: RHS);
5182 if (Op.getValueType().isInteger()) {
5183
5184 // Check for SMAX(lhs, 0) and SMIN(lhs, 0) patterns.
5185 // (SELECT_CC setgt, lhs, 0, lhs, 0) -> (BIC lhs, (SRA lhs, typesize-1))
5186 // (SELECT_CC setlt, lhs, 0, lhs, 0) -> (AND lhs, (SRA lhs, typesize-1))
5187 // Both require less instructions than compare and conditional select.
5188 if ((CC == ISD::SETGT || CC == ISD::SETLT) && LHS == TrueVal && RHSC &&
5189 RHSC->isZero() && CFVal && CFVal->isZero() &&
5190 LHS.getValueType() == RHS.getValueType()) {
5191 EVT VT = LHS.getValueType();
5192 SDValue Shift =
5193 DAG.getNode(Opcode: ISD::SRA, DL: dl, VT, N1: LHS,
5194 N2: DAG.getConstant(Val: VT.getSizeInBits() - 1, DL: dl, VT));
5195
5196 if (CC == ISD::SETGT)
5197 Shift = DAG.getNOT(DL: dl, Val: Shift, VT);
5198
5199 return DAG.getNode(Opcode: ISD::AND, DL: dl, VT, N1: LHS, N2: Shift);
5200 }
5201
5202 // (SELECT_CC setlt, x, 0, 1, 0) -> SRL(x, bw-1)
5203 if (CC == ISD::SETLT && isNullConstant(V: RHS) && isOneConstant(V: TrueVal) &&
5204 isNullConstant(V: FalseVal) && LHS.getValueType() == VT)
5205 return DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: LHS,
5206 N2: DAG.getConstant(Val: VT.getSizeInBits() - 1, DL: dl, VT));
5207 }
5208
5209 if (LHS.getValueType() == MVT::i32) {
5210 unsigned Opcode;
5211 bool InvertCond;
5212 if (SDValue Op =
5213 matchCSET(Opcode, InvertCond, TrueVal, FalseVal, Subtarget)) {
5214 if (InvertCond)
5215 CC = ISD::getSetCCInverse(Operation: CC, Type: LHS.getValueType());
5216
5217 SDValue ARMcc;
5218 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5219 EVT VT = Op.getValueType();
5220 return DAG.getNode(Opcode, DL: dl, VT, N1: Op, N2: Op, N3: ARMcc, N4: Cmp);
5221 }
5222 }
5223
5224 if (isUnsupportedFloatingType(VT: LHS.getValueType())) {
5225 softenSetCCOperands(DAG, VT: LHS.getValueType(), NewLHS&: LHS, NewRHS&: RHS, CCCode&: CC, DL: dl, OldLHS: LHS, OldRHS: RHS);
5226
5227 // If softenSetCCOperands only returned one value, we should compare it to
5228 // zero.
5229 if (!RHS.getNode()) {
5230 RHS = DAG.getConstant(Val: 0, DL: dl, VT: LHS.getValueType());
5231 CC = ISD::SETNE;
5232 }
5233 }
5234
5235 if (LHS.getValueType() == MVT::i32) {
5236 // Try to generate VSEL on ARMv8.
5237 // The VSEL instruction can't use all the usual ARM condition
5238 // codes: it only has two bits to select the condition code, so it's
5239 // constrained to use only GE, GT, VS and EQ.
5240 //
5241 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5242 // swap the operands of the previous compare instruction (effectively
5243 // inverting the compare condition, swapping 'less' and 'greater') and
5244 // sometimes need to swap the operands to the VSEL (which inverts the
5245 // condition in the sense of firing whenever the previous condition didn't)
5246 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5247 TrueVal.getValueType() == MVT::f32 ||
5248 TrueVal.getValueType() == MVT::f64)) {
5249 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5250 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5251 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5252 CC = ISD::getSetCCInverse(Operation: CC, Type: LHS.getValueType());
5253 std::swap(a&: TrueVal, b&: FalseVal);
5254 }
5255 }
5256
5257 SDValue ARMcc;
5258 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5259 // Choose GE over PL, which vsel does now support
5260 if (ARMcc->getAsZExtVal() == ARMCC::PL)
5261 ARMcc = DAG.getConstant(Val: ARMCC::GE, DL: dl, VT: MVT::i32);
5262 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Flags: Cmp, DAG);
5263 }
5264
5265 ARMCC::CondCodes CondCode, CondCode2;
5266 FPCCToARMCC(CC, CondCode, CondCode2);
5267
5268 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5269 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5270 // must use VSEL (limited condition codes), due to not having conditional f16
5271 // moves.
5272 if (Subtarget->hasFPARMv8Base() &&
5273 !(isFloatingPointZero(Op: RHS) && TrueVal.getValueType() != MVT::f16) &&
5274 (TrueVal.getValueType() == MVT::f16 ||
5275 TrueVal.getValueType() == MVT::f32 ||
5276 TrueVal.getValueType() == MVT::f64)) {
5277 bool swpCmpOps = false;
5278 bool swpVselOps = false;
5279 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5280
5281 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5282 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5283 if (swpCmpOps)
5284 std::swap(a&: LHS, b&: RHS);
5285 if (swpVselOps)
5286 std::swap(a&: TrueVal, b&: FalseVal);
5287 }
5288 }
5289
5290 SDValue ARMcc = DAG.getConstant(Val: CondCode, DL: dl, VT: MVT::i32);
5291 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5292 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Flags: Cmp, DAG);
5293 if (CondCode2 != ARMCC::AL) {
5294 SDValue ARMcc2 = DAG.getConstant(Val: CondCode2, DL: dl, VT: MVT::i32);
5295 Result = getCMOV(dl, VT, FalseVal: Result, TrueVal, ARMcc: ARMcc2, Flags: Cmp, DAG);
5296 }
5297 return Result;
5298}
5299
5300/// canChangeToInt - Given the fp compare operand, return true if it is suitable
5301/// to morph to an integer compare sequence.
5302static bool canChangeToInt(SDValue Op, bool &SeenZero,
5303 const ARMSubtarget *Subtarget) {
5304 SDNode *N = Op.getNode();
5305 if (!N->hasOneUse())
5306 // Otherwise it requires moving the value from fp to integer registers.
5307 return false;
5308 if (!N->getNumValues())
5309 return false;
5310 EVT VT = Op.getValueType();
5311 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5312 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5313 // vmrs are very slow, e.g. cortex-a8.
5314 return false;
5315
5316 if (isFloatingPointZero(Op)) {
5317 SeenZero = true;
5318 return true;
5319 }
5320 return ISD::isNormalLoad(N);
5321}
5322
5323static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5324 if (isFloatingPointZero(Op))
5325 return DAG.getConstant(Val: 0, DL: SDLoc(Op), VT: MVT::i32);
5326
5327 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val&: Op))
5328 return DAG.getLoad(VT: MVT::i32, dl: SDLoc(Op), Chain: Ld->getChain(), Ptr: Ld->getBasePtr(),
5329 PtrInfo: Ld->getPointerInfo(), Alignment: Ld->getAlign(),
5330 MMOFlags: Ld->getMemOperand()->getFlags());
5331
5332 llvm_unreachable("Unknown VFP cmp argument!");
5333}
5334
5335static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5336 SDValue &RetVal1, SDValue &RetVal2) {
5337 SDLoc dl(Op);
5338
5339 if (isFloatingPointZero(Op)) {
5340 RetVal1 = DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32);
5341 RetVal2 = DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32);
5342 return;
5343 }
5344
5345 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val&: Op)) {
5346 SDValue Ptr = Ld->getBasePtr();
5347 RetVal1 =
5348 DAG.getLoad(VT: MVT::i32, dl, Chain: Ld->getChain(), Ptr, PtrInfo: Ld->getPointerInfo(),
5349 Alignment: Ld->getAlign(), MMOFlags: Ld->getMemOperand()->getFlags());
5350
5351 EVT PtrType = Ptr.getValueType();
5352 SDValue NewPtr = DAG.getNode(Opcode: ISD::ADD, DL: dl,
5353 VT: PtrType, N1: Ptr, N2: DAG.getConstant(Val: 4, DL: dl, VT: PtrType));
5354 RetVal2 = DAG.getLoad(VT: MVT::i32, dl, Chain: Ld->getChain(), Ptr: NewPtr,
5355 PtrInfo: Ld->getPointerInfo().getWithOffset(O: 4),
5356 Alignment: commonAlignment(A: Ld->getAlign(), Offset: 4),
5357 MMOFlags: Ld->getMemOperand()->getFlags());
5358 return;
5359 }
5360
5361 llvm_unreachable("Unknown VFP cmp argument!");
5362}
5363
5364/// OptimizeVFPBrcond - With nnan and without daz, it's legal to optimize some
5365/// f32 and even f64 comparisons to integer ones.
5366SDValue
5367ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5368 SDValue Chain = Op.getOperand(i: 0);
5369 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 1))->get();
5370 SDValue LHS = Op.getOperand(i: 2);
5371 SDValue RHS = Op.getOperand(i: 3);
5372 SDValue Dest = Op.getOperand(i: 4);
5373 SDLoc dl(Op);
5374
5375 bool LHSSeenZero = false;
5376 bool LHSOk = canChangeToInt(Op: LHS, SeenZero&: LHSSeenZero, Subtarget);
5377 bool RHSSeenZero = false;
5378 bool RHSOk = canChangeToInt(Op: RHS, SeenZero&: RHSSeenZero, Subtarget);
5379 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5380 // If unsafe fp math optimization is enabled and there are no other uses of
5381 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5382 // to an integer comparison.
5383 if (CC == ISD::SETOEQ)
5384 CC = ISD::SETEQ;
5385 else if (CC == ISD::SETUNE)
5386 CC = ISD::SETNE;
5387
5388 SDValue Mask = DAG.getConstant(Val: 0x7fffffff, DL: dl, VT: MVT::i32);
5389 SDValue ARMcc;
5390 if (LHS.getValueType() == MVT::f32) {
5391 LHS = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32,
5392 N1: bitcastf32Toi32(Op: LHS, DAG), N2: Mask);
5393 RHS = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32,
5394 N1: bitcastf32Toi32(Op: RHS, DAG), N2: Mask);
5395 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5396 return DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, N1: Chain, N2: Dest, N3: ARMcc,
5397 N4: Cmp);
5398 }
5399
5400 SDValue LHS1, LHS2;
5401 SDValue RHS1, RHS2;
5402 expandf64Toi32(Op: LHS, DAG, RetVal1&: LHS1, RetVal2&: LHS2);
5403 expandf64Toi32(Op: RHS, DAG, RetVal1&: RHS1, RetVal2&: RHS2);
5404 LHS2 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: LHS2, N2: Mask);
5405 RHS2 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: RHS2, N2: Mask);
5406 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5407 ARMcc = DAG.getConstant(Val: CondCode, DL: dl, VT: MVT::i32);
5408 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5409 return DAG.getNode(Opcode: ARMISD::BCC_i64, DL: dl, VT: MVT::Other, Ops);
5410 }
5411
5412 return SDValue();
5413}
5414
5415// Generate CMP + CMOV for integer abs.
5416SDValue ARMTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
5417 SDLoc DL(Op);
5418
5419 SDValue Neg = DAG.getNegative(Val: Op.getOperand(i: 0), DL, VT: MVT::i32);
5420
5421 // Generate CMP & CMOV.
5422 SDValue Cmp = DAG.getNode(Opcode: ARMISD::CMP, DL, VT: FlagsVT, N1: Op.getOperand(i: 0),
5423 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
5424 return DAG.getNode(Opcode: ARMISD::CMOV, DL, VT: MVT::i32, N1: Op.getOperand(i: 0), N2: Neg,
5425 N3: DAG.getConstant(Val: ARMCC::MI, DL, VT: MVT::i32), N4: Cmp);
5426}
5427
5428static SDValue getInvertedARMCondCode(SDValue ARMcc, SelectionDAG &DAG) {
5429 ARMCC::CondCodes CondCode =
5430 (ARMCC::CondCodes)cast<ConstantSDNode>(Val&: ARMcc)->getZExtValue();
5431 CondCode = ARMCC::getOppositeCondition(CC: CondCode);
5432 return DAG.getConstant(Val: CondCode, DL: SDLoc(ARMcc), VT: MVT::i32);
5433}
5434
5435SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5436 SDValue Chain = Op.getOperand(i: 0);
5437 SDValue Cond = Op.getOperand(i: 1);
5438 SDValue Dest = Op.getOperand(i: 2);
5439 SDLoc dl(Op);
5440
5441 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5442 // instruction.
5443 unsigned Opc = Cond.getOpcode();
5444 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5445 !Subtarget->isThumb1Only();
5446 if (Cond.getResNo() == 1 &&
5447 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5448 Opc == ISD::USUBO || OptimizeMul)) {
5449 // Only lower legal XALUO ops.
5450 if (!isTypeLegal(VT: Cond->getValueType(ResNo: 0)))
5451 return SDValue();
5452
5453 // The actual operation with overflow check.
5454 SDValue Value, OverflowCmp;
5455 SDValue ARMcc;
5456 std::tie(args&: Value, args&: OverflowCmp) = getARMXALUOOp(Op: Cond, DAG, ARMcc);
5457
5458 // Reverse the condition code.
5459 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5460
5461 return DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, N1: Chain, N2: Dest, N3: ARMcc,
5462 N4: OverflowCmp);
5463 }
5464
5465 return SDValue();
5466}
5467
5468SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5469 SDValue Chain = Op.getOperand(i: 0);
5470 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 1))->get();
5471 SDValue LHS = Op.getOperand(i: 2);
5472 SDValue RHS = Op.getOperand(i: 3);
5473 SDValue Dest = Op.getOperand(i: 4);
5474 SDLoc dl(Op);
5475
5476 if (isUnsupportedFloatingType(VT: LHS.getValueType())) {
5477 softenSetCCOperands(DAG, VT: LHS.getValueType(), NewLHS&: LHS, NewRHS&: RHS, CCCode&: CC, DL: dl, OldLHS: LHS, OldRHS: RHS);
5478
5479 // If softenSetCCOperands only returned one value, we should compare it to
5480 // zero.
5481 if (!RHS.getNode()) {
5482 RHS = DAG.getConstant(Val: 0, DL: dl, VT: LHS.getValueType());
5483 CC = ISD::SETNE;
5484 }
5485 }
5486
5487 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5488 // instruction.
5489 unsigned Opc = LHS.getOpcode();
5490 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5491 !Subtarget->isThumb1Only();
5492 if (LHS.getResNo() == 1 && (isOneConstant(V: RHS) || isNullConstant(V: RHS)) &&
5493 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5494 Opc == ISD::USUBO || OptimizeMul) &&
5495 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5496 // Only lower legal XALUO ops.
5497 if (!isTypeLegal(VT: LHS->getValueType(ResNo: 0)))
5498 return SDValue();
5499
5500 // The actual operation with overflow check.
5501 SDValue Value, OverflowCmp;
5502 SDValue ARMcc;
5503 std::tie(args&: Value, args&: OverflowCmp) = getARMXALUOOp(Op: LHS.getValue(R: 0), DAG, ARMcc);
5504
5505 if ((CC == ISD::SETNE) != isOneConstant(V: RHS)) {
5506 // Reverse the condition code.
5507 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5508 }
5509
5510 return DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, N1: Chain, N2: Dest, N3: ARMcc,
5511 N4: OverflowCmp);
5512 }
5513
5514 if (LHS.getValueType() == MVT::i32) {
5515 SDValue ARMcc;
5516 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5517 return DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, N1: Chain, N2: Dest, N3: ARMcc, N4: Cmp);
5518 }
5519
5520 SDNodeFlags Flags = Op->getFlags();
5521 if (Flags.hasNoNaNs() &&
5522 DAG.getDenormalMode(VT: MVT::f32) == DenormalMode::getIEEE() &&
5523 DAG.getDenormalMode(VT: MVT::f64) == DenormalMode::getIEEE() &&
5524 (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETNE ||
5525 CC == ISD::SETUNE)) {
5526 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5527 return Result;
5528 }
5529
5530 ARMCC::CondCodes CondCode, CondCode2;
5531 FPCCToARMCC(CC, CondCode, CondCode2);
5532
5533 SDValue ARMcc = DAG.getConstant(Val: CondCode, DL: dl, VT: MVT::i32);
5534 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5535 SDValue Ops[] = {Chain, Dest, ARMcc, Cmp};
5536 SDValue Res = DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, Ops);
5537 if (CondCode2 != ARMCC::AL) {
5538 ARMcc = DAG.getConstant(Val: CondCode2, DL: dl, VT: MVT::i32);
5539 SDValue Ops[] = {Res, Dest, ARMcc, Cmp};
5540 Res = DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, Ops);
5541 }
5542 return Res;
5543}
5544
5545SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5546 SDValue Chain = Op.getOperand(i: 0);
5547 SDValue Table = Op.getOperand(i: 1);
5548 SDValue Index = Op.getOperand(i: 2);
5549 SDLoc dl(Op);
5550
5551 EVT PTy = getPointerTy(DL: DAG.getDataLayout());
5552 JumpTableSDNode *JT = cast<JumpTableSDNode>(Val&: Table);
5553 SDValue JTI = DAG.getTargetJumpTable(JTI: JT->getIndex(), VT: PTy);
5554 Table = DAG.getNode(Opcode: ARMISD::WrapperJT, DL: dl, VT: MVT::i32, Operand: JTI);
5555 Index = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: PTy, N1: Index, N2: DAG.getConstant(Val: 4, DL: dl, VT: PTy));
5556 SDValue Addr = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PTy, N1: Table, N2: Index);
5557 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5558 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5559 // which does another jump to the destination. This also makes it easier
5560 // to translate it to TBB / TBH later (Thumb2 only).
5561 // FIXME: This might not work if the function is extremely large.
5562 return DAG.getNode(Opcode: ARMISD::BR2_JT, DL: dl, VT: MVT::Other, N1: Chain,
5563 N2: Addr, N3: Op.getOperand(i: 2), N4: JTI);
5564 }
5565 if (isPositionIndependent() || Subtarget->isROPI()) {
5566 Addr =
5567 DAG.getLoad(VT: (EVT)MVT::i32, dl, Chain, Ptr: Addr,
5568 PtrInfo: MachinePointerInfo::getJumpTable(MF&: DAG.getMachineFunction()));
5569 Chain = Addr.getValue(R: 1);
5570 Addr = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PTy, N1: Table, N2: Addr);
5571 return DAG.getNode(Opcode: ARMISD::BR_JT, DL: dl, VT: MVT::Other, N1: Chain, N2: Addr, N3: JTI);
5572 } else {
5573 Addr =
5574 DAG.getLoad(VT: PTy, dl, Chain, Ptr: Addr,
5575 PtrInfo: MachinePointerInfo::getJumpTable(MF&: DAG.getMachineFunction()));
5576 Chain = Addr.getValue(R: 1);
5577 return DAG.getNode(Opcode: ARMISD::BR_JT, DL: dl, VT: MVT::Other, N1: Chain, N2: Addr, N3: JTI);
5578 }
5579}
5580
5581static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5582 EVT VT = Op.getValueType();
5583 SDLoc dl(Op);
5584
5585 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5586 if (Op.getOperand(i: 0).getValueType().getVectorElementType() == MVT::f32)
5587 return Op;
5588 return DAG.UnrollVectorOp(N: Op.getNode());
5589 }
5590
5591 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5592
5593 EVT NewTy;
5594 const EVT OpTy = Op.getOperand(i: 0).getValueType();
5595 if (OpTy == MVT::v4f32)
5596 NewTy = MVT::v4i32;
5597 else if (OpTy == MVT::v4f16 && HasFullFP16)
5598 NewTy = MVT::v4i16;
5599 else if (OpTy == MVT::v8f16 && HasFullFP16)
5600 NewTy = MVT::v8i16;
5601 else
5602 llvm_unreachable("Invalid type for custom lowering!");
5603
5604 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5605 return DAG.UnrollVectorOp(N: Op.getNode());
5606
5607 Op = DAG.getNode(Opcode: Op.getOpcode(), DL: dl, VT: NewTy, Operand: Op.getOperand(i: 0));
5608 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT, Operand: Op);
5609}
5610
5611SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5612 EVT VT = Op.getValueType();
5613 if (VT.isVector())
5614 return LowerVectorFP_TO_INT(Op, DAG);
5615
5616 bool IsStrict = Op->isStrictFPOpcode();
5617 SDValue SrcVal = Op.getOperand(i: IsStrict ? 1 : 0);
5618
5619 if (isUnsupportedFloatingType(VT: SrcVal.getValueType())) {
5620 RTLIB::Libcall LC;
5621 if (Op.getOpcode() == ISD::FP_TO_SINT ||
5622 Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5623 LC = RTLIB::getFPTOSINT(OpVT: SrcVal.getValueType(),
5624 RetVT: Op.getValueType());
5625 else
5626 LC = RTLIB::getFPTOUINT(OpVT: SrcVal.getValueType(),
5627 RetVT: Op.getValueType());
5628 SDLoc Loc(Op);
5629 MakeLibCallOptions CallOptions;
5630 SDValue Chain = IsStrict ? Op.getOperand(i: 0) : SDValue();
5631 SDValue Result;
5632 std::tie(args&: Result, args&: Chain) = makeLibCall(DAG, LC, RetVT: Op.getValueType(), Ops: SrcVal,
5633 CallOptions, dl: Loc, Chain);
5634 return IsStrict ? DAG.getMergeValues(Ops: {Result, Chain}, dl: Loc) : Result;
5635 }
5636
5637 // FIXME: Remove this when we have strict fp instruction selection patterns
5638 if (IsStrict) {
5639 SDLoc Loc(Op);
5640 SDValue Result =
5641 DAG.getNode(Opcode: Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5642 : ISD::FP_TO_UINT,
5643 DL: Loc, VT: Op.getValueType(), Operand: SrcVal);
5644 return DAG.getMergeValues(Ops: {Result, Op.getOperand(i: 0)}, dl: Loc);
5645 }
5646
5647 return Op;
5648}
5649
5650static SDValue LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
5651 const ARMSubtarget *Subtarget) {
5652 EVT VT = Op.getValueType();
5653 EVT ToVT = cast<VTSDNode>(Val: Op.getOperand(i: 1))->getVT();
5654 EVT FromVT = Op.getOperand(i: 0).getValueType();
5655
5656 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f32)
5657 return Op;
5658 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f64 &&
5659 Subtarget->hasFP64())
5660 return Op;
5661 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f16 &&
5662 Subtarget->hasFullFP16())
5663 return Op;
5664 if (VT == MVT::v4i32 && ToVT == MVT::i32 && FromVT == MVT::v4f32 &&
5665 Subtarget->hasMVEFloatOps())
5666 return Op;
5667 if (VT == MVT::v8i16 && ToVT == MVT::i16 && FromVT == MVT::v8f16 &&
5668 Subtarget->hasMVEFloatOps())
5669 return Op;
5670
5671 if (FromVT != MVT::v4f32 && FromVT != MVT::v8f16)
5672 return SDValue();
5673
5674 SDLoc DL(Op);
5675 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
5676 unsigned BW = ToVT.getScalarSizeInBits() - IsSigned;
5677 SDValue CVT = DAG.getNode(Opcode: Op.getOpcode(), DL, VT, N1: Op.getOperand(i: 0),
5678 N2: DAG.getValueType(VT.getScalarType()));
5679 SDValue Max = DAG.getNode(Opcode: IsSigned ? ISD::SMIN : ISD::UMIN, DL, VT, N1: CVT,
5680 N2: DAG.getConstant(Val: (1 << BW) - 1, DL, VT));
5681 if (IsSigned)
5682 Max = DAG.getNode(Opcode: ISD::SMAX, DL, VT, N1: Max,
5683 N2: DAG.getSignedConstant(Val: -(1 << BW), DL, VT));
5684 return Max;
5685}
5686
5687static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5688 EVT VT = Op.getValueType();
5689 SDLoc dl(Op);
5690
5691 if (Op.getOperand(i: 0).getValueType().getVectorElementType() == MVT::i32) {
5692 if (VT.getVectorElementType() == MVT::f32)
5693 return Op;
5694 return DAG.UnrollVectorOp(N: Op.getNode());
5695 }
5696
5697 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5698 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5699 "Invalid type for custom lowering!");
5700
5701 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5702
5703 EVT DestVecType;
5704 if (VT == MVT::v4f32)
5705 DestVecType = MVT::v4i32;
5706 else if (VT == MVT::v4f16 && HasFullFP16)
5707 DestVecType = MVT::v4i16;
5708 else if (VT == MVT::v8f16 && HasFullFP16)
5709 DestVecType = MVT::v8i16;
5710 else
5711 return DAG.UnrollVectorOp(N: Op.getNode());
5712
5713 unsigned CastOpc;
5714 unsigned Opc;
5715 switch (Op.getOpcode()) {
5716 default: llvm_unreachable("Invalid opcode!");
5717 case ISD::SINT_TO_FP:
5718 CastOpc = ISD::SIGN_EXTEND;
5719 Opc = ISD::SINT_TO_FP;
5720 break;
5721 case ISD::UINT_TO_FP:
5722 CastOpc = ISD::ZERO_EXTEND;
5723 Opc = ISD::UINT_TO_FP;
5724 break;
5725 }
5726
5727 Op = DAG.getNode(Opcode: CastOpc, DL: dl, VT: DestVecType, Operand: Op.getOperand(i: 0));
5728 return DAG.getNode(Opcode: Opc, DL: dl, VT, Operand: Op);
5729}
5730
5731SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5732 EVT VT = Op.getValueType();
5733 if (VT.isVector())
5734 return LowerVectorINT_TO_FP(Op, DAG);
5735 if (isUnsupportedFloatingType(VT)) {
5736 RTLIB::Libcall LC;
5737 if (Op.getOpcode() == ISD::SINT_TO_FP)
5738 LC = RTLIB::getSINTTOFP(OpVT: Op.getOperand(i: 0).getValueType(),
5739 RetVT: Op.getValueType());
5740 else
5741 LC = RTLIB::getUINTTOFP(OpVT: Op.getOperand(i: 0).getValueType(),
5742 RetVT: Op.getValueType());
5743 MakeLibCallOptions CallOptions;
5744 return makeLibCall(DAG, LC, RetVT: Op.getValueType(), Ops: Op.getOperand(i: 0),
5745 CallOptions, dl: SDLoc(Op)).first;
5746 }
5747
5748 return Op;
5749}
5750
5751SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5752 // Implement fcopysign with a fabs and a conditional fneg.
5753 SDValue Tmp0 = Op.getOperand(i: 0);
5754 SDValue Tmp1 = Op.getOperand(i: 1);
5755 SDLoc dl(Op);
5756 EVT VT = Op.getValueType();
5757 EVT SrcVT = Tmp1.getValueType();
5758 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5759 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5760 bool UseNEON = !InGPR && Subtarget->hasNEON();
5761
5762 if (UseNEON) {
5763 // Use VBSL to copy the sign bit.
5764 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode: 0x6, Val: 0x80);
5765 SDValue Mask = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: MVT::v2i32,
5766 Operand: DAG.getTargetConstant(Val: EncodedVal, DL: dl, VT: MVT::i32));
5767 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5768 if (VT == MVT::f64)
5769 Mask = DAG.getNode(Opcode: ARMISD::VSHLIMM, DL: dl, VT: OpVT,
5770 N1: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: OpVT, Operand: Mask),
5771 N2: DAG.getConstant(Val: 32, DL: dl, VT: MVT::i32));
5772 else /*if (VT == MVT::f32)*/
5773 Tmp0 = DAG.getNode(Opcode: ISD::SCALAR_TO_VECTOR, DL: dl, VT: MVT::v2f32, Operand: Tmp0);
5774 if (SrcVT == MVT::f32) {
5775 Tmp1 = DAG.getNode(Opcode: ISD::SCALAR_TO_VECTOR, DL: dl, VT: MVT::v2f32, Operand: Tmp1);
5776 if (VT == MVT::f64)
5777 Tmp1 = DAG.getNode(Opcode: ARMISD::VSHLIMM, DL: dl, VT: OpVT,
5778 N1: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: OpVT, Operand: Tmp1),
5779 N2: DAG.getConstant(Val: 32, DL: dl, VT: MVT::i32));
5780 } else if (VT == MVT::f32)
5781 Tmp1 = DAG.getNode(Opcode: ARMISD::VSHRuIMM, DL: dl, VT: MVT::v1i64,
5782 N1: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v1i64, Operand: Tmp1),
5783 N2: DAG.getConstant(Val: 32, DL: dl, VT: MVT::i32));
5784 Tmp0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: OpVT, Operand: Tmp0);
5785 Tmp1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: OpVT, Operand: Tmp1);
5786
5787 SDValue AllOnes = DAG.getTargetConstant(Val: ARM_AM::createVMOVModImm(OpCmode: 0xe, Val: 0xff),
5788 DL: dl, VT: MVT::i32);
5789 AllOnes = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: MVT::v8i8, Operand: AllOnes);
5790 SDValue MaskNot = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT: OpVT, N1: Mask,
5791 N2: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: OpVT, Operand: AllOnes));
5792
5793 SDValue Res = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: OpVT,
5794 N1: DAG.getNode(Opcode: ISD::AND, DL: dl, VT: OpVT, N1: Tmp1, N2: Mask),
5795 N2: DAG.getNode(Opcode: ISD::AND, DL: dl, VT: OpVT, N1: Tmp0, N2: MaskNot));
5796 if (VT == MVT::f32) {
5797 Res = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v2f32, Operand: Res);
5798 Res = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f32, N1: Res,
5799 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
5800 } else {
5801 Res = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f64, Operand: Res);
5802 }
5803
5804 return Res;
5805 }
5806
5807 // Bitcast operand 1 to i32.
5808 if (SrcVT == MVT::f64)
5809 Tmp1 = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
5810 N: Tmp1).getValue(R: 1);
5811 Tmp1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Tmp1);
5812
5813 // Or in the signbit with integer operations.
5814 SDValue Mask1 = DAG.getConstant(Val: 0x80000000, DL: dl, VT: MVT::i32);
5815 SDValue Mask2 = DAG.getConstant(Val: 0x7fffffff, DL: dl, VT: MVT::i32);
5816 Tmp1 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Tmp1, N2: Mask1);
5817 if (VT == MVT::f32) {
5818 Tmp0 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32,
5819 N1: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Tmp0), N2: Mask2);
5820 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f32,
5821 Operand: DAG.getNode(Opcode: ISD::OR, DL: dl, VT: MVT::i32, N1: Tmp0, N2: Tmp1));
5822 }
5823
5824 // f64: Or the high part with signbit and then combine two parts.
5825 Tmp0 = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
5826 N: Tmp0);
5827 SDValue Lo = Tmp0.getValue(R: 0);
5828 SDValue Hi = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Tmp0.getValue(R: 1), N2: Mask2);
5829 Hi = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: MVT::i32, N1: Hi, N2: Tmp1);
5830 return DAG.getNode(Opcode: ARMISD::VMOVDRR, DL: dl, VT: MVT::f64, N1: Lo, N2: Hi);
5831}
5832
5833SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5834 MachineFunction &MF = DAG.getMachineFunction();
5835 MachineFrameInfo &MFI = MF.getFrameInfo();
5836 MFI.setReturnAddressIsTaken(true);
5837
5838 EVT VT = Op.getValueType();
5839 SDLoc dl(Op);
5840 unsigned Depth = Op.getConstantOperandVal(i: 0);
5841 if (Depth) {
5842 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5843 SDValue Offset = DAG.getConstant(Val: 4, DL: dl, VT: MVT::i32);
5844 return DAG.getLoad(VT, dl, Chain: DAG.getEntryNode(),
5845 Ptr: DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: FrameAddr, N2: Offset),
5846 PtrInfo: MachinePointerInfo());
5847 }
5848
5849 // Return LR, which contains the return address. Mark it an implicit live-in.
5850 Register Reg = MF.addLiveIn(PReg: ARM::LR, RC: getRegClassFor(VT: MVT::i32));
5851 return DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl, Reg, VT);
5852}
5853
5854SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5855 const ARMBaseRegisterInfo &ARI =
5856 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5857 MachineFunction &MF = DAG.getMachineFunction();
5858 MachineFrameInfo &MFI = MF.getFrameInfo();
5859 MFI.setFrameAddressIsTaken(true);
5860
5861 EVT VT = Op.getValueType();
5862 SDLoc dl(Op); // FIXME probably not meaningful
5863 unsigned Depth = Op.getConstantOperandVal(i: 0);
5864 Register FrameReg = ARI.getFrameRegister(MF);
5865 SDValue FrameAddr = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl, Reg: FrameReg, VT);
5866 while (Depth--)
5867 FrameAddr = DAG.getLoad(VT, dl, Chain: DAG.getEntryNode(), Ptr: FrameAddr,
5868 PtrInfo: MachinePointerInfo());
5869 return FrameAddr;
5870}
5871
5872// FIXME? Maybe this could be a TableGen attribute on some registers and
5873// this table could be generated automatically from RegInfo.
5874Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
5875 const MachineFunction &MF) const {
5876 return StringSwitch<Register>(RegName)
5877 .Case(S: "sp", Value: ARM::SP)
5878 .Default(Value: Register());
5879}
5880
5881// Result is 64 bit value so split into two 32 bit values and return as a
5882// pair of values.
5883static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5884 SelectionDAG &DAG) {
5885 SDLoc DL(N);
5886
5887 // This function is only supposed to be called for i64 type destination.
5888 assert(N->getValueType(0) == MVT::i64
5889 && "ExpandREAD_REGISTER called for non-i64 type result.");
5890
5891 SDValue Read = DAG.getNode(Opcode: ISD::READ_REGISTER, DL,
5892 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32, VT3: MVT::Other),
5893 N1: N->getOperand(Num: 0),
5894 N2: N->getOperand(Num: 1));
5895
5896 Results.push_back(Elt: DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VT: MVT::i64, N1: Read.getValue(R: 0),
5897 N2: Read.getValue(R: 1)));
5898 Results.push_back(Elt: Read.getValue(R: 2)); // Chain
5899}
5900
5901/// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5902/// When \p DstVT, the destination type of \p BC, is on the vector
5903/// register bank and the source of bitcast, \p Op, operates on the same bank,
5904/// it might be possible to combine them, such that everything stays on the
5905/// vector register bank.
5906/// \p return The node that would replace \p BT, if the combine
5907/// is possible.
5908static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5909 SelectionDAG &DAG) {
5910 SDValue Op = BC->getOperand(Num: 0);
5911 EVT DstVT = BC->getValueType(ResNo: 0);
5912
5913 // The only vector instruction that can produce a scalar (remember,
5914 // since the bitcast was about to be turned into VMOVDRR, the source
5915 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5916 // Moreover, we can do this combine only if there is one use.
5917 // Finally, if the destination type is not a vector, there is not
5918 // much point on forcing everything on the vector bank.
5919 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5920 !Op.hasOneUse())
5921 return SDValue();
5922
5923 // If the index is not constant, we will introduce an additional
5924 // multiply that will stick.
5925 // Give up in that case.
5926 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 1));
5927 if (!Index)
5928 return SDValue();
5929 unsigned DstNumElt = DstVT.getVectorNumElements();
5930
5931 // Compute the new index.
5932 const APInt &APIntIndex = Index->getAPIntValue();
5933 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5934 NewIndex *= APIntIndex;
5935 // Check if the new constant index fits into i32.
5936 if (NewIndex.getBitWidth() > 32)
5937 return SDValue();
5938
5939 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5940 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5941 SDLoc dl(Op);
5942 SDValue ExtractSrc = Op.getOperand(i: 0);
5943 EVT VecVT = EVT::getVectorVT(
5944 Context&: *DAG.getContext(), VT: DstVT.getScalarType(),
5945 NumElements: ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5946 SDValue BitCast = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VecVT, Operand: ExtractSrc);
5947 return DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: DstVT, N1: BitCast,
5948 N2: DAG.getConstant(Val: NewIndex.getZExtValue(), DL: dl, VT: MVT::i32));
5949}
5950
5951/// ExpandBITCAST - If the target supports VFP, this function is called to
5952/// expand a bit convert where either the source or destination type is i64 to
5953/// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5954/// operand type is illegal (e.g., v2f32 for a target that doesn't support
5955/// vectors), since the legalizer won't know what to do with that.
5956SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5957 const ARMSubtarget *Subtarget) const {
5958 SDLoc dl(N);
5959 SDValue Op = N->getOperand(Num: 0);
5960
5961 // This function is only supposed to be called for i16 and i64 types, either
5962 // as the source or destination of the bit convert.
5963 EVT SrcVT = Op.getValueType();
5964 EVT DstVT = N->getValueType(ResNo: 0);
5965
5966 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
5967 (DstVT == MVT::f16 || DstVT == MVT::bf16))
5968 return MoveToHPR(dl: SDLoc(N), DAG, LocVT: MVT::i32, ValVT: DstVT.getSimpleVT(),
5969 Val: DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: SDLoc(N), VT: MVT::i32, Operand: Op));
5970
5971 if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
5972 (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) {
5973 if (Subtarget->hasFullFP16() && !Subtarget->hasBF16())
5974 Op = DAG.getBitcast(VT: MVT::f16, V: Op);
5975 return DAG.getNode(
5976 Opcode: ISD::TRUNCATE, DL: SDLoc(N), VT: DstVT,
5977 Operand: MoveFromHPR(dl: SDLoc(N), DAG, LocVT: MVT::i32, ValVT: SrcVT.getSimpleVT(), Val: Op));
5978 }
5979
5980 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5981 return SDValue();
5982
5983 // Turn i64->f64 into VMOVDRR.
5984 if (SrcVT == MVT::i64 && isTypeLegal(VT: DstVT)) {
5985 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5986 // if we can combine the bitcast with its source.
5987 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(BC: N, DAG))
5988 return Val;
5989 SDValue Lo, Hi;
5990 std::tie(args&: Lo, args&: Hi) = DAG.SplitScalar(N: Op, DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
5991 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: DstVT,
5992 Operand: DAG.getNode(Opcode: ARMISD::VMOVDRR, DL: dl, VT: MVT::f64, N1: Lo, N2: Hi));
5993 }
5994
5995 // Turn f64->i64 into VMOVRRD.
5996 if (DstVT == MVT::i64 && isTypeLegal(VT: SrcVT)) {
5997 SDValue Cvt;
5998 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5999 SrcVT.getVectorNumElements() > 1)
6000 Cvt = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl,
6001 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
6002 N: DAG.getNode(Opcode: ARMISD::VREV64, DL: dl, VT: SrcVT, Operand: Op));
6003 else
6004 Cvt = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl,
6005 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N: Op);
6006 // Merge the pieces into a single i64 value.
6007 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Cvt, N2: Cvt.getValue(R: 1));
6008 }
6009
6010 return SDValue();
6011}
6012
6013/// getZeroVector - Returns a vector of specified type with all zero elements.
6014/// Zero vectors are used to represent vector negation and in those cases
6015/// will be implemented with the NEON VNEG instruction. However, VNEG does
6016/// not support i64 elements, so sometimes the zero vectors will need to be
6017/// explicitly constructed. Regardless, use a canonical VMOV to create the
6018/// zero vector.
6019static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6020 assert(VT.isVector() && "Expected a vector type");
6021 // The canonical modified immediate encoding of a zero vector is....0!
6022 SDValue EncodedVal = DAG.getTargetConstant(Val: 0, DL: dl, VT: MVT::i32);
6023 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6024 SDValue Vmov = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: VmovVT, Operand: EncodedVal);
6025 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Vmov);
6026}
6027
6028/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6029/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6030SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6031 SelectionDAG &DAG) const {
6032 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6033 EVT VT = Op.getValueType();
6034 unsigned VTBits = VT.getSizeInBits();
6035 SDLoc dl(Op);
6036 SDValue ShOpLo = Op.getOperand(i: 0);
6037 SDValue ShOpHi = Op.getOperand(i: 1);
6038 SDValue ShAmt = Op.getOperand(i: 2);
6039 SDValue ARMcc;
6040 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6041
6042 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6043
6044 SDValue RevShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
6045 N1: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32), N2: ShAmt);
6046 SDValue Tmp1 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: ShOpLo, N2: ShAmt);
6047 SDValue ExtraShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: ShAmt,
6048 N2: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32));
6049 SDValue Tmp2 = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpHi, N2: RevShAmt);
6050 SDValue LoSmallShift = DAG.getNode(Opcode: ISD::OR, DL: dl, VT, N1: Tmp1, N2: Tmp2);
6051 SDValue LoBigShift = DAG.getNode(Opcode: Opc, DL: dl, VT, N1: ShOpHi, N2: ExtraShAmt);
6052 SDValue CmpLo = getARMCmp(LHS: ExtraShAmt, RHS: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32),
6053 CC: ISD::SETGE, ARMcc, DAG, dl);
6054 SDValue Lo =
6055 DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: LoSmallShift, N2: LoBigShift, N3: ARMcc, N4: CmpLo);
6056
6057 SDValue HiSmallShift = DAG.getNode(Opcode: Opc, DL: dl, VT, N1: ShOpHi, N2: ShAmt);
6058 SDValue HiBigShift = Opc == ISD::SRA
6059 ? DAG.getNode(Opcode: Opc, DL: dl, VT, N1: ShOpHi,
6060 N2: DAG.getConstant(Val: VTBits - 1, DL: dl, VT))
6061 : DAG.getConstant(Val: 0, DL: dl, VT);
6062 SDValue CmpHi = getARMCmp(LHS: ExtraShAmt, RHS: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32),
6063 CC: ISD::SETGE, ARMcc, DAG, dl);
6064 SDValue Hi =
6065 DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: HiSmallShift, N2: HiBigShift, N3: ARMcc, N4: CmpHi);
6066
6067 SDValue Ops[2] = { Lo, Hi };
6068 return DAG.getMergeValues(Ops, dl);
6069}
6070
6071/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6072/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6073SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6074 SelectionDAG &DAG) const {
6075 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6076 EVT VT = Op.getValueType();
6077 unsigned VTBits = VT.getSizeInBits();
6078 SDLoc dl(Op);
6079 SDValue ShOpLo = Op.getOperand(i: 0);
6080 SDValue ShOpHi = Op.getOperand(i: 1);
6081 SDValue ShAmt = Op.getOperand(i: 2);
6082 SDValue ARMcc;
6083
6084 assert(Op.getOpcode() == ISD::SHL_PARTS);
6085 SDValue RevShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
6086 N1: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32), N2: ShAmt);
6087 SDValue Tmp1 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: ShOpLo, N2: RevShAmt);
6088 SDValue Tmp2 = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpHi, N2: ShAmt);
6089 SDValue HiSmallShift = DAG.getNode(Opcode: ISD::OR, DL: dl, VT, N1: Tmp1, N2: Tmp2);
6090
6091 SDValue ExtraShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: ShAmt,
6092 N2: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32));
6093 SDValue HiBigShift = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpLo, N2: ExtraShAmt);
6094 SDValue CmpHi = getARMCmp(LHS: ExtraShAmt, RHS: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32),
6095 CC: ISD::SETGE, ARMcc, DAG, dl);
6096 SDValue Hi =
6097 DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: HiSmallShift, N2: HiBigShift, N3: ARMcc, N4: CmpHi);
6098
6099 SDValue CmpLo = getARMCmp(LHS: ExtraShAmt, RHS: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32),
6100 CC: ISD::SETGE, ARMcc, DAG, dl);
6101 SDValue LoSmallShift = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpLo, N2: ShAmt);
6102 SDValue Lo = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: LoSmallShift,
6103 N2: DAG.getConstant(Val: 0, DL: dl, VT), N3: ARMcc, N4: CmpLo);
6104
6105 SDValue Ops[2] = { Lo, Hi };
6106 return DAG.getMergeValues(Ops, dl);
6107}
6108
6109SDValue ARMTargetLowering::LowerGET_ROUNDING(SDValue Op,
6110 SelectionDAG &DAG) const {
6111 // The rounding mode is in bits 23:22 of the FPSCR.
6112 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6113 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6114 // so that the shift + and get folded into a bitfield extract.
6115 SDLoc dl(Op);
6116 SDValue Chain = Op.getOperand(i: 0);
6117 SDValue Ops[] = {Chain,
6118 DAG.getConstant(Val: Intrinsic::arm_get_fpscr, DL: dl, VT: MVT::i32)};
6119
6120 SDValue FPSCR =
6121 DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL: dl, ResultTys: {MVT::i32, MVT::Other}, Ops);
6122 Chain = FPSCR.getValue(R: 1);
6123 SDValue FltRounds = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: FPSCR,
6124 N2: DAG.getConstant(Val: 1U << 22, DL: dl, VT: MVT::i32));
6125 SDValue RMODE = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32, N1: FltRounds,
6126 N2: DAG.getConstant(Val: 22, DL: dl, VT: MVT::i32));
6127 SDValue And = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: RMODE,
6128 N2: DAG.getConstant(Val: 3, DL: dl, VT: MVT::i32));
6129 return DAG.getMergeValues(Ops: {And, Chain}, dl);
6130}
6131
6132SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op,
6133 SelectionDAG &DAG) const {
6134 SDLoc DL(Op);
6135 SDValue Chain = Op->getOperand(Num: 0);
6136 SDValue RMValue = Op->getOperand(Num: 1);
6137
6138 // The rounding mode is in bits 23:22 of the FPSCR.
6139 // The llvm.set.rounding argument value to ARM rounding mode value mapping
6140 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
6141 // ((arg - 1) & 3) << 22).
6142 //
6143 // It is expected that the argument of llvm.set.rounding is within the
6144 // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is
6145 // responsibility of the code generated llvm.set.rounding to ensure this
6146 // condition.
6147
6148 // Calculate new value of FPSCR[23:22].
6149 RMValue = DAG.getNode(Opcode: ISD::SUB, DL, VT: MVT::i32, N1: RMValue,
6150 N2: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
6151 RMValue = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: RMValue,
6152 N2: DAG.getConstant(Val: 0x3, DL, VT: MVT::i32));
6153 RMValue = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: RMValue,
6154 N2: DAG.getConstant(Val: ARM::RoundingBitsPos, DL, VT: MVT::i32));
6155
6156 // Get current value of FPSCR.
6157 SDValue Ops[] = {Chain,
6158 DAG.getConstant(Val: Intrinsic::arm_get_fpscr, DL, VT: MVT::i32)};
6159 SDValue FPSCR =
6160 DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL, ResultTys: {MVT::i32, MVT::Other}, Ops);
6161 Chain = FPSCR.getValue(R: 1);
6162 FPSCR = FPSCR.getValue(R: 0);
6163
6164 // Put new rounding mode into FPSCR[23:22].
6165 const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos);
6166 FPSCR = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: FPSCR,
6167 N2: DAG.getConstant(Val: RMMask, DL, VT: MVT::i32));
6168 FPSCR = DAG.getNode(Opcode: ISD::OR, DL, VT: MVT::i32, N1: FPSCR, N2: RMValue);
6169 SDValue Ops2[] = {
6170 Chain, DAG.getConstant(Val: Intrinsic::arm_set_fpscr, DL, VT: MVT::i32), FPSCR};
6171 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL, VT: MVT::Other, Ops: Ops2);
6172}
6173
6174SDValue ARMTargetLowering::LowerSET_FPMODE(SDValue Op,
6175 SelectionDAG &DAG) const {
6176 SDLoc DL(Op);
6177 SDValue Chain = Op->getOperand(Num: 0);
6178 SDValue Mode = Op->getOperand(Num: 1);
6179
6180 // Generate nodes to build:
6181 // FPSCR = (FPSCR & FPStatusBits) | (Mode & ~FPStatusBits)
6182 SDValue Ops[] = {Chain,
6183 DAG.getConstant(Val: Intrinsic::arm_get_fpscr, DL, VT: MVT::i32)};
6184 SDValue FPSCR =
6185 DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL, ResultTys: {MVT::i32, MVT::Other}, Ops);
6186 Chain = FPSCR.getValue(R: 1);
6187 FPSCR = FPSCR.getValue(R: 0);
6188
6189 SDValue FPSCRMasked =
6190 DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: FPSCR,
6191 N2: DAG.getConstant(Val: ARM::FPStatusBits, DL, VT: MVT::i32));
6192 SDValue InputMasked =
6193 DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: Mode,
6194 N2: DAG.getConstant(Val: ~ARM::FPStatusBits, DL, VT: MVT::i32));
6195 FPSCR = DAG.getNode(Opcode: ISD::OR, DL, VT: MVT::i32, N1: FPSCRMasked, N2: InputMasked);
6196
6197 SDValue Ops2[] = {
6198 Chain, DAG.getConstant(Val: Intrinsic::arm_set_fpscr, DL, VT: MVT::i32), FPSCR};
6199 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL, VT: MVT::Other, Ops: Ops2);
6200}
6201
6202SDValue ARMTargetLowering::LowerRESET_FPMODE(SDValue Op,
6203 SelectionDAG &DAG) const {
6204 SDLoc DL(Op);
6205 SDValue Chain = Op->getOperand(Num: 0);
6206
6207 // To get the default FP mode all control bits are cleared:
6208 // FPSCR = FPSCR & (FPStatusBits | FPReservedBits)
6209 SDValue Ops[] = {Chain,
6210 DAG.getConstant(Val: Intrinsic::arm_get_fpscr, DL, VT: MVT::i32)};
6211 SDValue FPSCR =
6212 DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL, ResultTys: {MVT::i32, MVT::Other}, Ops);
6213 Chain = FPSCR.getValue(R: 1);
6214 FPSCR = FPSCR.getValue(R: 0);
6215
6216 SDValue FPSCRMasked = DAG.getNode(
6217 Opcode: ISD::AND, DL, VT: MVT::i32, N1: FPSCR,
6218 N2: DAG.getConstant(Val: ARM::FPStatusBits | ARM::FPReservedBits, DL, VT: MVT::i32));
6219 SDValue Ops2[] = {Chain,
6220 DAG.getConstant(Val: Intrinsic::arm_set_fpscr, DL, VT: MVT::i32),
6221 FPSCRMasked};
6222 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL, VT: MVT::Other, Ops: Ops2);
6223}
6224
6225static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
6226 const ARMSubtarget *ST) {
6227 SDLoc dl(N);
6228 EVT VT = N->getValueType(ResNo: 0);
6229 if (VT.isVector() && ST->hasNEON()) {
6230
6231 // Compute the least significant set bit: LSB = X & -X
6232 SDValue X = N->getOperand(Num: 0);
6233 SDValue NX = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: getZeroVector(VT, DAG, dl), N2: X);
6234 SDValue LSB = DAG.getNode(Opcode: ISD::AND, DL: dl, VT, N1: X, N2: NX);
6235
6236 EVT ElemTy = VT.getVectorElementType();
6237
6238 if (ElemTy == MVT::i8) {
6239 // Compute with: cttz(x) = ctpop(lsb - 1)
6240 SDValue One = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT,
6241 Operand: DAG.getTargetConstant(Val: 1, DL: dl, VT: ElemTy));
6242 SDValue Bits = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: LSB, N2: One);
6243 return DAG.getNode(Opcode: ISD::CTPOP, DL: dl, VT, Operand: Bits);
6244 }
6245
6246 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6247 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6248 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6249 unsigned NumBits = ElemTy.getSizeInBits();
6250 SDValue WidthMinus1 =
6251 DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT,
6252 Operand: DAG.getTargetConstant(Val: NumBits - 1, DL: dl, VT: ElemTy));
6253 SDValue CTLZ = DAG.getNode(Opcode: ISD::CTLZ, DL: dl, VT, Operand: LSB);
6254 return DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: WidthMinus1, N2: CTLZ);
6255 }
6256
6257 // Compute with: cttz(x) = ctpop(lsb - 1)
6258
6259 // Compute LSB - 1.
6260 SDValue Bits;
6261 if (ElemTy == MVT::i64) {
6262 // Load constant 0xffff'ffff'ffff'ffff to register.
6263 SDValue FF = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT,
6264 Operand: DAG.getTargetConstant(Val: 0x1eff, DL: dl, VT: MVT::i32));
6265 Bits = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: LSB, N2: FF);
6266 } else {
6267 SDValue One = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT,
6268 Operand: DAG.getTargetConstant(Val: 1, DL: dl, VT: ElemTy));
6269 Bits = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: LSB, N2: One);
6270 }
6271 return DAG.getNode(Opcode: ISD::CTPOP, DL: dl, VT, Operand: Bits);
6272 }
6273
6274 if (!ST->hasV6T2Ops())
6275 return SDValue();
6276
6277 SDValue rbit = DAG.getNode(Opcode: ISD::BITREVERSE, DL: dl, VT, Operand: N->getOperand(Num: 0));
6278 return DAG.getNode(Opcode: ISD::CTLZ, DL: dl, VT, Operand: rbit);
6279}
6280
6281static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6282 const ARMSubtarget *ST) {
6283 EVT VT = N->getValueType(ResNo: 0);
6284 SDLoc DL(N);
6285
6286 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6287 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6288 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6289 "Unexpected type for custom ctpop lowering");
6290
6291 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6292 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6293 SDValue Res = DAG.getBitcast(VT: VT8Bit, V: N->getOperand(Num: 0));
6294 Res = DAG.getNode(Opcode: ISD::CTPOP, DL, VT: VT8Bit, Operand: Res);
6295
6296 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6297 unsigned EltSize = 8;
6298 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6299 while (EltSize != VT.getScalarSizeInBits()) {
6300 SmallVector<SDValue, 8> Ops;
6301 Ops.push_back(Elt: DAG.getConstant(Val: Intrinsic::arm_neon_vpaddlu, DL,
6302 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
6303 Ops.push_back(Elt: Res);
6304
6305 EltSize *= 2;
6306 NumElts /= 2;
6307 MVT WidenVT = MVT::getVectorVT(VT: MVT::getIntegerVT(BitWidth: EltSize), NumElements: NumElts);
6308 Res = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT: WidenVT, Ops);
6309 }
6310
6311 return Res;
6312}
6313
6314/// Getvshiftimm - Check if this is a valid build_vector for the immediate
6315/// operand of a vector shift operation, where all the elements of the
6316/// build_vector must have the same constant integer value.
6317static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6318 // Ignore bit_converts.
6319 while (Op.getOpcode() == ISD::BITCAST)
6320 Op = Op.getOperand(i: 0);
6321 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Val: Op.getNode());
6322 APInt SplatBits, SplatUndef;
6323 unsigned SplatBitSize;
6324 bool HasAnyUndefs;
6325 if (!BVN ||
6326 !BVN->isConstantSplat(SplatValue&: SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6327 MinSplatBits: ElementBits) ||
6328 SplatBitSize > ElementBits)
6329 return false;
6330 Cnt = SplatBits.getSExtValue();
6331 return true;
6332}
6333
6334/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6335/// operand of a vector shift left operation. That value must be in the range:
6336/// 0 <= Value < ElementBits for a left shift; or
6337/// 0 <= Value <= ElementBits for a long left shift.
6338static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6339 assert(VT.isVector() && "vector shift count is not a vector type");
6340 int64_t ElementBits = VT.getScalarSizeInBits();
6341 if (!getVShiftImm(Op, ElementBits, Cnt))
6342 return false;
6343 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6344}
6345
6346/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6347/// operand of a vector shift right operation. For a shift opcode, the value
6348/// is positive, but for an intrinsic the value count must be negative. The
6349/// absolute value must be in the range:
6350/// 1 <= |Value| <= ElementBits for a right shift; or
6351/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6352static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6353 int64_t &Cnt) {
6354 assert(VT.isVector() && "vector shift count is not a vector type");
6355 int64_t ElementBits = VT.getScalarSizeInBits();
6356 if (!getVShiftImm(Op, ElementBits, Cnt))
6357 return false;
6358 if (!isIntrinsic)
6359 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6360 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6361 Cnt = -Cnt;
6362 return true;
6363 }
6364 return false;
6365}
6366
6367static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6368 const ARMSubtarget *ST) {
6369 EVT VT = N->getValueType(ResNo: 0);
6370 SDLoc dl(N);
6371 int64_t Cnt;
6372
6373 if (!VT.isVector())
6374 return SDValue();
6375
6376 // We essentially have two forms here. Shift by an immediate and shift by a
6377 // vector register (there are also shift by a gpr, but that is just handled
6378 // with a tablegen pattern). We cannot easily match shift by an immediate in
6379 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6380 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6381 // signed or unsigned, and a negative shift indicates a shift right).
6382 if (N->getOpcode() == ISD::SHL) {
6383 if (isVShiftLImm(Op: N->getOperand(Num: 1), VT, isLong: false, Cnt))
6384 return DAG.getNode(Opcode: ARMISD::VSHLIMM, DL: dl, VT, N1: N->getOperand(Num: 0),
6385 N2: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
6386 return DAG.getNode(Opcode: ARMISD::VSHLu, DL: dl, VT, N1: N->getOperand(Num: 0),
6387 N2: N->getOperand(Num: 1));
6388 }
6389
6390 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6391 "unexpected vector shift opcode");
6392
6393 if (isVShiftRImm(Op: N->getOperand(Num: 1), VT, isNarrow: false, isIntrinsic: false, Cnt)) {
6394 unsigned VShiftOpc =
6395 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6396 return DAG.getNode(Opcode: VShiftOpc, DL: dl, VT, N1: N->getOperand(Num: 0),
6397 N2: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
6398 }
6399
6400 // Other right shifts we don't have operations for (we use a shift left by a
6401 // negative number).
6402 EVT ShiftVT = N->getOperand(Num: 1).getValueType();
6403 SDValue NegatedCount = DAG.getNode(
6404 Opcode: ISD::SUB, DL: dl, VT: ShiftVT, N1: getZeroVector(VT: ShiftVT, DAG, dl), N2: N->getOperand(Num: 1));
6405 unsigned VShiftOpc =
6406 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6407 return DAG.getNode(Opcode: VShiftOpc, DL: dl, VT, N1: N->getOperand(Num: 0), N2: NegatedCount);
6408}
6409
6410static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6411 const ARMSubtarget *ST) {
6412 EVT VT = N->getValueType(ResNo: 0);
6413 SDLoc dl(N);
6414
6415 // We can get here for a node like i32 = ISD::SHL i32, i64
6416 if (VT != MVT::i64)
6417 return SDValue();
6418
6419 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6420 N->getOpcode() == ISD::SHL) &&
6421 "Unknown shift to lower!");
6422
6423 unsigned ShOpc = N->getOpcode();
6424 if (ST->hasMVEIntegerOps()) {
6425 SDValue ShAmt = N->getOperand(Num: 1);
6426 unsigned ShPartsOpc = ARMISD::LSLL;
6427 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(Val&: ShAmt);
6428
6429 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6430 // then do the default optimisation
6431 if ((!Con && ShAmt->getValueType(ResNo: 0).getSizeInBits() > 64) ||
6432 (Con && (Con->getAPIntValue() == 0 || Con->getAPIntValue().uge(RHS: 32))))
6433 return SDValue();
6434
6435 // Extract the lower 32 bits of the shift amount if it's not an i32
6436 if (ShAmt->getValueType(ResNo: 0) != MVT::i32)
6437 ShAmt = DAG.getZExtOrTrunc(Op: ShAmt, DL: dl, VT: MVT::i32);
6438
6439 if (ShOpc == ISD::SRL) {
6440 if (!Con)
6441 // There is no t2LSRLr instruction so negate and perform an lsll if the
6442 // shift amount is in a register, emulating a right shift.
6443 ShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
6444 N1: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32), N2: ShAmt);
6445 else
6446 // Else generate an lsrl on the immediate shift amount
6447 ShPartsOpc = ARMISD::LSRL;
6448 } else if (ShOpc == ISD::SRA)
6449 ShPartsOpc = ARMISD::ASRL;
6450
6451 // Split Lower/Upper 32 bits of the destination/source
6452 SDValue Lo, Hi;
6453 std::tie(args&: Lo, args&: Hi) =
6454 DAG.SplitScalar(N: N->getOperand(Num: 0), DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
6455 // Generate the shift operation as computed above
6456 Lo = DAG.getNode(Opcode: ShPartsOpc, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N1: Lo, N2: Hi,
6457 N3: ShAmt);
6458 // The upper 32 bits come from the second return value of lsll
6459 Hi = SDValue(Lo.getNode(), 1);
6460 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lo, N2: Hi);
6461 }
6462
6463 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6464 if (!isOneConstant(V: N->getOperand(Num: 1)) || N->getOpcode() == ISD::SHL)
6465 return SDValue();
6466
6467 // If we are in thumb mode, we don't have RRX.
6468 if (ST->isThumb1Only())
6469 return SDValue();
6470
6471 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6472 SDValue Lo, Hi;
6473 std::tie(args&: Lo, args&: Hi) = DAG.SplitScalar(N: N->getOperand(Num: 0), DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
6474
6475 // First, build a LSRS1/ASRS1 op, which shifts the top part by one and
6476 // captures the shifted out bit into a carry flag.
6477 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::LSRS1 : ARMISD::ASRS1;
6478 Hi = DAG.getNode(Opcode: Opc, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT), N: Hi);
6479
6480 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6481 Lo = DAG.getNode(Opcode: ARMISD::RRX, DL: dl, VT: MVT::i32, N1: Lo, N2: Hi.getValue(R: 1));
6482
6483 // Merge the pieces into a single i64 value.
6484 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lo, N2: Hi);
6485}
6486
6487static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6488 const ARMSubtarget *ST) {
6489 bool Invert = false;
6490 bool Swap = false;
6491 unsigned Opc = ARMCC::AL;
6492
6493 SDValue Op0 = Op.getOperand(i: 0);
6494 SDValue Op1 = Op.getOperand(i: 1);
6495 SDValue CC = Op.getOperand(i: 2);
6496 EVT VT = Op.getValueType();
6497 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(Val&: CC)->get();
6498 SDLoc dl(Op);
6499
6500 EVT CmpVT;
6501 if (ST->hasNEON())
6502 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6503 else {
6504 assert(ST->hasMVEIntegerOps() &&
6505 "No hardware support for integer vector comparison!");
6506
6507 if (Op.getValueType().getVectorElementType() != MVT::i1)
6508 return SDValue();
6509
6510 // Make sure we expand floating point setcc to scalar if we do not have
6511 // mve.fp, so that we can handle them from there.
6512 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6513 return SDValue();
6514
6515 CmpVT = VT;
6516 }
6517
6518 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6519 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6520 // Special-case integer 64-bit equality comparisons. They aren't legal,
6521 // but they can be lowered with a few vector instructions.
6522 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6523 EVT SplitVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::i32, NumElements: CmpElements);
6524 SDValue CastOp0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: SplitVT, Operand: Op0);
6525 SDValue CastOp1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: SplitVT, Operand: Op1);
6526 SDValue Cmp = DAG.getNode(Opcode: ISD::SETCC, DL: dl, VT: SplitVT, N1: CastOp0, N2: CastOp1,
6527 N3: DAG.getCondCode(Cond: ISD::SETEQ));
6528 SDValue Reversed = DAG.getNode(Opcode: ARMISD::VREV64, DL: dl, VT: SplitVT, Operand: Cmp);
6529 SDValue Merged = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: SplitVT, N1: Cmp, N2: Reversed);
6530 Merged = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: CmpVT, Operand: Merged);
6531 if (SetCCOpcode == ISD::SETNE)
6532 Merged = DAG.getNOT(DL: dl, Val: Merged, VT: CmpVT);
6533 Merged = DAG.getSExtOrTrunc(Op: Merged, DL: dl, VT);
6534 return Merged;
6535 }
6536
6537 if (CmpVT.getVectorElementType() == MVT::i64)
6538 // 64-bit comparisons are not legal in general.
6539 return SDValue();
6540
6541 if (Op1.getValueType().isFloatingPoint()) {
6542 switch (SetCCOpcode) {
6543 default: llvm_unreachable("Illegal FP comparison");
6544 case ISD::SETUNE:
6545 case ISD::SETNE:
6546 if (ST->hasMVEFloatOps()) {
6547 Opc = ARMCC::NE; break;
6548 } else {
6549 Invert = true; [[fallthrough]];
6550 }
6551 case ISD::SETOEQ:
6552 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6553 case ISD::SETOLT:
6554 case ISD::SETLT: Swap = true; [[fallthrough]];
6555 case ISD::SETOGT:
6556 case ISD::SETGT: Opc = ARMCC::GT; break;
6557 case ISD::SETOLE:
6558 case ISD::SETLE: Swap = true; [[fallthrough]];
6559 case ISD::SETOGE:
6560 case ISD::SETGE: Opc = ARMCC::GE; break;
6561 case ISD::SETUGE: Swap = true; [[fallthrough]];
6562 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6563 case ISD::SETUGT: Swap = true; [[fallthrough]];
6564 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6565 case ISD::SETUEQ: Invert = true; [[fallthrough]];
6566 case ISD::SETONE: {
6567 // Expand this to (OLT | OGT).
6568 SDValue TmpOp0 = DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT: CmpVT, N1: Op1, N2: Op0,
6569 N3: DAG.getConstant(Val: ARMCC::GT, DL: dl, VT: MVT::i32));
6570 SDValue TmpOp1 = DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT: CmpVT, N1: Op0, N2: Op1,
6571 N3: DAG.getConstant(Val: ARMCC::GT, DL: dl, VT: MVT::i32));
6572 SDValue Result = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: CmpVT, N1: TmpOp0, N2: TmpOp1);
6573 if (Invert)
6574 Result = DAG.getNOT(DL: dl, Val: Result, VT);
6575 return Result;
6576 }
6577 case ISD::SETUO: Invert = true; [[fallthrough]];
6578 case ISD::SETO: {
6579 // Expand this to (OLT | OGE).
6580 SDValue TmpOp0 = DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT: CmpVT, N1: Op1, N2: Op0,
6581 N3: DAG.getConstant(Val: ARMCC::GT, DL: dl, VT: MVT::i32));
6582 SDValue TmpOp1 = DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT: CmpVT, N1: Op0, N2: Op1,
6583 N3: DAG.getConstant(Val: ARMCC::GE, DL: dl, VT: MVT::i32));
6584 SDValue Result = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: CmpVT, N1: TmpOp0, N2: TmpOp1);
6585 if (Invert)
6586 Result = DAG.getNOT(DL: dl, Val: Result, VT);
6587 return Result;
6588 }
6589 }
6590 } else {
6591 // Integer comparisons.
6592 switch (SetCCOpcode) {
6593 default: llvm_unreachable("Illegal integer comparison");
6594 case ISD::SETNE:
6595 if (ST->hasMVEIntegerOps()) {
6596 Opc = ARMCC::NE; break;
6597 } else {
6598 Invert = true; [[fallthrough]];
6599 }
6600 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6601 case ISD::SETLT: Swap = true; [[fallthrough]];
6602 case ISD::SETGT: Opc = ARMCC::GT; break;
6603 case ISD::SETLE: Swap = true; [[fallthrough]];
6604 case ISD::SETGE: Opc = ARMCC::GE; break;
6605 case ISD::SETULT: Swap = true; [[fallthrough]];
6606 case ISD::SETUGT: Opc = ARMCC::HI; break;
6607 case ISD::SETULE: Swap = true; [[fallthrough]];
6608 case ISD::SETUGE: Opc = ARMCC::HS; break;
6609 }
6610
6611 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6612 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6613 SDValue AndOp;
6614 if (ISD::isBuildVectorAllZeros(N: Op1.getNode()))
6615 AndOp = Op0;
6616 else if (ISD::isBuildVectorAllZeros(N: Op0.getNode()))
6617 AndOp = Op1;
6618
6619 // Ignore bitconvert.
6620 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6621 AndOp = AndOp.getOperand(i: 0);
6622
6623 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6624 Op0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: CmpVT, Operand: AndOp.getOperand(i: 0));
6625 Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: CmpVT, Operand: AndOp.getOperand(i: 1));
6626 SDValue Result = DAG.getNode(Opcode: ARMISD::VTST, DL: dl, VT: CmpVT, N1: Op0, N2: Op1);
6627 if (!Invert)
6628 Result = DAG.getNOT(DL: dl, Val: Result, VT);
6629 return Result;
6630 }
6631 }
6632 }
6633
6634 if (Swap)
6635 std::swap(a&: Op0, b&: Op1);
6636
6637 // If one of the operands is a constant vector zero, attempt to fold the
6638 // comparison to a specialized compare-against-zero form.
6639 if (ISD::isBuildVectorAllZeros(N: Op0.getNode()) &&
6640 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::EQ ||
6641 Opc == ARMCC::NE)) {
6642 if (Opc == ARMCC::GE)
6643 Opc = ARMCC::LE;
6644 else if (Opc == ARMCC::GT)
6645 Opc = ARMCC::LT;
6646 std::swap(a&: Op0, b&: Op1);
6647 }
6648
6649 SDValue Result;
6650 if (ISD::isBuildVectorAllZeros(N: Op1.getNode()) &&
6651 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::LE ||
6652 Opc == ARMCC::LT || Opc == ARMCC::NE || Opc == ARMCC::EQ))
6653 Result = DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT: CmpVT, N1: Op0,
6654 N2: DAG.getConstant(Val: Opc, DL: dl, VT: MVT::i32));
6655 else
6656 Result = DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT: CmpVT, N1: Op0, N2: Op1,
6657 N3: DAG.getConstant(Val: Opc, DL: dl, VT: MVT::i32));
6658
6659 Result = DAG.getSExtOrTrunc(Op: Result, DL: dl, VT);
6660
6661 if (Invert)
6662 Result = DAG.getNOT(DL: dl, Val: Result, VT);
6663
6664 return Result;
6665}
6666
6667static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6668 SDValue LHS = Op.getOperand(i: 0);
6669 SDValue RHS = Op.getOperand(i: 1);
6670 SDValue Carry = Op.getOperand(i: 2);
6671 SDValue Cond = Op.getOperand(i: 3);
6672 SDLoc DL(Op);
6673
6674 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6675
6676 // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
6677 // have to invert the carry first.
6678 Carry = DAG.getNode(Opcode: ISD::SUB, DL, VT: MVT::i32,
6679 N1: DAG.getConstant(Val: 1, DL, VT: MVT::i32), N2: Carry);
6680 // This converts the boolean value carry into the carry flag.
6681 Carry = ConvertBooleanCarryToCarryFlag(BoolCarry: Carry, DAG);
6682
6683 SDVTList VTs = DAG.getVTList(VT1: LHS.getValueType(), VT2: MVT::i32);
6684 SDValue Cmp = DAG.getNode(Opcode: ARMISD::SUBE, DL, VTList: VTs, N1: LHS, N2: RHS, N3: Carry);
6685
6686 SDValue FVal = DAG.getConstant(Val: 0, DL, VT: MVT::i32);
6687 SDValue TVal = DAG.getConstant(Val: 1, DL, VT: MVT::i32);
6688 SDValue ARMcc = DAG.getConstant(
6689 Val: IntCCToARMCC(CC: cast<CondCodeSDNode>(Val&: Cond)->get()), DL, VT: MVT::i32);
6690 return DAG.getNode(Opcode: ARMISD::CMOV, DL, VT: Op.getValueType(), N1: FVal, N2: TVal, N3: ARMcc,
6691 N4: Cmp.getValue(R: 1));
6692}
6693
6694/// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6695/// valid vector constant for a NEON or MVE instruction with a "modified
6696/// immediate" operand (e.g., VMOV). If so, return the encoded value.
6697static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6698 unsigned SplatBitSize, SelectionDAG &DAG,
6699 const SDLoc &dl, EVT &VT, EVT VectorVT,
6700 VMOVModImmType type) {
6701 unsigned OpCmode, Imm;
6702 bool is128Bits = VectorVT.is128BitVector();
6703
6704 // SplatBitSize is set to the smallest size that splats the vector, so a
6705 // zero vector will always have SplatBitSize == 8. However, NEON modified
6706 // immediate instructions others than VMOV do not support the 8-bit encoding
6707 // of a zero vector, and the default encoding of zero is supposed to be the
6708 // 32-bit version.
6709 if (SplatBits == 0)
6710 SplatBitSize = 32;
6711
6712 switch (SplatBitSize) {
6713 case 8:
6714 if (type != VMOVModImm)
6715 return SDValue();
6716 // Any 1-byte value is OK. Op=0, Cmode=1110.
6717 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6718 OpCmode = 0xe;
6719 Imm = SplatBits;
6720 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6721 break;
6722
6723 case 16:
6724 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6725 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6726 if ((SplatBits & ~0xff) == 0) {
6727 // Value = 0x00nn: Op=x, Cmode=100x.
6728 OpCmode = 0x8;
6729 Imm = SplatBits;
6730 break;
6731 }
6732 if ((SplatBits & ~0xff00) == 0) {
6733 // Value = 0xnn00: Op=x, Cmode=101x.
6734 OpCmode = 0xa;
6735 Imm = SplatBits >> 8;
6736 break;
6737 }
6738 return SDValue();
6739
6740 case 32:
6741 // NEON's 32-bit VMOV supports splat values where:
6742 // * only one byte is nonzero, or
6743 // * the least significant byte is 0xff and the second byte is nonzero, or
6744 // * the least significant 2 bytes are 0xff and the third is nonzero.
6745 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6746 if ((SplatBits & ~0xff) == 0) {
6747 // Value = 0x000000nn: Op=x, Cmode=000x.
6748 OpCmode = 0;
6749 Imm = SplatBits;
6750 break;
6751 }
6752 if ((SplatBits & ~0xff00) == 0) {
6753 // Value = 0x0000nn00: Op=x, Cmode=001x.
6754 OpCmode = 0x2;
6755 Imm = SplatBits >> 8;
6756 break;
6757 }
6758 if ((SplatBits & ~0xff0000) == 0) {
6759 // Value = 0x00nn0000: Op=x, Cmode=010x.
6760 OpCmode = 0x4;
6761 Imm = SplatBits >> 16;
6762 break;
6763 }
6764 if ((SplatBits & ~0xff000000) == 0) {
6765 // Value = 0xnn000000: Op=x, Cmode=011x.
6766 OpCmode = 0x6;
6767 Imm = SplatBits >> 24;
6768 break;
6769 }
6770
6771 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6772 if (type == OtherModImm) return SDValue();
6773
6774 if ((SplatBits & ~0xffff) == 0 &&
6775 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6776 // Value = 0x0000nnff: Op=x, Cmode=1100.
6777 OpCmode = 0xc;
6778 Imm = SplatBits >> 8;
6779 break;
6780 }
6781
6782 // cmode == 0b1101 is not supported for MVE VMVN
6783 if (type == MVEVMVNModImm)
6784 return SDValue();
6785
6786 if ((SplatBits & ~0xffffff) == 0 &&
6787 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6788 // Value = 0x00nnffff: Op=x, Cmode=1101.
6789 OpCmode = 0xd;
6790 Imm = SplatBits >> 16;
6791 break;
6792 }
6793
6794 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6795 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6796 // VMOV.I32. A (very) minor optimization would be to replicate the value
6797 // and fall through here to test for a valid 64-bit splat. But, then the
6798 // caller would also need to check and handle the change in size.
6799 return SDValue();
6800
6801 case 64: {
6802 if (type != VMOVModImm)
6803 return SDValue();
6804 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6805 uint64_t BitMask = 0xff;
6806 unsigned ImmMask = 1;
6807 Imm = 0;
6808 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6809 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6810 Imm |= ImmMask;
6811 } else if ((SplatBits & BitMask) != 0) {
6812 return SDValue();
6813 }
6814 BitMask <<= 8;
6815 ImmMask <<= 1;
6816 }
6817
6818 // Op=1, Cmode=1110.
6819 OpCmode = 0x1e;
6820 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6821 break;
6822 }
6823
6824 default:
6825 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6826 }
6827
6828 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Val: Imm);
6829 return DAG.getTargetConstant(Val: EncodedVal, DL: dl, VT: MVT::i32);
6830}
6831
6832SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6833 const ARMSubtarget *ST) const {
6834 EVT VT = Op.getValueType();
6835 bool IsDouble = (VT == MVT::f64);
6836 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Val&: Op);
6837 const APFloat &FPVal = CFP->getValueAPF();
6838
6839 // Prevent floating-point constants from using literal loads
6840 // when execute-only is enabled.
6841 if (ST->genExecuteOnly()) {
6842 // We shouldn't trigger this for v6m execute-only
6843 assert((!ST->isThumb1Only() || ST->hasV8MBaselineOps()) &&
6844 "Unexpected architecture");
6845
6846 // If we can represent the constant as an immediate, don't lower it
6847 if (isFPImmLegal(Imm: FPVal, VT))
6848 return Op;
6849 // Otherwise, construct as integer, and move to float register
6850 APInt INTVal = FPVal.bitcastToAPInt();
6851 SDLoc DL(CFP);
6852 switch (VT.getSimpleVT().SimpleTy) {
6853 default:
6854 llvm_unreachable("Unknown floating point type!");
6855 break;
6856 case MVT::f64: {
6857 SDValue Lo = DAG.getConstant(Val: INTVal.trunc(width: 32), DL, VT: MVT::i32);
6858 SDValue Hi = DAG.getConstant(Val: INTVal.lshr(shiftAmt: 32).trunc(width: 32), DL, VT: MVT::i32);
6859 return DAG.getNode(Opcode: ARMISD::VMOVDRR, DL, VT: MVT::f64, N1: Lo, N2: Hi);
6860 }
6861 case MVT::f32:
6862 return DAG.getNode(Opcode: ARMISD::VMOVSR, DL, VT,
6863 Operand: DAG.getConstant(Val: INTVal, DL, VT: MVT::i32));
6864 }
6865 }
6866
6867 if (!ST->hasVFP3Base())
6868 return SDValue();
6869
6870 // Use the default (constant pool) lowering for double constants when we have
6871 // an SP-only FPU
6872 if (IsDouble && !Subtarget->hasFP64())
6873 return SDValue();
6874
6875 // Try splatting with a VMOV.f32...
6876 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPImm: FPVal) : ARM_AM::getFP32Imm(FPImm: FPVal);
6877
6878 if (ImmVal != -1) {
6879 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6880 // We have code in place to select a valid ConstantFP already, no need to
6881 // do any mangling.
6882 return Op;
6883 }
6884
6885 // It's a float and we are trying to use NEON operations where
6886 // possible. Lower it to a splat followed by an extract.
6887 SDLoc DL(Op);
6888 SDValue NewVal = DAG.getTargetConstant(Val: ImmVal, DL, VT: MVT::i32);
6889 SDValue VecConstant = DAG.getNode(Opcode: ARMISD::VMOVFPIMM, DL, VT: MVT::v2f32,
6890 Operand: NewVal);
6891 return DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: VecConstant,
6892 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
6893 }
6894
6895 // The rest of our options are NEON only, make sure that's allowed before
6896 // proceeding..
6897 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6898 return SDValue();
6899
6900 EVT VMovVT;
6901 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6902
6903 // It wouldn't really be worth bothering for doubles except for one very
6904 // important value, which does happen to match: 0.0. So make sure we don't do
6905 // anything stupid.
6906 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6907 return SDValue();
6908
6909 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6910 SDValue NewVal = isVMOVModifiedImm(SplatBits: iVal & 0xffffffffU, SplatUndef: 0, SplatBitSize: 32, DAG, dl: SDLoc(Op),
6911 VT&: VMovVT, VectorVT: VT, type: VMOVModImm);
6912 if (NewVal != SDValue()) {
6913 SDLoc DL(Op);
6914 SDValue VecConstant = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL, VT: VMovVT,
6915 Operand: NewVal);
6916 if (IsDouble)
6917 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::f64, Operand: VecConstant);
6918
6919 // It's a float: cast and extract a vector element.
6920 SDValue VecFConstant = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::v2f32,
6921 Operand: VecConstant);
6922 return DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: VecFConstant,
6923 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
6924 }
6925
6926 // Finally, try a VMVN.i32
6927 NewVal = isVMOVModifiedImm(SplatBits: ~iVal & 0xffffffffU, SplatUndef: 0, SplatBitSize: 32, DAG, dl: SDLoc(Op), VT&: VMovVT,
6928 VectorVT: VT, type: VMVNModImm);
6929 if (NewVal != SDValue()) {
6930 SDLoc DL(Op);
6931 SDValue VecConstant = DAG.getNode(Opcode: ARMISD::VMVNIMM, DL, VT: VMovVT, Operand: NewVal);
6932
6933 if (IsDouble)
6934 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::f64, Operand: VecConstant);
6935
6936 // It's a float: cast and extract a vector element.
6937 SDValue VecFConstant = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::v2f32,
6938 Operand: VecConstant);
6939 return DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: VecFConstant,
6940 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
6941 }
6942
6943 return SDValue();
6944}
6945
6946// check if an VEXT instruction can handle the shuffle mask when the
6947// vector sources of the shuffle are the same.
6948static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6949 unsigned NumElts = VT.getVectorNumElements();
6950
6951 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6952 if (M[0] < 0)
6953 return false;
6954
6955 Imm = M[0];
6956
6957 // If this is a VEXT shuffle, the immediate value is the index of the first
6958 // element. The other shuffle indices must be the successive elements after
6959 // the first one.
6960 unsigned ExpectedElt = Imm;
6961 for (unsigned i = 1; i < NumElts; ++i) {
6962 // Increment the expected index. If it wraps around, just follow it
6963 // back to index zero and keep going.
6964 ++ExpectedElt;
6965 if (ExpectedElt == NumElts)
6966 ExpectedElt = 0;
6967
6968 if (M[i] < 0) continue; // ignore UNDEF indices
6969 if (ExpectedElt != static_cast<unsigned>(M[i]))
6970 return false;
6971 }
6972
6973 return true;
6974}
6975
6976static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6977 bool &ReverseVEXT, unsigned &Imm) {
6978 unsigned NumElts = VT.getVectorNumElements();
6979 ReverseVEXT = false;
6980
6981 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6982 if (M[0] < 0)
6983 return false;
6984
6985 Imm = M[0];
6986
6987 // If this is a VEXT shuffle, the immediate value is the index of the first
6988 // element. The other shuffle indices must be the successive elements after
6989 // the first one.
6990 unsigned ExpectedElt = Imm;
6991 for (unsigned i = 1; i < NumElts; ++i) {
6992 // Increment the expected index. If it wraps around, it may still be
6993 // a VEXT but the source vectors must be swapped.
6994 ExpectedElt += 1;
6995 if (ExpectedElt == NumElts * 2) {
6996 ExpectedElt = 0;
6997 ReverseVEXT = true;
6998 }
6999
7000 if (M[i] < 0) continue; // ignore UNDEF indices
7001 if (ExpectedElt != static_cast<unsigned>(M[i]))
7002 return false;
7003 }
7004
7005 // Adjust the index value if the source operands will be swapped.
7006 if (ReverseVEXT)
7007 Imm -= NumElts;
7008
7009 return true;
7010}
7011
7012static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
7013 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
7014 // range, then 0 is placed into the resulting vector. So pretty much any mask
7015 // of 8 elements can work here.
7016 return VT == MVT::v8i8 && M.size() == 8;
7017}
7018
7019static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
7020 unsigned Index) {
7021 if (Mask.size() == Elements * 2)
7022 return Index / Elements;
7023 return Mask[Index] == 0 ? 0 : 1;
7024}
7025
7026// Checks whether the shuffle mask represents a vector transpose (VTRN) by
7027// checking that pairs of elements in the shuffle mask represent the same index
7028// in each vector, incrementing the expected index by 2 at each step.
7029// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
7030// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
7031// v2={e,f,g,h}
7032// WhichResult gives the offset for each element in the mask based on which
7033// of the two results it belongs to.
7034//
7035// The transpose can be represented either as:
7036// result1 = shufflevector v1, v2, result1_shuffle_mask
7037// result2 = shufflevector v1, v2, result2_shuffle_mask
7038// where v1/v2 and the shuffle masks have the same number of elements
7039// (here WhichResult (see below) indicates which result is being checked)
7040//
7041// or as:
7042// results = shufflevector v1, v2, shuffle_mask
7043// where both results are returned in one vector and the shuffle mask has twice
7044// as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7045// want to check the low half and high half of the shuffle mask as if it were
7046// the other case
7047static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7048 unsigned EltSz = VT.getScalarSizeInBits();
7049 if (EltSz == 64)
7050 return false;
7051
7052 unsigned NumElts = VT.getVectorNumElements();
7053 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7054 return false;
7055
7056 // If the mask is twice as long as the input vector then we need to check the
7057 // upper and lower parts of the mask with a matching value for WhichResult
7058 // FIXME: A mask with only even values will be rejected in case the first
7059 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7060 // M[0] is used to determine WhichResult
7061 for (unsigned i = 0; i < M.size(); i += NumElts) {
7062 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7063 for (unsigned j = 0; j < NumElts; j += 2) {
7064 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7065 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7066 return false;
7067 }
7068 }
7069
7070 if (M.size() == NumElts*2)
7071 WhichResult = 0;
7072
7073 return true;
7074}
7075
7076/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7077/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7078/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7079static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7080 unsigned EltSz = VT.getScalarSizeInBits();
7081 if (EltSz == 64)
7082 return false;
7083
7084 unsigned NumElts = VT.getVectorNumElements();
7085 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7086 return false;
7087
7088 for (unsigned i = 0; i < M.size(); i += NumElts) {
7089 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7090 for (unsigned j = 0; j < NumElts; j += 2) {
7091 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7092 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7093 return false;
7094 }
7095 }
7096
7097 if (M.size() == NumElts*2)
7098 WhichResult = 0;
7099
7100 return true;
7101}
7102
7103// Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7104// that the mask elements are either all even and in steps of size 2 or all odd
7105// and in steps of size 2.
7106// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7107// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7108// v2={e,f,g,h}
7109// Requires similar checks to that of isVTRNMask with
7110// respect the how results are returned.
7111static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7112 unsigned EltSz = VT.getScalarSizeInBits();
7113 if (EltSz == 64)
7114 return false;
7115
7116 unsigned NumElts = VT.getVectorNumElements();
7117 if (M.size() != NumElts && M.size() != NumElts*2)
7118 return false;
7119
7120 for (unsigned i = 0; i < M.size(); i += NumElts) {
7121 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7122 for (unsigned j = 0; j < NumElts; ++j) {
7123 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7124 return false;
7125 }
7126 }
7127
7128 if (M.size() == NumElts*2)
7129 WhichResult = 0;
7130
7131 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7132 if (VT.is64BitVector() && EltSz == 32)
7133 return false;
7134
7135 return true;
7136}
7137
7138/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7139/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7140/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7141static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7142 unsigned EltSz = VT.getScalarSizeInBits();
7143 if (EltSz == 64)
7144 return false;
7145
7146 unsigned NumElts = VT.getVectorNumElements();
7147 if (M.size() != NumElts && M.size() != NumElts*2)
7148 return false;
7149
7150 unsigned Half = NumElts / 2;
7151 for (unsigned i = 0; i < M.size(); i += NumElts) {
7152 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7153 for (unsigned j = 0; j < NumElts; j += Half) {
7154 unsigned Idx = WhichResult;
7155 for (unsigned k = 0; k < Half; ++k) {
7156 int MIdx = M[i + j + k];
7157 if (MIdx >= 0 && (unsigned) MIdx != Idx)
7158 return false;
7159 Idx += 2;
7160 }
7161 }
7162 }
7163
7164 if (M.size() == NumElts*2)
7165 WhichResult = 0;
7166
7167 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7168 if (VT.is64BitVector() && EltSz == 32)
7169 return false;
7170
7171 return true;
7172}
7173
7174// Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7175// that pairs of elements of the shufflemask represent the same index in each
7176// vector incrementing sequentially through the vectors.
7177// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7178// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7179// v2={e,f,g,h}
7180// Requires similar checks to that of isVTRNMask with respect the how results
7181// are returned.
7182static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7183 unsigned EltSz = VT.getScalarSizeInBits();
7184 if (EltSz == 64)
7185 return false;
7186
7187 unsigned NumElts = VT.getVectorNumElements();
7188 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7189 return false;
7190
7191 for (unsigned i = 0; i < M.size(); i += NumElts) {
7192 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7193 unsigned Idx = WhichResult * NumElts / 2;
7194 for (unsigned j = 0; j < NumElts; j += 2) {
7195 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7196 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7197 return false;
7198 Idx += 1;
7199 }
7200 }
7201
7202 if (M.size() == NumElts*2)
7203 WhichResult = 0;
7204
7205 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7206 if (VT.is64BitVector() && EltSz == 32)
7207 return false;
7208
7209 return true;
7210}
7211
7212/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7213/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7214/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7215static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7216 unsigned EltSz = VT.getScalarSizeInBits();
7217 if (EltSz == 64)
7218 return false;
7219
7220 unsigned NumElts = VT.getVectorNumElements();
7221 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7222 return false;
7223
7224 for (unsigned i = 0; i < M.size(); i += NumElts) {
7225 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7226 unsigned Idx = WhichResult * NumElts / 2;
7227 for (unsigned j = 0; j < NumElts; j += 2) {
7228 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7229 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7230 return false;
7231 Idx += 1;
7232 }
7233 }
7234
7235 if (M.size() == NumElts*2)
7236 WhichResult = 0;
7237
7238 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7239 if (VT.is64BitVector() && EltSz == 32)
7240 return false;
7241
7242 return true;
7243}
7244
7245/// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7246/// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7247static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7248 unsigned &WhichResult,
7249 bool &isV_UNDEF) {
7250 isV_UNDEF = false;
7251 if (isVTRNMask(M: ShuffleMask, VT, WhichResult))
7252 return ARMISD::VTRN;
7253 if (isVUZPMask(M: ShuffleMask, VT, WhichResult))
7254 return ARMISD::VUZP;
7255 if (isVZIPMask(M: ShuffleMask, VT, WhichResult))
7256 return ARMISD::VZIP;
7257
7258 isV_UNDEF = true;
7259 if (isVTRN_v_undef_Mask(M: ShuffleMask, VT, WhichResult))
7260 return ARMISD::VTRN;
7261 if (isVUZP_v_undef_Mask(M: ShuffleMask, VT, WhichResult))
7262 return ARMISD::VUZP;
7263 if (isVZIP_v_undef_Mask(M: ShuffleMask, VT, WhichResult))
7264 return ARMISD::VZIP;
7265
7266 return 0;
7267}
7268
7269/// \return true if this is a reverse operation on an vector.
7270static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7271 unsigned NumElts = VT.getVectorNumElements();
7272 // Make sure the mask has the right size.
7273 if (NumElts != M.size())
7274 return false;
7275
7276 // Look for <15, ..., 3, -1, 1, 0>.
7277 for (unsigned i = 0; i != NumElts; ++i)
7278 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7279 return false;
7280
7281 return true;
7282}
7283
7284static bool isTruncMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7285 unsigned NumElts = VT.getVectorNumElements();
7286 // Make sure the mask has the right size.
7287 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7288 return false;
7289
7290 // Half-width truncation patterns (e.g. v4i32 -> v8i16):
7291 // !Top && SingleSource: <0, 2, 4, 6, 0, 2, 4, 6>
7292 // !Top && !SingleSource: <0, 2, 4, 6, 8, 10, 12, 14>
7293 // Top && SingleSource: <1, 3, 5, 7, 1, 3, 5, 7>
7294 // Top && !SingleSource: <1, 3, 5, 7, 9, 11, 13, 15>
7295 int Ofs = Top ? 1 : 0;
7296 int Upper = SingleSource ? 0 : NumElts;
7297 for (int i = 0, e = NumElts / 2; i != e; ++i) {
7298 if (M[i] >= 0 && M[i] != (i * 2) + Ofs)
7299 return false;
7300 if (M[i + e] >= 0 && M[i + e] != (i * 2) + Ofs + Upper)
7301 return false;
7302 }
7303 return true;
7304}
7305
7306static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7307 unsigned NumElts = VT.getVectorNumElements();
7308 // Make sure the mask has the right size.
7309 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7310 return false;
7311
7312 // If Top
7313 // Look for <0, N, 2, N+2, 4, N+4, ..>.
7314 // This inserts Input2 into Input1
7315 // else if not Top
7316 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
7317 // This inserts Input1 into Input2
7318 unsigned Offset = Top ? 0 : 1;
7319 unsigned N = SingleSource ? 0 : NumElts;
7320 for (unsigned i = 0; i < NumElts; i += 2) {
7321 if (M[i] >= 0 && M[i] != (int)i)
7322 return false;
7323 if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset))
7324 return false;
7325 }
7326
7327 return true;
7328}
7329
7330static bool isVMOVNTruncMask(ArrayRef<int> M, EVT ToVT, bool rev) {
7331 unsigned NumElts = ToVT.getVectorNumElements();
7332 if (NumElts != M.size())
7333 return false;
7334
7335 // Test if the Trunc can be convertible to a VMOVN with this shuffle. We are
7336 // looking for patterns of:
7337 // !rev: 0 N/2 1 N/2+1 2 N/2+2 ...
7338 // rev: N/2 0 N/2+1 1 N/2+2 2 ...
7339
7340 unsigned Off0 = rev ? NumElts / 2 : 0;
7341 unsigned Off1 = rev ? 0 : NumElts / 2;
7342 for (unsigned i = 0; i < NumElts; i += 2) {
7343 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
7344 return false;
7345 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
7346 return false;
7347 }
7348
7349 return true;
7350}
7351
7352// Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7353// from a pair of inputs. For example:
7354// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7355// FP_ROUND(EXTRACT_ELT(Y, 0),
7356// FP_ROUND(EXTRACT_ELT(X, 1),
7357// FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7358static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG,
7359 const ARMSubtarget *ST) {
7360 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7361 if (!ST->hasMVEFloatOps())
7362 return SDValue();
7363
7364 SDLoc dl(BV);
7365 EVT VT = BV.getValueType();
7366 if (VT != MVT::v8f16)
7367 return SDValue();
7368
7369 // We are looking for a buildvector of fptrunc elements, where all the
7370 // elements are interleavingly extracted from two sources. Check the first two
7371 // items are valid enough and extract some info from them (they are checked
7372 // properly in the loop below).
7373 if (BV.getOperand(i: 0).getOpcode() != ISD::FP_ROUND ||
7374 BV.getOperand(i: 0).getOperand(i: 0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7375 BV.getOperand(i: 0).getOperand(i: 0).getConstantOperandVal(i: 1) != 0)
7376 return SDValue();
7377 if (BV.getOperand(i: 1).getOpcode() != ISD::FP_ROUND ||
7378 BV.getOperand(i: 1).getOperand(i: 0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7379 BV.getOperand(i: 1).getOperand(i: 0).getConstantOperandVal(i: 1) != 0)
7380 return SDValue();
7381 SDValue Op0 = BV.getOperand(i: 0).getOperand(i: 0).getOperand(i: 0);
7382 SDValue Op1 = BV.getOperand(i: 1).getOperand(i: 0).getOperand(i: 0);
7383 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7384 return SDValue();
7385
7386 // Check all the values in the BuildVector line up with our expectations.
7387 for (unsigned i = 1; i < 4; i++) {
7388 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7389 return Trunc.getOpcode() == ISD::FP_ROUND &&
7390 Trunc.getOperand(i: 0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7391 Trunc.getOperand(i: 0).getOperand(i: 0) == Op &&
7392 Trunc.getOperand(i: 0).getConstantOperandVal(i: 1) == Idx;
7393 };
7394 if (!Check(BV.getOperand(i: i * 2 + 0), Op0, i))
7395 return SDValue();
7396 if (!Check(BV.getOperand(i: i * 2 + 1), Op1, i))
7397 return SDValue();
7398 }
7399
7400 SDValue N1 = DAG.getNode(Opcode: ARMISD::VCVTN, DL: dl, VT, N1: DAG.getUNDEF(VT), N2: Op0,
7401 N3: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
7402 return DAG.getNode(Opcode: ARMISD::VCVTN, DL: dl, VT, N1, N2: Op1,
7403 N3: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
7404}
7405
7406// Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7407// from a single input on alternating lanes. For example:
7408// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7409// FP_ROUND(EXTRACT_ELT(X, 2),
7410// FP_ROUND(EXTRACT_ELT(X, 4), ...)
7411static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG,
7412 const ARMSubtarget *ST) {
7413 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7414 if (!ST->hasMVEFloatOps())
7415 return SDValue();
7416
7417 SDLoc dl(BV);
7418 EVT VT = BV.getValueType();
7419 if (VT != MVT::v4f32)
7420 return SDValue();
7421
7422 // We are looking for a buildvector of fptext elements, where all the
7423 // elements are alternating lanes from a single source. For example <0,2,4,6>
7424 // or <1,3,5,7>. Check the first two items are valid enough and extract some
7425 // info from them (they are checked properly in the loop below).
7426 if (BV.getOperand(i: 0).getOpcode() != ISD::FP_EXTEND ||
7427 BV.getOperand(i: 0).getOperand(i: 0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7428 return SDValue();
7429 SDValue Op0 = BV.getOperand(i: 0).getOperand(i: 0).getOperand(i: 0);
7430 int Offset = BV.getOperand(i: 0).getOperand(i: 0).getConstantOperandVal(i: 1);
7431 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7432 return SDValue();
7433
7434 // Check all the values in the BuildVector line up with our expectations.
7435 for (unsigned i = 1; i < 4; i++) {
7436 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7437 return Trunc.getOpcode() == ISD::FP_EXTEND &&
7438 Trunc.getOperand(i: 0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7439 Trunc.getOperand(i: 0).getOperand(i: 0) == Op &&
7440 Trunc.getOperand(i: 0).getConstantOperandVal(i: 1) == Idx;
7441 };
7442 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7443 return SDValue();
7444 }
7445
7446 return DAG.getNode(Opcode: ARMISD::VCVTL, DL: dl, VT, N1: Op0,
7447 N2: DAG.getConstant(Val: Offset, DL: dl, VT: MVT::i32));
7448}
7449
7450// If N is an integer constant that can be moved into a register in one
7451// instruction, return an SDValue of such a constant (will become a MOV
7452// instruction). Otherwise return null.
7453static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7454 const ARMSubtarget *ST, const SDLoc &dl) {
7455 uint64_t Val;
7456 if (!isa<ConstantSDNode>(Val: N))
7457 return SDValue();
7458 Val = N->getAsZExtVal();
7459
7460 if (ST->isThumb1Only()) {
7461 if (Val <= 255 || ~Val <= 255)
7462 return DAG.getConstant(Val, DL: dl, VT: MVT::i32);
7463 } else {
7464 if (ARM_AM::getSOImmVal(Arg: Val) != -1 || ARM_AM::getSOImmVal(Arg: ~Val) != -1)
7465 return DAG.getConstant(Val, DL: dl, VT: MVT::i32);
7466 }
7467 return SDValue();
7468}
7469
7470static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7471 const ARMSubtarget *ST) {
7472 SDLoc dl(Op);
7473 EVT VT = Op.getValueType();
7474
7475 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7476
7477 unsigned NumElts = VT.getVectorNumElements();
7478 unsigned BoolMask;
7479 unsigned BitsPerBool;
7480 if (NumElts == 2) {
7481 BitsPerBool = 8;
7482 BoolMask = 0xff;
7483 } else if (NumElts == 4) {
7484 BitsPerBool = 4;
7485 BoolMask = 0xf;
7486 } else if (NumElts == 8) {
7487 BitsPerBool = 2;
7488 BoolMask = 0x3;
7489 } else if (NumElts == 16) {
7490 BitsPerBool = 1;
7491 BoolMask = 0x1;
7492 } else
7493 return SDValue();
7494
7495 // If this is a single value copied into all lanes (a splat), we can just sign
7496 // extend that single value
7497 SDValue FirstOp = Op.getOperand(i: 0);
7498 if (!isa<ConstantSDNode>(Val: FirstOp) &&
7499 llvm::all_of(Range: llvm::drop_begin(RangeOrContainer: Op->ops()), P: [&FirstOp](const SDUse &U) {
7500 return U.get().isUndef() || U.get() == FirstOp;
7501 })) {
7502 SDValue Ext = DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL: dl, VT: MVT::i32, N1: FirstOp,
7503 N2: DAG.getValueType(MVT::i1));
7504 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: Op.getValueType(), Operand: Ext);
7505 }
7506
7507 // First create base with bits set where known
7508 unsigned Bits32 = 0;
7509 for (unsigned i = 0; i < NumElts; ++i) {
7510 SDValue V = Op.getOperand(i);
7511 if (!isa<ConstantSDNode>(Val: V) && !V.isUndef())
7512 continue;
7513 bool BitSet = V.isUndef() ? false : V->getAsZExtVal();
7514 if (BitSet)
7515 Bits32 |= BoolMask << (i * BitsPerBool);
7516 }
7517
7518 // Add in unknown nodes
7519 SDValue Base = DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT,
7520 Operand: DAG.getConstant(Val: Bits32, DL: dl, VT: MVT::i32));
7521 for (unsigned i = 0; i < NumElts; ++i) {
7522 SDValue V = Op.getOperand(i);
7523 if (isa<ConstantSDNode>(Val: V) || V.isUndef())
7524 continue;
7525 Base = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT, N1: Base, N2: V,
7526 N3: DAG.getConstant(Val: i, DL: dl, VT: MVT::i32));
7527 }
7528
7529 return Base;
7530}
7531
7532static SDValue LowerBUILD_VECTORToVIDUP(SDValue Op, SelectionDAG &DAG,
7533 const ARMSubtarget *ST) {
7534 if (!ST->hasMVEIntegerOps())
7535 return SDValue();
7536
7537 // We are looking for a buildvector where each element is Op[0] + i*N
7538 EVT VT = Op.getValueType();
7539 SDValue Op0 = Op.getOperand(i: 0);
7540 unsigned NumElts = VT.getVectorNumElements();
7541
7542 // Get the increment value from operand 1
7543 SDValue Op1 = Op.getOperand(i: 1);
7544 if (Op1.getOpcode() != ISD::ADD || Op1.getOperand(i: 0) != Op0 ||
7545 !isa<ConstantSDNode>(Val: Op1.getOperand(i: 1)))
7546 return SDValue();
7547 unsigned N = Op1.getConstantOperandVal(i: 1);
7548 if (N != 1 && N != 2 && N != 4 && N != 8)
7549 return SDValue();
7550
7551 // Check that each other operand matches
7552 for (unsigned I = 2; I < NumElts; I++) {
7553 SDValue OpI = Op.getOperand(i: I);
7554 if (OpI.getOpcode() != ISD::ADD || OpI.getOperand(i: 0) != Op0 ||
7555 !isa<ConstantSDNode>(Val: OpI.getOperand(i: 1)) ||
7556 OpI.getConstantOperandVal(i: 1) != I * N)
7557 return SDValue();
7558 }
7559
7560 SDLoc DL(Op);
7561 return DAG.getNode(Opcode: ARMISD::VIDUP, DL, VTList: DAG.getVTList(VT1: VT, VT2: MVT::i32), N1: Op0,
7562 N2: DAG.getConstant(Val: N, DL, VT: MVT::i32));
7563}
7564
7565// Returns true if the operation N can be treated as qr instruction variant at
7566// operand Op.
7567static bool IsQRMVEInstruction(const SDNode *N, const SDNode *Op) {
7568 switch (N->getOpcode()) {
7569 case ISD::ADD:
7570 case ISD::MUL:
7571 case ISD::SADDSAT:
7572 case ISD::UADDSAT:
7573 case ISD::AVGFLOORS:
7574 case ISD::AVGFLOORU:
7575 return true;
7576 case ISD::SUB:
7577 case ISD::SSUBSAT:
7578 case ISD::USUBSAT:
7579 return N->getOperand(Num: 1).getNode() == Op;
7580 case ISD::INTRINSIC_WO_CHAIN:
7581 switch (N->getConstantOperandVal(Num: 0)) {
7582 case Intrinsic::arm_mve_add_predicated:
7583 case Intrinsic::arm_mve_mul_predicated:
7584 case Intrinsic::arm_mve_qadd_predicated:
7585 case Intrinsic::arm_mve_vhadd:
7586 case Intrinsic::arm_mve_hadd_predicated:
7587 case Intrinsic::arm_mve_vqdmulh:
7588 case Intrinsic::arm_mve_qdmulh_predicated:
7589 case Intrinsic::arm_mve_vqrdmulh:
7590 case Intrinsic::arm_mve_qrdmulh_predicated:
7591 case Intrinsic::arm_mve_vqdmull:
7592 case Intrinsic::arm_mve_vqdmull_predicated:
7593 return true;
7594 case Intrinsic::arm_mve_sub_predicated:
7595 case Intrinsic::arm_mve_qsub_predicated:
7596 case Intrinsic::arm_mve_vhsub:
7597 case Intrinsic::arm_mve_hsub_predicated:
7598 return N->getOperand(Num: 2).getNode() == Op;
7599 default:
7600 return false;
7601 }
7602 default:
7603 return false;
7604 }
7605}
7606
7607// If this is a case we can't handle, return null and let the default
7608// expansion code take care of it.
7609SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7610 const ARMSubtarget *ST) const {
7611 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Val: Op.getNode());
7612 SDLoc dl(Op);
7613 EVT VT = Op.getValueType();
7614
7615 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7616 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7617
7618 if (SDValue R = LowerBUILD_VECTORToVIDUP(Op, DAG, ST))
7619 return R;
7620
7621 APInt SplatBits, SplatUndef;
7622 unsigned SplatBitSize;
7623 bool HasAnyUndefs;
7624 if (BVN->isConstantSplat(SplatValue&: SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7625 if (SplatUndef.isAllOnes())
7626 return DAG.getUNDEF(VT);
7627
7628 // If all the users of this constant splat are qr instruction variants,
7629 // generate a vdup of the constant.
7630 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == SplatBitSize &&
7631 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32) &&
7632 all_of(Range: BVN->users(),
7633 P: [BVN](const SDNode *U) { return IsQRMVEInstruction(N: U, Op: BVN); })) {
7634 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7635 : SplatBitSize == 16 ? MVT::v8i16
7636 : MVT::v16i8;
7637 SDValue Const = DAG.getConstant(Val: SplatBits.getZExtValue(), DL: dl, VT: MVT::i32);
7638 SDValue VDup = DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT: DupVT, Operand: Const);
7639 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: VDup);
7640 }
7641
7642 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7643 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7644 // Check if an immediate VMOV works.
7645 EVT VmovVT;
7646 SDValue Val =
7647 isVMOVModifiedImm(SplatBits: SplatBits.getZExtValue(), SplatUndef: SplatUndef.getZExtValue(),
7648 SplatBitSize, DAG, dl, VT&: VmovVT, VectorVT: VT, type: VMOVModImm);
7649
7650 if (Val.getNode()) {
7651 SDValue Vmov = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: VmovVT, Operand: Val);
7652 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Vmov);
7653 }
7654
7655 // Try an immediate VMVN.
7656 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7657 Val = isVMOVModifiedImm(
7658 SplatBits: NegatedImm, SplatUndef: SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VT&: VmovVT,
7659 VectorVT: VT, type: ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7660 if (Val.getNode()) {
7661 SDValue Vmov = DAG.getNode(Opcode: ARMISD::VMVNIMM, DL: dl, VT: VmovVT, Operand: Val);
7662 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Vmov);
7663 }
7664
7665 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7666 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7667 int ImmVal = ARM_AM::getFP32Imm(Imm: SplatBits);
7668 if (ImmVal != -1) {
7669 SDValue Val = DAG.getTargetConstant(Val: ImmVal, DL: dl, VT: MVT::i32);
7670 return DAG.getNode(Opcode: ARMISD::VMOVFPIMM, DL: dl, VT, Operand: Val);
7671 }
7672 }
7673
7674 // If we are under MVE, generate a VDUP(constant), bitcast to the original
7675 // type.
7676 if (ST->hasMVEIntegerOps() &&
7677 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32)) {
7678 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7679 : SplatBitSize == 16 ? MVT::v8i16
7680 : MVT::v16i8;
7681 SDValue Const = DAG.getConstant(Val: SplatBits.getZExtValue(), DL: dl, VT: MVT::i32);
7682 SDValue VDup = DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT: DupVT, Operand: Const);
7683 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: VDup);
7684 }
7685 }
7686 }
7687
7688 // Scan through the operands to see if only one value is used.
7689 //
7690 // As an optimisation, even if more than one value is used it may be more
7691 // profitable to splat with one value then change some lanes.
7692 //
7693 // Heuristically we decide to do this if the vector has a "dominant" value,
7694 // defined as splatted to more than half of the lanes.
7695 unsigned NumElts = VT.getVectorNumElements();
7696 bool isOnlyLowElement = true;
7697 bool usesOnlyOneValue = true;
7698 bool hasDominantValue = false;
7699 bool isConstant = true;
7700
7701 // Map of the number of times a particular SDValue appears in the
7702 // element list.
7703 DenseMap<SDValue, unsigned> ValueCounts;
7704 SDValue Value;
7705 for (unsigned i = 0; i < NumElts; ++i) {
7706 SDValue V = Op.getOperand(i);
7707 if (V.isUndef())
7708 continue;
7709 if (i > 0)
7710 isOnlyLowElement = false;
7711 if (!isa<ConstantFPSDNode>(Val: V) && !isa<ConstantSDNode>(Val: V))
7712 isConstant = false;
7713
7714 unsigned &Count = ValueCounts[V];
7715
7716 // Is this value dominant? (takes up more than half of the lanes)
7717 if (++Count > (NumElts / 2)) {
7718 hasDominantValue = true;
7719 Value = V;
7720 }
7721 }
7722 if (ValueCounts.size() != 1)
7723 usesOnlyOneValue = false;
7724 if (!Value.getNode() && !ValueCounts.empty())
7725 Value = ValueCounts.begin()->first;
7726
7727 if (ValueCounts.empty())
7728 return DAG.getUNDEF(VT);
7729
7730 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7731 // Keep going if we are hitting this case.
7732 if (isOnlyLowElement && !ISD::isNormalLoad(N: Value.getNode()))
7733 return DAG.getNode(Opcode: ISD::SCALAR_TO_VECTOR, DL: dl, VT, Operand: Value);
7734
7735 unsigned EltSize = VT.getScalarSizeInBits();
7736
7737 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7738 // i32 and try again.
7739 if (hasDominantValue && EltSize <= 32) {
7740 if (!isConstant) {
7741 SDValue N;
7742
7743 // If we are VDUPing a value that comes directly from a vector, that will
7744 // cause an unnecessary move to and from a GPR, where instead we could
7745 // just use VDUPLANE. We can only do this if the lane being extracted
7746 // is at a constant index, as the VDUP from lane instructions only have
7747 // constant-index forms.
7748 ConstantSDNode *constIndex;
7749 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7750 (constIndex = dyn_cast<ConstantSDNode>(Val: Value->getOperand(Num: 1)))) {
7751 // We need to create a new undef vector to use for the VDUPLANE if the
7752 // size of the vector from which we get the value is different than the
7753 // size of the vector that we need to create. We will insert the element
7754 // such that the register coalescer will remove unnecessary copies.
7755 if (VT != Value->getOperand(Num: 0).getValueType()) {
7756 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7757 VT.getVectorNumElements();
7758 N = DAG.getNode(Opcode: ARMISD::VDUPLANE, DL: dl, VT,
7759 N1: DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT, N1: DAG.getUNDEF(VT),
7760 N2: Value, N3: DAG.getConstant(Val: index, DL: dl, VT: MVT::i32)),
7761 N2: DAG.getConstant(Val: index, DL: dl, VT: MVT::i32));
7762 } else
7763 N = DAG.getNode(Opcode: ARMISD::VDUPLANE, DL: dl, VT,
7764 N1: Value->getOperand(Num: 0), N2: Value->getOperand(Num: 1));
7765 } else
7766 N = DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT, Operand: Value);
7767
7768 if (!usesOnlyOneValue) {
7769 // The dominant value was splatted as 'N', but we now have to insert
7770 // all differing elements.
7771 for (unsigned I = 0; I < NumElts; ++I) {
7772 if (Op.getOperand(i: I) == Value)
7773 continue;
7774 SmallVector<SDValue, 3> Ops;
7775 Ops.push_back(Elt: N);
7776 Ops.push_back(Elt: Op.getOperand(i: I));
7777 Ops.push_back(Elt: DAG.getConstant(Val: I, DL: dl, VT: MVT::i32));
7778 N = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT, Ops);
7779 }
7780 }
7781 return N;
7782 }
7783 if (VT.getVectorElementType().isFloatingPoint()) {
7784 SmallVector<SDValue, 8> Ops;
7785 MVT FVT = VT.getVectorElementType().getSimpleVT();
7786 assert(FVT == MVT::f32 || FVT == MVT::f16);
7787 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7788 for (unsigned i = 0; i < NumElts; ++i)
7789 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: IVT,
7790 Operand: Op.getOperand(i)));
7791 EVT VecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: IVT, NumElements: NumElts);
7792 SDValue Val = DAG.getBuildVector(VT: VecVT, DL: dl, Ops);
7793 Val = LowerBUILD_VECTOR(Op: Val, DAG, ST);
7794 if (Val.getNode())
7795 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Val);
7796 }
7797 if (usesOnlyOneValue) {
7798 SDValue Val = IsSingleInstrConstant(N: Value, DAG, ST, dl);
7799 if (isConstant && Val.getNode())
7800 return DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT, Operand: Val);
7801 }
7802 }
7803
7804 // If all elements are constants and the case above didn't get hit, fall back
7805 // to the default expansion, which will generate a load from the constant
7806 // pool.
7807 if (isConstant)
7808 return SDValue();
7809
7810 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7811 // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7812 // length <= 2.
7813 if (NumElts >= 4)
7814 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7815 return shuffle;
7816
7817 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7818 // VCVT's
7819 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(BV: Op, DAG, ST: Subtarget))
7820 return VCVT;
7821 if (SDValue VCVT = LowerBuildVectorOfFPExt(BV: Op, DAG, ST: Subtarget))
7822 return VCVT;
7823
7824 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7825 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7826 // into two 64-bit vectors; we might discover a better way to lower it.
7827 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7828 EVT ExtVT = VT.getVectorElementType();
7829 EVT HVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: ExtVT, NumElements: NumElts / 2);
7830 SDValue Lower = DAG.getBuildVector(VT: HVT, DL: dl, Ops: ArrayRef(&Ops[0], NumElts / 2));
7831 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7832 Lower = LowerBUILD_VECTOR(Op: Lower, DAG, ST);
7833 SDValue Upper =
7834 DAG.getBuildVector(VT: HVT, DL: dl, Ops: ArrayRef(&Ops[NumElts / 2], NumElts / 2));
7835 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7836 Upper = LowerBUILD_VECTOR(Op: Upper, DAG, ST);
7837 if (Lower && Upper)
7838 return DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: dl, VT, N1: Lower, N2: Upper);
7839 }
7840
7841 // Vectors with 32- or 64-bit elements can be built by directly assigning
7842 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7843 // will be legalized.
7844 if (EltSize >= 32) {
7845 // Do the expansion with floating-point types, since that is what the VFP
7846 // registers are defined to use, and since i64 is not legal.
7847 EVT EltVT = EVT::getFloatingPointVT(BitWidth: EltSize);
7848 EVT VecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: EltVT, NumElements: NumElts);
7849 SmallVector<SDValue, 8> Ops;
7850 for (unsigned i = 0; i < NumElts; ++i)
7851 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: EltVT, Operand: Op.getOperand(i)));
7852 SDValue Val = DAG.getNode(Opcode: ARMISD::BUILD_VECTOR, DL: dl, VT: VecVT, Ops);
7853 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Val);
7854 }
7855
7856 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7857 // know the default expansion would otherwise fall back on something even
7858 // worse. For a vector with one or two non-undef values, that's
7859 // scalar_to_vector for the elements followed by a shuffle (provided the
7860 // shuffle is valid for the target) and materialization element by element
7861 // on the stack followed by a load for everything else.
7862 if (!isConstant && !usesOnlyOneValue) {
7863 SDValue Vec = DAG.getUNDEF(VT);
7864 for (unsigned i = 0 ; i < NumElts; ++i) {
7865 SDValue V = Op.getOperand(i);
7866 if (V.isUndef())
7867 continue;
7868 SDValue LaneIdx = DAG.getConstant(Val: i, DL: dl, VT: MVT::i32);
7869 Vec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT, N1: Vec, N2: V, N3: LaneIdx);
7870 }
7871 return Vec;
7872 }
7873
7874 return SDValue();
7875}
7876
7877// Gather data to see if the operation can be modelled as a
7878// shuffle in combination with VEXTs.
7879SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7880 SelectionDAG &DAG) const {
7881 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7882 SDLoc dl(Op);
7883 EVT VT = Op.getValueType();
7884 unsigned NumElts = VT.getVectorNumElements();
7885
7886 struct ShuffleSourceInfo {
7887 SDValue Vec;
7888 unsigned MinElt = std::numeric_limits<unsigned>::max();
7889 unsigned MaxElt = 0;
7890
7891 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7892 // be compatible with the shuffle we intend to construct. As a result
7893 // ShuffleVec will be some sliding window into the original Vec.
7894 SDValue ShuffleVec;
7895
7896 // Code should guarantee that element i in Vec starts at element "WindowBase
7897 // + i * WindowScale in ShuffleVec".
7898 int WindowBase = 0;
7899 int WindowScale = 1;
7900
7901 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7902
7903 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7904 };
7905
7906 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7907 // node.
7908 SmallVector<ShuffleSourceInfo, 2> Sources;
7909 for (unsigned i = 0; i < NumElts; ++i) {
7910 SDValue V = Op.getOperand(i);
7911 if (V.isUndef())
7912 continue;
7913 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7914 // A shuffle can only come from building a vector from various
7915 // elements of other vectors.
7916 return SDValue();
7917 } else if (!isa<ConstantSDNode>(Val: V.getOperand(i: 1))) {
7918 // Furthermore, shuffles require a constant mask, whereas extractelts
7919 // accept variable indices.
7920 return SDValue();
7921 }
7922
7923 // Add this element source to the list if it's not already there.
7924 SDValue SourceVec = V.getOperand(i: 0);
7925 auto Source = llvm::find(Range&: Sources, Val: SourceVec);
7926 if (Source == Sources.end())
7927 Source = Sources.insert(I: Sources.end(), Elt: ShuffleSourceInfo(SourceVec));
7928
7929 // Update the minimum and maximum lane number seen.
7930 unsigned EltNo = V.getConstantOperandVal(i: 1);
7931 Source->MinElt = std::min(a: Source->MinElt, b: EltNo);
7932 Source->MaxElt = std::max(a: Source->MaxElt, b: EltNo);
7933 }
7934
7935 // Currently only do something sane when at most two source vectors
7936 // are involved.
7937 if (Sources.size() > 2)
7938 return SDValue();
7939
7940 // Find out the smallest element size among result and two sources, and use
7941 // it as element size to build the shuffle_vector.
7942 EVT SmallestEltTy = VT.getVectorElementType();
7943 for (auto &Source : Sources) {
7944 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7945 if (SrcEltTy.bitsLT(VT: SmallestEltTy))
7946 SmallestEltTy = SrcEltTy;
7947 }
7948 unsigned ResMultiplier =
7949 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7950 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7951 EVT ShuffleVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: SmallestEltTy, NumElements: NumElts);
7952
7953 // If the source vector is too wide or too narrow, we may nevertheless be able
7954 // to construct a compatible shuffle either by concatenating it with UNDEF or
7955 // extracting a suitable range of elements.
7956 for (auto &Src : Sources) {
7957 EVT SrcVT = Src.ShuffleVec.getValueType();
7958
7959 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
7960 uint64_t VTSize = VT.getFixedSizeInBits();
7961 if (SrcVTSize == VTSize)
7962 continue;
7963
7964 // This stage of the search produces a source with the same element type as
7965 // the original, but with a total width matching the BUILD_VECTOR output.
7966 EVT EltVT = SrcVT.getVectorElementType();
7967 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
7968 EVT DestVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: EltVT, NumElements: NumSrcElts);
7969
7970 if (SrcVTSize < VTSize) {
7971 if (2 * SrcVTSize != VTSize)
7972 return SDValue();
7973 // We can pad out the smaller vector for free, so if it's part of a
7974 // shuffle...
7975 Src.ShuffleVec =
7976 DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: dl, VT: DestVT, N1: Src.ShuffleVec,
7977 N2: DAG.getUNDEF(VT: Src.ShuffleVec.getValueType()));
7978 continue;
7979 }
7980
7981 if (SrcVTSize != 2 * VTSize)
7982 return SDValue();
7983
7984 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7985 // Span too large for a VEXT to cope
7986 return SDValue();
7987 }
7988
7989 if (Src.MinElt >= NumSrcElts) {
7990 // The extraction can just take the second half
7991 Src.ShuffleVec =
7992 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: DestVT, N1: Src.ShuffleVec,
7993 N2: DAG.getConstant(Val: NumSrcElts, DL: dl, VT: MVT::i32));
7994 Src.WindowBase = -NumSrcElts;
7995 } else if (Src.MaxElt < NumSrcElts) {
7996 // The extraction can just take the first half
7997 Src.ShuffleVec =
7998 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: DestVT, N1: Src.ShuffleVec,
7999 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
8000 } else {
8001 // An actual VEXT is needed
8002 SDValue VEXTSrc1 =
8003 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: DestVT, N1: Src.ShuffleVec,
8004 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
8005 SDValue VEXTSrc2 =
8006 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: DestVT, N1: Src.ShuffleVec,
8007 N2: DAG.getConstant(Val: NumSrcElts, DL: dl, VT: MVT::i32));
8008
8009 Src.ShuffleVec = DAG.getNode(Opcode: ARMISD::VEXT, DL: dl, VT: DestVT, N1: VEXTSrc1,
8010 N2: VEXTSrc2,
8011 N3: DAG.getConstant(Val: Src.MinElt, DL: dl, VT: MVT::i32));
8012 Src.WindowBase = -Src.MinElt;
8013 }
8014 }
8015
8016 // Another possible incompatibility occurs from the vector element types. We
8017 // can fix this by bitcasting the source vectors to the same type we intend
8018 // for the shuffle.
8019 for (auto &Src : Sources) {
8020 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8021 if (SrcEltTy == SmallestEltTy)
8022 continue;
8023 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
8024 Src.ShuffleVec = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: ShuffleVT, Operand: Src.ShuffleVec);
8025 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
8026 Src.WindowBase *= Src.WindowScale;
8027 }
8028
8029 // Final check before we try to actually produce a shuffle.
8030 LLVM_DEBUG({
8031 for (auto Src : Sources)
8032 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
8033 });
8034
8035 // The stars all align, our next step is to produce the mask for the shuffle.
8036 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8037 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8038 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8039 SDValue Entry = Op.getOperand(i);
8040 if (Entry.isUndef())
8041 continue;
8042
8043 auto Src = llvm::find(Range&: Sources, Val: Entry.getOperand(i: 0));
8044 int EltNo = cast<ConstantSDNode>(Val: Entry.getOperand(i: 1))->getSExtValue();
8045
8046 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8047 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8048 // segment.
8049 EVT OrigEltTy = Entry.getOperand(i: 0).getValueType().getVectorElementType();
8050 int BitsDefined = std::min(a: OrigEltTy.getScalarSizeInBits(),
8051 b: VT.getScalarSizeInBits());
8052 int LanesDefined = BitsDefined / BitsPerShuffleLane;
8053
8054 // This source is expected to fill ResMultiplier lanes of the final shuffle,
8055 // starting at the appropriate offset.
8056 int *LaneMask = &Mask[i * ResMultiplier];
8057
8058 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8059 ExtractBase += NumElts * (Src - Sources.begin());
8060 for (int j = 0; j < LanesDefined; ++j)
8061 LaneMask[j] = ExtractBase + j;
8062 }
8063
8064
8065 // We can't handle more than two sources. This should have already
8066 // been checked before this point.
8067 assert(Sources.size() <= 2 && "Too many sources!");
8068
8069 SDValue ShuffleOps[] = { DAG.getUNDEF(VT: ShuffleVT), DAG.getUNDEF(VT: ShuffleVT) };
8070 for (unsigned i = 0; i < Sources.size(); ++i)
8071 ShuffleOps[i] = Sources[i].ShuffleVec;
8072
8073 SDValue Shuffle = buildLegalVectorShuffle(VT: ShuffleVT, DL: dl, N0: ShuffleOps[0],
8074 N1: ShuffleOps[1], Mask, DAG);
8075 if (!Shuffle)
8076 return SDValue();
8077 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Shuffle);
8078}
8079
8080enum ShuffleOpCodes {
8081 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8082 OP_VREV,
8083 OP_VDUP0,
8084 OP_VDUP1,
8085 OP_VDUP2,
8086 OP_VDUP3,
8087 OP_VEXT1,
8088 OP_VEXT2,
8089 OP_VEXT3,
8090 OP_VUZPL, // VUZP, left result
8091 OP_VUZPR, // VUZP, right result
8092 OP_VZIPL, // VZIP, left result
8093 OP_VZIPR, // VZIP, right result
8094 OP_VTRNL, // VTRN, left result
8095 OP_VTRNR // VTRN, right result
8096};
8097
8098static bool isLegalMVEShuffleOp(unsigned PFEntry) {
8099 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8100 switch (OpNum) {
8101 case OP_COPY:
8102 case OP_VREV:
8103 case OP_VDUP0:
8104 case OP_VDUP1:
8105 case OP_VDUP2:
8106 case OP_VDUP3:
8107 return true;
8108 }
8109 return false;
8110}
8111
8112/// isShuffleMaskLegal - Targets can use this to indicate that they only
8113/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8114/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8115/// are assumed to be legal.
8116bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8117 if (VT.getVectorNumElements() == 4 &&
8118 (VT.is128BitVector() || VT.is64BitVector())) {
8119 unsigned PFIndexes[4];
8120 for (unsigned i = 0; i != 4; ++i) {
8121 if (M[i] < 0)
8122 PFIndexes[i] = 8;
8123 else
8124 PFIndexes[i] = M[i];
8125 }
8126
8127 // Compute the index in the perfect shuffle table.
8128 unsigned PFTableIndex =
8129 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8130 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8131 unsigned Cost = (PFEntry >> 30);
8132
8133 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
8134 return true;
8135 }
8136
8137 bool ReverseVEXT, isV_UNDEF;
8138 unsigned Imm, WhichResult;
8139
8140 unsigned EltSize = VT.getScalarSizeInBits();
8141 if (EltSize >= 32 ||
8142 ShuffleVectorSDNode::isSplatMask(Mask: M) ||
8143 ShuffleVectorInst::isIdentityMask(Mask: M, NumSrcElts: M.size()) ||
8144 isVREVMask(M, VT, BlockSize: 64) ||
8145 isVREVMask(M, VT, BlockSize: 32) ||
8146 isVREVMask(M, VT, BlockSize: 16))
8147 return true;
8148 else if (Subtarget->hasNEON() &&
8149 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
8150 isVTBLMask(M, VT) ||
8151 isNEONTwoResultShuffleMask(ShuffleMask: M, VT, WhichResult, isV_UNDEF)))
8152 return true;
8153 else if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8154 isReverseMask(M, VT))
8155 return true;
8156 else if (Subtarget->hasMVEIntegerOps() &&
8157 (isVMOVNMask(M, VT, Top: true, SingleSource: false) ||
8158 isVMOVNMask(M, VT, Top: false, SingleSource: false) || isVMOVNMask(M, VT, Top: true, SingleSource: true)))
8159 return true;
8160 else if (Subtarget->hasMVEIntegerOps() &&
8161 (isTruncMask(M, VT, Top: false, SingleSource: false) ||
8162 isTruncMask(M, VT, Top: false, SingleSource: true) ||
8163 isTruncMask(M, VT, Top: true, SingleSource: false) || isTruncMask(M, VT, Top: true, SingleSource: true)))
8164 return true;
8165 else
8166 return false;
8167}
8168
8169/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8170/// the specified operations to build the shuffle.
8171static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8172 SDValue RHS, SelectionDAG &DAG,
8173 const SDLoc &dl) {
8174 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8175 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8176 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8177
8178 if (OpNum == OP_COPY) {
8179 if (LHSID == (1*9+2)*9+3) return LHS;
8180 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8181 return RHS;
8182 }
8183
8184 SDValue OpLHS, OpRHS;
8185 OpLHS = GeneratePerfectShuffle(PFEntry: PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8186 OpRHS = GeneratePerfectShuffle(PFEntry: PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8187 EVT VT = OpLHS.getValueType();
8188
8189 switch (OpNum) {
8190 default: llvm_unreachable("Unknown shuffle opcode!");
8191 case OP_VREV:
8192 // VREV divides the vector in half and swaps within the half.
8193 if (VT.getScalarSizeInBits() == 32)
8194 return DAG.getNode(Opcode: ARMISD::VREV64, DL: dl, VT, Operand: OpLHS);
8195 // vrev <4 x i16> -> VREV32
8196 if (VT.getScalarSizeInBits() == 16)
8197 return DAG.getNode(Opcode: ARMISD::VREV32, DL: dl, VT, Operand: OpLHS);
8198 // vrev <4 x i8> -> VREV16
8199 assert(VT.getScalarSizeInBits() == 8);
8200 return DAG.getNode(Opcode: ARMISD::VREV16, DL: dl, VT, Operand: OpLHS);
8201 case OP_VDUP0:
8202 case OP_VDUP1:
8203 case OP_VDUP2:
8204 case OP_VDUP3:
8205 return DAG.getNode(Opcode: ARMISD::VDUPLANE, DL: dl, VT,
8206 N1: OpLHS, N2: DAG.getConstant(Val: OpNum-OP_VDUP0, DL: dl, VT: MVT::i32));
8207 case OP_VEXT1:
8208 case OP_VEXT2:
8209 case OP_VEXT3:
8210 return DAG.getNode(Opcode: ARMISD::VEXT, DL: dl, VT,
8211 N1: OpLHS, N2: OpRHS,
8212 N3: DAG.getConstant(Val: OpNum - OP_VEXT1 + 1, DL: dl, VT: MVT::i32));
8213 case OP_VUZPL:
8214 case OP_VUZPR:
8215 return DAG.getNode(Opcode: ARMISD::VUZP, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT),
8216 N1: OpLHS, N2: OpRHS).getValue(R: OpNum-OP_VUZPL);
8217 case OP_VZIPL:
8218 case OP_VZIPR:
8219 return DAG.getNode(Opcode: ARMISD::VZIP, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT),
8220 N1: OpLHS, N2: OpRHS).getValue(R: OpNum-OP_VZIPL);
8221 case OP_VTRNL:
8222 case OP_VTRNR:
8223 return DAG.getNode(Opcode: ARMISD::VTRN, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT),
8224 N1: OpLHS, N2: OpRHS).getValue(R: OpNum-OP_VTRNL);
8225 }
8226}
8227
8228static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
8229 ArrayRef<int> ShuffleMask,
8230 SelectionDAG &DAG) {
8231 // Check to see if we can use the VTBL instruction.
8232 SDValue V1 = Op.getOperand(i: 0);
8233 SDValue V2 = Op.getOperand(i: 1);
8234 SDLoc DL(Op);
8235
8236 SmallVector<SDValue, 8> VTBLMask;
8237 for (int I : ShuffleMask)
8238 VTBLMask.push_back(Elt: DAG.getSignedConstant(Val: I, DL, VT: MVT::i32));
8239
8240 if (V2.getNode()->isUndef())
8241 return DAG.getNode(Opcode: ARMISD::VTBL1, DL, VT: MVT::v8i8, N1: V1,
8242 N2: DAG.getBuildVector(VT: MVT::v8i8, DL, Ops: VTBLMask));
8243
8244 return DAG.getNode(Opcode: ARMISD::VTBL2, DL, VT: MVT::v8i8, N1: V1, N2: V2,
8245 N3: DAG.getBuildVector(VT: MVT::v8i8, DL, Ops: VTBLMask));
8246}
8247
8248static SDValue LowerReverse_VECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
8249 SDLoc DL(Op);
8250 EVT VT = Op.getValueType();
8251
8252 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8253 "Expect an v8i16/v16i8 type");
8254 SDValue OpLHS = DAG.getNode(Opcode: ARMISD::VREV64, DL, VT, Operand: Op.getOperand(i: 0));
8255 // For a v16i8 type: After the VREV, we have got <7, ..., 0, 15, ..., 8>. Now,
8256 // extract the first 8 bytes into the top double word and the last 8 bytes
8257 // into the bottom double word, through a new vector shuffle that will be
8258 // turned into a VEXT on Neon, or a couple of VMOVDs on MVE.
8259 std::vector<int> NewMask;
8260 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8261 NewMask.push_back(x: VT.getVectorNumElements() / 2 + i);
8262 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8263 NewMask.push_back(x: i);
8264 return DAG.getVectorShuffle(VT, dl: DL, N1: OpLHS, N2: OpLHS, Mask: NewMask);
8265}
8266
8267static EVT getVectorTyFromPredicateVector(EVT VT) {
8268 switch (VT.getSimpleVT().SimpleTy) {
8269 case MVT::v2i1:
8270 return MVT::v2f64;
8271 case MVT::v4i1:
8272 return MVT::v4i32;
8273 case MVT::v8i1:
8274 return MVT::v8i16;
8275 case MVT::v16i1:
8276 return MVT::v16i8;
8277 default:
8278 llvm_unreachable("Unexpected vector predicate type");
8279 }
8280}
8281
8282static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
8283 SelectionDAG &DAG) {
8284 // Converting from boolean predicates to integers involves creating a vector
8285 // of all ones or all zeroes and selecting the lanes based upon the real
8286 // predicate.
8287 SDValue AllOnes =
8288 DAG.getTargetConstant(Val: ARM_AM::createVMOVModImm(OpCmode: 0xe, Val: 0xff), DL: dl, VT: MVT::i32);
8289 AllOnes = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: MVT::v16i8, Operand: AllOnes);
8290
8291 SDValue AllZeroes =
8292 DAG.getTargetConstant(Val: ARM_AM::createVMOVModImm(OpCmode: 0xe, Val: 0x0), DL: dl, VT: MVT::i32);
8293 AllZeroes = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: MVT::v16i8, Operand: AllZeroes);
8294
8295 // Get full vector type from predicate type
8296 EVT NewVT = getVectorTyFromPredicateVector(VT);
8297
8298 SDValue RecastV1;
8299 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8300 // this to a v16i1. This cannot be done with an ordinary bitcast because the
8301 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8302 // since we know in hardware the sizes are really the same.
8303 if (VT != MVT::v16i1)
8304 RecastV1 = DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::v16i1, Operand: Pred);
8305 else
8306 RecastV1 = Pred;
8307
8308 // Select either all ones or zeroes depending upon the real predicate bits.
8309 SDValue PredAsVector =
8310 DAG.getNode(Opcode: ISD::VSELECT, DL: dl, VT: MVT::v16i8, N1: RecastV1, N2: AllOnes, N3: AllZeroes);
8311
8312 // Recast our new predicate-as-integer v16i8 vector into something
8313 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8314 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: NewVT, Operand: PredAsVector);
8315}
8316
8317static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
8318 const ARMSubtarget *ST) {
8319 EVT VT = Op.getValueType();
8320 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Val: Op.getNode());
8321 ArrayRef<int> ShuffleMask = SVN->getMask();
8322
8323 assert(ST->hasMVEIntegerOps() &&
8324 "No support for vector shuffle of boolean predicates");
8325
8326 SDValue V1 = Op.getOperand(i: 0);
8327 SDValue V2 = Op.getOperand(i: 1);
8328 SDLoc dl(Op);
8329 if (isReverseMask(M: ShuffleMask, VT)) {
8330 SDValue cast = DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::i32, Operand: V1);
8331 SDValue rbit = DAG.getNode(Opcode: ISD::BITREVERSE, DL: dl, VT: MVT::i32, Operand: cast);
8332 SDValue srl = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32, N1: rbit,
8333 N2: DAG.getConstant(Val: 16, DL: dl, VT: MVT::i32));
8334 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT, Operand: srl);
8335 }
8336
8337 // Until we can come up with optimised cases for every single vector
8338 // shuffle in existence we have chosen the least painful strategy. This is
8339 // to essentially promote the boolean predicate to a 8-bit integer, where
8340 // each predicate represents a byte. Then we fall back on a normal integer
8341 // vector shuffle and convert the result back into a predicate vector. In
8342 // many cases the generated code might be even better than scalar code
8343 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8344 // fields in a register into 8 other arbitrary 2-bit fields!
8345 SDValue PredAsVector1 = PromoteMVEPredVector(dl, Pred: V1, VT, DAG);
8346 EVT NewVT = PredAsVector1.getValueType();
8347 SDValue PredAsVector2 = V2.isUndef() ? DAG.getUNDEF(VT: NewVT)
8348 : PromoteMVEPredVector(dl, Pred: V2, VT, DAG);
8349 assert(PredAsVector2.getValueType() == NewVT &&
8350 "Expected identical vector type in expanded i1 shuffle!");
8351
8352 // Do the shuffle!
8353 SDValue Shuffled = DAG.getVectorShuffle(VT: NewVT, dl, N1: PredAsVector1,
8354 N2: PredAsVector2, Mask: ShuffleMask);
8355
8356 // Now return the result of comparing the shuffled vector with zero,
8357 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. For a v2i1
8358 // we convert to a v4i1 compare to fill in the two halves of the i64 as i32s.
8359 if (VT == MVT::v2i1) {
8360 SDValue BC = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: Shuffled);
8361 SDValue Cmp = DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT: MVT::v4i1, N1: BC,
8362 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8363 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::v2i1, Operand: Cmp);
8364 }
8365 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: Shuffled,
8366 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8367}
8368
8369static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
8370 ArrayRef<int> ShuffleMask,
8371 SelectionDAG &DAG) {
8372 // Attempt to lower the vector shuffle using as many whole register movs as
8373 // possible. This is useful for types smaller than 32bits, which would
8374 // often otherwise become a series for grp movs.
8375 SDLoc dl(Op);
8376 EVT VT = Op.getValueType();
8377 if (VT.getScalarSizeInBits() >= 32)
8378 return SDValue();
8379
8380 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8381 "Unexpected vector type");
8382 int NumElts = VT.getVectorNumElements();
8383 int QuarterSize = NumElts / 4;
8384 // The four final parts of the vector, as i32's
8385 SDValue Parts[4];
8386
8387 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8388 // <u,u,u,u>), returning the vmov lane index
8389 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8390 // Detect which mov lane this would be from the first non-undef element.
8391 int MovIdx = -1;
8392 for (int i = 0; i < Length; i++) {
8393 if (ShuffleMask[Start + i] >= 0) {
8394 if (ShuffleMask[Start + i] % Length != i)
8395 return -1;
8396 MovIdx = ShuffleMask[Start + i] / Length;
8397 break;
8398 }
8399 }
8400 // If all items are undef, leave this for other combines
8401 if (MovIdx == -1)
8402 return -1;
8403 // Check the remaining values are the correct part of the same mov
8404 for (int i = 1; i < Length; i++) {
8405 if (ShuffleMask[Start + i] >= 0 &&
8406 (ShuffleMask[Start + i] / Length != MovIdx ||
8407 ShuffleMask[Start + i] % Length != i))
8408 return -1;
8409 }
8410 return MovIdx;
8411 };
8412
8413 for (int Part = 0; Part < 4; ++Part) {
8414 // Does this part look like a mov
8415 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8416 if (Elt != -1) {
8417 SDValue Input = Op->getOperand(Num: 0);
8418 if (Elt >= 4) {
8419 Input = Op->getOperand(Num: 1);
8420 Elt -= 4;
8421 }
8422 SDValue BitCast = DAG.getBitcast(VT: MVT::v4f32, V: Input);
8423 Parts[Part] = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f32, N1: BitCast,
8424 N2: DAG.getConstant(Val: Elt, DL: dl, VT: MVT::i32));
8425 }
8426 }
8427
8428 // Nothing interesting found, just return
8429 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8430 return SDValue();
8431
8432 // The other parts need to be built with the old shuffle vector, cast to a
8433 // v4i32 and extract_vector_elts
8434 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8435 SmallVector<int, 16> NewShuffleMask;
8436 for (int Part = 0; Part < 4; ++Part)
8437 for (int i = 0; i < QuarterSize; i++)
8438 NewShuffleMask.push_back(
8439 Elt: Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8440 SDValue NewShuffle = DAG.getVectorShuffle(
8441 VT, dl, N1: Op->getOperand(Num: 0), N2: Op->getOperand(Num: 1), Mask: NewShuffleMask);
8442 SDValue BitCast = DAG.getBitcast(VT: MVT::v4f32, V: NewShuffle);
8443
8444 for (int Part = 0; Part < 4; ++Part)
8445 if (!Parts[Part])
8446 Parts[Part] = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f32,
8447 N1: BitCast, N2: DAG.getConstant(Val: Part, DL: dl, VT: MVT::i32));
8448 }
8449 // Build a vector out of the various parts and bitcast it back to the original
8450 // type.
8451 SDValue NewVec = DAG.getNode(Opcode: ARMISD::BUILD_VECTOR, DL: dl, VT: MVT::v4f32, Ops: Parts);
8452 return DAG.getBitcast(VT, V: NewVec);
8453}
8454
8455static SDValue LowerVECTOR_SHUFFLEUsingOneOff(SDValue Op,
8456 ArrayRef<int> ShuffleMask,
8457 SelectionDAG &DAG) {
8458 SDValue V1 = Op.getOperand(i: 0);
8459 SDValue V2 = Op.getOperand(i: 1);
8460 EVT VT = Op.getValueType();
8461 unsigned NumElts = VT.getVectorNumElements();
8462
8463 // An One-Off Identity mask is one that is mostly an identity mask from as
8464 // single source but contains a single element out-of-place, either from a
8465 // different vector or from another position in the same vector. As opposed to
8466 // lowering this via a ARMISD::BUILD_VECTOR we can generate an extract/insert
8467 // pair directly.
8468 auto isOneOffIdentityMask = [](ArrayRef<int> Mask, EVT VT, int BaseOffset,
8469 int &OffElement) {
8470 OffElement = -1;
8471 int NonUndef = 0;
8472 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
8473 if (Mask[i] == -1)
8474 continue;
8475 NonUndef++;
8476 if (Mask[i] != i + BaseOffset) {
8477 if (OffElement == -1)
8478 OffElement = i;
8479 else
8480 return false;
8481 }
8482 }
8483 return NonUndef > 2 && OffElement != -1;
8484 };
8485 int OffElement;
8486 SDValue VInput;
8487 if (isOneOffIdentityMask(ShuffleMask, VT, 0, OffElement))
8488 VInput = V1;
8489 else if (isOneOffIdentityMask(ShuffleMask, VT, NumElts, OffElement))
8490 VInput = V2;
8491 else
8492 return SDValue();
8493
8494 SDLoc dl(Op);
8495 EVT SVT = VT.getScalarType() == MVT::i8 || VT.getScalarType() == MVT::i16
8496 ? MVT::i32
8497 : VT.getScalarType();
8498 SDValue Elt = DAG.getNode(
8499 Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: SVT,
8500 N1: ShuffleMask[OffElement] < (int)NumElts ? V1 : V2,
8501 N2: DAG.getVectorIdxConstant(Val: ShuffleMask[OffElement] % NumElts, DL: dl));
8502 return DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT, N1: VInput, N2: Elt,
8503 N3: DAG.getVectorIdxConstant(Val: OffElement % NumElts, DL: dl));
8504}
8505
8506static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
8507 const ARMSubtarget *ST) {
8508 SDValue V1 = Op.getOperand(i: 0);
8509 SDValue V2 = Op.getOperand(i: 1);
8510 SDLoc dl(Op);
8511 EVT VT = Op.getValueType();
8512 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Val: Op.getNode());
8513 unsigned EltSize = VT.getScalarSizeInBits();
8514
8515 if (ST->hasMVEIntegerOps() && EltSize == 1)
8516 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8517
8518 // Convert shuffles that are directly supported on NEON to target-specific
8519 // DAG nodes, instead of keeping them as shuffles and matching them again
8520 // during code selection. This is more efficient and avoids the possibility
8521 // of inconsistencies between legalization and selection.
8522 // FIXME: floating-point vectors should be canonicalized to integer vectors
8523 // of the same time so that they get CSEd properly.
8524 ArrayRef<int> ShuffleMask = SVN->getMask();
8525
8526 if (EltSize <= 32) {
8527 if (SVN->isSplat()) {
8528 int Lane = SVN->getSplatIndex();
8529 // If this is undef splat, generate it via "just" vdup, if possible.
8530 if (Lane == -1) Lane = 0;
8531
8532 // Test if V1 is a SCALAR_TO_VECTOR.
8533 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8534 return DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT, Operand: V1.getOperand(i: 0));
8535 }
8536 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8537 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8538 // reaches it).
8539 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8540 !isa<ConstantSDNode>(Val: V1.getOperand(i: 0))) {
8541 bool IsScalarToVector = true;
8542 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8543 if (!V1.getOperand(i).isUndef()) {
8544 IsScalarToVector = false;
8545 break;
8546 }
8547 if (IsScalarToVector)
8548 return DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT, Operand: V1.getOperand(i: 0));
8549 }
8550 return DAG.getNode(Opcode: ARMISD::VDUPLANE, DL: dl, VT, N1: V1,
8551 N2: DAG.getConstant(Val: Lane, DL: dl, VT: MVT::i32));
8552 }
8553
8554 bool ReverseVEXT = false;
8555 unsigned Imm = 0;
8556 if (ST->hasNEON() && isVEXTMask(M: ShuffleMask, VT, ReverseVEXT, Imm)) {
8557 if (ReverseVEXT)
8558 std::swap(a&: V1, b&: V2);
8559 return DAG.getNode(Opcode: ARMISD::VEXT, DL: dl, VT, N1: V1, N2: V2,
8560 N3: DAG.getConstant(Val: Imm, DL: dl, VT: MVT::i32));
8561 }
8562
8563 if (isVREVMask(M: ShuffleMask, VT, BlockSize: 64))
8564 return DAG.getNode(Opcode: ARMISD::VREV64, DL: dl, VT, Operand: V1);
8565 if (isVREVMask(M: ShuffleMask, VT, BlockSize: 32))
8566 return DAG.getNode(Opcode: ARMISD::VREV32, DL: dl, VT, Operand: V1);
8567 if (isVREVMask(M: ShuffleMask, VT, BlockSize: 16))
8568 return DAG.getNode(Opcode: ARMISD::VREV16, DL: dl, VT, Operand: V1);
8569
8570 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(M: ShuffleMask, VT, Imm)) {
8571 return DAG.getNode(Opcode: ARMISD::VEXT, DL: dl, VT, N1: V1, N2: V1,
8572 N3: DAG.getConstant(Val: Imm, DL: dl, VT: MVT::i32));
8573 }
8574
8575 // Check for Neon shuffles that modify both input vectors in place.
8576 // If both results are used, i.e., if there are two shuffles with the same
8577 // source operands and with masks corresponding to both results of one of
8578 // these operations, DAG memoization will ensure that a single node is
8579 // used for both shuffles.
8580 unsigned WhichResult = 0;
8581 bool isV_UNDEF = false;
8582 if (ST->hasNEON()) {
8583 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8584 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8585 if (isV_UNDEF)
8586 V2 = V1;
8587 return DAG.getNode(Opcode: ShuffleOpc, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT), N1: V1, N2: V2)
8588 .getValue(R: WhichResult);
8589 }
8590 }
8591 if (ST->hasMVEIntegerOps()) {
8592 if (isVMOVNMask(M: ShuffleMask, VT, Top: false, SingleSource: false))
8593 return DAG.getNode(Opcode: ARMISD::VMOVN, DL: dl, VT, N1: V2, N2: V1,
8594 N3: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
8595 if (isVMOVNMask(M: ShuffleMask, VT, Top: true, SingleSource: false))
8596 return DAG.getNode(Opcode: ARMISD::VMOVN, DL: dl, VT, N1: V1, N2: V2,
8597 N3: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
8598 if (isVMOVNMask(M: ShuffleMask, VT, Top: true, SingleSource: true))
8599 return DAG.getNode(Opcode: ARMISD::VMOVN, DL: dl, VT, N1: V1, N2: V1,
8600 N3: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
8601 }
8602
8603 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8604 // shuffles that produce a result larger than their operands with:
8605 // shuffle(concat(v1, undef), concat(v2, undef))
8606 // ->
8607 // shuffle(concat(v1, v2), undef)
8608 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8609 //
8610 // This is useful in the general case, but there are special cases where
8611 // native shuffles produce larger results: the two-result ops.
8612 //
8613 // Look through the concat when lowering them:
8614 // shuffle(concat(v1, v2), undef)
8615 // ->
8616 // concat(VZIP(v1, v2):0, :1)
8617 //
8618 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8619 SDValue SubV1 = V1->getOperand(Num: 0);
8620 SDValue SubV2 = V1->getOperand(Num: 1);
8621 EVT SubVT = SubV1.getValueType();
8622
8623 // We expect these to have been canonicalized to -1.
8624 assert(llvm::all_of(ShuffleMask, [&](int i) {
8625 return i < (int)VT.getVectorNumElements();
8626 }) && "Unexpected shuffle index into UNDEF operand!");
8627
8628 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8629 ShuffleMask, VT: SubVT, WhichResult, isV_UNDEF)) {
8630 if (isV_UNDEF)
8631 SubV2 = SubV1;
8632 assert((WhichResult == 0) &&
8633 "In-place shuffle of concat can only have one result!");
8634 SDValue Res = DAG.getNode(Opcode: ShuffleOpc, DL: dl, VTList: DAG.getVTList(VT1: SubVT, VT2: SubVT),
8635 N1: SubV1, N2: SubV2);
8636 return DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: dl, VT, N1: Res.getValue(R: 0),
8637 N2: Res.getValue(R: 1));
8638 }
8639 }
8640 }
8641
8642 if (ST->hasMVEIntegerOps() && EltSize <= 32) {
8643 if (SDValue V = LowerVECTOR_SHUFFLEUsingOneOff(Op, ShuffleMask, DAG))
8644 return V;
8645
8646 for (bool Top : {false, true}) {
8647 for (bool SingleSource : {false, true}) {
8648 if (isTruncMask(M: ShuffleMask, VT, Top, SingleSource)) {
8649 MVT FromSVT = MVT::getIntegerVT(BitWidth: EltSize * 2);
8650 MVT FromVT = MVT::getVectorVT(VT: FromSVT, NumElements: ShuffleMask.size() / 2);
8651 SDValue Lo = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: FromVT, Operand: V1);
8652 SDValue Hi = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: FromVT,
8653 Operand: SingleSource ? V1 : V2);
8654 if (Top) {
8655 SDValue Amt = DAG.getConstant(Val: EltSize, DL: dl, VT: FromVT);
8656 Lo = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: FromVT, N1: Lo, N2: Amt);
8657 Hi = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: FromVT, N1: Hi, N2: Amt);
8658 }
8659 return DAG.getNode(Opcode: ARMISD::MVETRUNC, DL: dl, VT, N1: Lo, N2: Hi);
8660 }
8661 }
8662 }
8663 }
8664
8665 // If the shuffle is not directly supported and it has 4 elements, use
8666 // the PerfectShuffle-generated table to synthesize it from other shuffles.
8667 unsigned NumElts = VT.getVectorNumElements();
8668 if (NumElts == 4) {
8669 unsigned PFIndexes[4];
8670 for (unsigned i = 0; i != 4; ++i) {
8671 if (ShuffleMask[i] < 0)
8672 PFIndexes[i] = 8;
8673 else
8674 PFIndexes[i] = ShuffleMask[i];
8675 }
8676
8677 // Compute the index in the perfect shuffle table.
8678 unsigned PFTableIndex =
8679 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8680 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8681 unsigned Cost = (PFEntry >> 30);
8682
8683 if (Cost <= 4) {
8684 if (ST->hasNEON())
8685 return GeneratePerfectShuffle(PFEntry, LHS: V1, RHS: V2, DAG, dl);
8686 else if (isLegalMVEShuffleOp(PFEntry)) {
8687 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8688 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8689 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8690 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8691 if (isLegalMVEShuffleOp(PFEntry: PFEntryLHS) && isLegalMVEShuffleOp(PFEntry: PFEntryRHS))
8692 return GeneratePerfectShuffle(PFEntry, LHS: V1, RHS: V2, DAG, dl);
8693 }
8694 }
8695 }
8696
8697 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8698 if (EltSize >= 32) {
8699 // Do the expansion with floating-point types, since that is what the VFP
8700 // registers are defined to use, and since i64 is not legal.
8701 EVT EltVT = EVT::getFloatingPointVT(BitWidth: EltSize);
8702 EVT VecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: EltVT, NumElements: NumElts);
8703 V1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VecVT, Operand: V1);
8704 V2 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VecVT, Operand: V2);
8705 SmallVector<SDValue, 8> Ops;
8706 for (unsigned i = 0; i < NumElts; ++i) {
8707 if (ShuffleMask[i] < 0)
8708 Ops.push_back(Elt: DAG.getUNDEF(VT: EltVT));
8709 else
8710 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT,
8711 N1: ShuffleMask[i] < (int)NumElts ? V1 : V2,
8712 N2: DAG.getConstant(Val: ShuffleMask[i] & (NumElts-1),
8713 DL: dl, VT: MVT::i32)));
8714 }
8715 SDValue Val = DAG.getNode(Opcode: ARMISD::BUILD_VECTOR, DL: dl, VT: VecVT, Ops);
8716 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Val);
8717 }
8718
8719 if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8720 isReverseMask(M: ShuffleMask, VT))
8721 return LowerReverse_VECTOR_SHUFFLE(Op, DAG);
8722
8723 if (ST->hasNEON() && VT == MVT::v8i8)
8724 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8725 return NewOp;
8726
8727 if (ST->hasMVEIntegerOps())
8728 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8729 return NewOp;
8730
8731 return SDValue();
8732}
8733
8734static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8735 const ARMSubtarget *ST) {
8736 EVT VecVT = Op.getOperand(i: 0).getValueType();
8737 SDLoc dl(Op);
8738
8739 assert(ST->hasMVEIntegerOps() &&
8740 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8741
8742 SDValue Conv =
8743 DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::i32, Operand: Op->getOperand(Num: 0));
8744 unsigned Lane = Op.getConstantOperandVal(i: 2);
8745 unsigned LaneWidth =
8746 getVectorTyFromPredicateVector(VT: VecVT).getScalarSizeInBits() / 8;
8747 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8748 SDValue Ext = DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL: dl, VT: MVT::i32,
8749 N1: Op.getOperand(i: 1), N2: DAG.getValueType(MVT::i1));
8750 SDValue BFI = DAG.getNode(Opcode: ARMISD::BFI, DL: dl, VT: MVT::i32, N1: Conv, N2: Ext,
8751 N3: DAG.getConstant(Val: ~Mask, DL: dl, VT: MVT::i32));
8752 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: Op.getValueType(), Operand: BFI);
8753}
8754
8755SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8756 SelectionDAG &DAG) const {
8757 // INSERT_VECTOR_ELT is legal only for immediate indexes.
8758 SDValue Lane = Op.getOperand(i: 2);
8759 if (!isa<ConstantSDNode>(Val: Lane))
8760 return SDValue();
8761
8762 SDValue Elt = Op.getOperand(i: 1);
8763 EVT EltVT = Elt.getValueType();
8764
8765 if (Subtarget->hasMVEIntegerOps() &&
8766 Op.getValueType().getScalarSizeInBits() == 1)
8767 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, ST: Subtarget);
8768
8769 if (getTypeAction(Context&: *DAG.getContext(), VT: EltVT) ==
8770 TargetLowering::TypeSoftPromoteHalf) {
8771 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8772 // but the type system will try to do that if we don't intervene.
8773 // Reinterpret any such vector-element insertion as one with the
8774 // corresponding integer types.
8775
8776 SDLoc dl(Op);
8777
8778 EVT IEltVT = MVT::getIntegerVT(BitWidth: EltVT.getScalarSizeInBits());
8779 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8780 TargetLowering::TypeSoftPromoteHalf);
8781
8782 SDValue VecIn = Op.getOperand(i: 0);
8783 EVT VecVT = VecIn.getValueType();
8784 EVT IVecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: IEltVT,
8785 NumElements: VecVT.getVectorNumElements());
8786
8787 SDValue IElt = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: IEltVT, Operand: Elt);
8788 SDValue IVecIn = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: IVecVT, Operand: VecIn);
8789 SDValue IVecOut = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: IVecVT,
8790 N1: IVecIn, N2: IElt, N3: Lane);
8791 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VecVT, Operand: IVecOut);
8792 }
8793
8794 return Op;
8795}
8796
8797static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8798 const ARMSubtarget *ST) {
8799 EVT VecVT = Op.getOperand(i: 0).getValueType();
8800 SDLoc dl(Op);
8801
8802 assert(ST->hasMVEIntegerOps() &&
8803 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8804
8805 SDValue Conv =
8806 DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::i32, Operand: Op->getOperand(Num: 0));
8807 unsigned Lane = Op.getConstantOperandVal(i: 1);
8808 unsigned LaneWidth =
8809 getVectorTyFromPredicateVector(VT: VecVT).getScalarSizeInBits() / 8;
8810 SDValue Shift = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32, N1: Conv,
8811 N2: DAG.getConstant(Val: Lane * LaneWidth, DL: dl, VT: MVT::i32));
8812 return Shift;
8813}
8814
8815static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8816 const ARMSubtarget *ST) {
8817 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8818 SDValue Lane = Op.getOperand(i: 1);
8819 if (!isa<ConstantSDNode>(Val: Lane))
8820 return SDValue();
8821
8822 SDValue Vec = Op.getOperand(i: 0);
8823 EVT VT = Vec.getValueType();
8824
8825 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8826 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8827
8828 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8829 SDLoc dl(Op);
8830 return DAG.getNode(Opcode: ARMISD::VGETLANEu, DL: dl, VT: MVT::i32, N1: Vec, N2: Lane);
8831 }
8832
8833 return Op;
8834}
8835
8836static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8837 const ARMSubtarget *ST) {
8838 SDLoc dl(Op);
8839 assert(Op.getValueType().getScalarSizeInBits() == 1 &&
8840 "Unexpected custom CONCAT_VECTORS lowering");
8841 assert(isPowerOf2_32(Op.getNumOperands()) &&
8842 "Unexpected custom CONCAT_VECTORS lowering");
8843 assert(ST->hasMVEIntegerOps() &&
8844 "CONCAT_VECTORS lowering only supported for MVE");
8845
8846 auto ConcatPair = [&](SDValue V1, SDValue V2) {
8847 EVT Op1VT = V1.getValueType();
8848 EVT Op2VT = V2.getValueType();
8849 assert(Op1VT == Op2VT && "Operand types don't match!");
8850 assert((Op1VT == MVT::v2i1 || Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) &&
8851 "Unexpected i1 concat operations!");
8852 EVT VT = Op1VT.getDoubleNumVectorElementsVT(Context&: *DAG.getContext());
8853
8854 SDValue NewV1 = PromoteMVEPredVector(dl, Pred: V1, VT: Op1VT, DAG);
8855 SDValue NewV2 = PromoteMVEPredVector(dl, Pred: V2, VT: Op2VT, DAG);
8856
8857 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8858 // promoted to v8i16, etc.
8859 MVT ElType =
8860 getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8861 unsigned NumElts = 2 * Op1VT.getVectorNumElements();
8862
8863 EVT ConcatVT = MVT::getVectorVT(VT: ElType, NumElements: NumElts);
8864 if (Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) {
8865 // Use MVETRUNC to truncate the combined NewV1::NewV2 into the smaller
8866 // ConcatVT.
8867 SDValue ConVec =
8868 DAG.getNode(Opcode: ARMISD::MVETRUNC, DL: dl, VT: ConcatVT, N1: NewV1, N2: NewV2);
8869 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: ConVec,
8870 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8871 }
8872
8873 // Extract the vector elements from Op1 and Op2 one by one and truncate them
8874 // to be the right size for the destination. For example, if Op1 is v4i1
8875 // then the promoted vector is v4i32. The result of concatenation gives a
8876 // v8i1, which when promoted is v8i16. That means each i32 element from Op1
8877 // needs truncating to i16 and inserting in the result.
8878 auto ExtractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8879 EVT NewVT = NewV.getValueType();
8880 EVT ConcatVT = ConVec.getValueType();
8881 unsigned ExtScale = 1;
8882 if (NewVT == MVT::v2f64) {
8883 NewV = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: NewV);
8884 ExtScale = 2;
8885 }
8886 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8887 SDValue Elt = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::i32, N1: NewV,
8888 N2: DAG.getIntPtrConstant(Val: i * ExtScale, DL: dl));
8889 ConVec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: ConcatVT, N1: ConVec, N2: Elt,
8890 N3: DAG.getConstant(Val: j, DL: dl, VT: MVT::i32));
8891 }
8892 return ConVec;
8893 };
8894 unsigned j = 0;
8895 SDValue ConVec = DAG.getNode(Opcode: ISD::UNDEF, DL: dl, VT: ConcatVT);
8896 ConVec = ExtractInto(NewV1, ConVec, j);
8897 ConVec = ExtractInto(NewV2, ConVec, j);
8898
8899 // Now return the result of comparing the subvector with zero, which will
8900 // generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8901 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: ConVec,
8902 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8903 };
8904
8905 // Concat each pair of subvectors and pack into the lower half of the array.
8906 SmallVector<SDValue> ConcatOps(Op->ops());
8907 while (ConcatOps.size() > 1) {
8908 for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
8909 SDValue V1 = ConcatOps[I];
8910 SDValue V2 = ConcatOps[I + 1];
8911 ConcatOps[I / 2] = ConcatPair(V1, V2);
8912 }
8913 ConcatOps.resize(N: ConcatOps.size() / 2);
8914 }
8915 return ConcatOps[0];
8916}
8917
8918static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8919 const ARMSubtarget *ST) {
8920 EVT VT = Op->getValueType(ResNo: 0);
8921 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8922 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8923
8924 // The only time a CONCAT_VECTORS operation can have legal types is when
8925 // two 64-bit vectors are concatenated to a 128-bit vector.
8926 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8927 "unexpected CONCAT_VECTORS");
8928 SDLoc dl(Op);
8929 SDValue Val = DAG.getUNDEF(VT: MVT::v2f64);
8930 SDValue Op0 = Op.getOperand(i: 0);
8931 SDValue Op1 = Op.getOperand(i: 1);
8932 if (!Op0.isUndef())
8933 Val = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: MVT::v2f64, N1: Val,
8934 N2: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f64, Operand: Op0),
8935 N3: DAG.getIntPtrConstant(Val: 0, DL: dl));
8936 if (!Op1.isUndef())
8937 Val = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: MVT::v2f64, N1: Val,
8938 N2: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f64, Operand: Op1),
8939 N3: DAG.getIntPtrConstant(Val: 1, DL: dl));
8940 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: Op.getValueType(), Operand: Val);
8941}
8942
8943static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8944 const ARMSubtarget *ST) {
8945 SDValue V1 = Op.getOperand(i: 0);
8946 SDValue V2 = Op.getOperand(i: 1);
8947 SDLoc dl(Op);
8948 EVT VT = Op.getValueType();
8949 EVT Op1VT = V1.getValueType();
8950 unsigned NumElts = VT.getVectorNumElements();
8951 unsigned Index = V2->getAsZExtVal();
8952
8953 assert(VT.getScalarSizeInBits() == 1 &&
8954 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8955 assert(ST->hasMVEIntegerOps() &&
8956 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8957
8958 SDValue NewV1 = PromoteMVEPredVector(dl, Pred: V1, VT: Op1VT, DAG);
8959
8960 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8961 // promoted to v8i16, etc.
8962
8963 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8964
8965 if (NumElts == 2) {
8966 EVT SubVT = MVT::v4i32;
8967 SDValue SubVec = DAG.getNode(Opcode: ISD::UNDEF, DL: dl, VT: SubVT);
8968 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j += 2) {
8969 SDValue Elt = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::i32, N1: NewV1,
8970 N2: DAG.getIntPtrConstant(Val: i, DL: dl));
8971 SubVec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: SubVT, N1: SubVec, N2: Elt,
8972 N3: DAG.getConstant(Val: j, DL: dl, VT: MVT::i32));
8973 SubVec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: SubVT, N1: SubVec, N2: Elt,
8974 N3: DAG.getConstant(Val: j + 1, DL: dl, VT: MVT::i32));
8975 }
8976 SDValue Cmp = DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT: MVT::v4i1, N1: SubVec,
8977 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8978 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::v2i1, Operand: Cmp);
8979 }
8980
8981 EVT SubVT = MVT::getVectorVT(VT: ElType, NumElements: NumElts);
8982 SDValue SubVec = DAG.getNode(Opcode: ISD::UNDEF, DL: dl, VT: SubVT);
8983 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8984 SDValue Elt = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::i32, N1: NewV1,
8985 N2: DAG.getIntPtrConstant(Val: i, DL: dl));
8986 SubVec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: SubVT, N1: SubVec, N2: Elt,
8987 N3: DAG.getConstant(Val: j, DL: dl, VT: MVT::i32));
8988 }
8989
8990 // Now return the result of comparing the subvector with zero,
8991 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8992 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: SubVec,
8993 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8994}
8995
8996// Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0).
8997static SDValue LowerTruncatei1(SDNode *N, SelectionDAG &DAG,
8998 const ARMSubtarget *ST) {
8999 assert(ST->hasMVEIntegerOps() && "Expected MVE!");
9000 EVT VT = N->getValueType(ResNo: 0);
9001 assert((VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) &&
9002 "Expected a vector i1 type!");
9003 SDValue Op = N->getOperand(Num: 0);
9004 EVT FromVT = Op.getValueType();
9005 SDLoc DL(N);
9006
9007 SDValue And =
9008 DAG.getNode(Opcode: ISD::AND, DL, VT: FromVT, N1: Op, N2: DAG.getConstant(Val: 1, DL, VT: FromVT));
9009 return DAG.getNode(Opcode: ISD::SETCC, DL, VT, N1: And, N2: DAG.getConstant(Val: 0, DL, VT: FromVT),
9010 N3: DAG.getCondCode(Cond: ISD::SETNE));
9011}
9012
9013static SDValue LowerTruncate(SDNode *N, SelectionDAG &DAG,
9014 const ARMSubtarget *Subtarget) {
9015 if (!Subtarget->hasMVEIntegerOps())
9016 return SDValue();
9017
9018 EVT ToVT = N->getValueType(ResNo: 0);
9019 if (ToVT.getScalarType() == MVT::i1)
9020 return LowerTruncatei1(N, DAG, ST: Subtarget);
9021
9022 // MVE does not have a single instruction to perform the truncation of a v4i32
9023 // into the lower half of a v8i16, in the same way that a NEON vmovn would.
9024 // Most of the instructions in MVE follow the 'Beats' system, where moving
9025 // values from different lanes is usually something that the instructions
9026 // avoid.
9027 //
9028 // Instead it has top/bottom instructions such as VMOVLT/B and VMOVNT/B,
9029 // which take a the top/bottom half of a larger lane and extend it (or do the
9030 // opposite, truncating into the top/bottom lane from a larger lane). Note
9031 // that because of the way we widen lanes, a v4i16 is really a v4i32 using the
9032 // bottom 16bits from each vector lane. This works really well with T/B
9033 // instructions, but that doesn't extend to v8i32->v8i16 where the lanes need
9034 // to move order.
9035 //
9036 // But truncates and sext/zext are always going to be fairly common from llvm.
9037 // We have several options for how to deal with them:
9038 // - Wherever possible combine them into an instruction that makes them
9039 // "free". This includes loads/stores, which can perform the trunc as part
9040 // of the memory operation. Or certain shuffles that can be turned into
9041 // VMOVN/VMOVL.
9042 // - Lane Interleaving to transform blocks surrounded by ext/trunc. So
9043 // trunc(mul(sext(a), sext(b))) may become
9044 // VMOVNT(VMUL(VMOVLB(a), VMOVLB(b)), VMUL(VMOVLT(a), VMOVLT(b))). (Which in
9045 // this case can use VMULL). This is performed in the
9046 // MVELaneInterleavingPass.
9047 // - Otherwise we have an option. By default we would expand the
9048 // zext/sext/trunc into a series of lane extract/inserts going via GPR
9049 // registers. One for each vector lane in the vector. This can obviously be
9050 // very expensive.
9051 // - The other option is to use the fact that loads/store can extend/truncate
9052 // to turn a trunc into two truncating stack stores and a stack reload. This
9053 // becomes 3 back-to-back memory operations, but at least that is less than
9054 // all the insert/extracts.
9055 //
9056 // In order to do the last, we convert certain trunc's into MVETRUNC, which
9057 // are either optimized where they can be, or eventually lowered into stack
9058 // stores/loads. This prevents us from splitting a v8i16 trunc into two stores
9059 // two early, where other instructions would be better, and stops us from
9060 // having to reconstruct multiple buildvector shuffles into loads/stores.
9061 if (ToVT != MVT::v8i16 && ToVT != MVT::v16i8)
9062 return SDValue();
9063 EVT FromVT = N->getOperand(Num: 0).getValueType();
9064 if (FromVT != MVT::v8i32 && FromVT != MVT::v16i16)
9065 return SDValue();
9066
9067 SDValue Lo, Hi;
9068 std::tie(args&: Lo, args&: Hi) = DAG.SplitVectorOperand(N, OpNo: 0);
9069 SDLoc DL(N);
9070 return DAG.getNode(Opcode: ARMISD::MVETRUNC, DL, VT: ToVT, N1: Lo, N2: Hi);
9071}
9072
9073static SDValue LowerVectorExtend(SDNode *N, SelectionDAG &DAG,
9074 const ARMSubtarget *Subtarget) {
9075 if (!Subtarget->hasMVEIntegerOps())
9076 return SDValue();
9077
9078 // See LowerTruncate above for an explanation of MVEEXT/MVETRUNC.
9079
9080 EVT ToVT = N->getValueType(ResNo: 0);
9081 if (ToVT != MVT::v16i32 && ToVT != MVT::v8i32 && ToVT != MVT::v16i16)
9082 return SDValue();
9083 SDValue Op = N->getOperand(Num: 0);
9084 EVT FromVT = Op.getValueType();
9085 if (FromVT != MVT::v8i16 && FromVT != MVT::v16i8)
9086 return SDValue();
9087
9088 SDLoc DL(N);
9089 EVT ExtVT = ToVT.getHalfNumVectorElementsVT(Context&: *DAG.getContext());
9090 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8)
9091 ExtVT = MVT::v8i16;
9092
9093 unsigned Opcode =
9094 N->getOpcode() == ISD::SIGN_EXTEND ? ARMISD::MVESEXT : ARMISD::MVEZEXT;
9095 SDValue Ext = DAG.getNode(Opcode, DL, VTList: DAG.getVTList(VT1: ExtVT, VT2: ExtVT), N: Op);
9096 SDValue Ext1 = Ext.getValue(R: 1);
9097
9098 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8) {
9099 Ext = DAG.getNode(Opcode: N->getOpcode(), DL, VT: MVT::v8i32, Operand: Ext);
9100 Ext1 = DAG.getNode(Opcode: N->getOpcode(), DL, VT: MVT::v8i32, Operand: Ext1);
9101 }
9102
9103 return DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: ToVT, N1: Ext, N2: Ext1);
9104}
9105
9106/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
9107/// element has been zero/sign-extended, depending on the isSigned parameter,
9108/// from an integer type half its size.
9109static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
9110 bool isSigned) {
9111 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
9112 EVT VT = N->getValueType(ResNo: 0);
9113 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
9114 SDNode *BVN = N->getOperand(Num: 0).getNode();
9115 if (BVN->getValueType(ResNo: 0) != MVT::v4i32 ||
9116 BVN->getOpcode() != ISD::BUILD_VECTOR)
9117 return false;
9118 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9119 unsigned HiElt = 1 - LoElt;
9120 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(Val: BVN->getOperand(Num: LoElt));
9121 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(Val: BVN->getOperand(Num: HiElt));
9122 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(Val: BVN->getOperand(Num: LoElt+2));
9123 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(Val: BVN->getOperand(Num: HiElt+2));
9124 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
9125 return false;
9126 if (isSigned) {
9127 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
9128 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
9129 return true;
9130 } else {
9131 if (Hi0->isZero() && Hi1->isZero())
9132 return true;
9133 }
9134 return false;
9135 }
9136
9137 if (N->getOpcode() != ISD::BUILD_VECTOR)
9138 return false;
9139
9140 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9141 SDNode *Elt = N->getOperand(Num: i).getNode();
9142 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val: Elt)) {
9143 unsigned EltSize = VT.getScalarSizeInBits();
9144 unsigned HalfSize = EltSize / 2;
9145 if (isSigned) {
9146 if (!isIntN(N: HalfSize, x: C->getSExtValue()))
9147 return false;
9148 } else {
9149 if (!isUIntN(N: HalfSize, x: C->getZExtValue()))
9150 return false;
9151 }
9152 continue;
9153 }
9154 return false;
9155 }
9156
9157 return true;
9158}
9159
9160/// isSignExtended - Check if a node is a vector value that is sign-extended
9161/// or a constant BUILD_VECTOR with sign-extended elements.
9162static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
9163 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
9164 return true;
9165 if (isExtendedBUILD_VECTOR(N, DAG, isSigned: true))
9166 return true;
9167 return false;
9168}
9169
9170/// isZeroExtended - Check if a node is a vector value that is zero-extended (or
9171/// any-extended) or a constant BUILD_VECTOR with zero-extended elements.
9172static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
9173 if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND ||
9174 ISD::isZEXTLoad(N))
9175 return true;
9176 if (isExtendedBUILD_VECTOR(N, DAG, isSigned: false))
9177 return true;
9178 return false;
9179}
9180
9181static EVT getExtensionTo64Bits(const EVT &OrigVT) {
9182 if (OrigVT.getSizeInBits() >= 64)
9183 return OrigVT;
9184
9185 assert(OrigVT.isSimple() && "Expecting a simple value type");
9186
9187 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
9188 switch (OrigSimpleTy) {
9189 default: llvm_unreachable("Unexpected Vector Type");
9190 case MVT::v2i8:
9191 case MVT::v2i16:
9192 return MVT::v2i32;
9193 case MVT::v4i8:
9194 return MVT::v4i16;
9195 }
9196}
9197
9198/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
9199/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
9200/// We insert the required extension here to get the vector to fill a D register.
9201static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
9202 const EVT &OrigTy,
9203 const EVT &ExtTy,
9204 unsigned ExtOpcode) {
9205 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
9206 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
9207 // 64-bits we need to insert a new extension so that it will be 64-bits.
9208 assert(ExtTy.is128BitVector() && "Unexpected extension size");
9209 if (OrigTy.getSizeInBits() >= 64)
9210 return N;
9211
9212 // Must extend size to at least 64 bits to be used as an operand for VMULL.
9213 EVT NewVT = getExtensionTo64Bits(OrigVT: OrigTy);
9214
9215 return DAG.getNode(Opcode: ExtOpcode, DL: SDLoc(N), VT: NewVT, Operand: N);
9216}
9217
9218/// SkipLoadExtensionForVMULL - return a load of the original vector size that
9219/// does not do any sign/zero extension. If the original vector is less
9220/// than 64 bits, an appropriate extension will be added after the load to
9221/// reach a total size of 64 bits. We have to add the extension separately
9222/// because ARM does not have a sign/zero extending load for vectors.
9223static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
9224 EVT ExtendedTy = getExtensionTo64Bits(OrigVT: LD->getMemoryVT());
9225
9226 // The load already has the right type.
9227 if (ExtendedTy == LD->getMemoryVT())
9228 return DAG.getLoad(VT: LD->getMemoryVT(), dl: SDLoc(LD), Chain: LD->getChain(),
9229 Ptr: LD->getBasePtr(), PtrInfo: LD->getPointerInfo(), Alignment: LD->getAlign(),
9230 MMOFlags: LD->getMemOperand()->getFlags());
9231
9232 // We need to create a zextload/sextload. We cannot just create a load
9233 // followed by a zext/zext node because LowerMUL is also run during normal
9234 // operation legalization where we can't create illegal types.
9235 return DAG.getExtLoad(ExtType: LD->getExtensionType(), dl: SDLoc(LD), VT: ExtendedTy,
9236 Chain: LD->getChain(), Ptr: LD->getBasePtr(), PtrInfo: LD->getPointerInfo(),
9237 MemVT: LD->getMemoryVT(), Alignment: LD->getAlign(),
9238 MMOFlags: LD->getMemOperand()->getFlags());
9239}
9240
9241/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
9242/// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return
9243/// the unextended value. The unextended vector should be 64 bits so that it can
9244/// be used as an operand to a VMULL instruction. If the original vector size
9245/// before extension is less than 64 bits we add a an extension to resize
9246/// the vector to 64 bits.
9247static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
9248 if (N->getOpcode() == ISD::SIGN_EXTEND ||
9249 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
9250 return AddRequiredExtensionForVMULL(N: N->getOperand(Num: 0), DAG,
9251 OrigTy: N->getOperand(Num: 0)->getValueType(ResNo: 0),
9252 ExtTy: N->getValueType(ResNo: 0),
9253 ExtOpcode: N->getOpcode());
9254
9255 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: N)) {
9256 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
9257 "Expected extending load");
9258
9259 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
9260 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 1), To: newLoad.getValue(R: 1));
9261 unsigned Opcode = ISD::isSEXTLoad(N: LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9262 SDValue extLoad =
9263 DAG.getNode(Opcode, DL: SDLoc(newLoad), VT: LD->getValueType(ResNo: 0), Operand: newLoad);
9264 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 0), To: extLoad);
9265
9266 return newLoad;
9267 }
9268
9269 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
9270 // have been legalized as a BITCAST from v4i32.
9271 if (N->getOpcode() == ISD::BITCAST) {
9272 SDNode *BVN = N->getOperand(Num: 0).getNode();
9273 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
9274 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
9275 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9276 return DAG.getBuildVector(
9277 VT: MVT::v2i32, DL: SDLoc(N),
9278 Ops: {BVN->getOperand(Num: LowElt), BVN->getOperand(Num: LowElt + 2)});
9279 }
9280 // Construct a new BUILD_VECTOR with elements truncated to half the size.
9281 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
9282 EVT VT = N->getValueType(ResNo: 0);
9283 unsigned EltSize = VT.getScalarSizeInBits() / 2;
9284 unsigned NumElts = VT.getVectorNumElements();
9285 MVT TruncVT = MVT::getIntegerVT(BitWidth: EltSize);
9286 SmallVector<SDValue, 8> Ops;
9287 SDLoc dl(N);
9288 for (unsigned i = 0; i != NumElts; ++i) {
9289 const APInt &CInt = N->getConstantOperandAPInt(Num: i);
9290 // Element types smaller than 32 bits are not legal, so use i32 elements.
9291 // The values are implicitly truncated so sext vs. zext doesn't matter.
9292 Ops.push_back(Elt: DAG.getConstant(Val: CInt.zextOrTrunc(width: 32), DL: dl, VT: MVT::i32));
9293 }
9294 return DAG.getBuildVector(VT: MVT::getVectorVT(VT: TruncVT, NumElements: NumElts), DL: dl, Ops);
9295}
9296
9297static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
9298 unsigned Opcode = N->getOpcode();
9299 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9300 SDNode *N0 = N->getOperand(Num: 0).getNode();
9301 SDNode *N1 = N->getOperand(Num: 1).getNode();
9302 return N0->hasOneUse() && N1->hasOneUse() &&
9303 isSignExtended(N: N0, DAG) && isSignExtended(N: N1, DAG);
9304 }
9305 return false;
9306}
9307
9308static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
9309 unsigned Opcode = N->getOpcode();
9310 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9311 SDNode *N0 = N->getOperand(Num: 0).getNode();
9312 SDNode *N1 = N->getOperand(Num: 1).getNode();
9313 return N0->hasOneUse() && N1->hasOneUse() &&
9314 isZeroExtended(N: N0, DAG) && isZeroExtended(N: N1, DAG);
9315 }
9316 return false;
9317}
9318
9319static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
9320 // Multiplications are only custom-lowered for 128-bit vectors so that
9321 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
9322 EVT VT = Op.getValueType();
9323 assert(VT.is128BitVector() && VT.isInteger() &&
9324 "unexpected type for custom-lowering ISD::MUL");
9325 SDNode *N0 = Op.getOperand(i: 0).getNode();
9326 SDNode *N1 = Op.getOperand(i: 1).getNode();
9327 unsigned NewOpc = 0;
9328 bool isMLA = false;
9329 bool isN0SExt = isSignExtended(N: N0, DAG);
9330 bool isN1SExt = isSignExtended(N: N1, DAG);
9331 if (isN0SExt && isN1SExt)
9332 NewOpc = ARMISD::VMULLs;
9333 else {
9334 bool isN0ZExt = isZeroExtended(N: N0, DAG);
9335 bool isN1ZExt = isZeroExtended(N: N1, DAG);
9336 if (isN0ZExt && isN1ZExt)
9337 NewOpc = ARMISD::VMULLu;
9338 else if (isN1SExt || isN1ZExt) {
9339 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
9340 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
9341 if (isN1SExt && isAddSubSExt(N: N0, DAG)) {
9342 NewOpc = ARMISD::VMULLs;
9343 isMLA = true;
9344 } else if (isN1ZExt && isAddSubZExt(N: N0, DAG)) {
9345 NewOpc = ARMISD::VMULLu;
9346 isMLA = true;
9347 } else if (isN0ZExt && isAddSubZExt(N: N1, DAG)) {
9348 std::swap(a&: N0, b&: N1);
9349 NewOpc = ARMISD::VMULLu;
9350 isMLA = true;
9351 }
9352 }
9353
9354 if (!NewOpc) {
9355 if (VT == MVT::v2i64)
9356 // Fall through to expand this. It is not legal.
9357 return SDValue();
9358 else
9359 // Other vector multiplications are legal.
9360 return Op;
9361 }
9362 }
9363
9364 // Legalize to a VMULL instruction.
9365 SDLoc DL(Op);
9366 SDValue Op0;
9367 SDValue Op1 = SkipExtensionForVMULL(N: N1, DAG);
9368 if (!isMLA) {
9369 Op0 = SkipExtensionForVMULL(N: N0, DAG);
9370 assert(Op0.getValueType().is64BitVector() &&
9371 Op1.getValueType().is64BitVector() &&
9372 "unexpected types for extended operands to VMULL");
9373 return DAG.getNode(Opcode: NewOpc, DL, VT, N1: Op0, N2: Op1);
9374 }
9375
9376 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
9377 // isel lowering to take advantage of no-stall back to back vmul + vmla.
9378 // vmull q0, d4, d6
9379 // vmlal q0, d5, d6
9380 // is faster than
9381 // vaddl q0, d4, d5
9382 // vmovl q1, d6
9383 // vmul q0, q0, q1
9384 SDValue N00 = SkipExtensionForVMULL(N: N0->getOperand(Num: 0).getNode(), DAG);
9385 SDValue N01 = SkipExtensionForVMULL(N: N0->getOperand(Num: 1).getNode(), DAG);
9386 EVT Op1VT = Op1.getValueType();
9387 return DAG.getNode(Opcode: N0->getOpcode(), DL, VT,
9388 N1: DAG.getNode(Opcode: NewOpc, DL, VT,
9389 N1: DAG.getNode(Opcode: ISD::BITCAST, DL, VT: Op1VT, Operand: N00), N2: Op1),
9390 N2: DAG.getNode(Opcode: NewOpc, DL, VT,
9391 N1: DAG.getNode(Opcode: ISD::BITCAST, DL, VT: Op1VT, Operand: N01), N2: Op1));
9392}
9393
9394static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
9395 SelectionDAG &DAG) {
9396 // TODO: Should this propagate fast-math-flags?
9397
9398 // Convert to float
9399 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
9400 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
9401 X = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v4i32, Operand: X);
9402 Y = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v4i32, Operand: Y);
9403 X = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: X);
9404 Y = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: Y);
9405 // Get reciprocal estimate.
9406 // float4 recip = vrecpeq_f32(yf);
9407 Y = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9408 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecpe, DL: dl, VT: MVT::i32),
9409 N2: Y);
9410 // Because char has a smaller range than uchar, we can actually get away
9411 // without any newton steps. This requires that we use a weird bias
9412 // of 0xb000, however (again, this has been exhaustively tested).
9413 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
9414 X = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1: X, N2: Y);
9415 X = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4i32, Operand: X);
9416 Y = DAG.getConstant(Val: 0xb000, DL: dl, VT: MVT::v4i32);
9417 X = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::v4i32, N1: X, N2: Y);
9418 X = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4f32, Operand: X);
9419 // Convert back to short.
9420 X = DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: dl, VT: MVT::v4i32, Operand: X);
9421 X = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::v4i16, Operand: X);
9422 return X;
9423}
9424
9425static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
9426 SelectionDAG &DAG) {
9427 // TODO: Should this propagate fast-math-flags?
9428
9429 SDValue N2;
9430 // Convert to float.
9431 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
9432 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
9433 N0 = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v4i32, Operand: N0);
9434 N1 = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v4i32, Operand: N1);
9435 N0 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: N0);
9436 N1 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: N1);
9437
9438 // Use reciprocal estimate and one refinement step.
9439 // float4 recip = vrecpeq_f32(yf);
9440 // recip *= vrecpsq_f32(yf, recip);
9441 N2 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9442 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecpe, DL: dl, VT: MVT::i32),
9443 N2: N1);
9444 N1 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9445 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecps, DL: dl, VT: MVT::i32),
9446 N2: N1, N3: N2);
9447 N2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1, N2);
9448 // Because short has a smaller range than ushort, we can actually get away
9449 // with only a single newton step. This requires that we use a weird bias
9450 // of 89, however (again, this has been exhaustively tested).
9451 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9452 N0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1: N0, N2);
9453 N0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4i32, Operand: N0);
9454 N1 = DAG.getConstant(Val: 0x89, DL: dl, VT: MVT::v4i32);
9455 N0 = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::v4i32, N1: N0, N2: N1);
9456 N0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4f32, Operand: N0);
9457 // Convert back to integer and return.
9458 // return vmovn_s32(vcvt_s32_f32(result));
9459 N0 = DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: dl, VT: MVT::v4i32, Operand: N0);
9460 N0 = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::v4i16, Operand: N0);
9461 return N0;
9462}
9463
9464static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
9465 const ARMSubtarget *ST) {
9466 EVT VT = Op.getValueType();
9467 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9468 "unexpected type for custom-lowering ISD::SDIV");
9469
9470 SDLoc dl(Op);
9471 SDValue N0 = Op.getOperand(i: 0);
9472 SDValue N1 = Op.getOperand(i: 1);
9473 SDValue N2, N3;
9474
9475 if (VT == MVT::v8i8) {
9476 N0 = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v8i16, Operand: N0);
9477 N1 = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v8i16, Operand: N1);
9478
9479 N2 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1: N0,
9480 N2: DAG.getIntPtrConstant(Val: 4, DL: dl));
9481 N3 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1,
9482 N2: DAG.getIntPtrConstant(Val: 4, DL: dl));
9483 N0 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1: N0,
9484 N2: DAG.getIntPtrConstant(Val: 0, DL: dl));
9485 N1 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1,
9486 N2: DAG.getIntPtrConstant(Val: 0, DL: dl));
9487
9488 N0 = LowerSDIV_v4i8(X: N0, Y: N1, dl, DAG); // v4i16
9489 N2 = LowerSDIV_v4i8(X: N2, Y: N3, dl, DAG); // v4i16
9490
9491 N0 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: dl, VT: MVT::v8i16, N1: N0, N2);
9492 N0 = LowerCONCAT_VECTORS(Op: N0, DAG, ST);
9493
9494 N0 = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::v8i8, Operand: N0);
9495 return N0;
9496 }
9497 return LowerSDIV_v4i16(N0, N1, dl, DAG);
9498}
9499
9500static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
9501 const ARMSubtarget *ST) {
9502 // TODO: Should this propagate fast-math-flags?
9503 EVT VT = Op.getValueType();
9504 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9505 "unexpected type for custom-lowering ISD::UDIV");
9506
9507 SDLoc dl(Op);
9508 SDValue N0 = Op.getOperand(i: 0);
9509 SDValue N1 = Op.getOperand(i: 1);
9510 SDValue N2, N3;
9511
9512 if (VT == MVT::v8i8) {
9513 N0 = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: MVT::v8i16, Operand: N0);
9514 N1 = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: MVT::v8i16, Operand: N1);
9515
9516 N2 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1: N0,
9517 N2: DAG.getIntPtrConstant(Val: 4, DL: dl));
9518 N3 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1,
9519 N2: DAG.getIntPtrConstant(Val: 4, DL: dl));
9520 N0 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1: N0,
9521 N2: DAG.getIntPtrConstant(Val: 0, DL: dl));
9522 N1 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1,
9523 N2: DAG.getIntPtrConstant(Val: 0, DL: dl));
9524
9525 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9526 N2 = LowerSDIV_v4i16(N0: N2, N1: N3, dl, DAG); // v4i16
9527
9528 N0 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: dl, VT: MVT::v8i16, N1: N0, N2);
9529 N0 = LowerCONCAT_VECTORS(Op: N0, DAG, ST);
9530
9531 N0 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v8i8,
9532 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vqmovnsu, DL: dl,
9533 VT: MVT::i32),
9534 N2: N0);
9535 return N0;
9536 }
9537
9538 // v4i16 sdiv ... Convert to float.
9539 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9540 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9541 N0 = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: MVT::v4i32, Operand: N0);
9542 N1 = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: MVT::v4i32, Operand: N1);
9543 N0 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: N0);
9544 SDValue BN1 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: N1);
9545
9546 // Use reciprocal estimate and two refinement steps.
9547 // float4 recip = vrecpeq_f32(yf);
9548 // recip *= vrecpsq_f32(yf, recip);
9549 // recip *= vrecpsq_f32(yf, recip);
9550 N2 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9551 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecpe, DL: dl, VT: MVT::i32),
9552 N2: BN1);
9553 N1 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9554 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecps, DL: dl, VT: MVT::i32),
9555 N2: BN1, N3: N2);
9556 N2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1, N2);
9557 N1 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9558 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecps, DL: dl, VT: MVT::i32),
9559 N2: BN1, N3: N2);
9560 N2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1, N2);
9561 // Simply multiplying by the reciprocal estimate can leave us a few ulps
9562 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9563 // and that it will never cause us to return an answer too large).
9564 // float4 result = as_float4(as_int4(xf*recip) + 2);
9565 N0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1: N0, N2);
9566 N0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4i32, Operand: N0);
9567 N1 = DAG.getConstant(Val: 2, DL: dl, VT: MVT::v4i32);
9568 N0 = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::v4i32, N1: N0, N2: N1);
9569 N0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4f32, Operand: N0);
9570 // Convert back to integer and return.
9571 // return vmovn_u32(vcvt_s32_f32(result));
9572 N0 = DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: dl, VT: MVT::v4i32, Operand: N0);
9573 N0 = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::v4i16, Operand: N0);
9574 return N0;
9575}
9576
9577static SDValue LowerUADDSUBO_CARRY(SDValue Op, SelectionDAG &DAG) {
9578 SDNode *N = Op.getNode();
9579 EVT VT = N->getValueType(ResNo: 0);
9580 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::i32);
9581
9582 SDValue Carry = Op.getOperand(i: 2);
9583
9584 SDLoc DL(Op);
9585
9586 SDValue Result;
9587 if (Op.getOpcode() == ISD::UADDO_CARRY) {
9588 // This converts the boolean value carry into the carry flag.
9589 Carry = ConvertBooleanCarryToCarryFlag(BoolCarry: Carry, DAG);
9590
9591 // Do the addition proper using the carry flag we wanted.
9592 Result = DAG.getNode(Opcode: ARMISD::ADDE, DL, VTList: VTs, N1: Op.getOperand(i: 0),
9593 N2: Op.getOperand(i: 1), N3: Carry);
9594
9595 // Now convert the carry flag into a boolean value.
9596 Carry = ConvertCarryFlagToBooleanCarry(Flags: Result.getValue(R: 1), VT, DAG);
9597 } else {
9598 // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
9599 // have to invert the carry first.
9600 Carry = DAG.getNode(Opcode: ISD::SUB, DL, VT: MVT::i32,
9601 N1: DAG.getConstant(Val: 1, DL, VT: MVT::i32), N2: Carry);
9602 // This converts the boolean value carry into the carry flag.
9603 Carry = ConvertBooleanCarryToCarryFlag(BoolCarry: Carry, DAG);
9604
9605 // Do the subtraction proper using the carry flag we wanted.
9606 Result = DAG.getNode(Opcode: ARMISD::SUBE, DL, VTList: VTs, N1: Op.getOperand(i: 0),
9607 N2: Op.getOperand(i: 1), N3: Carry);
9608
9609 // Now convert the carry flag into a boolean value.
9610 Carry = ConvertCarryFlagToBooleanCarry(Flags: Result.getValue(R: 1), VT, DAG);
9611 // But the carry returned by ARMISD::SUBE is not a borrow as expected
9612 // by ISD::USUBO_CARRY, so compute 1 - C.
9613 Carry = DAG.getNode(Opcode: ISD::SUB, DL, VT: MVT::i32,
9614 N1: DAG.getConstant(Val: 1, DL, VT: MVT::i32), N2: Carry);
9615 }
9616
9617 // Return both values.
9618 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL, VTList: N->getVTList(), N1: Result, N2: Carry);
9619}
9620
9621SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9622 bool Signed,
9623 SDValue &Chain) const {
9624 EVT VT = Op.getValueType();
9625 assert((VT == MVT::i32 || VT == MVT::i64) &&
9626 "unexpected type for custom lowering DIV");
9627 SDLoc dl(Op);
9628
9629 const auto &DL = DAG.getDataLayout();
9630 RTLIB::Libcall LC;
9631 if (Signed)
9632 LC = VT == MVT::i32 ? RTLIB::SDIVREM_I32 : RTLIB::SDIVREM_I64;
9633 else
9634 LC = VT == MVT::i32 ? RTLIB::UDIVREM_I32 : RTLIB::UDIVREM_I64;
9635
9636 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(Call: LC);
9637 SDValue ES = DAG.getExternalSymbol(LCImpl, VT: getPointerTy(DL));
9638
9639 ARMTargetLowering::ArgListTy Args;
9640
9641 for (auto AI : {1, 0}) {
9642 SDValue Operand = Op.getOperand(i: AI);
9643 Args.emplace_back(args&: Operand,
9644 args: Operand.getValueType().getTypeForEVT(Context&: *DAG.getContext()));
9645 }
9646
9647 CallLoweringInfo CLI(DAG);
9648 CLI.setDebugLoc(dl).setChain(Chain).setCallee(
9649 CC: DAG.getLibcalls().getLibcallImplCallingConv(Call: LCImpl),
9650 ResultType: VT.getTypeForEVT(Context&: *DAG.getContext()), Target: ES, ArgsList: std::move(Args));
9651
9652 return LowerCallTo(CLI).first;
9653}
9654
9655// This is a code size optimisation: return the original SDIV node to
9656// DAGCombiner when we don't want to expand SDIV into a sequence of
9657// instructions, and an empty node otherwise which will cause the
9658// SDIV to be expanded in DAGCombine.
9659SDValue
9660ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9661 SelectionDAG &DAG,
9662 SmallVectorImpl<SDNode *> &Created) const {
9663 // TODO: Support SREM
9664 if (N->getOpcode() != ISD::SDIV)
9665 return SDValue();
9666
9667 const auto &ST = DAG.getSubtarget<ARMSubtarget>();
9668 const bool MinSize = ST.hasMinSize();
9669 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9670 : ST.hasDivideInARMMode();
9671
9672 // Don't touch vector types; rewriting this may lead to scalarizing
9673 // the int divs.
9674 if (N->getOperand(Num: 0).getValueType().isVector())
9675 return SDValue();
9676
9677 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9678 // hwdiv support for this to be really profitable.
9679 if (!(MinSize && HasDivide))
9680 return SDValue();
9681
9682 // ARM mode is a bit simpler than Thumb: we can handle large power
9683 // of 2 immediates with 1 mov instruction; no further checks required,
9684 // just return the sdiv node.
9685 if (!ST.isThumb())
9686 return SDValue(N, 0);
9687
9688 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9689 // and thus lose the code size benefits of a MOVS that requires only 2.
9690 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9691 // but as it's doing exactly this, it's not worth the trouble to get TTI.
9692 if (Divisor.sgt(RHS: 128))
9693 return SDValue();
9694
9695 return SDValue(N, 0);
9696}
9697
9698SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9699 bool Signed) const {
9700 assert(Op.getValueType() == MVT::i32 &&
9701 "unexpected type for custom lowering DIV");
9702 SDLoc dl(Op);
9703
9704 SDValue DBZCHK = DAG.getNode(Opcode: ARMISD::WIN__DBZCHK, DL: dl, VT: MVT::Other,
9705 N1: DAG.getEntryNode(), N2: Op.getOperand(i: 1));
9706
9707 return LowerWindowsDIVLibCall(Op, DAG, Signed, Chain&: DBZCHK);
9708}
9709
9710static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9711 SDLoc DL(N);
9712 SDValue Op = N->getOperand(Num: 1);
9713 if (N->getValueType(ResNo: 0) == MVT::i32)
9714 return DAG.getNode(Opcode: ARMISD::WIN__DBZCHK, DL, VT: MVT::Other, N1: InChain, N2: Op);
9715 SDValue Lo, Hi;
9716 std::tie(args&: Lo, args&: Hi) = DAG.SplitScalar(N: Op, DL, LoVT: MVT::i32, HiVT: MVT::i32);
9717 return DAG.getNode(Opcode: ARMISD::WIN__DBZCHK, DL, VT: MVT::Other, N1: InChain,
9718 N2: DAG.getNode(Opcode: ISD::OR, DL, VT: MVT::i32, N1: Lo, N2: Hi));
9719}
9720
9721void ARMTargetLowering::ExpandDIV_Windows(
9722 SDValue Op, SelectionDAG &DAG, bool Signed,
9723 SmallVectorImpl<SDValue> &Results) const {
9724 const auto &DL = DAG.getDataLayout();
9725
9726 assert(Op.getValueType() == MVT::i64 &&
9727 "unexpected type for custom lowering DIV");
9728 SDLoc dl(Op);
9729
9730 SDValue DBZCHK = WinDBZCheckDenominator(DAG, N: Op.getNode(), InChain: DAG.getEntryNode());
9731
9732 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, Chain&: DBZCHK);
9733
9734 SDValue Lower = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::i32, Operand: Result);
9735 SDValue Upper = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i64, N1: Result,
9736 N2: DAG.getConstant(Val: 32, DL: dl, VT: getPointerTy(DL)));
9737 Upper = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::i32, Operand: Upper);
9738
9739 Results.push_back(Elt: DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lower, N2: Upper));
9740}
9741
9742std::pair<SDValue, SDValue>
9743ARMTargetLowering::LowerAEABIUnalignedLoad(SDValue Op,
9744 SelectionDAG &DAG) const {
9745 // If we have an unaligned load from a i32 or i64 that would normally be
9746 // split into separate ldrb's, we can use the __aeabi_uread4/__aeabi_uread8
9747 // functions instead.
9748 LoadSDNode *LD = cast<LoadSDNode>(Val: Op.getNode());
9749 EVT MemVT = LD->getMemoryVT();
9750 if (MemVT != MVT::i32 && MemVT != MVT::i64)
9751 return std::make_pair(x: SDValue(), y: SDValue());
9752
9753 const auto &MF = DAG.getMachineFunction();
9754 unsigned AS = LD->getAddressSpace();
9755 Align Alignment = LD->getAlign();
9756 const DataLayout &DL = DAG.getDataLayout();
9757 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9758
9759 if (MF.getFunction().hasMinSize() && !AllowsUnaligned &&
9760 Alignment <= llvm::Align(2)) {
9761
9762 RTLIB::Libcall LC =
9763 (MemVT == MVT::i32) ? RTLIB::AEABI_UREAD4 : RTLIB::AEABI_UREAD8;
9764
9765 MakeLibCallOptions Opts;
9766 SDLoc dl(Op);
9767
9768 auto Pair = makeLibCall(DAG, LC, RetVT: MemVT.getSimpleVT(), Ops: LD->getBasePtr(),
9769 CallOptions: Opts, dl, Chain: LD->getChain());
9770
9771 // If necessary, extend the node to 64bit
9772 if (LD->getExtensionType() != ISD::NON_EXTLOAD) {
9773 unsigned ExtType = LD->getExtensionType() == ISD::SEXTLOAD
9774 ? ISD::SIGN_EXTEND
9775 : ISD::ZERO_EXTEND;
9776 SDValue EN = DAG.getNode(Opcode: ExtType, DL: dl, VT: LD->getValueType(ResNo: 0), Operand: Pair.first);
9777 Pair.first = EN;
9778 }
9779 return Pair;
9780 }
9781
9782 // Default expand to individual loads
9783 if (!allowsMemoryAccess(Context&: *DAG.getContext(), DL, VT: MemVT, AddrSpace: AS, Alignment))
9784 return expandUnalignedLoad(LD, DAG);
9785 return std::make_pair(x: SDValue(), y: SDValue());
9786}
9787
9788SDValue ARMTargetLowering::LowerAEABIUnalignedStore(SDValue Op,
9789 SelectionDAG &DAG) const {
9790 // If we have an unaligned store to a i32 or i64 that would normally be
9791 // split into separate ldrb's, we can use the __aeabi_uwrite4/__aeabi_uwrite8
9792 // functions instead.
9793 StoreSDNode *ST = cast<StoreSDNode>(Val: Op.getNode());
9794 EVT MemVT = ST->getMemoryVT();
9795 if (MemVT != MVT::i32 && MemVT != MVT::i64)
9796 return SDValue();
9797
9798 const auto &MF = DAG.getMachineFunction();
9799 unsigned AS = ST->getAddressSpace();
9800 Align Alignment = ST->getAlign();
9801 const DataLayout &DL = DAG.getDataLayout();
9802 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9803
9804 if (MF.getFunction().hasMinSize() && !AllowsUnaligned &&
9805 Alignment <= llvm::Align(2)) {
9806
9807 SDLoc dl(Op);
9808
9809 // If necessary, trunc the value to 32bit
9810 SDValue StoreVal = ST->getOperand(Num: 1);
9811 if (ST->isTruncatingStore())
9812 StoreVal = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MemVT, Operand: ST->getOperand(Num: 1));
9813
9814 RTLIB::Libcall LC =
9815 (MemVT == MVT::i32) ? RTLIB::AEABI_UWRITE4 : RTLIB::AEABI_UWRITE8;
9816
9817 MakeLibCallOptions Opts;
9818 auto CallResult =
9819 makeLibCall(DAG, LC, RetVT: MVT::isVoid, Ops: {StoreVal, ST->getBasePtr()}, CallOptions: Opts,
9820 dl, Chain: ST->getChain());
9821
9822 return CallResult.second;
9823 }
9824
9825 // Default expand to individual stores
9826 if (!allowsMemoryAccess(Context&: *DAG.getContext(), DL, VT: MemVT, AddrSpace: AS, Alignment))
9827 return expandUnalignedStore(ST, DAG);
9828 return SDValue();
9829}
9830
9831static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9832 LoadSDNode *LD = cast<LoadSDNode>(Val: Op.getNode());
9833 EVT MemVT = LD->getMemoryVT();
9834 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9835 MemVT == MVT::v16i1) &&
9836 "Expected a predicate type!");
9837 assert(MemVT == Op.getValueType());
9838 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9839 "Expected a non-extending load");
9840 assert(LD->isUnindexed() && "Expected a unindexed load");
9841
9842 // The basic MVE VLDR on a v2i1/v4i1/v8i1 actually loads the entire 16bit
9843 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9844 // need to make sure that 8/4/2 bits are actually loaded into the correct
9845 // place, which means loading the value and then shuffling the values into
9846 // the bottom bits of the predicate.
9847 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9848 // for BE).
9849 // Speaking of BE, apparently the rest of llvm will assume a reverse order to
9850 // a natural VMSR(load), so needs to be reversed.
9851
9852 SDLoc dl(Op);
9853 SDValue Load = DAG.getExtLoad(
9854 ExtType: ISD::EXTLOAD, dl, VT: MVT::i32, Chain: LD->getChain(), Ptr: LD->getBasePtr(),
9855 MemVT: EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: MemVT.getSizeInBits()),
9856 MMO: LD->getMemOperand());
9857 SDValue Val = Load;
9858 if (DAG.getDataLayout().isBigEndian())
9859 Val = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32,
9860 N1: DAG.getNode(Opcode: ISD::BITREVERSE, DL: dl, VT: MVT::i32, Operand: Load),
9861 N2: DAG.getConstant(Val: 32 - MemVT.getSizeInBits(), DL: dl, VT: MVT::i32));
9862 SDValue Pred = DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::v16i1, Operand: Val);
9863 if (MemVT != MVT::v16i1)
9864 Pred = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MemVT, N1: Pred,
9865 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
9866 return DAG.getMergeValues(Ops: {Pred, Load.getValue(R: 1)}, dl);
9867}
9868
9869void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9870 SelectionDAG &DAG) const {
9871 LoadSDNode *LD = cast<LoadSDNode>(Val: N);
9872 EVT MemVT = LD->getMemoryVT();
9873
9874 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9875 !Subtarget->isThumb1Only() && LD->isVolatile() &&
9876 LD->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
9877 assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9878 SDLoc dl(N);
9879 SDValue Result = DAG.getMemIntrinsicNode(
9880 Opcode: ARMISD::LDRD, dl, VTList: DAG.getVTList(VTs: {MVT::i32, MVT::i32, MVT::Other}),
9881 Ops: {LD->getChain(), LD->getBasePtr()}, MemVT, MMO: LD->getMemOperand());
9882 SDValue Lo = Result.getValue(R: DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9883 SDValue Hi = Result.getValue(R: DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9884 SDValue Pair = DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lo, N2: Hi);
9885 Results.append(IL: {Pair, Result.getValue(R: 2)});
9886 } else if (MemVT == MVT::i32 || MemVT == MVT::i64) {
9887 auto Pair = LowerAEABIUnalignedLoad(Op: SDValue(N, 0), DAG);
9888 if (Pair.first) {
9889 Results.push_back(Elt: Pair.first);
9890 Results.push_back(Elt: Pair.second);
9891 }
9892 }
9893}
9894
9895static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9896 StoreSDNode *ST = cast<StoreSDNode>(Val: Op.getNode());
9897 EVT MemVT = ST->getMemoryVT();
9898 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9899 MemVT == MVT::v16i1) &&
9900 "Expected a predicate type!");
9901 assert(MemVT == ST->getValue().getValueType());
9902 assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9903 assert(ST->isUnindexed() && "Expected a unindexed store");
9904
9905 // Only store the v2i1 or v4i1 or v8i1 worth of bits, via a buildvector with
9906 // top bits unset and a scalar store.
9907 SDLoc dl(Op);
9908 SDValue Build = ST->getValue();
9909 if (MemVT != MVT::v16i1) {
9910 SmallVector<SDValue, 16> Ops;
9911 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) {
9912 unsigned Elt = DAG.getDataLayout().isBigEndian()
9913 ? MemVT.getVectorNumElements() - I - 1
9914 : I;
9915 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::i32, N1: Build,
9916 N2: DAG.getConstant(Val: Elt, DL: dl, VT: MVT::i32)));
9917 }
9918 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9919 Ops.push_back(Elt: DAG.getUNDEF(VT: MVT::i32));
9920 Build = DAG.getNode(Opcode: ISD::BUILD_VECTOR, DL: dl, VT: MVT::v16i1, Ops);
9921 }
9922 SDValue GRP = DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::i32, Operand: Build);
9923 if (MemVT == MVT::v16i1 && DAG.getDataLayout().isBigEndian())
9924 GRP = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32,
9925 N1: DAG.getNode(Opcode: ISD::BITREVERSE, DL: dl, VT: MVT::i32, Operand: GRP),
9926 N2: DAG.getConstant(Val: 16, DL: dl, VT: MVT::i32));
9927 return DAG.getTruncStore(
9928 Chain: ST->getChain(), dl, Val: GRP, Ptr: ST->getBasePtr(),
9929 SVT: EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: MemVT.getSizeInBits()),
9930 MMO: ST->getMemOperand());
9931}
9932
9933SDValue ARMTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG,
9934 const ARMSubtarget *Subtarget) const {
9935 StoreSDNode *ST = cast<StoreSDNode>(Val: Op.getNode());
9936 EVT MemVT = ST->getMemoryVT();
9937
9938 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9939 !Subtarget->isThumb1Only() && ST->isVolatile() &&
9940 ST->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
9941 assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9942 SDNode *N = Op.getNode();
9943 SDLoc dl(N);
9944
9945 SDValue Lo = DAG.getNode(
9946 Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32, N1: ST->getValue(),
9947 N2: DAG.getTargetConstant(Val: DAG.getDataLayout().isLittleEndian() ? 0 : 1, DL: dl,
9948 VT: MVT::i32));
9949 SDValue Hi = DAG.getNode(
9950 Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32, N1: ST->getValue(),
9951 N2: DAG.getTargetConstant(Val: DAG.getDataLayout().isLittleEndian() ? 1 : 0, DL: dl,
9952 VT: MVT::i32));
9953
9954 return DAG.getMemIntrinsicNode(Opcode: ARMISD::STRD, dl, VTList: DAG.getVTList(VT: MVT::Other),
9955 Ops: {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9956 MemVT, MMO: ST->getMemOperand());
9957 } else if (Subtarget->hasMVEIntegerOps() &&
9958 ((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9959 MemVT == MVT::v16i1))) {
9960 return LowerPredicateStore(Op, DAG);
9961 } else if (MemVT == MVT::i32 || MemVT == MVT::i64) {
9962 return LowerAEABIUnalignedStore(Op, DAG);
9963 }
9964 return SDValue();
9965}
9966
9967static bool isZeroVector(SDValue N) {
9968 return (ISD::isBuildVectorAllZeros(N: N.getNode()) ||
9969 (N->getOpcode() == ARMISD::VMOVIMM &&
9970 isNullConstant(V: N->getOperand(Num: 0))));
9971}
9972
9973static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9974 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Val: Op.getNode());
9975 MVT VT = Op.getSimpleValueType();
9976 SDValue Mask = N->getMask();
9977 SDValue PassThru = N->getPassThru();
9978 SDLoc dl(Op);
9979
9980 if (isZeroVector(N: PassThru))
9981 return Op;
9982
9983 // MVE Masked loads use zero as the passthru value. Here we convert undef to
9984 // zero too, and other values are lowered to a select.
9985 SDValue ZeroVec = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT,
9986 Operand: DAG.getTargetConstant(Val: 0, DL: dl, VT: MVT::i32));
9987 SDValue NewLoad = DAG.getMaskedLoad(
9988 VT, dl, Chain: N->getChain(), Base: N->getBasePtr(), Offset: N->getOffset(), Mask, Src0: ZeroVec,
9989 MemVT: N->getMemoryVT(), MMO: N->getMemOperand(), AM: N->getAddressingMode(),
9990 N->getExtensionType(), IsExpanding: N->isExpandingLoad());
9991 SDValue Combo = NewLoad;
9992 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9993 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9994 isZeroVector(N: PassThru->getOperand(Num: 0));
9995 if (!PassThru.isUndef() && !PassThruIsCastZero)
9996 Combo = DAG.getNode(Opcode: ISD::VSELECT, DL: dl, VT, N1: Mask, N2: NewLoad, N3: PassThru);
9997 return DAG.getMergeValues(Ops: {Combo, NewLoad.getValue(R: 1)}, dl);
9998}
9999
10000static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG,
10001 const ARMSubtarget *ST) {
10002 if (!ST->hasMVEIntegerOps())
10003 return SDValue();
10004
10005 SDLoc dl(Op);
10006 unsigned BaseOpcode = 0;
10007 switch (Op->getOpcode()) {
10008 default: llvm_unreachable("Expected VECREDUCE opcode");
10009 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
10010 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
10011 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break;
10012 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break;
10013 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break;
10014 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break;
10015 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
10016 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
10017 }
10018
10019 SDValue Op0 = Op->getOperand(Num: 0);
10020 EVT VT = Op0.getValueType();
10021 EVT EltVT = VT.getVectorElementType();
10022 unsigned NumElts = VT.getVectorNumElements();
10023 unsigned NumActiveLanes = NumElts;
10024
10025 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10026 NumActiveLanes == 2) &&
10027 "Only expected a power 2 vector size");
10028
10029 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
10030 // allows us to easily extract vector elements from the lanes.
10031 while (NumActiveLanes > 4) {
10032 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
10033 SDValue Rev = DAG.getNode(Opcode: RevOpcode, DL: dl, VT, Operand: Op0);
10034 Op0 = DAG.getNode(Opcode: BaseOpcode, DL: dl, VT, N1: Op0, N2: Rev);
10035 NumActiveLanes /= 2;
10036 }
10037
10038 SDValue Res;
10039 if (NumActiveLanes == 4) {
10040 // The remaining 4 elements are summed sequentially
10041 SDValue Ext0 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10042 N2: DAG.getConstant(Val: 0 * NumElts / 4, DL: dl, VT: MVT::i32));
10043 SDValue Ext1 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10044 N2: DAG.getConstant(Val: 1 * NumElts / 4, DL: dl, VT: MVT::i32));
10045 SDValue Ext2 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10046 N2: DAG.getConstant(Val: 2 * NumElts / 4, DL: dl, VT: MVT::i32));
10047 SDValue Ext3 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10048 N2: DAG.getConstant(Val: 3 * NumElts / 4, DL: dl, VT: MVT::i32));
10049 SDValue Res0 = DAG.getNode(Opcode: BaseOpcode, DL: dl, VT: EltVT, N1: Ext0, N2: Ext1, Flags: Op->getFlags());
10050 SDValue Res1 = DAG.getNode(Opcode: BaseOpcode, DL: dl, VT: EltVT, N1: Ext2, N2: Ext3, Flags: Op->getFlags());
10051 Res = DAG.getNode(Opcode: BaseOpcode, DL: dl, VT: EltVT, N1: Res0, N2: Res1, Flags: Op->getFlags());
10052 } else {
10053 SDValue Ext0 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10054 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
10055 SDValue Ext1 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10056 N2: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
10057 Res = DAG.getNode(Opcode: BaseOpcode, DL: dl, VT: EltVT, N1: Ext0, N2: Ext1, Flags: Op->getFlags());
10058 }
10059
10060 // Result type may be wider than element type.
10061 if (EltVT != Op->getValueType(ResNo: 0))
10062 Res = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL: dl, VT: Op->getValueType(ResNo: 0), Operand: Res);
10063 return Res;
10064}
10065
10066static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG,
10067 const ARMSubtarget *ST) {
10068 if (!ST->hasMVEFloatOps())
10069 return SDValue();
10070 return LowerVecReduce(Op, DAG, ST);
10071}
10072
10073static SDValue LowerVecReduceMinMax(SDValue Op, SelectionDAG &DAG,
10074 const ARMSubtarget *ST) {
10075 if (!ST->hasNEON())
10076 return SDValue();
10077
10078 SDLoc dl(Op);
10079 SDValue Op0 = Op->getOperand(Num: 0);
10080 EVT VT = Op0.getValueType();
10081 EVT EltVT = VT.getVectorElementType();
10082
10083 unsigned PairwiseIntrinsic = 0;
10084 switch (Op->getOpcode()) {
10085 default:
10086 llvm_unreachable("Expected VECREDUCE opcode");
10087 case ISD::VECREDUCE_UMIN:
10088 PairwiseIntrinsic = Intrinsic::arm_neon_vpminu;
10089 break;
10090 case ISD::VECREDUCE_UMAX:
10091 PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxu;
10092 break;
10093 case ISD::VECREDUCE_SMIN:
10094 PairwiseIntrinsic = Intrinsic::arm_neon_vpmins;
10095 break;
10096 case ISD::VECREDUCE_SMAX:
10097 PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxs;
10098 break;
10099 }
10100 SDValue PairwiseOp = DAG.getConstant(Val: PairwiseIntrinsic, DL: dl, VT: MVT::i32);
10101
10102 unsigned NumElts = VT.getVectorNumElements();
10103 unsigned NumActiveLanes = NumElts;
10104
10105 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10106 NumActiveLanes == 2) &&
10107 "Only expected a power 2 vector size");
10108
10109 // Split 128-bit vectors, since vpmin/max takes 2 64-bit vectors.
10110 if (VT.is128BitVector()) {
10111 SDValue Lo, Hi;
10112 std::tie(args&: Lo, args&: Hi) = DAG.SplitVector(N: Op0, DL: dl);
10113 VT = Lo.getValueType();
10114 Op0 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT, Ops: {PairwiseOp, Lo, Hi});
10115 NumActiveLanes /= 2;
10116 }
10117
10118 // Use pairwise reductions until one lane remains
10119 while (NumActiveLanes > 1) {
10120 Op0 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT, Ops: {PairwiseOp, Op0, Op0});
10121 NumActiveLanes /= 2;
10122 }
10123
10124 SDValue Res = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10125 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
10126
10127 // Result type may be wider than element type.
10128 if (EltVT != Op.getValueType()) {
10129 unsigned Extend = 0;
10130 switch (Op->getOpcode()) {
10131 default:
10132 llvm_unreachable("Expected VECREDUCE opcode");
10133 case ISD::VECREDUCE_UMIN:
10134 case ISD::VECREDUCE_UMAX:
10135 Extend = ISD::ZERO_EXTEND;
10136 break;
10137 case ISD::VECREDUCE_SMIN:
10138 case ISD::VECREDUCE_SMAX:
10139 Extend = ISD::SIGN_EXTEND;
10140 break;
10141 }
10142 Res = DAG.getNode(Opcode: Extend, DL: dl, VT: Op.getValueType(), Operand: Res);
10143 }
10144 return Res;
10145}
10146
10147static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
10148 if (isStrongerThanMonotonic(AO: cast<AtomicSDNode>(Val&: Op)->getSuccessOrdering()))
10149 // Acquire/Release load/store is not legal for targets without a dmb or
10150 // equivalent available.
10151 return SDValue();
10152
10153 // Monotonic load/store is legal for all targets.
10154 return Op;
10155}
10156
10157static void ReplaceREADCYCLECOUNTER(SDNode *N,
10158 SmallVectorImpl<SDValue> &Results,
10159 SelectionDAG &DAG,
10160 const ARMSubtarget *Subtarget) {
10161 SDLoc DL(N);
10162 // Under Power Management extensions, the cycle-count is:
10163 // mrc p15, #0, <Rt>, c9, c13, #0
10164 SDValue Ops[] = { N->getOperand(Num: 0), // Chain
10165 DAG.getTargetConstant(Val: Intrinsic::arm_mrc, DL, VT: MVT::i32),
10166 DAG.getTargetConstant(Val: 15, DL, VT: MVT::i32),
10167 DAG.getTargetConstant(Val: 0, DL, VT: MVT::i32),
10168 DAG.getTargetConstant(Val: 9, DL, VT: MVT::i32),
10169 DAG.getTargetConstant(Val: 13, DL, VT: MVT::i32),
10170 DAG.getTargetConstant(Val: 0, DL, VT: MVT::i32)
10171 };
10172
10173 SDValue Cycles32 = DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL,
10174 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), Ops);
10175 Results.push_back(Elt: DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VT: MVT::i64, N1: Cycles32,
10176 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32)));
10177 Results.push_back(Elt: Cycles32.getValue(R: 1));
10178}
10179
10180static SDValue createGPRPairNode2xi32(SelectionDAG &DAG, SDValue V0,
10181 SDValue V1) {
10182 SDLoc dl(V0.getNode());
10183 SDValue RegClass =
10184 DAG.getTargetConstant(Val: ARM::GPRPairRegClassID, DL: dl, VT: MVT::i32);
10185 SDValue SubReg0 = DAG.getTargetConstant(Val: ARM::gsub_0, DL: dl, VT: MVT::i32);
10186 SDValue SubReg1 = DAG.getTargetConstant(Val: ARM::gsub_1, DL: dl, VT: MVT::i32);
10187 const SDValue Ops[] = {RegClass, V0, SubReg0, V1, SubReg1};
10188 return SDValue(
10189 DAG.getMachineNode(Opcode: TargetOpcode::REG_SEQUENCE, dl, VT: MVT::Untyped, Ops), 0);
10190}
10191
10192static SDValue createGPRPairNodei64(SelectionDAG &DAG, SDValue V) {
10193 SDLoc dl(V.getNode());
10194 auto [VLo, VHi] = DAG.SplitScalar(N: V, DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
10195 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10196 if (isBigEndian)
10197 std::swap(a&: VLo, b&: VHi);
10198 return createGPRPairNode2xi32(DAG, V0: VLo, V1: VHi);
10199}
10200
10201static void ReplaceCMP_SWAP_64Results(SDNode *N,
10202 SmallVectorImpl<SDValue> &Results,
10203 SelectionDAG &DAG) {
10204 assert(N->getValueType(0) == MVT::i64 &&
10205 "AtomicCmpSwap on types less than 64 should be legal");
10206 SDValue Ops[] = {
10207 createGPRPairNode2xi32(DAG, V0: N->getOperand(Num: 1),
10208 V1: DAG.getUNDEF(VT: MVT::i32)), // pointer, temp
10209 createGPRPairNodei64(DAG, V: N->getOperand(Num: 2)), // expected
10210 createGPRPairNodei64(DAG, V: N->getOperand(Num: 3)), // new
10211 N->getOperand(Num: 0), // chain in
10212 };
10213 SDNode *CmpSwap = DAG.getMachineNode(
10214 Opcode: ARM::CMP_SWAP_64, dl: SDLoc(N),
10215 VTs: DAG.getVTList(VT1: MVT::Untyped, VT2: MVT::Untyped, VT3: MVT::Other), Ops);
10216
10217 MachineMemOperand *MemOp = cast<MemSDNode>(Val: N)->getMemOperand();
10218 DAG.setNodeMemRefs(N: cast<MachineSDNode>(Val: CmpSwap), NewMemRefs: {MemOp});
10219
10220 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10221
10222 SDValue Lo =
10223 DAG.getTargetExtractSubreg(SRIdx: isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
10224 DL: SDLoc(N), VT: MVT::i32, Operand: SDValue(CmpSwap, 0));
10225 SDValue Hi =
10226 DAG.getTargetExtractSubreg(SRIdx: isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
10227 DL: SDLoc(N), VT: MVT::i32, Operand: SDValue(CmpSwap, 0));
10228 Results.push_back(Elt: DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: SDLoc(N), VT: MVT::i64, N1: Lo, N2: Hi));
10229 Results.push_back(Elt: SDValue(CmpSwap, 2));
10230}
10231
10232SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
10233 SDLoc dl(Op);
10234 EVT VT = Op.getValueType();
10235 SDValue Chain = Op.getOperand(i: 0);
10236 SDValue LHS = Op.getOperand(i: 1);
10237 SDValue RHS = Op.getOperand(i: 2);
10238 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 3))->get();
10239 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
10240
10241 // If we don't have instructions of this float type then soften to a libcall
10242 // and use SETCC instead.
10243 if (isUnsupportedFloatingType(VT: LHS.getValueType())) {
10244 softenSetCCOperands(DAG, VT: LHS.getValueType(), NewLHS&: LHS, NewRHS&: RHS, CCCode&: CC, DL: dl, OldLHS: LHS, OldRHS: RHS,
10245 Chain, IsSignaling);
10246 if (!RHS.getNode()) {
10247 RHS = DAG.getConstant(Val: 0, DL: dl, VT: LHS.getValueType());
10248 CC = ISD::SETNE;
10249 }
10250 SDValue Result = DAG.getNode(Opcode: ISD::SETCC, DL: dl, VT, N1: LHS, N2: RHS,
10251 N3: DAG.getCondCode(Cond: CC));
10252 return DAG.getMergeValues(Ops: {Result, Chain}, dl);
10253 }
10254
10255 ARMCC::CondCodes CondCode, CondCode2;
10256 FPCCToARMCC(CC, CondCode, CondCode2);
10257
10258 SDValue True = DAG.getConstant(Val: 1, DL: dl, VT);
10259 SDValue False = DAG.getConstant(Val: 0, DL: dl, VT);
10260 SDValue ARMcc = DAG.getConstant(Val: CondCode, DL: dl, VT: MVT::i32);
10261 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, Signaling: IsSignaling);
10262 SDValue Result = getCMOV(dl, VT, FalseVal: False, TrueVal: True, ARMcc, Flags: Cmp, DAG);
10263 if (CondCode2 != ARMCC::AL) {
10264 ARMcc = DAG.getConstant(Val: CondCode2, DL: dl, VT: MVT::i32);
10265 Result = getCMOV(dl, VT, FalseVal: Result, TrueVal: True, ARMcc, Flags: Cmp, DAG);
10266 }
10267 return DAG.getMergeValues(Ops: {Result, Chain}, dl);
10268}
10269
10270SDValue ARMTargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const {
10271 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10272
10273 EVT VT = getPointerTy(DL: DAG.getDataLayout());
10274 int FI = MFI.CreateFixedObject(Size: 4, SPOffset: 0, IsImmutable: false);
10275 return DAG.getFrameIndex(FI, VT);
10276}
10277
10278SDValue ARMTargetLowering::LowerFP_TO_BF16(SDValue Op,
10279 SelectionDAG &DAG) const {
10280 SDLoc DL(Op);
10281 MakeLibCallOptions CallOptions;
10282 MVT SVT = Op.getOperand(i: 0).getSimpleValueType();
10283 RTLIB::Libcall LC = RTLIB::getFPROUND(OpVT: SVT, RetVT: MVT::bf16);
10284 SDValue Res =
10285 makeLibCall(DAG, LC, RetVT: MVT::f32, Ops: Op.getOperand(i: 0), CallOptions, dl: DL).first;
10286 return DAG.getBitcast(VT: MVT::i32, V: Res);
10287}
10288
10289SDValue ARMTargetLowering::LowerCMP(SDValue Op, SelectionDAG &DAG) const {
10290 SDLoc dl(Op);
10291 SDValue LHS = Op.getOperand(i: 0);
10292 SDValue RHS = Op.getOperand(i: 1);
10293
10294 // Determine if this is signed or unsigned comparison
10295 bool IsSigned = (Op.getOpcode() == ISD::SCMP);
10296
10297 // Special case for Thumb1 UCMP only
10298 if (!IsSigned && Subtarget->isThumb1Only()) {
10299 // For Thumb unsigned comparison, use this sequence:
10300 // subs r2, r0, r1 ; r2 = LHS - RHS, sets flags
10301 // sbc r2, r2 ; r2 = r2 - r2 - !carry
10302 // cmp r1, r0 ; compare RHS with LHS
10303 // sbc r1, r1 ; r1 = r1 - r1 - !carry
10304 // subs r0, r2, r1 ; r0 = r2 - r1 (final result)
10305
10306 // First subtraction: LHS - RHS
10307 SDValue Sub1WithFlags = DAG.getNode(
10308 Opcode: ARMISD::SUBC, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT), N1: LHS, N2: RHS);
10309 SDValue Sub1Result = Sub1WithFlags.getValue(R: 0);
10310 SDValue Flags1 = Sub1WithFlags.getValue(R: 1);
10311
10312 // SUBE: Sub1Result - Sub1Result - !carry
10313 // This gives 0 if LHS >= RHS (unsigned), -1 if LHS < RHS (unsigned)
10314 SDValue Sbc1 =
10315 DAG.getNode(Opcode: ARMISD::SUBE, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT),
10316 N1: Sub1Result, N2: Sub1Result, N3: Flags1);
10317 SDValue Sbc1Result = Sbc1.getValue(R: 0);
10318
10319 // Second comparison: RHS vs LHS (reverse comparison)
10320 SDValue CmpFlags = DAG.getNode(Opcode: ARMISD::CMP, DL: dl, VT: FlagsVT, N1: RHS, N2: LHS);
10321
10322 // SUBE: RHS - RHS - !carry
10323 // This gives 0 if RHS <= LHS (unsigned), -1 if RHS > LHS (unsigned)
10324 SDValue Sbc2 = DAG.getNode(
10325 Opcode: ARMISD::SUBE, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT), N1: RHS, N2: RHS, N3: CmpFlags);
10326 SDValue Sbc2Result = Sbc2.getValue(R: 0);
10327
10328 // Final subtraction: Sbc1Result - Sbc2Result (no flags needed)
10329 SDValue Result =
10330 DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: Sbc1Result, N2: Sbc2Result);
10331 if (Op.getValueType() != MVT::i32)
10332 Result = DAG.getSExtOrTrunc(Op: Result, DL: dl, VT: Op.getValueType());
10333
10334 return Result;
10335 }
10336
10337 // For the ARM assembly pattern:
10338 // subs r0, r0, r1 ; subtract RHS from LHS and set flags
10339 // movgt r0, #1 ; if LHS > RHS, set result to 1 (GT for signed, HI for
10340 // unsigned) mvnlt r0, #0 ; if LHS < RHS, set result to -1 (LT for
10341 // signed, LO for unsigned)
10342 // ; if LHS == RHS, result remains 0 from the subs
10343
10344 // Optimization: if RHS is a subtraction against 0, use ADDC instead of SUBC
10345 unsigned Opcode = ARMISD::SUBC;
10346
10347 // Check if RHS is a subtraction against 0: (0 - X)
10348 if (RHS.getOpcode() == ISD::SUB) {
10349 SDValue SubLHS = RHS.getOperand(i: 0);
10350 SDValue SubRHS = RHS.getOperand(i: 1);
10351
10352 // Check if it's 0 - X
10353 if (isNullConstant(V: SubLHS)) {
10354 bool CanUseAdd = false;
10355 if (IsSigned) {
10356 // For SCMP: only if X is known to never be INT_MIN (to avoid overflow)
10357 if (RHS->getFlags().hasNoSignedWrap() || !DAG.computeKnownBits(Op: SubRHS)
10358 .getSignedMinValue()
10359 .isMinSignedValue()) {
10360 CanUseAdd = true;
10361 }
10362 } else {
10363 // For UCMP: only if X is known to never be zero
10364 if (DAG.isKnownNeverZero(Op: SubRHS)) {
10365 CanUseAdd = true;
10366 }
10367 }
10368
10369 if (CanUseAdd) {
10370 Opcode = ARMISD::ADDC;
10371 RHS = SubRHS; // Replace RHS with X, so we do LHS + X instead of
10372 // LHS - (0 - X)
10373 }
10374 }
10375 }
10376
10377 // Generate the operation with flags
10378 SDValue OpWithFlags =
10379 DAG.getNode(Opcode, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT), N1: LHS, N2: RHS);
10380
10381 SDValue OpResult = OpWithFlags.getValue(R: 0);
10382 SDValue Flags = OpWithFlags.getValue(R: 1);
10383
10384 // Constants for conditional moves
10385 SDValue One = DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32);
10386 SDValue MinusOne = DAG.getAllOnesConstant(DL: dl, VT: MVT::i32);
10387
10388 // Select condition codes based on signed vs unsigned
10389 ARMCC::CondCodes GTCond = IsSigned ? ARMCC::GT : ARMCC::HI;
10390 ARMCC::CondCodes LTCond = IsSigned ? ARMCC::LT : ARMCC::LO;
10391
10392 // First conditional move: if greater than, set to 1
10393 SDValue GTCondValue = DAG.getConstant(Val: GTCond, DL: dl, VT: MVT::i32);
10394 SDValue Result1 = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT: MVT::i32, N1: OpResult, N2: One,
10395 N3: GTCondValue, N4: Flags);
10396
10397 // Second conditional move: if less than, set to -1
10398 SDValue LTCondValue = DAG.getConstant(Val: LTCond, DL: dl, VT: MVT::i32);
10399 SDValue Result2 = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT: MVT::i32, N1: Result1, N2: MinusOne,
10400 N3: LTCondValue, N4: Flags);
10401
10402 if (Op.getValueType() != MVT::i32)
10403 Result2 = DAG.getSExtOrTrunc(Op: Result2, DL: dl, VT: Op.getValueType());
10404
10405 return Result2;
10406}
10407
10408SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10409 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
10410 switch (Op.getOpcode()) {
10411 default: llvm_unreachable("Don't know how to custom lower this!");
10412 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
10413 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10414 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10415 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10416 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10417 case ISD::SELECT: return LowerSELECT(Op, DAG);
10418 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
10419 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10420 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
10421 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
10422 case ISD::VASTART: return LowerVASTART(Op, DAG);
10423 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
10424 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
10425 case ISD::SINT_TO_FP:
10426 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
10427 case ISD::STRICT_FP_TO_SINT:
10428 case ISD::STRICT_FP_TO_UINT:
10429 case ISD::FP_TO_SINT:
10430 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
10431 case ISD::FP_TO_SINT_SAT:
10432 case ISD::FP_TO_UINT_SAT: return LowerFP_TO_INT_SAT(Op, DAG, Subtarget);
10433 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10434 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10435 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10436 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
10437 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
10438 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
10439 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
10440 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
10441 Subtarget);
10442 case ISD::BITCAST: return ExpandBITCAST(N: Op.getNode(), DAG, Subtarget);
10443 case ISD::SHL:
10444 case ISD::SRL:
10445 case ISD::SRA: return LowerShift(N: Op.getNode(), DAG, ST: Subtarget);
10446 case ISD::SREM: return LowerREM(N: Op.getNode(), DAG);
10447 case ISD::UREM: return LowerREM(N: Op.getNode(), DAG);
10448 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
10449 case ISD::SRL_PARTS:
10450 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
10451 case ISD::CTTZ:
10452 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(N: Op.getNode(), DAG, ST: Subtarget);
10453 case ISD::CTPOP: return LowerCTPOP(N: Op.getNode(), DAG, ST: Subtarget);
10454 case ISD::SETCC: return LowerVSETCC(Op, DAG, ST: Subtarget);
10455 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
10456 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, ST: Subtarget);
10457 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, ST: Subtarget);
10458 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, ST: Subtarget);
10459 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, ST: Subtarget);
10460 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10461 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, ST: Subtarget);
10462 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, ST: Subtarget);
10463 case ISD::TRUNCATE: return LowerTruncate(N: Op.getNode(), DAG, Subtarget);
10464 case ISD::SIGN_EXTEND:
10465 case ISD::ZERO_EXTEND: return LowerVectorExtend(N: Op.getNode(), DAG, Subtarget);
10466 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG);
10467 case ISD::SET_ROUNDING: return LowerSET_ROUNDING(Op, DAG);
10468 case ISD::SET_FPMODE:
10469 return LowerSET_FPMODE(Op, DAG);
10470 case ISD::RESET_FPMODE:
10471 return LowerRESET_FPMODE(Op, DAG);
10472 case ISD::MUL: return LowerMUL(Op, DAG);
10473 case ISD::SDIV:
10474 if (getTargetMachine().getTargetTriple().isOSWindows() &&
10475 !Op.getValueType().isVector())
10476 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
10477 return LowerSDIV(Op, DAG, ST: Subtarget);
10478 case ISD::UDIV:
10479 if (getTargetMachine().getTargetTriple().isOSWindows() &&
10480 !Op.getValueType().isVector())
10481 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
10482 return LowerUDIV(Op, DAG, ST: Subtarget);
10483 case ISD::UADDO_CARRY:
10484 case ISD::USUBO_CARRY:
10485 return LowerUADDSUBO_CARRY(Op, DAG);
10486 case ISD::UADDO:
10487 case ISD::USUBO:
10488 case ISD::UMULO:
10489 case ISD::SADDO:
10490 case ISD::SSUBO:
10491 case ISD::SMULO:
10492 return LowerALUO(Op, DAG);
10493 case ISD::SADDSAT:
10494 case ISD::SSUBSAT:
10495 case ISD::UADDSAT:
10496 case ISD::USUBSAT:
10497 return LowerADDSUBSAT(Op, DAG, Subtarget);
10498 case ISD::LOAD: {
10499 auto *LD = cast<LoadSDNode>(Val&: Op);
10500 EVT MemVT = LD->getMemoryVT();
10501 if (Subtarget->hasMVEIntegerOps() &&
10502 (MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10503 MemVT == MVT::v16i1))
10504 return LowerPredicateLoad(Op, DAG);
10505
10506 auto Pair = LowerAEABIUnalignedLoad(Op, DAG);
10507 if (Pair.first)
10508 return DAG.getMergeValues(Ops: {Pair.first, Pair.second}, dl: SDLoc(Pair.first));
10509 return SDValue();
10510 }
10511 case ISD::STORE:
10512 return LowerSTORE(Op, DAG, Subtarget);
10513 case ISD::MLOAD:
10514 return LowerMLOAD(Op, DAG);
10515 case ISD::VECREDUCE_MUL:
10516 case ISD::VECREDUCE_AND:
10517 case ISD::VECREDUCE_OR:
10518 case ISD::VECREDUCE_XOR:
10519 return LowerVecReduce(Op, DAG, ST: Subtarget);
10520 case ISD::VECREDUCE_FADD:
10521 case ISD::VECREDUCE_FMUL:
10522 case ISD::VECREDUCE_FMIN:
10523 case ISD::VECREDUCE_FMAX:
10524 return LowerVecReduceF(Op, DAG, ST: Subtarget);
10525 case ISD::VECREDUCE_UMIN:
10526 case ISD::VECREDUCE_UMAX:
10527 case ISD::VECREDUCE_SMIN:
10528 case ISD::VECREDUCE_SMAX:
10529 return LowerVecReduceMinMax(Op, DAG, ST: Subtarget);
10530 case ISD::ATOMIC_LOAD:
10531 case ISD::ATOMIC_STORE:
10532 return LowerAtomicLoadStore(Op, DAG);
10533 case ISD::SDIVREM:
10534 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
10535 case ISD::DYNAMIC_STACKALLOC:
10536 if (getTargetMachine().getTargetTriple().isOSWindows())
10537 return LowerDYNAMIC_STACKALLOC(Op, DAG);
10538 llvm_unreachable("Don't know how to custom lower this!");
10539 case ISD::STRICT_FP_ROUND:
10540 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
10541 case ISD::STRICT_FP_EXTEND:
10542 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
10543 case ISD::STRICT_FSETCC:
10544 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
10545 case ISD::SPONENTRY:
10546 return LowerSPONENTRY(Op, DAG);
10547 case ISD::FP_TO_BF16:
10548 return LowerFP_TO_BF16(Op, DAG);
10549 case ARMISD::WIN__DBZCHK: return SDValue();
10550 case ISD::UCMP:
10551 case ISD::SCMP:
10552 return LowerCMP(Op, DAG);
10553 case ISD::ABS:
10554 return LowerABS(Op, DAG);
10555 case ISD::STRICT_LROUND:
10556 case ISD::STRICT_LLROUND:
10557 case ISD::STRICT_LRINT:
10558 case ISD::STRICT_LLRINT: {
10559 assert((Op.getOperand(1).getValueType() == MVT::f16 ||
10560 Op.getOperand(1).getValueType() == MVT::bf16) &&
10561 "Expected custom lowering of rounding operations only for f16");
10562 SDLoc DL(Op);
10563 SDValue Ext = DAG.getNode(Opcode: ISD::STRICT_FP_EXTEND, DL, ResultTys: {MVT::f32, MVT::Other},
10564 Ops: {Op.getOperand(i: 0), Op.getOperand(i: 1)});
10565 return DAG.getNode(Opcode: Op.getOpcode(), DL, ResultTys: {Op.getValueType(), MVT::Other},
10566 Ops: {Ext.getValue(R: 1), Ext.getValue(R: 0)});
10567 }
10568 }
10569}
10570
10571static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
10572 SelectionDAG &DAG) {
10573 unsigned IntNo = N->getConstantOperandVal(Num: 0);
10574 unsigned Opc = 0;
10575 if (IntNo == Intrinsic::arm_smlald)
10576 Opc = ARMISD::SMLALD;
10577 else if (IntNo == Intrinsic::arm_smlaldx)
10578 Opc = ARMISD::SMLALDX;
10579 else if (IntNo == Intrinsic::arm_smlsld)
10580 Opc = ARMISD::SMLSLD;
10581 else if (IntNo == Intrinsic::arm_smlsldx)
10582 Opc = ARMISD::SMLSLDX;
10583 else
10584 return;
10585
10586 SDLoc dl(N);
10587 SDValue Lo, Hi;
10588 std::tie(args&: Lo, args&: Hi) = DAG.SplitScalar(N: N->getOperand(Num: 3), DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
10589
10590 SDValue LongMul = DAG.getNode(Opcode: Opc, DL: dl,
10591 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
10592 N1: N->getOperand(Num: 1), N2: N->getOperand(Num: 2),
10593 N3: Lo, N4: Hi);
10594 Results.push_back(Elt: DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64,
10595 N1: LongMul.getValue(R: 0), N2: LongMul.getValue(R: 1)));
10596}
10597
10598/// ReplaceNodeResults - Replace the results of node with an illegal result
10599/// type with new values built out of custom code.
10600void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
10601 SmallVectorImpl<SDValue> &Results,
10602 SelectionDAG &DAG) const {
10603 SDValue Res;
10604 switch (N->getOpcode()) {
10605 default:
10606 llvm_unreachable("Don't know how to custom expand this!");
10607 case ISD::READ_REGISTER:
10608 ExpandREAD_REGISTER(N, Results, DAG);
10609 break;
10610 case ISD::BITCAST:
10611 Res = ExpandBITCAST(N, DAG, Subtarget);
10612 break;
10613 case ISD::SRL:
10614 case ISD::SRA:
10615 case ISD::SHL:
10616 Res = Expand64BitShift(N, DAG, ST: Subtarget);
10617 break;
10618 case ISD::SREM:
10619 case ISD::UREM:
10620 Res = LowerREM(N, DAG);
10621 break;
10622 case ISD::SDIVREM:
10623 case ISD::UDIVREM:
10624 Res = LowerDivRem(Op: SDValue(N, 0), DAG);
10625 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
10626 Results.push_back(Elt: Res.getValue(R: 0));
10627 Results.push_back(Elt: Res.getValue(R: 1));
10628 return;
10629 case ISD::SADDSAT:
10630 case ISD::SSUBSAT:
10631 case ISD::UADDSAT:
10632 case ISD::USUBSAT:
10633 Res = LowerADDSUBSAT(Op: SDValue(N, 0), DAG, Subtarget);
10634 break;
10635 case ISD::READCYCLECOUNTER:
10636 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
10637 return;
10638 case ISD::UDIV:
10639 case ISD::SDIV:
10640 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
10641 "can only expand DIV on Windows");
10642 return ExpandDIV_Windows(Op: SDValue(N, 0), DAG, Signed: N->getOpcode() == ISD::SDIV,
10643 Results);
10644 case ISD::ATOMIC_CMP_SWAP:
10645 ReplaceCMP_SWAP_64Results(N, Results, DAG);
10646 return;
10647 case ISD::INTRINSIC_WO_CHAIN:
10648 return ReplaceLongIntrinsic(N, Results, DAG);
10649 case ISD::LOAD:
10650 LowerLOAD(N, Results, DAG);
10651 break;
10652 case ISD::STORE:
10653 Res = LowerAEABIUnalignedStore(Op: SDValue(N, 0), DAG);
10654 break;
10655 case ISD::TRUNCATE:
10656 Res = LowerTruncate(N, DAG, Subtarget);
10657 break;
10658 case ISD::SIGN_EXTEND:
10659 case ISD::ZERO_EXTEND:
10660 Res = LowerVectorExtend(N, DAG, Subtarget);
10661 break;
10662 case ISD::FP_TO_SINT_SAT:
10663 case ISD::FP_TO_UINT_SAT:
10664 Res = LowerFP_TO_INT_SAT(Op: SDValue(N, 0), DAG, Subtarget);
10665 break;
10666 }
10667 if (Res.getNode())
10668 Results.push_back(Elt: Res);
10669}
10670
10671//===----------------------------------------------------------------------===//
10672// ARM Scheduler Hooks
10673//===----------------------------------------------------------------------===//
10674
10675/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
10676/// registers the function context.
10677void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
10678 MachineBasicBlock *MBB,
10679 MachineBasicBlock *DispatchBB,
10680 int FI) const {
10681 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
10682 "ROPI/RWPI not currently supported with SjLj");
10683 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10684 DebugLoc dl = MI.getDebugLoc();
10685 MachineFunction *MF = MBB->getParent();
10686 MachineRegisterInfo *MRI = &MF->getRegInfo();
10687 MachineConstantPool *MCP = MF->getConstantPool();
10688 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
10689 const Function &F = MF->getFunction();
10690
10691 bool isThumb = Subtarget->isThumb();
10692 bool isThumb2 = Subtarget->isThumb2();
10693
10694 unsigned PCLabelId = AFI->createPICLabelUId();
10695 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
10696 ARMConstantPoolValue *CPV =
10697 ARMConstantPoolMBB::Create(C&: F.getContext(), mbb: DispatchBB, ID: PCLabelId, PCAdj);
10698 unsigned CPI = MCP->getConstantPoolIndex(V: CPV, Alignment: Align(4));
10699
10700 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
10701 : &ARM::GPRRegClass;
10702
10703 // Grab constant pool and fixed stack memory operands.
10704 MachineMemOperand *CPMMO =
10705 MF->getMachineMemOperand(PtrInfo: MachinePointerInfo::getConstantPool(MF&: *MF),
10706 F: MachineMemOperand::MOLoad, Size: 4, BaseAlignment: Align(4));
10707
10708 MachineMemOperand *FIMMOSt =
10709 MF->getMachineMemOperand(PtrInfo: MachinePointerInfo::getFixedStack(MF&: *MF, FI),
10710 F: MachineMemOperand::MOStore, Size: 4, BaseAlignment: Align(4));
10711
10712 // Load the address of the dispatch MBB into the jump buffer.
10713 if (isThumb2) {
10714 // Incoming value: jbuf
10715 // ldr.n r5, LCPI1_1
10716 // orr r5, r5, #1
10717 // add r5, pc
10718 // str r5, [$jbuf, #+4] ; &jbuf[1]
10719 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
10720 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::t2LDRpci), DestReg: NewVReg1)
10721 .addConstantPoolIndex(Idx: CPI)
10722 .addMemOperand(MMO: CPMMO)
10723 .add(MOs: predOps(Pred: ARMCC::AL));
10724 // Set the low bit because of thumb mode.
10725 Register NewVReg2 = MRI->createVirtualRegister(RegClass: TRC);
10726 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::t2ORRri), DestReg: NewVReg2)
10727 .addReg(RegNo: NewVReg1, Flags: RegState::Kill)
10728 .addImm(Val: 0x01)
10729 .add(MOs: predOps(Pred: ARMCC::AL))
10730 .add(MO: condCodeOp());
10731 Register NewVReg3 = MRI->createVirtualRegister(RegClass: TRC);
10732 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tPICADD), DestReg: NewVReg3)
10733 .addReg(RegNo: NewVReg2, Flags: RegState::Kill)
10734 .addImm(Val: PCLabelId);
10735 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::t2STRi12))
10736 .addReg(RegNo: NewVReg3, Flags: RegState::Kill)
10737 .addFrameIndex(Idx: FI)
10738 .addImm(Val: 36) // &jbuf[1] :: pc
10739 .addMemOperand(MMO: FIMMOSt)
10740 .add(MOs: predOps(Pred: ARMCC::AL));
10741 } else if (isThumb) {
10742 // Incoming value: jbuf
10743 // ldr.n r1, LCPI1_4
10744 // add r1, pc
10745 // mov r2, #1
10746 // orrs r1, r2
10747 // add r2, $jbuf, #+4 ; &jbuf[1]
10748 // str r1, [r2]
10749 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
10750 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDRpci), DestReg: NewVReg1)
10751 .addConstantPoolIndex(Idx: CPI)
10752 .addMemOperand(MMO: CPMMO)
10753 .add(MOs: predOps(Pred: ARMCC::AL));
10754 Register NewVReg2 = MRI->createVirtualRegister(RegClass: TRC);
10755 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tPICADD), DestReg: NewVReg2)
10756 .addReg(RegNo: NewVReg1, Flags: RegState::Kill)
10757 .addImm(Val: PCLabelId);
10758 // Set the low bit because of thumb mode.
10759 Register NewVReg3 = MRI->createVirtualRegister(RegClass: TRC);
10760 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tMOVi8), DestReg: NewVReg3)
10761 .addReg(RegNo: ARM::CPSR, Flags: RegState::Define)
10762 .addImm(Val: 1)
10763 .add(MOs: predOps(Pred: ARMCC::AL));
10764 Register NewVReg4 = MRI->createVirtualRegister(RegClass: TRC);
10765 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tORR), DestReg: NewVReg4)
10766 .addReg(RegNo: ARM::CPSR, Flags: RegState::Define)
10767 .addReg(RegNo: NewVReg2, Flags: RegState::Kill)
10768 .addReg(RegNo: NewVReg3, Flags: RegState::Kill)
10769 .add(MOs: predOps(Pred: ARMCC::AL));
10770 Register NewVReg5 = MRI->createVirtualRegister(RegClass: TRC);
10771 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tADDframe), DestReg: NewVReg5)
10772 .addFrameIndex(Idx: FI)
10773 .addImm(Val: 36); // &jbuf[1] :: pc
10774 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tSTRi))
10775 .addReg(RegNo: NewVReg4, Flags: RegState::Kill)
10776 .addReg(RegNo: NewVReg5, Flags: RegState::Kill)
10777 .addImm(Val: 0)
10778 .addMemOperand(MMO: FIMMOSt)
10779 .add(MOs: predOps(Pred: ARMCC::AL));
10780 } else {
10781 // Incoming value: jbuf
10782 // ldr r1, LCPI1_1
10783 // add r1, pc, r1
10784 // str r1, [$jbuf, #+4] ; &jbuf[1]
10785 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
10786 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::LDRi12), DestReg: NewVReg1)
10787 .addConstantPoolIndex(Idx: CPI)
10788 .addImm(Val: 0)
10789 .addMemOperand(MMO: CPMMO)
10790 .add(MOs: predOps(Pred: ARMCC::AL));
10791 Register NewVReg2 = MRI->createVirtualRegister(RegClass: TRC);
10792 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::PICADD), DestReg: NewVReg2)
10793 .addReg(RegNo: NewVReg1, Flags: RegState::Kill)
10794 .addImm(Val: PCLabelId)
10795 .add(MOs: predOps(Pred: ARMCC::AL));
10796 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::STRi12))
10797 .addReg(RegNo: NewVReg2, Flags: RegState::Kill)
10798 .addFrameIndex(Idx: FI)
10799 .addImm(Val: 36) // &jbuf[1] :: pc
10800 .addMemOperand(MMO: FIMMOSt)
10801 .add(MOs: predOps(Pred: ARMCC::AL));
10802 }
10803}
10804
10805void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10806 MachineBasicBlock *MBB) const {
10807 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10808 DebugLoc dl = MI.getDebugLoc();
10809 MachineFunction *MF = MBB->getParent();
10810 MachineRegisterInfo *MRI = &MF->getRegInfo();
10811 MachineFrameInfo &MFI = MF->getFrameInfo();
10812 int FI = MFI.getFunctionContextIndex();
10813
10814 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10815 : &ARM::GPRnopcRegClass;
10816
10817 // Get a mapping of the call site numbers to all of the landing pads they're
10818 // associated with.
10819 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10820 unsigned MaxCSNum = 0;
10821 for (MachineBasicBlock &BB : *MF) {
10822 if (!BB.isEHPad())
10823 continue;
10824
10825 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10826 // pad.
10827 for (MachineInstr &II : BB) {
10828 if (!II.isEHLabel())
10829 continue;
10830
10831 MCSymbol *Sym = II.getOperand(i: 0).getMCSymbol();
10832 if (!MF->hasCallSiteLandingPad(Sym)) continue;
10833
10834 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10835 for (unsigned Idx : CallSiteIdxs) {
10836 CallSiteNumToLPad[Idx].push_back(Elt: &BB);
10837 MaxCSNum = std::max(a: MaxCSNum, b: Idx);
10838 }
10839 break;
10840 }
10841 }
10842
10843 // Get an ordered list of the machine basic blocks for the jump table.
10844 std::vector<MachineBasicBlock*> LPadList;
10845 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10846 LPadList.reserve(n: CallSiteNumToLPad.size());
10847 for (unsigned I = 1; I <= MaxCSNum; ++I) {
10848 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10849 for (MachineBasicBlock *MBB : MBBList) {
10850 LPadList.push_back(x: MBB);
10851 InvokeBBs.insert_range(R: MBB->predecessors());
10852 }
10853 }
10854
10855 assert(!LPadList.empty() &&
10856 "No landing pad destinations for the dispatch jump table!");
10857
10858 // Create the jump table and associated information.
10859 MachineJumpTableInfo *JTI =
10860 MF->getOrCreateJumpTableInfo(JTEntryKind: MachineJumpTableInfo::EK_Inline);
10861 unsigned MJTI = JTI->createJumpTableIndex(DestBBs: LPadList);
10862
10863 // Create the MBBs for the dispatch code.
10864
10865 // Shove the dispatch's address into the return slot in the function context.
10866 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10867 DispatchBB->setIsEHPad();
10868
10869 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10870
10871 BuildMI(BB: TrapBB, MIMD: dl, MCID: TII->get(Opcode: Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
10872 DispatchBB->addSuccessor(Succ: TrapBB);
10873
10874 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10875 DispatchBB->addSuccessor(Succ: DispContBB);
10876
10877 // Insert and MBBs.
10878 MF->insert(MBBI: MF->end(), MBB: DispatchBB);
10879 MF->insert(MBBI: MF->end(), MBB: DispContBB);
10880 MF->insert(MBBI: MF->end(), MBB: TrapBB);
10881
10882 // Insert code into the entry block that creates and registers the function
10883 // context.
10884 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10885
10886 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10887 PtrInfo: MachinePointerInfo::getFixedStack(MF&: *MF, FI),
10888 F: MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, Size: 4, BaseAlignment: Align(4));
10889
10890 MachineInstrBuilder MIB;
10891 MIB = BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::Int_eh_sjlj_dispatchsetup));
10892
10893 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10894 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10895
10896 // Add a register mask with no preserved registers. This results in all
10897 // registers being marked as clobbered. This can't work if the dispatch block
10898 // is in a Thumb1 function and is linked with ARM code which uses the FP
10899 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10900 MIB.addRegMask(Mask: RI.getSjLjDispatchPreservedMask(MF: *MF));
10901
10902 bool IsPositionIndependent = isPositionIndependent();
10903 unsigned NumLPads = LPadList.size();
10904 if (Subtarget->isThumb2()) {
10905 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
10906 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2LDRi12), DestReg: NewVReg1)
10907 .addFrameIndex(Idx: FI)
10908 .addImm(Val: 4)
10909 .addMemOperand(MMO: FIMMOLd)
10910 .add(MOs: predOps(Pred: ARMCC::AL));
10911
10912 if (NumLPads < 256) {
10913 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2CMPri))
10914 .addReg(RegNo: NewVReg1)
10915 .addImm(Val: LPadList.size())
10916 .add(MOs: predOps(Pred: ARMCC::AL));
10917 } else {
10918 Register VReg1 = MRI->createVirtualRegister(RegClass: TRC);
10919 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2MOVi16), DestReg: VReg1)
10920 .addImm(Val: NumLPads & 0xFFFF)
10921 .add(MOs: predOps(Pred: ARMCC::AL));
10922
10923 unsigned VReg2 = VReg1;
10924 if ((NumLPads & 0xFFFF0000) != 0) {
10925 VReg2 = MRI->createVirtualRegister(RegClass: TRC);
10926 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2MOVTi16), DestReg: VReg2)
10927 .addReg(RegNo: VReg1)
10928 .addImm(Val: NumLPads >> 16)
10929 .add(MOs: predOps(Pred: ARMCC::AL));
10930 }
10931
10932 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2CMPrr))
10933 .addReg(RegNo: NewVReg1)
10934 .addReg(RegNo: VReg2)
10935 .add(MOs: predOps(Pred: ARMCC::AL));
10936 }
10937
10938 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2Bcc))
10939 .addMBB(MBB: TrapBB)
10940 .addImm(Val: ARMCC::HI)
10941 .addReg(RegNo: ARM::CPSR);
10942
10943 Register NewVReg3 = MRI->createVirtualRegister(RegClass: TRC);
10944 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2LEApcrelJT), DestReg: NewVReg3)
10945 .addJumpTableIndex(Idx: MJTI)
10946 .add(MOs: predOps(Pred: ARMCC::AL));
10947
10948 Register NewVReg4 = MRI->createVirtualRegister(RegClass: TRC);
10949 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2ADDrs), DestReg: NewVReg4)
10950 .addReg(RegNo: NewVReg3, Flags: RegState::Kill)
10951 .addReg(RegNo: NewVReg1)
10952 .addImm(Val: ARM_AM::getSORegOpc(ShOp: ARM_AM::lsl, Imm: 2))
10953 .add(MOs: predOps(Pred: ARMCC::AL))
10954 .add(MO: condCodeOp());
10955
10956 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2BR_JT))
10957 .addReg(RegNo: NewVReg4, Flags: RegState::Kill)
10958 .addReg(RegNo: NewVReg1)
10959 .addJumpTableIndex(Idx: MJTI);
10960 } else if (Subtarget->isThumb()) {
10961 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
10962 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDRspi), DestReg: NewVReg1)
10963 .addFrameIndex(Idx: FI)
10964 .addImm(Val: 1)
10965 .addMemOperand(MMO: FIMMOLd)
10966 .add(MOs: predOps(Pred: ARMCC::AL));
10967
10968 if (NumLPads < 256) {
10969 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tCMPi8))
10970 .addReg(RegNo: NewVReg1)
10971 .addImm(Val: NumLPads)
10972 .add(MOs: predOps(Pred: ARMCC::AL));
10973 } else {
10974 MachineConstantPool *ConstantPool = MF->getConstantPool();
10975 Type *Int32Ty = Type::getInt32Ty(C&: MF->getFunction().getContext());
10976 const Constant *C = ConstantInt::get(Ty: Int32Ty, V: NumLPads);
10977
10978 // MachineConstantPool wants an explicit alignment.
10979 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Ty: Int32Ty);
10980 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10981
10982 Register VReg1 = MRI->createVirtualRegister(RegClass: TRC);
10983 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDRpci))
10984 .addReg(RegNo: VReg1, Flags: RegState::Define)
10985 .addConstantPoolIndex(Idx)
10986 .add(MOs: predOps(Pred: ARMCC::AL));
10987 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tCMPr))
10988 .addReg(RegNo: NewVReg1)
10989 .addReg(RegNo: VReg1)
10990 .add(MOs: predOps(Pred: ARMCC::AL));
10991 }
10992
10993 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tBcc))
10994 .addMBB(MBB: TrapBB)
10995 .addImm(Val: ARMCC::HI)
10996 .addReg(RegNo: ARM::CPSR);
10997
10998 Register NewVReg2 = MRI->createVirtualRegister(RegClass: TRC);
10999 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tLSLri), DestReg: NewVReg2)
11000 .addReg(RegNo: ARM::CPSR, Flags: RegState::Define)
11001 .addReg(RegNo: NewVReg1)
11002 .addImm(Val: 2)
11003 .add(MOs: predOps(Pred: ARMCC::AL));
11004
11005 Register NewVReg3 = MRI->createVirtualRegister(RegClass: TRC);
11006 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tLEApcrelJT), DestReg: NewVReg3)
11007 .addJumpTableIndex(Idx: MJTI)
11008 .add(MOs: predOps(Pred: ARMCC::AL));
11009
11010 Register NewVReg4 = MRI->createVirtualRegister(RegClass: TRC);
11011 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tADDrr), DestReg: NewVReg4)
11012 .addReg(RegNo: ARM::CPSR, Flags: RegState::Define)
11013 .addReg(RegNo: NewVReg2, Flags: RegState::Kill)
11014 .addReg(RegNo: NewVReg3)
11015 .add(MOs: predOps(Pred: ARMCC::AL));
11016
11017 MachineMemOperand *JTMMOLd =
11018 MF->getMachineMemOperand(PtrInfo: MachinePointerInfo::getJumpTable(MF&: *MF),
11019 F: MachineMemOperand::MOLoad, Size: 4, BaseAlignment: Align(4));
11020
11021 Register NewVReg5 = MRI->createVirtualRegister(RegClass: TRC);
11022 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDRi), DestReg: NewVReg5)
11023 .addReg(RegNo: NewVReg4, Flags: RegState::Kill)
11024 .addImm(Val: 0)
11025 .addMemOperand(MMO: JTMMOLd)
11026 .add(MOs: predOps(Pred: ARMCC::AL));
11027
11028 unsigned NewVReg6 = NewVReg5;
11029 if (IsPositionIndependent) {
11030 NewVReg6 = MRI->createVirtualRegister(RegClass: TRC);
11031 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tADDrr), DestReg: NewVReg6)
11032 .addReg(RegNo: ARM::CPSR, Flags: RegState::Define)
11033 .addReg(RegNo: NewVReg5, Flags: RegState::Kill)
11034 .addReg(RegNo: NewVReg3)
11035 .add(MOs: predOps(Pred: ARMCC::AL));
11036 }
11037
11038 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tBR_JTr))
11039 .addReg(RegNo: NewVReg6, Flags: RegState::Kill)
11040 .addJumpTableIndex(Idx: MJTI);
11041 } else {
11042 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
11043 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::LDRi12), DestReg: NewVReg1)
11044 .addFrameIndex(Idx: FI)
11045 .addImm(Val: 4)
11046 .addMemOperand(MMO: FIMMOLd)
11047 .add(MOs: predOps(Pred: ARMCC::AL));
11048
11049 if (NumLPads < 256) {
11050 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::CMPri))
11051 .addReg(RegNo: NewVReg1)
11052 .addImm(Val: NumLPads)
11053 .add(MOs: predOps(Pred: ARMCC::AL));
11054 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(x: NumLPads)) {
11055 Register VReg1 = MRI->createVirtualRegister(RegClass: TRC);
11056 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::MOVi16), DestReg: VReg1)
11057 .addImm(Val: NumLPads & 0xFFFF)
11058 .add(MOs: predOps(Pred: ARMCC::AL));
11059
11060 unsigned VReg2 = VReg1;
11061 if ((NumLPads & 0xFFFF0000) != 0) {
11062 VReg2 = MRI->createVirtualRegister(RegClass: TRC);
11063 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::MOVTi16), DestReg: VReg2)
11064 .addReg(RegNo: VReg1)
11065 .addImm(Val: NumLPads >> 16)
11066 .add(MOs: predOps(Pred: ARMCC::AL));
11067 }
11068
11069 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::CMPrr))
11070 .addReg(RegNo: NewVReg1)
11071 .addReg(RegNo: VReg2)
11072 .add(MOs: predOps(Pred: ARMCC::AL));
11073 } else {
11074 MachineConstantPool *ConstantPool = MF->getConstantPool();
11075 Type *Int32Ty = Type::getInt32Ty(C&: MF->getFunction().getContext());
11076 const Constant *C = ConstantInt::get(Ty: Int32Ty, V: NumLPads);
11077
11078 // MachineConstantPool wants an explicit alignment.
11079 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Ty: Int32Ty);
11080 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11081
11082 Register VReg1 = MRI->createVirtualRegister(RegClass: TRC);
11083 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::LDRcp))
11084 .addReg(RegNo: VReg1, Flags: RegState::Define)
11085 .addConstantPoolIndex(Idx)
11086 .addImm(Val: 0)
11087 .add(MOs: predOps(Pred: ARMCC::AL));
11088 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::CMPrr))
11089 .addReg(RegNo: NewVReg1)
11090 .addReg(RegNo: VReg1, Flags: RegState::Kill)
11091 .add(MOs: predOps(Pred: ARMCC::AL));
11092 }
11093
11094 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::Bcc))
11095 .addMBB(MBB: TrapBB)
11096 .addImm(Val: ARMCC::HI)
11097 .addReg(RegNo: ARM::CPSR);
11098
11099 Register NewVReg3 = MRI->createVirtualRegister(RegClass: TRC);
11100 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::MOVsi), DestReg: NewVReg3)
11101 .addReg(RegNo: NewVReg1)
11102 .addImm(Val: ARM_AM::getSORegOpc(ShOp: ARM_AM::lsl, Imm: 2))
11103 .add(MOs: predOps(Pred: ARMCC::AL))
11104 .add(MO: condCodeOp());
11105 Register NewVReg4 = MRI->createVirtualRegister(RegClass: TRC);
11106 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::LEApcrelJT), DestReg: NewVReg4)
11107 .addJumpTableIndex(Idx: MJTI)
11108 .add(MOs: predOps(Pred: ARMCC::AL));
11109
11110 MachineMemOperand *JTMMOLd =
11111 MF->getMachineMemOperand(PtrInfo: MachinePointerInfo::getJumpTable(MF&: *MF),
11112 F: MachineMemOperand::MOLoad, Size: 4, BaseAlignment: Align(4));
11113 Register NewVReg5 = MRI->createVirtualRegister(RegClass: TRC);
11114 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::LDRrs), DestReg: NewVReg5)
11115 .addReg(RegNo: NewVReg3, Flags: RegState::Kill)
11116 .addReg(RegNo: NewVReg4)
11117 .addImm(Val: 0)
11118 .addMemOperand(MMO: JTMMOLd)
11119 .add(MOs: predOps(Pred: ARMCC::AL));
11120
11121 if (IsPositionIndependent) {
11122 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::BR_JTadd))
11123 .addReg(RegNo: NewVReg5, Flags: RegState::Kill)
11124 .addReg(RegNo: NewVReg4)
11125 .addJumpTableIndex(Idx: MJTI);
11126 } else {
11127 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::BR_JTr))
11128 .addReg(RegNo: NewVReg5, Flags: RegState::Kill)
11129 .addJumpTableIndex(Idx: MJTI);
11130 }
11131 }
11132
11133 // Add the jump table entries as successors to the MBB.
11134 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
11135 for (MachineBasicBlock *CurMBB : LPadList) {
11136 if (SeenMBBs.insert(Ptr: CurMBB).second)
11137 DispContBB->addSuccessor(Succ: CurMBB);
11138 }
11139
11140 // N.B. the order the invoke BBs are processed in doesn't matter here.
11141 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
11142 SmallVector<MachineBasicBlock*, 64> MBBLPads;
11143 for (MachineBasicBlock *BB : InvokeBBs) {
11144
11145 // Remove the landing pad successor from the invoke block and replace it
11146 // with the new dispatch block.
11147 SmallVector<MachineBasicBlock*, 4> Successors(BB->successors());
11148 while (!Successors.empty()) {
11149 MachineBasicBlock *SMBB = Successors.pop_back_val();
11150 if (SMBB->isEHPad()) {
11151 BB->removeSuccessor(Succ: SMBB);
11152 MBBLPads.push_back(Elt: SMBB);
11153 }
11154 }
11155
11156 BB->addSuccessor(Succ: DispatchBB, Prob: BranchProbability::getZero());
11157 BB->normalizeSuccProbs();
11158
11159 // Find the invoke call and mark all of the callee-saved registers as
11160 // 'implicit defined' so that they're spilled. This prevents code from
11161 // moving instructions to before the EH block, where they will never be
11162 // executed.
11163 for (MachineBasicBlock::reverse_iterator
11164 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
11165 if (!II->isCall()) continue;
11166
11167 DenseSet<unsigned> DefRegs;
11168 for (MachineInstr::mop_iterator
11169 OI = II->operands_begin(), OE = II->operands_end();
11170 OI != OE; ++OI) {
11171 if (!OI->isReg()) continue;
11172 DefRegs.insert(V: OI->getReg());
11173 }
11174
11175 MachineInstrBuilder MIB(*MF, &*II);
11176
11177 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
11178 unsigned Reg = SavedRegs[i];
11179 if (Subtarget->isThumb2() &&
11180 !ARM::tGPRRegClass.contains(Reg) &&
11181 !ARM::hGPRRegClass.contains(Reg))
11182 continue;
11183 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
11184 continue;
11185 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
11186 continue;
11187 if (!DefRegs.contains(V: Reg))
11188 MIB.addReg(RegNo: Reg, Flags: RegState::ImplicitDefine | RegState::Dead);
11189 }
11190
11191 break;
11192 }
11193 }
11194
11195 // Mark all former landing pads as non-landing pads. The dispatch is the only
11196 // landing pad now.
11197 for (MachineBasicBlock *MBBLPad : MBBLPads)
11198 MBBLPad->setIsEHPad(false);
11199
11200 // The instruction is gone now.
11201 MI.eraseFromParent();
11202}
11203
11204static
11205MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
11206 for (MachineBasicBlock *S : MBB->successors())
11207 if (S != Succ)
11208 return S;
11209 llvm_unreachable("Expecting a BB with two successors!");
11210}
11211
11212/// Return the load opcode for a given load size. If load size >= 8,
11213/// neon opcode will be returned.
11214static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
11215 if (LdSize >= 8)
11216 return LdSize == 16 ? ARM::VLD1q32wb_fixed
11217 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
11218 if (IsThumb1)
11219 return LdSize == 4 ? ARM::tLDRi
11220 : LdSize == 2 ? ARM::tLDRHi
11221 : LdSize == 1 ? ARM::tLDRBi : 0;
11222 if (IsThumb2)
11223 return LdSize == 4 ? ARM::t2LDR_POST
11224 : LdSize == 2 ? ARM::t2LDRH_POST
11225 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
11226 return LdSize == 4 ? ARM::LDR_POST_IMM
11227 : LdSize == 2 ? ARM::LDRH_POST
11228 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
11229}
11230
11231/// Return the store opcode for a given store size. If store size >= 8,
11232/// neon opcode will be returned.
11233static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
11234 if (StSize >= 8)
11235 return StSize == 16 ? ARM::VST1q32wb_fixed
11236 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
11237 if (IsThumb1)
11238 return StSize == 4 ? ARM::tSTRi
11239 : StSize == 2 ? ARM::tSTRHi
11240 : StSize == 1 ? ARM::tSTRBi : 0;
11241 if (IsThumb2)
11242 return StSize == 4 ? ARM::t2STR_POST
11243 : StSize == 2 ? ARM::t2STRH_POST
11244 : StSize == 1 ? ARM::t2STRB_POST : 0;
11245 return StSize == 4 ? ARM::STR_POST_IMM
11246 : StSize == 2 ? ARM::STRH_POST
11247 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
11248}
11249
11250/// Emit a post-increment load operation with given size. The instructions
11251/// will be added to BB at Pos.
11252static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11253 const TargetInstrInfo *TII, const DebugLoc &dl,
11254 unsigned LdSize, unsigned Data, unsigned AddrIn,
11255 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11256 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
11257 assert(LdOpc != 0 && "Should have a load opcode");
11258 if (LdSize >= 8) {
11259 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: LdOpc), DestReg: Data)
11260 .addReg(RegNo: AddrOut, Flags: RegState::Define)
11261 .addReg(RegNo: AddrIn)
11262 .addImm(Val: 0)
11263 .add(MOs: predOps(Pred: ARMCC::AL));
11264 } else if (IsThumb1) {
11265 // load + update AddrIn
11266 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: LdOpc), DestReg: Data)
11267 .addReg(RegNo: AddrIn)
11268 .addImm(Val: 0)
11269 .add(MOs: predOps(Pred: ARMCC::AL));
11270 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: ARM::tADDi8), DestReg: AddrOut)
11271 .add(MO: t1CondCodeOp())
11272 .addReg(RegNo: AddrIn)
11273 .addImm(Val: LdSize)
11274 .add(MOs: predOps(Pred: ARMCC::AL));
11275 } else if (IsThumb2) {
11276 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: LdOpc), DestReg: Data)
11277 .addReg(RegNo: AddrOut, Flags: RegState::Define)
11278 .addReg(RegNo: AddrIn)
11279 .addImm(Val: LdSize)
11280 .add(MOs: predOps(Pred: ARMCC::AL));
11281 } else { // arm
11282 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: LdOpc), DestReg: Data)
11283 .addReg(RegNo: AddrOut, Flags: RegState::Define)
11284 .addReg(RegNo: AddrIn)
11285 .addReg(RegNo: 0)
11286 .addImm(Val: LdSize)
11287 .add(MOs: predOps(Pred: ARMCC::AL));
11288 }
11289}
11290
11291/// Emit a post-increment store operation with given size. The instructions
11292/// will be added to BB at Pos.
11293static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11294 const TargetInstrInfo *TII, const DebugLoc &dl,
11295 unsigned StSize, unsigned Data, unsigned AddrIn,
11296 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11297 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
11298 assert(StOpc != 0 && "Should have a store opcode");
11299 if (StSize >= 8) {
11300 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: StOpc), DestReg: AddrOut)
11301 .addReg(RegNo: AddrIn)
11302 .addImm(Val: 0)
11303 .addReg(RegNo: Data)
11304 .add(MOs: predOps(Pred: ARMCC::AL));
11305 } else if (IsThumb1) {
11306 // store + update AddrIn
11307 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: StOpc))
11308 .addReg(RegNo: Data)
11309 .addReg(RegNo: AddrIn)
11310 .addImm(Val: 0)
11311 .add(MOs: predOps(Pred: ARMCC::AL));
11312 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: ARM::tADDi8), DestReg: AddrOut)
11313 .add(MO: t1CondCodeOp())
11314 .addReg(RegNo: AddrIn)
11315 .addImm(Val: StSize)
11316 .add(MOs: predOps(Pred: ARMCC::AL));
11317 } else if (IsThumb2) {
11318 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: StOpc), DestReg: AddrOut)
11319 .addReg(RegNo: Data)
11320 .addReg(RegNo: AddrIn)
11321 .addImm(Val: StSize)
11322 .add(MOs: predOps(Pred: ARMCC::AL));
11323 } else { // arm
11324 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: StOpc), DestReg: AddrOut)
11325 .addReg(RegNo: Data)
11326 .addReg(RegNo: AddrIn)
11327 .addReg(RegNo: 0)
11328 .addImm(Val: StSize)
11329 .add(MOs: predOps(Pred: ARMCC::AL));
11330 }
11331}
11332
11333MachineBasicBlock *
11334ARMTargetLowering::EmitStructByval(MachineInstr &MI,
11335 MachineBasicBlock *BB) const {
11336 // This pseudo instruction has 3 operands: dst, src, size
11337 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
11338 // Otherwise, we will generate unrolled scalar copies.
11339 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11340 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11341 MachineFunction::iterator It = ++BB->getIterator();
11342
11343 Register dest = MI.getOperand(i: 0).getReg();
11344 Register src = MI.getOperand(i: 1).getReg();
11345 unsigned SizeVal = MI.getOperand(i: 2).getImm();
11346 unsigned Alignment = MI.getOperand(i: 3).getImm();
11347 DebugLoc dl = MI.getDebugLoc();
11348
11349 MachineFunction *MF = BB->getParent();
11350 MachineRegisterInfo &MRI = MF->getRegInfo();
11351 unsigned UnitSize = 0;
11352 const TargetRegisterClass *TRC = nullptr;
11353 const TargetRegisterClass *VecTRC = nullptr;
11354
11355 bool IsThumb1 = Subtarget->isThumb1Only();
11356 bool IsThumb2 = Subtarget->isThumb2();
11357 bool IsThumb = Subtarget->isThumb();
11358
11359 if (Alignment & 1) {
11360 UnitSize = 1;
11361 } else if (Alignment & 2) {
11362 UnitSize = 2;
11363 } else {
11364 // Check whether we can use NEON instructions.
11365 if (!MF->getFunction().hasFnAttribute(Kind: Attribute::NoImplicitFloat) &&
11366 Subtarget->hasNEON()) {
11367 if ((Alignment % 16 == 0) && SizeVal >= 16)
11368 UnitSize = 16;
11369 else if ((Alignment % 8 == 0) && SizeVal >= 8)
11370 UnitSize = 8;
11371 }
11372 // Can't use NEON instructions.
11373 if (UnitSize == 0)
11374 UnitSize = 4;
11375 }
11376
11377 // Select the correct opcode and register class for unit size load/store
11378 bool IsNeon = UnitSize >= 8;
11379 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
11380 if (IsNeon)
11381 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
11382 : UnitSize == 8 ? &ARM::DPRRegClass
11383 : nullptr;
11384
11385 unsigned BytesLeft = SizeVal % UnitSize;
11386 unsigned LoopSize = SizeVal - BytesLeft;
11387
11388 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
11389 // Use LDR and STR to copy.
11390 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
11391 // [destOut] = STR_POST(scratch, destIn, UnitSize)
11392 unsigned srcIn = src;
11393 unsigned destIn = dest;
11394 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
11395 Register srcOut = MRI.createVirtualRegister(RegClass: TRC);
11396 Register destOut = MRI.createVirtualRegister(RegClass: TRC);
11397 Register scratch = MRI.createVirtualRegister(RegClass: IsNeon ? VecTRC : TRC);
11398 emitPostLd(BB, Pos: MI, TII, dl, LdSize: UnitSize, Data: scratch, AddrIn: srcIn, AddrOut: srcOut,
11399 IsThumb1, IsThumb2);
11400 emitPostSt(BB, Pos: MI, TII, dl, StSize: UnitSize, Data: scratch, AddrIn: destIn, AddrOut: destOut,
11401 IsThumb1, IsThumb2);
11402 srcIn = srcOut;
11403 destIn = destOut;
11404 }
11405
11406 // Handle the leftover bytes with LDRB and STRB.
11407 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
11408 // [destOut] = STRB_POST(scratch, destIn, 1)
11409 for (unsigned i = 0; i < BytesLeft; i++) {
11410 Register srcOut = MRI.createVirtualRegister(RegClass: TRC);
11411 Register destOut = MRI.createVirtualRegister(RegClass: TRC);
11412 Register scratch = MRI.createVirtualRegister(RegClass: TRC);
11413 emitPostLd(BB, Pos: MI, TII, dl, LdSize: 1, Data: scratch, AddrIn: srcIn, AddrOut: srcOut,
11414 IsThumb1, IsThumb2);
11415 emitPostSt(BB, Pos: MI, TII, dl, StSize: 1, Data: scratch, AddrIn: destIn, AddrOut: destOut,
11416 IsThumb1, IsThumb2);
11417 srcIn = srcOut;
11418 destIn = destOut;
11419 }
11420 MI.eraseFromParent(); // The instruction is gone now.
11421 return BB;
11422 }
11423
11424 // Expand the pseudo op to a loop.
11425 // thisMBB:
11426 // ...
11427 // movw varEnd, # --> with thumb2
11428 // movt varEnd, #
11429 // ldrcp varEnd, idx --> without thumb2
11430 // fallthrough --> loopMBB
11431 // loopMBB:
11432 // PHI varPhi, varEnd, varLoop
11433 // PHI srcPhi, src, srcLoop
11434 // PHI destPhi, dst, destLoop
11435 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11436 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
11437 // subs varLoop, varPhi, #UnitSize
11438 // bne loopMBB
11439 // fallthrough --> exitMBB
11440 // exitMBB:
11441 // epilogue to handle left-over bytes
11442 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11443 // [destOut] = STRB_POST(scratch, destLoop, 1)
11444 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(BB: LLVM_BB);
11445 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(BB: LLVM_BB);
11446 MF->insert(MBBI: It, MBB: loopMBB);
11447 MF->insert(MBBI: It, MBB: exitMBB);
11448
11449 // Set the call frame size on entry to the new basic blocks.
11450 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
11451 loopMBB->setCallFrameSize(CallFrameSize);
11452 exitMBB->setCallFrameSize(CallFrameSize);
11453
11454 // Transfer the remainder of BB and its successor edges to exitMBB.
11455 exitMBB->splice(Where: exitMBB->begin(), Other: BB,
11456 From: std::next(x: MachineBasicBlock::iterator(MI)), To: BB->end());
11457 exitMBB->transferSuccessorsAndUpdatePHIs(FromMBB: BB);
11458
11459 // Load an immediate to varEnd.
11460 Register varEnd = MRI.createVirtualRegister(RegClass: TRC);
11461 if (Subtarget->useMovt()) {
11462 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: IsThumb ? ARM::t2MOVi32imm : ARM::MOVi32imm),
11463 DestReg: varEnd)
11464 .addImm(Val: LoopSize);
11465 } else if (Subtarget->genExecuteOnly()) {
11466 assert(IsThumb && "Non-thumb expected to have used movt");
11467 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::tMOVi32imm), DestReg: varEnd).addImm(Val: LoopSize);
11468 } else {
11469 MachineConstantPool *ConstantPool = MF->getConstantPool();
11470 Type *Int32Ty = Type::getInt32Ty(C&: MF->getFunction().getContext());
11471 const Constant *C = ConstantInt::get(Ty: Int32Ty, V: LoopSize);
11472
11473 // MachineConstantPool wants an explicit alignment.
11474 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Ty: Int32Ty);
11475 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11476 MachineMemOperand *CPMMO =
11477 MF->getMachineMemOperand(PtrInfo: MachinePointerInfo::getConstantPool(MF&: *MF),
11478 F: MachineMemOperand::MOLoad, Size: 4, BaseAlignment: Align(4));
11479
11480 if (IsThumb)
11481 BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDRpci))
11482 .addReg(RegNo: varEnd, Flags: RegState::Define)
11483 .addConstantPoolIndex(Idx)
11484 .add(MOs: predOps(Pred: ARMCC::AL))
11485 .addMemOperand(MMO: CPMMO);
11486 else
11487 BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::LDRcp))
11488 .addReg(RegNo: varEnd, Flags: RegState::Define)
11489 .addConstantPoolIndex(Idx)
11490 .addImm(Val: 0)
11491 .add(MOs: predOps(Pred: ARMCC::AL))
11492 .addMemOperand(MMO: CPMMO);
11493 }
11494 BB->addSuccessor(Succ: loopMBB);
11495
11496 // Generate the loop body:
11497 // varPhi = PHI(varLoop, varEnd)
11498 // srcPhi = PHI(srcLoop, src)
11499 // destPhi = PHI(destLoop, dst)
11500 MachineBasicBlock *entryBB = BB;
11501 BB = loopMBB;
11502 Register varLoop = MRI.createVirtualRegister(RegClass: TRC);
11503 Register varPhi = MRI.createVirtualRegister(RegClass: TRC);
11504 Register srcLoop = MRI.createVirtualRegister(RegClass: TRC);
11505 Register srcPhi = MRI.createVirtualRegister(RegClass: TRC);
11506 Register destLoop = MRI.createVirtualRegister(RegClass: TRC);
11507 Register destPhi = MRI.createVirtualRegister(RegClass: TRC);
11508
11509 BuildMI(BB&: *BB, I: BB->begin(), MIMD: dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: varPhi)
11510 .addReg(RegNo: varLoop).addMBB(MBB: loopMBB)
11511 .addReg(RegNo: varEnd).addMBB(MBB: entryBB);
11512 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: srcPhi)
11513 .addReg(RegNo: srcLoop).addMBB(MBB: loopMBB)
11514 .addReg(RegNo: src).addMBB(MBB: entryBB);
11515 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: destPhi)
11516 .addReg(RegNo: destLoop).addMBB(MBB: loopMBB)
11517 .addReg(RegNo: dest).addMBB(MBB: entryBB);
11518
11519 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11520 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
11521 Register scratch = MRI.createVirtualRegister(RegClass: IsNeon ? VecTRC : TRC);
11522 emitPostLd(BB, Pos: BB->end(), TII, dl, LdSize: UnitSize, Data: scratch, AddrIn: srcPhi, AddrOut: srcLoop,
11523 IsThumb1, IsThumb2);
11524 emitPostSt(BB, Pos: BB->end(), TII, dl, StSize: UnitSize, Data: scratch, AddrIn: destPhi, AddrOut: destLoop,
11525 IsThumb1, IsThumb2);
11526
11527 // Decrement loop variable by UnitSize.
11528 if (IsThumb1) {
11529 BuildMI(BB&: *BB, I: BB->end(), MIMD: dl, MCID: TII->get(Opcode: ARM::tSUBi8), DestReg: varLoop)
11530 .add(MO: t1CondCodeOp())
11531 .addReg(RegNo: varPhi)
11532 .addImm(Val: UnitSize)
11533 .add(MOs: predOps(Pred: ARMCC::AL));
11534 } else {
11535 MachineInstrBuilder MIB =
11536 BuildMI(BB&: *BB, I: BB->end(), MIMD: dl,
11537 MCID: TII->get(Opcode: IsThumb2 ? ARM::t2SUBri : ARM::SUBri), DestReg: varLoop);
11538 MIB.addReg(RegNo: varPhi)
11539 .addImm(Val: UnitSize)
11540 .add(MOs: predOps(Pred: ARMCC::AL))
11541 .add(MO: condCodeOp());
11542 MIB->getOperand(i: 5).setReg(ARM::CPSR);
11543 MIB->getOperand(i: 5).setIsDef(true);
11544 }
11545 BuildMI(BB&: *BB, I: BB->end(), MIMD: dl,
11546 MCID: TII->get(Opcode: IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
11547 .addMBB(MBB: loopMBB).addImm(Val: ARMCC::NE).addReg(RegNo: ARM::CPSR);
11548
11549 // loopMBB can loop back to loopMBB or fall through to exitMBB.
11550 BB->addSuccessor(Succ: loopMBB);
11551 BB->addSuccessor(Succ: exitMBB);
11552
11553 // Add epilogue to handle BytesLeft.
11554 BB = exitMBB;
11555 auto StartOfExit = exitMBB->begin();
11556
11557 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11558 // [destOut] = STRB_POST(scratch, destLoop, 1)
11559 unsigned srcIn = srcLoop;
11560 unsigned destIn = destLoop;
11561 for (unsigned i = 0; i < BytesLeft; i++) {
11562 Register srcOut = MRI.createVirtualRegister(RegClass: TRC);
11563 Register destOut = MRI.createVirtualRegister(RegClass: TRC);
11564 Register scratch = MRI.createVirtualRegister(RegClass: TRC);
11565 emitPostLd(BB, Pos: StartOfExit, TII, dl, LdSize: 1, Data: scratch, AddrIn: srcIn, AddrOut: srcOut,
11566 IsThumb1, IsThumb2);
11567 emitPostSt(BB, Pos: StartOfExit, TII, dl, StSize: 1, Data: scratch, AddrIn: destIn, AddrOut: destOut,
11568 IsThumb1, IsThumb2);
11569 srcIn = srcOut;
11570 destIn = destOut;
11571 }
11572
11573 MI.eraseFromParent(); // The instruction is gone now.
11574 return BB;
11575}
11576
11577MachineBasicBlock *
11578ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
11579 MachineBasicBlock *MBB) const {
11580 const TargetMachine &TM = getTargetMachine();
11581 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
11582 DebugLoc DL = MI.getDebugLoc();
11583
11584 assert(TM.getTargetTriple().isOSWindows() &&
11585 "__chkstk is only supported on Windows");
11586 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
11587
11588 // __chkstk takes the number of words to allocate on the stack in R4, and
11589 // returns the stack adjustment in number of bytes in R4. This will not
11590 // clober any other registers (other than the obvious lr).
11591 //
11592 // Although, technically, IP should be considered a register which may be
11593 // clobbered, the call itself will not touch it. Windows on ARM is a pure
11594 // thumb-2 environment, so there is no interworking required. As a result, we
11595 // do not expect a veneer to be emitted by the linker, clobbering IP.
11596 //
11597 // Each module receives its own copy of __chkstk, so no import thunk is
11598 // required, again, ensuring that IP is not clobbered.
11599 //
11600 // Finally, although some linkers may theoretically provide a trampoline for
11601 // out of range calls (which is quite common due to a 32M range limitation of
11602 // branches for Thumb), we can generate the long-call version via
11603 // -mcmodel=large, alleviating the need for the trampoline which may clobber
11604 // IP.
11605
11606 RTLIB::LibcallImpl ChkStkLibcall = getLibcallImpl(Call: RTLIB::STACK_PROBE);
11607 if (ChkStkLibcall == RTLIB::Unsupported)
11608 reportFatalUsageError(reason: "no available implementation of __chkstk");
11609
11610 const char *ChkStk = getLibcallImplName(Call: ChkStkLibcall).data();
11611 switch (TM.getCodeModel()) {
11612 case CodeModel::Tiny:
11613 llvm_unreachable("Tiny code model not available on ARM.");
11614 case CodeModel::Small:
11615 case CodeModel::Medium:
11616 case CodeModel::Kernel:
11617 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::tBL))
11618 .add(MOs: predOps(Pred: ARMCC::AL))
11619 .addExternalSymbol(FnName: ChkStk)
11620 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit | RegState::Kill)
11621 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit | RegState::Define)
11622 .addReg(RegNo: ARM::R12,
11623 Flags: RegState::Implicit | RegState::Define | RegState::Dead)
11624 .addReg(RegNo: ARM::CPSR,
11625 Flags: RegState::Implicit | RegState::Define | RegState::Dead);
11626 break;
11627 case CodeModel::Large: {
11628 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11629 Register Reg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11630
11631 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::t2MOVi32imm), DestReg: Reg)
11632 .addExternalSymbol(FnName: ChkStk);
11633 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII.get(Opcode: gettBLXrOpcode(MF: *MBB->getParent())))
11634 .add(MOs: predOps(Pred: ARMCC::AL))
11635 .addReg(RegNo: Reg, Flags: RegState::Kill)
11636 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit | RegState::Kill)
11637 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit | RegState::Define)
11638 .addReg(RegNo: ARM::R12,
11639 Flags: RegState::Implicit | RegState::Define | RegState::Dead)
11640 .addReg(RegNo: ARM::CPSR,
11641 Flags: RegState::Implicit | RegState::Define | RegState::Dead);
11642 break;
11643 }
11644 }
11645
11646 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::t2SUBrr), DestReg: ARM::SP)
11647 .addReg(RegNo: ARM::SP, Flags: RegState::Kill)
11648 .addReg(RegNo: ARM::R4, Flags: RegState::Kill)
11649 .setMIFlags(MachineInstr::FrameSetup)
11650 .add(MOs: predOps(Pred: ARMCC::AL))
11651 .add(MO: condCodeOp());
11652
11653 MI.eraseFromParent();
11654 return MBB;
11655}
11656
11657MachineBasicBlock *
11658ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
11659 MachineBasicBlock *MBB) const {
11660 DebugLoc DL = MI.getDebugLoc();
11661 MachineFunction *MF = MBB->getParent();
11662 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11663
11664 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
11665 MF->insert(MBBI: ++MBB->getIterator(), MBB: ContBB);
11666 ContBB->splice(Where: ContBB->begin(), Other: MBB,
11667 From: std::next(x: MachineBasicBlock::iterator(MI)), To: MBB->end());
11668 ContBB->transferSuccessorsAndUpdatePHIs(FromMBB: MBB);
11669 MBB->addSuccessor(Succ: ContBB);
11670
11671 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
11672 BuildMI(BB: TrapBB, MIMD: DL, MCID: TII->get(Opcode: ARM::t__brkdiv0));
11673 MF->push_back(MBB: TrapBB);
11674 MBB->addSuccessor(Succ: TrapBB);
11675
11676 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII->get(Opcode: ARM::tCMPi8))
11677 .addReg(RegNo: MI.getOperand(i: 0).getReg())
11678 .addImm(Val: 0)
11679 .add(MOs: predOps(Pred: ARMCC::AL));
11680 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII->get(Opcode: ARM::t2Bcc))
11681 .addMBB(MBB: TrapBB)
11682 .addImm(Val: ARMCC::EQ)
11683 .addReg(RegNo: ARM::CPSR);
11684
11685 MI.eraseFromParent();
11686 return ContBB;
11687}
11688
11689// The CPSR operand of SelectItr might be missing a kill marker
11690// because there were multiple uses of CPSR, and ISel didn't know
11691// which to mark. Figure out whether SelectItr should have had a
11692// kill marker, and set it if it should. Returns the correct kill
11693// marker value.
11694static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
11695 MachineBasicBlock* BB,
11696 const TargetRegisterInfo* TRI) {
11697 // Scan forward through BB for a use/def of CPSR.
11698 MachineBasicBlock::iterator miI(std::next(x: SelectItr));
11699 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
11700 const MachineInstr& mi = *miI;
11701 if (mi.readsRegister(Reg: ARM::CPSR, /*TRI=*/nullptr))
11702 return false;
11703 if (mi.definesRegister(Reg: ARM::CPSR, /*TRI=*/nullptr))
11704 break; // Should have kill-flag - update below.
11705 }
11706
11707 // If we hit the end of the block, check whether CPSR is live into a
11708 // successor.
11709 if (miI == BB->end()) {
11710 for (MachineBasicBlock *Succ : BB->successors())
11711 if (Succ->isLiveIn(Reg: ARM::CPSR))
11712 return false;
11713 }
11714
11715 // We found a def, or hit the end of the basic block and CPSR wasn't live
11716 // out. SelectMI should have a kill flag on CPSR.
11717 SelectItr->addRegisterKilled(IncomingReg: ARM::CPSR, RegInfo: TRI);
11718 return true;
11719}
11720
11721/// Adds logic in loop entry MBB to calculate loop iteration count and adds
11722/// t2WhileLoopSetup and t2WhileLoopStart to generate WLS loop
11723static Register genTPEntry(MachineBasicBlock *TpEntry,
11724 MachineBasicBlock *TpLoopBody,
11725 MachineBasicBlock *TpExit, Register OpSizeReg,
11726 const TargetInstrInfo *TII, DebugLoc Dl,
11727 MachineRegisterInfo &MRI) {
11728 // Calculates loop iteration count = ceil(n/16) = (n + 15) >> 4.
11729 Register AddDestReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11730 BuildMI(BB: TpEntry, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2ADDri), DestReg: AddDestReg)
11731 .addUse(RegNo: OpSizeReg)
11732 .addImm(Val: 15)
11733 .add(MOs: predOps(Pred: ARMCC::AL))
11734 .addReg(RegNo: 0);
11735
11736 Register LsrDestReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11737 BuildMI(BB: TpEntry, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2LSRri), DestReg: LsrDestReg)
11738 .addUse(RegNo: AddDestReg, Flags: RegState::Kill)
11739 .addImm(Val: 4)
11740 .add(MOs: predOps(Pred: ARMCC::AL))
11741 .addReg(RegNo: 0);
11742
11743 Register TotalIterationsReg = MRI.createVirtualRegister(RegClass: &ARM::GPRlrRegClass);
11744 BuildMI(BB: TpEntry, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2WhileLoopSetup), DestReg: TotalIterationsReg)
11745 .addUse(RegNo: LsrDestReg, Flags: RegState::Kill);
11746
11747 BuildMI(BB: TpEntry, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2WhileLoopStart))
11748 .addUse(RegNo: TotalIterationsReg)
11749 .addMBB(MBB: TpExit);
11750
11751 BuildMI(BB: TpEntry, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2B))
11752 .addMBB(MBB: TpLoopBody)
11753 .add(MOs: predOps(Pred: ARMCC::AL));
11754
11755 return TotalIterationsReg;
11756}
11757
11758/// Adds logic in the loopBody MBB to generate MVE_VCTP, t2DoLoopDec and
11759/// t2DoLoopEnd. These are used by later passes to generate tail predicated
11760/// loops.
11761static void genTPLoopBody(MachineBasicBlock *TpLoopBody,
11762 MachineBasicBlock *TpEntry, MachineBasicBlock *TpExit,
11763 const TargetInstrInfo *TII, DebugLoc Dl,
11764 MachineRegisterInfo &MRI, Register OpSrcReg,
11765 Register OpDestReg, Register ElementCountReg,
11766 Register TotalIterationsReg, bool IsMemcpy) {
11767 // First insert 4 PHI nodes for: Current pointer to Src (if memcpy), Dest
11768 // array, loop iteration counter, predication counter.
11769
11770 Register SrcPhiReg, CurrSrcReg;
11771 if (IsMemcpy) {
11772 // Current position in the src array
11773 SrcPhiReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11774 CurrSrcReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11775 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: SrcPhiReg)
11776 .addUse(RegNo: OpSrcReg)
11777 .addMBB(MBB: TpEntry)
11778 .addUse(RegNo: CurrSrcReg)
11779 .addMBB(MBB: TpLoopBody);
11780 }
11781
11782 // Current position in the dest array
11783 Register DestPhiReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11784 Register CurrDestReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11785 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: DestPhiReg)
11786 .addUse(RegNo: OpDestReg)
11787 .addMBB(MBB: TpEntry)
11788 .addUse(RegNo: CurrDestReg)
11789 .addMBB(MBB: TpLoopBody);
11790
11791 // Current loop counter
11792 Register LoopCounterPhiReg = MRI.createVirtualRegister(RegClass: &ARM::GPRlrRegClass);
11793 Register RemainingLoopIterationsReg =
11794 MRI.createVirtualRegister(RegClass: &ARM::GPRlrRegClass);
11795 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: LoopCounterPhiReg)
11796 .addUse(RegNo: TotalIterationsReg)
11797 .addMBB(MBB: TpEntry)
11798 .addUse(RegNo: RemainingLoopIterationsReg)
11799 .addMBB(MBB: TpLoopBody);
11800
11801 // Predication counter
11802 Register PredCounterPhiReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11803 Register RemainingElementsReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11804 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: PredCounterPhiReg)
11805 .addUse(RegNo: ElementCountReg)
11806 .addMBB(MBB: TpEntry)
11807 .addUse(RegNo: RemainingElementsReg)
11808 .addMBB(MBB: TpLoopBody);
11809
11810 // Pass predication counter to VCTP
11811 Register VccrReg = MRI.createVirtualRegister(RegClass: &ARM::VCCRRegClass);
11812 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::MVE_VCTP8), DestReg: VccrReg)
11813 .addUse(RegNo: PredCounterPhiReg)
11814 .addImm(Val: ARMVCC::None)
11815 .addReg(RegNo: 0)
11816 .addReg(RegNo: 0);
11817
11818 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2SUBri), DestReg: RemainingElementsReg)
11819 .addUse(RegNo: PredCounterPhiReg)
11820 .addImm(Val: 16)
11821 .add(MOs: predOps(Pred: ARMCC::AL))
11822 .addReg(RegNo: 0);
11823
11824 // VLDRB (only if memcpy) and VSTRB instructions, predicated using VPR
11825 Register SrcValueReg;
11826 if (IsMemcpy) {
11827 SrcValueReg = MRI.createVirtualRegister(RegClass: &ARM::MQPRRegClass);
11828 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::MVE_VLDRBU8_post))
11829 .addDef(RegNo: CurrSrcReg)
11830 .addDef(RegNo: SrcValueReg)
11831 .addReg(RegNo: SrcPhiReg)
11832 .addImm(Val: 16)
11833 .addImm(Val: ARMVCC::Then)
11834 .addUse(RegNo: VccrReg)
11835 .addReg(RegNo: 0);
11836 } else
11837 SrcValueReg = OpSrcReg;
11838
11839 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::MVE_VSTRBU8_post))
11840 .addDef(RegNo: CurrDestReg)
11841 .addUse(RegNo: SrcValueReg)
11842 .addReg(RegNo: DestPhiReg)
11843 .addImm(Val: 16)
11844 .addImm(Val: ARMVCC::Then)
11845 .addUse(RegNo: VccrReg)
11846 .addReg(RegNo: 0);
11847
11848 // Add the pseudoInstrs for decrementing the loop counter and marking the
11849 // end:t2DoLoopDec and t2DoLoopEnd
11850 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2LoopDec), DestReg: RemainingLoopIterationsReg)
11851 .addUse(RegNo: LoopCounterPhiReg)
11852 .addImm(Val: 1);
11853
11854 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2LoopEnd))
11855 .addUse(RegNo: RemainingLoopIterationsReg)
11856 .addMBB(MBB: TpLoopBody);
11857
11858 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2B))
11859 .addMBB(MBB: TpExit)
11860 .add(MOs: predOps(Pred: ARMCC::AL));
11861}
11862
11863bool ARMTargetLowering::supportKCFIBundles() const {
11864 // KCFI is supported in all ARM/Thumb modes
11865 return true;
11866}
11867
11868MachineInstr *
11869ARMTargetLowering::EmitKCFICheck(MachineBasicBlock &MBB,
11870 MachineBasicBlock::instr_iterator &MBBI,
11871 const TargetInstrInfo *TII) const {
11872 assert(MBBI->isCall() && MBBI->getCFIType() &&
11873 "Invalid call instruction for a KCFI check");
11874
11875 MachineOperand *TargetOp = nullptr;
11876 switch (MBBI->getOpcode()) {
11877 // ARM mode opcodes
11878 case ARM::BLX:
11879 case ARM::BLX_pred:
11880 case ARM::BLX_noip:
11881 case ARM::BLX_pred_noip:
11882 case ARM::BX_CALL:
11883 TargetOp = &MBBI->getOperand(i: 0);
11884 break;
11885 case ARM::TCRETURNri:
11886 case ARM::TCRETURNrinotr12:
11887 case ARM::TAILJMPr:
11888 case ARM::TAILJMPr4:
11889 TargetOp = &MBBI->getOperand(i: 0);
11890 break;
11891 // Thumb mode opcodes (Thumb1 and Thumb2)
11892 // Note: Most Thumb call instructions have predicate operands before the
11893 // target register Format: tBLXr pred, predreg, target_register, ...
11894 case ARM::tBLXr: // Thumb1/Thumb2: BLX register (requires V5T)
11895 case ARM::tBLXr_noip: // Thumb1/Thumb2: BLX register, no IP clobber
11896 case ARM::tBX_CALL: // Thumb1 only: BX call (push LR, BX)
11897 TargetOp = &MBBI->getOperand(i: 2);
11898 break;
11899 // Tail call instructions don't have predicates, target is operand 0
11900 case ARM::tTAILJMPr: // Thumb1/Thumb2: Tail call via register
11901 TargetOp = &MBBI->getOperand(i: 0);
11902 break;
11903 default:
11904 llvm_unreachable("Unexpected CFI call opcode");
11905 }
11906
11907 assert(TargetOp && TargetOp->isReg() && "Invalid target operand");
11908 TargetOp->setIsRenamable(false);
11909
11910 // Select the appropriate KCFI_CHECK variant based on the instruction set
11911 unsigned KCFICheckOpcode;
11912 if (Subtarget->isThumb()) {
11913 if (Subtarget->isThumb2()) {
11914 KCFICheckOpcode = ARM::KCFI_CHECK_Thumb2;
11915 } else {
11916 KCFICheckOpcode = ARM::KCFI_CHECK_Thumb1;
11917 }
11918 } else {
11919 KCFICheckOpcode = ARM::KCFI_CHECK_ARM;
11920 }
11921
11922 return BuildMI(BB&: MBB, I: MBBI, MIMD: MBBI->getDebugLoc(), MCID: TII->get(Opcode: KCFICheckOpcode))
11923 .addReg(RegNo: TargetOp->getReg())
11924 .addImm(Val: MBBI->getCFIType())
11925 .getInstr();
11926}
11927
11928MachineBasicBlock *
11929ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11930 MachineBasicBlock *BB) const {
11931 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11932 DebugLoc dl = MI.getDebugLoc();
11933 bool isThumb2 = Subtarget->isThumb2();
11934 switch (MI.getOpcode()) {
11935 default: {
11936 MI.print(OS&: errs());
11937 llvm_unreachable("Unexpected instr type to insert");
11938 }
11939
11940 // Thumb1 post-indexed loads are really just single-register LDMs.
11941 case ARM::tLDR_postidx: {
11942 MachineOperand Def(MI.getOperand(i: 1));
11943 BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDMIA_UPD))
11944 .add(MO: Def) // Rn_wb
11945 .add(MO: MI.getOperand(i: 2)) // Rn
11946 .add(MO: MI.getOperand(i: 3)) // PredImm
11947 .add(MO: MI.getOperand(i: 4)) // PredReg
11948 .add(MO: MI.getOperand(i: 0)) // Rt
11949 .cloneMemRefs(OtherMI: MI);
11950 MI.eraseFromParent();
11951 return BB;
11952 }
11953
11954 case ARM::MVE_MEMCPYLOOPINST:
11955 case ARM::MVE_MEMSETLOOPINST: {
11956
11957 // Transformation below expands MVE_MEMCPYLOOPINST/MVE_MEMSETLOOPINST Pseudo
11958 // into a Tail Predicated (TP) Loop. It adds the instructions to calculate
11959 // the iteration count =ceil(size_in_bytes/16)) in the TP entry block and
11960 // adds the relevant instructions in the TP loop Body for generation of a
11961 // WLSTP loop.
11962
11963 // Below is relevant portion of the CFG after the transformation.
11964 // The Machine Basic Blocks are shown along with branch conditions (in
11965 // brackets). Note that TP entry/exit MBBs depict the entry/exit of this
11966 // portion of the CFG and may not necessarily be the entry/exit of the
11967 // function.
11968
11969 // (Relevant) CFG after transformation:
11970 // TP entry MBB
11971 // |
11972 // |-----------------|
11973 // (n <= 0) (n > 0)
11974 // | |
11975 // | TP loop Body MBB<--|
11976 // | | |
11977 // \ |___________|
11978 // \ /
11979 // TP exit MBB
11980
11981 MachineFunction *MF = BB->getParent();
11982 MachineFunctionProperties &Properties = MF->getProperties();
11983 MachineRegisterInfo &MRI = MF->getRegInfo();
11984
11985 Register OpDestReg = MI.getOperand(i: 0).getReg();
11986 Register OpSrcReg = MI.getOperand(i: 1).getReg();
11987 Register OpSizeReg = MI.getOperand(i: 2).getReg();
11988
11989 // Allocate the required MBBs and add to parent function.
11990 MachineBasicBlock *TpEntry = BB;
11991 MachineBasicBlock *TpLoopBody = MF->CreateMachineBasicBlock();
11992 MachineBasicBlock *TpExit;
11993
11994 MF->push_back(MBB: TpLoopBody);
11995
11996 // If any instructions are present in the current block after
11997 // MVE_MEMCPYLOOPINST or MVE_MEMSETLOOPINST, split the current block and
11998 // move the instructions into the newly created exit block. If there are no
11999 // instructions add an explicit branch to the FallThrough block and then
12000 // split.
12001 //
12002 // The split is required for two reasons:
12003 // 1) A terminator(t2WhileLoopStart) will be placed at that site.
12004 // 2) Since a TPLoopBody will be added later, any phis in successive blocks
12005 // need to be updated. splitAt() already handles this.
12006 TpExit = BB->splitAt(SplitInst&: MI, UpdateLiveIns: false);
12007 if (TpExit == BB) {
12008 assert(BB->canFallThrough() && "Exit Block must be Fallthrough of the "
12009 "block containing memcpy/memset Pseudo");
12010 TpExit = BB->getFallThrough();
12011 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2B))
12012 .addMBB(MBB: TpExit)
12013 .add(MOs: predOps(Pred: ARMCC::AL));
12014 TpExit = BB->splitAt(SplitInst&: MI, UpdateLiveIns: false);
12015 }
12016
12017 // Add logic for iteration count
12018 Register TotalIterationsReg =
12019 genTPEntry(TpEntry, TpLoopBody, TpExit, OpSizeReg, TII, Dl: dl, MRI);
12020
12021 // Add the vectorized (and predicated) loads/store instructions
12022 bool IsMemcpy = MI.getOpcode() == ARM::MVE_MEMCPYLOOPINST;
12023 genTPLoopBody(TpLoopBody, TpEntry, TpExit, TII, Dl: dl, MRI, OpSrcReg,
12024 OpDestReg, ElementCountReg: OpSizeReg, TotalIterationsReg, IsMemcpy);
12025
12026 // Required to avoid conflict with the MachineVerifier during testing.
12027 Properties.resetNoPHIs();
12028
12029 // Connect the blocks
12030 TpEntry->addSuccessor(Succ: TpLoopBody);
12031 TpLoopBody->addSuccessor(Succ: TpLoopBody);
12032 TpLoopBody->addSuccessor(Succ: TpExit);
12033
12034 // Reorder for a more natural layout
12035 TpLoopBody->moveAfter(NewBefore: TpEntry);
12036 TpExit->moveAfter(NewBefore: TpLoopBody);
12037
12038 // Finally, remove the memcpy Pseudo Instruction
12039 MI.eraseFromParent();
12040
12041 // Return the exit block as it may contain other instructions requiring a
12042 // custom inserter
12043 return TpExit;
12044 }
12045
12046 // The Thumb2 pre-indexed stores have the same MI operands, they just
12047 // define them differently in the .td files from the isel patterns, so
12048 // they need pseudos.
12049 case ARM::t2STR_preidx:
12050 MI.setDesc(TII->get(Opcode: ARM::t2STR_PRE));
12051 return BB;
12052 case ARM::t2STRB_preidx:
12053 MI.setDesc(TII->get(Opcode: ARM::t2STRB_PRE));
12054 return BB;
12055 case ARM::t2STRH_preidx:
12056 MI.setDesc(TII->get(Opcode: ARM::t2STRH_PRE));
12057 return BB;
12058
12059 case ARM::STRi_preidx:
12060 case ARM::STRBi_preidx: {
12061 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
12062 : ARM::STRB_PRE_IMM;
12063 // Decode the offset.
12064 unsigned Offset = MI.getOperand(i: 4).getImm();
12065 bool isSub = ARM_AM::getAM2Op(AM2Opc: Offset) == ARM_AM::sub;
12066 Offset = ARM_AM::getAM2Offset(AM2Opc: Offset);
12067 if (isSub)
12068 Offset = -Offset;
12069
12070 MachineMemOperand *MMO = *MI.memoperands_begin();
12071 BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: NewOpc))
12072 .add(MO: MI.getOperand(i: 0)) // Rn_wb
12073 .add(MO: MI.getOperand(i: 1)) // Rt
12074 .add(MO: MI.getOperand(i: 2)) // Rn
12075 .addImm(Val: Offset) // offset (skip GPR==zero_reg)
12076 .add(MO: MI.getOperand(i: 5)) // pred
12077 .add(MO: MI.getOperand(i: 6))
12078 .addMemOperand(MMO);
12079 MI.eraseFromParent();
12080 return BB;
12081 }
12082 case ARM::STRr_preidx:
12083 case ARM::STRBr_preidx:
12084 case ARM::STRH_preidx: {
12085 unsigned NewOpc;
12086 switch (MI.getOpcode()) {
12087 default: llvm_unreachable("unexpected opcode!");
12088 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
12089 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
12090 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
12091 }
12092 MachineInstrBuilder MIB = BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: NewOpc));
12093 for (const MachineOperand &MO : MI.operands())
12094 MIB.add(MO);
12095 MI.eraseFromParent();
12096 return BB;
12097 }
12098
12099 case ARM::tMOVCCr_pseudo: {
12100 // To "insert" a SELECT_CC instruction, we actually have to insert the
12101 // diamond control-flow pattern. The incoming instruction knows the
12102 // destination vreg to set, the condition code register to branch on, the
12103 // true/false values to select between, and a branch opcode to use.
12104 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12105 MachineFunction::iterator It = ++BB->getIterator();
12106
12107 // thisMBB:
12108 // ...
12109 // TrueVal = ...
12110 // cmpTY ccX, r1, r2
12111 // bCC copy1MBB
12112 // fallthrough --> copy0MBB
12113 MachineBasicBlock *thisMBB = BB;
12114 MachineFunction *F = BB->getParent();
12115 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(BB: LLVM_BB);
12116 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(BB: LLVM_BB);
12117 F->insert(MBBI: It, MBB: copy0MBB);
12118 F->insert(MBBI: It, MBB: sinkMBB);
12119
12120 // Set the call frame size on entry to the new basic blocks.
12121 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
12122 copy0MBB->setCallFrameSize(CallFrameSize);
12123 sinkMBB->setCallFrameSize(CallFrameSize);
12124
12125 // Check whether CPSR is live past the tMOVCCr_pseudo.
12126 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
12127 if (!MI.killsRegister(Reg: ARM::CPSR, /*TRI=*/nullptr) &&
12128 !checkAndUpdateCPSRKill(SelectItr: MI, BB: thisMBB, TRI)) {
12129 copy0MBB->addLiveIn(PhysReg: ARM::CPSR);
12130 sinkMBB->addLiveIn(PhysReg: ARM::CPSR);
12131 }
12132
12133 // Transfer the remainder of BB and its successor edges to sinkMBB.
12134 sinkMBB->splice(Where: sinkMBB->begin(), Other: BB,
12135 From: std::next(x: MachineBasicBlock::iterator(MI)), To: BB->end());
12136 sinkMBB->transferSuccessorsAndUpdatePHIs(FromMBB: BB);
12137
12138 BB->addSuccessor(Succ: copy0MBB);
12139 BB->addSuccessor(Succ: sinkMBB);
12140
12141 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::tBcc))
12142 .addMBB(MBB: sinkMBB)
12143 .addImm(Val: MI.getOperand(i: 3).getImm())
12144 .addReg(RegNo: MI.getOperand(i: 4).getReg());
12145
12146 // copy0MBB:
12147 // %FalseValue = ...
12148 // # fallthrough to sinkMBB
12149 BB = copy0MBB;
12150
12151 // Update machine-CFG edges
12152 BB->addSuccessor(Succ: sinkMBB);
12153
12154 // sinkMBB:
12155 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12156 // ...
12157 BB = sinkMBB;
12158 BuildMI(BB&: *BB, I: BB->begin(), MIMD: dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: MI.getOperand(i: 0).getReg())
12159 .addReg(RegNo: MI.getOperand(i: 1).getReg())
12160 .addMBB(MBB: copy0MBB)
12161 .addReg(RegNo: MI.getOperand(i: 2).getReg())
12162 .addMBB(MBB: thisMBB);
12163
12164 MI.eraseFromParent(); // The pseudo instruction is gone now.
12165 return BB;
12166 }
12167
12168 case ARM::BCCi64:
12169 case ARM::BCCZi64: {
12170 // If there is an unconditional branch to the other successor, remove it.
12171 BB->erase(I: std::next(x: MachineBasicBlock::iterator(MI)), E: BB->end());
12172
12173 // Compare both parts that make up the double comparison separately for
12174 // equality.
12175 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
12176
12177 Register LHS1 = MI.getOperand(i: 1).getReg();
12178 Register LHS2 = MI.getOperand(i: 2).getReg();
12179 if (RHSisZero) {
12180 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12181 .addReg(RegNo: LHS1)
12182 .addImm(Val: 0)
12183 .add(MOs: predOps(Pred: ARMCC::AL));
12184 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12185 .addReg(RegNo: LHS2).addImm(Val: 0)
12186 .addImm(Val: ARMCC::EQ).addReg(RegNo: ARM::CPSR);
12187 } else {
12188 Register RHS1 = MI.getOperand(i: 3).getReg();
12189 Register RHS2 = MI.getOperand(i: 4).getReg();
12190 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12191 .addReg(RegNo: LHS1)
12192 .addReg(RegNo: RHS1)
12193 .add(MOs: predOps(Pred: ARMCC::AL));
12194 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12195 .addReg(RegNo: LHS2).addReg(RegNo: RHS2)
12196 .addImm(Val: ARMCC::EQ).addReg(RegNo: ARM::CPSR);
12197 }
12198
12199 MachineBasicBlock *destMBB = MI.getOperand(i: RHSisZero ? 3 : 5).getMBB();
12200 MachineBasicBlock *exitMBB = OtherSucc(MBB: BB, Succ: destMBB);
12201 if (MI.getOperand(i: 0).getImm() == ARMCC::NE)
12202 std::swap(a&: destMBB, b&: exitMBB);
12203
12204 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: isThumb2 ? ARM::t2Bcc : ARM::Bcc))
12205 .addMBB(MBB: destMBB).addImm(Val: ARMCC::EQ).addReg(RegNo: ARM::CPSR);
12206 if (isThumb2)
12207 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2B))
12208 .addMBB(MBB: exitMBB)
12209 .add(MOs: predOps(Pred: ARMCC::AL));
12210 else
12211 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::B)) .addMBB(MBB: exitMBB);
12212
12213 MI.eraseFromParent(); // The pseudo instruction is gone now.
12214 return BB;
12215 }
12216
12217 case ARM::Int_eh_sjlj_setjmp:
12218 case ARM::Int_eh_sjlj_setjmp_nofp:
12219 case ARM::tInt_eh_sjlj_setjmp:
12220 case ARM::t2Int_eh_sjlj_setjmp:
12221 case ARM::t2Int_eh_sjlj_setjmp_nofp:
12222 return BB;
12223
12224 case ARM::Int_eh_sjlj_setup_dispatch:
12225 EmitSjLjDispatchBlock(MI, MBB: BB);
12226 return BB;
12227 case ARM::COPY_STRUCT_BYVAL_I32:
12228 ++NumLoopByVals;
12229 return EmitStructByval(MI, BB);
12230 case ARM::WIN__CHKSTK:
12231 return EmitLowered__chkstk(MI, MBB: BB);
12232 case ARM::WIN__DBZCHK:
12233 return EmitLowered__dbzchk(MI, MBB: BB);
12234 }
12235}
12236
12237/// Attaches vregs to MEMCPY that it will use as scratch registers
12238/// when it is expanded into LDM/STM. This is done as a post-isel lowering
12239/// instead of as a custom inserter because we need the use list from the SDNode.
12240static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
12241 MachineInstr &MI, const SDNode *Node) {
12242 bool isThumb1 = Subtarget->isThumb1Only();
12243
12244 MachineFunction *MF = MI.getParent()->getParent();
12245 MachineRegisterInfo &MRI = MF->getRegInfo();
12246 MachineInstrBuilder MIB(*MF, MI);
12247
12248 // If the new dst/src is unused mark it as dead.
12249 if (!Node->hasAnyUseOfValue(Value: 0)) {
12250 MI.getOperand(i: 0).setIsDead(true);
12251 }
12252 if (!Node->hasAnyUseOfValue(Value: 1)) {
12253 MI.getOperand(i: 1).setIsDead(true);
12254 }
12255
12256 // The MEMCPY both defines and kills the scratch registers.
12257 for (unsigned I = 0; I != MI.getOperand(i: 4).getImm(); ++I) {
12258 Register TmpReg = MRI.createVirtualRegister(RegClass: isThumb1 ? &ARM::tGPRRegClass
12259 : &ARM::GPRRegClass);
12260 MIB.addReg(RegNo: TmpReg, Flags: RegState::Define|RegState::Dead);
12261 }
12262}
12263
12264void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
12265 SDNode *Node) const {
12266 if (MI.getOpcode() == ARM::MEMCPY) {
12267 attachMEMCPYScratchRegs(Subtarget, MI, Node);
12268 return;
12269 }
12270
12271 const MCInstrDesc *MCID = &MI.getDesc();
12272 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
12273 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
12274 // operand is still set to noreg. If needed, set the optional operand's
12275 // register to CPSR, and remove the redundant implicit def.
12276 //
12277 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
12278
12279 // Rename pseudo opcodes.
12280 unsigned NewOpc = convertAddSubFlagsOpcode(OldOpc: MI.getOpcode());
12281 unsigned ccOutIdx;
12282 if (NewOpc) {
12283 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
12284 MCID = &TII->get(Opcode: NewOpc);
12285
12286 assert(MCID->getNumOperands() ==
12287 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
12288 && "converted opcode should be the same except for cc_out"
12289 " (and, on Thumb1, pred)");
12290
12291 MI.setDesc(*MCID);
12292
12293 // Add the optional cc_out operand
12294 MI.addOperand(Op: MachineOperand::CreateReg(Reg: 0, /*isDef=*/true));
12295
12296 // On Thumb1, move all input operands to the end, then add the predicate
12297 if (Subtarget->isThumb1Only()) {
12298 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
12299 MI.addOperand(Op: MI.getOperand(i: 1));
12300 MI.removeOperand(OpNo: 1);
12301 }
12302
12303 // Restore the ties
12304 for (unsigned i = MI.getNumOperands(); i--;) {
12305 const MachineOperand& op = MI.getOperand(i);
12306 if (op.isReg() && op.isUse()) {
12307 int DefIdx = MCID->getOperandConstraint(OpNum: i, Constraint: MCOI::TIED_TO);
12308 if (DefIdx != -1)
12309 MI.tieOperands(DefIdx, UseIdx: i);
12310 }
12311 }
12312
12313 MI.addOperand(Op: MachineOperand::CreateImm(Val: ARMCC::AL));
12314 MI.addOperand(Op: MachineOperand::CreateReg(Reg: 0, /*isDef=*/false));
12315 ccOutIdx = 1;
12316 } else
12317 ccOutIdx = MCID->getNumOperands() - 1;
12318 } else
12319 ccOutIdx = MCID->getNumOperands() - 1;
12320
12321 // Any ARM instruction that sets the 's' bit should specify an optional
12322 // "cc_out" operand in the last operand position.
12323 if (!MI.hasOptionalDef() || !MCID->operands()[ccOutIdx].isOptionalDef()) {
12324 assert(!NewOpc && "Optional cc_out operand required");
12325 return;
12326 }
12327 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
12328 // since we already have an optional CPSR def.
12329 bool definesCPSR = false;
12330 bool deadCPSR = false;
12331 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
12332 ++i) {
12333 const MachineOperand &MO = MI.getOperand(i);
12334 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
12335 definesCPSR = true;
12336 if (MO.isDead())
12337 deadCPSR = true;
12338 MI.removeOperand(OpNo: i);
12339 break;
12340 }
12341 }
12342 if (!definesCPSR) {
12343 assert(!NewOpc && "Optional cc_out operand required");
12344 return;
12345 }
12346 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
12347 if (deadCPSR) {
12348 assert(!MI.getOperand(ccOutIdx).getReg() &&
12349 "expect uninitialized optional cc_out operand");
12350 // Thumb1 instructions must have the S bit even if the CPSR is dead.
12351 if (!Subtarget->isThumb1Only())
12352 return;
12353 }
12354
12355 // If this instruction was defined with an optional CPSR def and its dag node
12356 // had a live implicit CPSR def, then activate the optional CPSR def.
12357 MachineOperand &MO = MI.getOperand(i: ccOutIdx);
12358 MO.setReg(ARM::CPSR);
12359 MO.setIsDef(true);
12360}
12361
12362//===----------------------------------------------------------------------===//
12363// ARM Optimization Hooks
12364//===----------------------------------------------------------------------===//
12365
12366// Helper function that checks if N is a null or all ones constant.
12367static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
12368 return AllOnes ? isAllOnesConstant(V: N) : isNullConstant(V: N);
12369}
12370
12371// Return true if N is conditionally 0 or all ones.
12372// Detects these expressions where cc is an i1 value:
12373//
12374// (select cc 0, y) [AllOnes=0]
12375// (select cc y, 0) [AllOnes=0]
12376// (zext cc) [AllOnes=0]
12377// (sext cc) [AllOnes=0/1]
12378// (select cc -1, y) [AllOnes=1]
12379// (select cc y, -1) [AllOnes=1]
12380//
12381// Invert is set when N is the null/all ones constant when CC is false.
12382// OtherOp is set to the alternative value of N.
12383static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
12384 SDValue &CC, bool &Invert,
12385 SDValue &OtherOp,
12386 SelectionDAG &DAG) {
12387 switch (N->getOpcode()) {
12388 default: return false;
12389 case ISD::SELECT: {
12390 CC = N->getOperand(Num: 0);
12391 SDValue N1 = N->getOperand(Num: 1);
12392 SDValue N2 = N->getOperand(Num: 2);
12393 if (isZeroOrAllOnes(N: N1, AllOnes)) {
12394 Invert = false;
12395 OtherOp = N2;
12396 return true;
12397 }
12398 if (isZeroOrAllOnes(N: N2, AllOnes)) {
12399 Invert = true;
12400 OtherOp = N1;
12401 return true;
12402 }
12403 return false;
12404 }
12405 case ISD::ZERO_EXTEND:
12406 // (zext cc) can never be the all ones value.
12407 if (AllOnes)
12408 return false;
12409 [[fallthrough]];
12410 case ISD::SIGN_EXTEND: {
12411 SDLoc dl(N);
12412 EVT VT = N->getValueType(ResNo: 0);
12413 CC = N->getOperand(Num: 0);
12414 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
12415 return false;
12416 Invert = !AllOnes;
12417 if (AllOnes)
12418 // When looking for an AllOnes constant, N is an sext, and the 'other'
12419 // value is 0.
12420 OtherOp = DAG.getConstant(Val: 0, DL: dl, VT);
12421 else if (N->getOpcode() == ISD::ZERO_EXTEND)
12422 // When looking for a 0 constant, N can be zext or sext.
12423 OtherOp = DAG.getConstant(Val: 1, DL: dl, VT);
12424 else
12425 OtherOp = DAG.getAllOnesConstant(DL: dl, VT);
12426 return true;
12427 }
12428 }
12429}
12430
12431// Combine a constant select operand into its use:
12432//
12433// (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12434// (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12435// (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
12436// (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12437// (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12438//
12439// The transform is rejected if the select doesn't have a constant operand that
12440// is null, or all ones when AllOnes is set.
12441//
12442// Also recognize sext/zext from i1:
12443//
12444// (add (zext cc), x) -> (select cc (add x, 1), x)
12445// (add (sext cc), x) -> (select cc (add x, -1), x)
12446//
12447// These transformations eventually create predicated instructions.
12448//
12449// @param N The node to transform.
12450// @param Slct The N operand that is a select.
12451// @param OtherOp The other N operand (x above).
12452// @param DCI Context.
12453// @param AllOnes Require the select constant to be all ones instead of null.
12454// @returns The new node, or SDValue() on failure.
12455static
12456SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
12457 TargetLowering::DAGCombinerInfo &DCI,
12458 bool AllOnes = false) {
12459 SelectionDAG &DAG = DCI.DAG;
12460 EVT VT = N->getValueType(ResNo: 0);
12461 SDValue NonConstantVal;
12462 SDValue CCOp;
12463 bool SwapSelectOps;
12464 if (!isConditionalZeroOrAllOnes(N: Slct.getNode(), AllOnes, CC&: CCOp, Invert&: SwapSelectOps,
12465 OtherOp&: NonConstantVal, DAG))
12466 return SDValue();
12467
12468 // Slct is now know to be the desired identity constant when CC is true.
12469 SDValue TrueVal = OtherOp;
12470 SDValue FalseVal = DAG.getNode(Opcode: N->getOpcode(), DL: SDLoc(N), VT,
12471 N1: OtherOp, N2: NonConstantVal);
12472 // Unless SwapSelectOps says CC should be false.
12473 if (SwapSelectOps)
12474 std::swap(a&: TrueVal, b&: FalseVal);
12475
12476 return DAG.getNode(Opcode: ISD::SELECT, DL: SDLoc(N), VT,
12477 N1: CCOp, N2: TrueVal, N3: FalseVal);
12478}
12479
12480// Attempt combineSelectAndUse on each operand of a commutative operator N.
12481static
12482SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
12483 TargetLowering::DAGCombinerInfo &DCI) {
12484 SDValue N0 = N->getOperand(Num: 0);
12485 SDValue N1 = N->getOperand(Num: 1);
12486 if (N0.getNode()->hasOneUse())
12487 if (SDValue Result = combineSelectAndUse(N, Slct: N0, OtherOp: N1, DCI, AllOnes))
12488 return Result;
12489 if (N1.getNode()->hasOneUse())
12490 if (SDValue Result = combineSelectAndUse(N, Slct: N1, OtherOp: N0, DCI, AllOnes))
12491 return Result;
12492 return SDValue();
12493}
12494
12495static bool IsVUZPShuffleNode(SDNode *N) {
12496 // VUZP shuffle node.
12497 if (N->getOpcode() == ARMISD::VUZP)
12498 return true;
12499
12500 // "VUZP" on i32 is an alias for VTRN.
12501 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(ResNo: 0) == MVT::v2i32)
12502 return true;
12503
12504 return false;
12505}
12506
12507static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
12508 TargetLowering::DAGCombinerInfo &DCI,
12509 const ARMSubtarget *Subtarget) {
12510 // Look for ADD(VUZP.0, VUZP.1).
12511 if (!IsVUZPShuffleNode(N: N0.getNode()) || N0.getNode() != N1.getNode() ||
12512 N0 == N1)
12513 return SDValue();
12514
12515 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
12516 if (!N->getValueType(ResNo: 0).is64BitVector())
12517 return SDValue();
12518
12519 // Generate vpadd.
12520 SelectionDAG &DAG = DCI.DAG;
12521 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12522 SDLoc dl(N);
12523 SDNode *Unzip = N0.getNode();
12524 EVT VT = N->getValueType(ResNo: 0);
12525
12526 SmallVector<SDValue, 8> Ops;
12527 Ops.push_back(Elt: DAG.getConstant(Val: Intrinsic::arm_neon_vpadd, DL: dl,
12528 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
12529 Ops.push_back(Elt: Unzip->getOperand(Num: 0));
12530 Ops.push_back(Elt: Unzip->getOperand(Num: 1));
12531
12532 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT, Ops);
12533}
12534
12535static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12536 TargetLowering::DAGCombinerInfo &DCI,
12537 const ARMSubtarget *Subtarget) {
12538 // Check for two extended operands.
12539 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
12540 N1.getOpcode() == ISD::SIGN_EXTEND) &&
12541 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
12542 N1.getOpcode() == ISD::ZERO_EXTEND))
12543 return SDValue();
12544
12545 SDValue N00 = N0.getOperand(i: 0);
12546 SDValue N10 = N1.getOperand(i: 0);
12547
12548 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
12549 if (!IsVUZPShuffleNode(N: N00.getNode()) || N00.getNode() != N10.getNode() ||
12550 N00 == N10)
12551 return SDValue();
12552
12553 // We only recognize Q register paddl here; this can't be reached until
12554 // after type legalization.
12555 if (!N00.getValueType().is64BitVector() ||
12556 !N0.getValueType().is128BitVector())
12557 return SDValue();
12558
12559 // Generate vpaddl.
12560 SelectionDAG &DAG = DCI.DAG;
12561 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12562 SDLoc dl(N);
12563 EVT VT = N->getValueType(ResNo: 0);
12564
12565 SmallVector<SDValue, 8> Ops;
12566 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
12567 unsigned Opcode;
12568 if (N0.getOpcode() == ISD::SIGN_EXTEND)
12569 Opcode = Intrinsic::arm_neon_vpaddls;
12570 else
12571 Opcode = Intrinsic::arm_neon_vpaddlu;
12572 Ops.push_back(Elt: DAG.getConstant(Val: Opcode, DL: dl,
12573 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
12574 EVT ElemTy = N00.getValueType().getVectorElementType();
12575 unsigned NumElts = VT.getVectorNumElements();
12576 EVT ConcatVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: ElemTy, NumElements: NumElts * 2);
12577 SDValue Concat = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: SDLoc(N), VT: ConcatVT,
12578 N1: N00.getOperand(i: 0), N2: N00.getOperand(i: 1));
12579 Ops.push_back(Elt: Concat);
12580
12581 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT, Ops);
12582}
12583
12584// FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
12585// an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
12586// much easier to match.
12587static SDValue
12588AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12589 TargetLowering::DAGCombinerInfo &DCI,
12590 const ARMSubtarget *Subtarget) {
12591 // Only perform optimization if after legalize, and if NEON is available. We
12592 // also expected both operands to be BUILD_VECTORs.
12593 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
12594 || N0.getOpcode() != ISD::BUILD_VECTOR
12595 || N1.getOpcode() != ISD::BUILD_VECTOR)
12596 return SDValue();
12597
12598 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
12599 EVT VT = N->getValueType(ResNo: 0);
12600 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
12601 return SDValue();
12602
12603 // Check that the vector operands are of the right form.
12604 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
12605 // operands, where N is the size of the formed vector.
12606 // Each EXTRACT_VECTOR should have the same input vector and odd or even
12607 // index such that we have a pair wise add pattern.
12608
12609 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
12610 if (N0->getOperand(Num: 0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12611 return SDValue();
12612 SDValue Vec = N0->getOperand(Num: 0)->getOperand(Num: 0);
12613 SDNode *V = Vec.getNode();
12614 unsigned nextIndex = 0;
12615
12616 // For each operands to the ADD which are BUILD_VECTORs,
12617 // check to see if each of their operands are an EXTRACT_VECTOR with
12618 // the same vector and appropriate index.
12619 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
12620 if (N0->getOperand(Num: i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
12621 && N1->getOperand(Num: i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12622
12623 SDValue ExtVec0 = N0->getOperand(Num: i);
12624 SDValue ExtVec1 = N1->getOperand(Num: i);
12625
12626 // First operand is the vector, verify its the same.
12627 if (V != ExtVec0->getOperand(Num: 0).getNode() ||
12628 V != ExtVec1->getOperand(Num: 0).getNode())
12629 return SDValue();
12630
12631 // Second is the constant, verify its correct.
12632 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(Val: ExtVec0->getOperand(Num: 1));
12633 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Val: ExtVec1->getOperand(Num: 1));
12634
12635 // For the constant, we want to see all the even or all the odd.
12636 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
12637 || C1->getZExtValue() != nextIndex+1)
12638 return SDValue();
12639
12640 // Increment index.
12641 nextIndex+=2;
12642 } else
12643 return SDValue();
12644 }
12645
12646 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
12647 // we're using the entire input vector, otherwise there's a size/legality
12648 // mismatch somewhere.
12649 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
12650 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
12651 return SDValue();
12652
12653 // Create VPADDL node.
12654 SelectionDAG &DAG = DCI.DAG;
12655 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12656
12657 SDLoc dl(N);
12658
12659 // Build operand list.
12660 SmallVector<SDValue, 8> Ops;
12661 Ops.push_back(Elt: DAG.getConstant(Val: Intrinsic::arm_neon_vpaddls, DL: dl,
12662 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
12663
12664 // Input is the vector.
12665 Ops.push_back(Elt: Vec);
12666
12667 // Get widened type and narrowed type.
12668 MVT widenType;
12669 unsigned numElem = VT.getVectorNumElements();
12670
12671 EVT inputLaneType = Vec.getValueType().getVectorElementType();
12672 switch (inputLaneType.getSimpleVT().SimpleTy) {
12673 case MVT::i8: widenType = MVT::getVectorVT(VT: MVT::i16, NumElements: numElem); break;
12674 case MVT::i16: widenType = MVT::getVectorVT(VT: MVT::i32, NumElements: numElem); break;
12675 case MVT::i32: widenType = MVT::getVectorVT(VT: MVT::i64, NumElements: numElem); break;
12676 default:
12677 llvm_unreachable("Invalid vector element type for padd optimization.");
12678 }
12679
12680 SDValue tmp = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: widenType, Ops);
12681 unsigned ExtOp = VT.bitsGT(VT: tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
12682 return DAG.getNode(Opcode: ExtOp, DL: dl, VT, Operand: tmp);
12683}
12684
12685static SDValue findMUL_LOHI(SDValue V) {
12686 if (V->getOpcode() == ISD::UMUL_LOHI ||
12687 V->getOpcode() == ISD::SMUL_LOHI)
12688 return V;
12689 return SDValue();
12690}
12691
12692static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
12693 TargetLowering::DAGCombinerInfo &DCI,
12694 const ARMSubtarget *Subtarget) {
12695 if (!Subtarget->hasBaseDSP())
12696 return SDValue();
12697
12698 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
12699 // accumulates the product into a 64-bit value. The 16-bit values will
12700 // be sign extended somehow or SRA'd into 32-bit values
12701 // (addc (adde (mul 16bit, 16bit), lo), hi)
12702 SDValue Mul = AddcNode->getOperand(Num: 0);
12703 SDValue Lo = AddcNode->getOperand(Num: 1);
12704 if (Mul.getOpcode() != ISD::MUL) {
12705 Lo = AddcNode->getOperand(Num: 0);
12706 Mul = AddcNode->getOperand(Num: 1);
12707 if (Mul.getOpcode() != ISD::MUL)
12708 return SDValue();
12709 }
12710
12711 SDValue SRA = AddeNode->getOperand(Num: 0);
12712 SDValue Hi = AddeNode->getOperand(Num: 1);
12713 if (SRA.getOpcode() != ISD::SRA) {
12714 SRA = AddeNode->getOperand(Num: 1);
12715 Hi = AddeNode->getOperand(Num: 0);
12716 if (SRA.getOpcode() != ISD::SRA)
12717 return SDValue();
12718 }
12719 if (auto Const = dyn_cast<ConstantSDNode>(Val: SRA.getOperand(i: 1))) {
12720 if (Const->getZExtValue() != 31)
12721 return SDValue();
12722 } else
12723 return SDValue();
12724
12725 if (SRA.getOperand(i: 0) != Mul)
12726 return SDValue();
12727
12728 SelectionDAG &DAG = DCI.DAG;
12729 SDLoc dl(AddcNode);
12730 unsigned Opcode = 0;
12731 SDValue Op0;
12732 SDValue Op1;
12733
12734 if (isS16(Op: Mul.getOperand(i: 0), DAG) && isS16(Op: Mul.getOperand(i: 1), DAG)) {
12735 Opcode = ARMISD::SMLALBB;
12736 Op0 = Mul.getOperand(i: 0);
12737 Op1 = Mul.getOperand(i: 1);
12738 } else if (isS16(Op: Mul.getOperand(i: 0), DAG) && isSRA16(Op: Mul.getOperand(i: 1))) {
12739 Opcode = ARMISD::SMLALBT;
12740 Op0 = Mul.getOperand(i: 0);
12741 Op1 = Mul.getOperand(i: 1).getOperand(i: 0);
12742 } else if (isSRA16(Op: Mul.getOperand(i: 0)) && isS16(Op: Mul.getOperand(i: 1), DAG)) {
12743 Opcode = ARMISD::SMLALTB;
12744 Op0 = Mul.getOperand(i: 0).getOperand(i: 0);
12745 Op1 = Mul.getOperand(i: 1);
12746 } else if (isSRA16(Op: Mul.getOperand(i: 0)) && isSRA16(Op: Mul.getOperand(i: 1))) {
12747 Opcode = ARMISD::SMLALTT;
12748 Op0 = Mul->getOperand(Num: 0).getOperand(i: 0);
12749 Op1 = Mul->getOperand(Num: 1).getOperand(i: 0);
12750 }
12751
12752 if (!Op0 || !Op1)
12753 return SDValue();
12754
12755 SDValue SMLAL = DAG.getNode(Opcode, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
12756 N1: Op0, N2: Op1, N3: Lo, N4: Hi);
12757 // Replace the ADDs' nodes uses by the MLA node's values.
12758 SDValue HiMLALResult(SMLAL.getNode(), 1);
12759 SDValue LoMLALResult(SMLAL.getNode(), 0);
12760
12761 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddcNode, 0), To: LoMLALResult);
12762 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddeNode, 0), To: HiMLALResult);
12763
12764 // Return original node to notify the driver to stop replacing.
12765 SDValue resNode(AddcNode, 0);
12766 return resNode;
12767}
12768
12769static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
12770 TargetLowering::DAGCombinerInfo &DCI,
12771 const ARMSubtarget *Subtarget) {
12772 // Look for multiply add opportunities.
12773 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
12774 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
12775 // a glue link from the first add to the second add.
12776 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
12777 // a S/UMLAL instruction.
12778 // UMUL_LOHI
12779 // / :lo \ :hi
12780 // V \ [no multiline comment]
12781 // loAdd -> ADDC |
12782 // \ :carry /
12783 // V V
12784 // ADDE <- hiAdd
12785 //
12786 // In the special case where only the higher part of a signed result is used
12787 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
12788 // a constant with the exact value of 0x80000000, we recognize we are dealing
12789 // with a "rounded multiply and add" (or subtract) and transform it into
12790 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
12791
12792 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
12793 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
12794 "Expect an ADDE or SUBE");
12795
12796 assert(AddeSubeNode->getNumOperands() == 3 &&
12797 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
12798 "ADDE node has the wrong inputs");
12799
12800 // Check that we are chained to the right ADDC or SUBC node.
12801 SDNode *AddcSubcNode = AddeSubeNode->getOperand(Num: 2).getNode();
12802 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12803 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
12804 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
12805 AddcSubcNode->getOpcode() != ARMISD::SUBC))
12806 return SDValue();
12807
12808 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(Num: 0);
12809 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(Num: 1);
12810
12811 // Check if the two operands are from the same mul_lohi node.
12812 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
12813 return SDValue();
12814
12815 assert(AddcSubcNode->getNumValues() == 2 &&
12816 AddcSubcNode->getValueType(0) == MVT::i32 &&
12817 "Expect ADDC with two result values. First: i32");
12818
12819 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
12820 // maybe a SMLAL which multiplies two 16-bit values.
12821 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12822 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
12823 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
12824 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
12825 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
12826 return AddCombineTo64BitSMLAL16(AddcNode: AddcSubcNode, AddeNode: AddeSubeNode, DCI, Subtarget);
12827
12828 // Check for the triangle shape.
12829 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(Num: 0);
12830 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(Num: 1);
12831
12832 // Make sure that the ADDE/SUBE operands are not coming from the same node.
12833 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
12834 return SDValue();
12835
12836 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
12837 bool IsLeftOperandMUL = false;
12838 SDValue MULOp = findMUL_LOHI(V: AddeSubeOp0);
12839 if (MULOp == SDValue())
12840 MULOp = findMUL_LOHI(V: AddeSubeOp1);
12841 else
12842 IsLeftOperandMUL = true;
12843 if (MULOp == SDValue())
12844 return SDValue();
12845
12846 // Figure out the right opcode.
12847 unsigned Opc = MULOp->getOpcode();
12848 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
12849
12850 // Figure out the high and low input values to the MLAL node.
12851 SDValue *HiAddSub = nullptr;
12852 SDValue *LoMul = nullptr;
12853 SDValue *LowAddSub = nullptr;
12854
12855 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
12856 if ((AddeSubeOp0 != MULOp.getValue(R: 1)) && (AddeSubeOp1 != MULOp.getValue(R: 1)))
12857 return SDValue();
12858
12859 if (IsLeftOperandMUL)
12860 HiAddSub = &AddeSubeOp1;
12861 else
12862 HiAddSub = &AddeSubeOp0;
12863
12864 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
12865 // whose low result is fed to the ADDC/SUBC we are checking.
12866
12867 if (AddcSubcOp0 == MULOp.getValue(R: 0)) {
12868 LoMul = &AddcSubcOp0;
12869 LowAddSub = &AddcSubcOp1;
12870 }
12871 if (AddcSubcOp1 == MULOp.getValue(R: 0)) {
12872 LoMul = &AddcSubcOp1;
12873 LowAddSub = &AddcSubcOp0;
12874 }
12875
12876 if (!LoMul)
12877 return SDValue();
12878
12879 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
12880 // the replacement below will create a cycle.
12881 if (AddcSubcNode == HiAddSub->getNode() ||
12882 AddcSubcNode->isPredecessorOf(N: HiAddSub->getNode()))
12883 return SDValue();
12884
12885 // Create the merged node.
12886 SelectionDAG &DAG = DCI.DAG;
12887
12888 // Start building operand list.
12889 SmallVector<SDValue, 8> Ops;
12890 Ops.push_back(Elt: LoMul->getOperand(i: 0));
12891 Ops.push_back(Elt: LoMul->getOperand(i: 1));
12892
12893 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
12894 // the case, we must be doing signed multiplication and only use the higher
12895 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
12896 // addition or subtraction with the value of 0x800000.
12897 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
12898 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(Value: 1) &&
12899 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
12900 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
12901 0x80000000) {
12902 Ops.push_back(Elt: *HiAddSub);
12903 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
12904 FinalOpc = ARMISD::SMMLSR;
12905 } else {
12906 FinalOpc = ARMISD::SMMLAR;
12907 }
12908 SDValue NewNode = DAG.getNode(Opcode: FinalOpc, DL: SDLoc(AddcSubcNode), VT: MVT::i32, Ops);
12909 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddeSubeNode, 0), To: NewNode);
12910
12911 return SDValue(AddeSubeNode, 0);
12912 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
12913 // SMMLS is generated during instruction selection and the rest of this
12914 // function can not handle the case where AddcSubcNode is a SUBC.
12915 return SDValue();
12916
12917 // Finish building the operand list for {U/S}MLAL
12918 Ops.push_back(Elt: *LowAddSub);
12919 Ops.push_back(Elt: *HiAddSub);
12920
12921 SDValue MLALNode = DAG.getNode(Opcode: FinalOpc, DL: SDLoc(AddcSubcNode),
12922 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), Ops);
12923
12924 // Replace the ADDs' nodes uses by the MLA node's values.
12925 SDValue HiMLALResult(MLALNode.getNode(), 1);
12926 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddeSubeNode, 0), To: HiMLALResult);
12927
12928 SDValue LoMLALResult(MLALNode.getNode(), 0);
12929 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddcSubcNode, 0), To: LoMLALResult);
12930
12931 // Return original node to notify the driver to stop replacing.
12932 return SDValue(AddeSubeNode, 0);
12933}
12934
12935static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
12936 TargetLowering::DAGCombinerInfo &DCI,
12937 const ARMSubtarget *Subtarget) {
12938 // UMAAL is similar to UMLAL except that it adds two unsigned values.
12939 // While trying to combine for the other MLAL nodes, first search for the
12940 // chance to use UMAAL. Check if Addc uses a node which has already
12941 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
12942 // as the addend, and it's handled in PerformUMLALCombine.
12943
12944 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12945 return AddCombineTo64bitMLAL(AddeSubeNode: AddeNode, DCI, Subtarget);
12946
12947 // Check that we have a glued ADDC node.
12948 SDNode* AddcNode = AddeNode->getOperand(Num: 2).getNode();
12949 if (AddcNode->getOpcode() != ARMISD::ADDC)
12950 return SDValue();
12951
12952 // Find the converted UMAAL or quit if it doesn't exist.
12953 SDNode *UmlalNode = nullptr;
12954 SDValue AddHi;
12955 if (AddcNode->getOperand(Num: 0).getOpcode() == ARMISD::UMLAL) {
12956 UmlalNode = AddcNode->getOperand(Num: 0).getNode();
12957 AddHi = AddcNode->getOperand(Num: 1);
12958 } else if (AddcNode->getOperand(Num: 1).getOpcode() == ARMISD::UMLAL) {
12959 UmlalNode = AddcNode->getOperand(Num: 1).getNode();
12960 AddHi = AddcNode->getOperand(Num: 0);
12961 } else {
12962 return AddCombineTo64bitMLAL(AddeSubeNode: AddeNode, DCI, Subtarget);
12963 }
12964
12965 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
12966 // the ADDC as well as Zero.
12967 if (!isNullConstant(V: UmlalNode->getOperand(Num: 3)))
12968 return SDValue();
12969
12970 if ((isNullConstant(V: AddeNode->getOperand(Num: 0)) &&
12971 AddeNode->getOperand(Num: 1).getNode() == UmlalNode) ||
12972 (AddeNode->getOperand(Num: 0).getNode() == UmlalNode &&
12973 isNullConstant(V: AddeNode->getOperand(Num: 1)))) {
12974 SelectionDAG &DAG = DCI.DAG;
12975 SDValue Ops[] = { UmlalNode->getOperand(Num: 0), UmlalNode->getOperand(Num: 1),
12976 UmlalNode->getOperand(Num: 2), AddHi };
12977 SDValue UMAAL = DAG.getNode(Opcode: ARMISD::UMAAL, DL: SDLoc(AddcNode),
12978 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), Ops);
12979
12980 // Replace the ADDs' nodes uses by the UMAAL node's values.
12981 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddeNode, 0), To: SDValue(UMAAL.getNode(), 1));
12982 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddcNode, 0), To: SDValue(UMAAL.getNode(), 0));
12983
12984 // Return original node to notify the driver to stop replacing.
12985 return SDValue(AddeNode, 0);
12986 }
12987 return SDValue();
12988}
12989
12990static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
12991 const ARMSubtarget *Subtarget) {
12992 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12993 return SDValue();
12994
12995 // Check that we have a pair of ADDC and ADDE as operands.
12996 // Both addends of the ADDE must be zero.
12997 SDNode* AddcNode = N->getOperand(Num: 2).getNode();
12998 SDNode* AddeNode = N->getOperand(Num: 3).getNode();
12999 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
13000 (AddeNode->getOpcode() == ARMISD::ADDE) &&
13001 isNullConstant(V: AddeNode->getOperand(Num: 0)) &&
13002 isNullConstant(V: AddeNode->getOperand(Num: 1)) &&
13003 (AddeNode->getOperand(Num: 2).getNode() == AddcNode))
13004 return DAG.getNode(Opcode: ARMISD::UMAAL, DL: SDLoc(N),
13005 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
13006 Ops: {N->getOperand(Num: 0), N->getOperand(Num: 1),
13007 AddcNode->getOperand(Num: 0), AddcNode->getOperand(Num: 1)});
13008 else
13009 return SDValue();
13010}
13011
13012static SDValue PerformAddcSubcCombine(SDNode *N,
13013 TargetLowering::DAGCombinerInfo &DCI,
13014 const ARMSubtarget *Subtarget) {
13015 SelectionDAG &DAG(DCI.DAG);
13016
13017 if (N->getOpcode() == ARMISD::SUBC && N->hasAnyUseOfValue(Value: 1)) {
13018 // (SUBC (ADDE 0, 0, C), 1) -> C
13019 SDValue LHS = N->getOperand(Num: 0);
13020 SDValue RHS = N->getOperand(Num: 1);
13021 if (LHS->getOpcode() == ARMISD::ADDE &&
13022 isNullConstant(V: LHS->getOperand(Num: 0)) &&
13023 isNullConstant(V: LHS->getOperand(Num: 1)) && isOneConstant(V: RHS)) {
13024 return DCI.CombineTo(N, Res0: SDValue(N, 0), Res1: LHS->getOperand(Num: 2));
13025 }
13026 }
13027
13028 if (Subtarget->isThumb1Only()) {
13029 SDValue RHS = N->getOperand(Num: 1);
13030 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: RHS)) {
13031 int32_t imm = C->getSExtValue();
13032 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
13033 SDLoc DL(N);
13034 RHS = DAG.getConstant(Val: -imm, DL, VT: MVT::i32);
13035 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
13036 : ARMISD::ADDC;
13037 return DAG.getNode(Opcode, DL, VTList: N->getVTList(), N1: N->getOperand(Num: 0), N2: RHS);
13038 }
13039 }
13040 }
13041
13042 return SDValue();
13043}
13044
13045static SDValue PerformAddeSubeCombine(SDNode *N,
13046 TargetLowering::DAGCombinerInfo &DCI,
13047 const ARMSubtarget *Subtarget) {
13048 if (Subtarget->isThumb1Only()) {
13049 SelectionDAG &DAG = DCI.DAG;
13050 SDValue RHS = N->getOperand(Num: 1);
13051 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: RHS)) {
13052 int64_t imm = C->getSExtValue();
13053 if (imm < 0) {
13054 SDLoc DL(N);
13055
13056 // The with-carry-in form matches bitwise not instead of the negation.
13057 // Effectively, the inverse interpretation of the carry flag already
13058 // accounts for part of the negation.
13059 RHS = DAG.getConstant(Val: ~imm, DL, VT: MVT::i32);
13060
13061 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
13062 : ARMISD::ADDE;
13063 return DAG.getNode(Opcode, DL, VTList: N->getVTList(),
13064 N1: N->getOperand(Num: 0), N2: RHS, N3: N->getOperand(Num: 2));
13065 }
13066 }
13067 } else if (N->getOperand(Num: 1)->getOpcode() == ISD::SMUL_LOHI) {
13068 return AddCombineTo64bitMLAL(AddeSubeNode: N, DCI, Subtarget);
13069 }
13070 return SDValue();
13071}
13072
13073static SDValue PerformSELECTCombine(SDNode *N,
13074 TargetLowering::DAGCombinerInfo &DCI,
13075 const ARMSubtarget *Subtarget) {
13076 if (!Subtarget->hasMVEIntegerOps())
13077 return SDValue();
13078
13079 SDLoc dl(N);
13080 SDValue SetCC;
13081 SDValue LHS;
13082 SDValue RHS;
13083 ISD::CondCode CC;
13084 SDValue TrueVal;
13085 SDValue FalseVal;
13086
13087 if (N->getOpcode() == ISD::SELECT &&
13088 N->getOperand(Num: 0)->getOpcode() == ISD::SETCC) {
13089 SetCC = N->getOperand(Num: 0);
13090 LHS = SetCC->getOperand(Num: 0);
13091 RHS = SetCC->getOperand(Num: 1);
13092 CC = cast<CondCodeSDNode>(Val: SetCC->getOperand(Num: 2))->get();
13093 TrueVal = N->getOperand(Num: 1);
13094 FalseVal = N->getOperand(Num: 2);
13095 } else if (N->getOpcode() == ISD::SELECT_CC) {
13096 LHS = N->getOperand(Num: 0);
13097 RHS = N->getOperand(Num: 1);
13098 CC = cast<CondCodeSDNode>(Val: N->getOperand(Num: 4))->get();
13099 TrueVal = N->getOperand(Num: 2);
13100 FalseVal = N->getOperand(Num: 3);
13101 } else {
13102 return SDValue();
13103 }
13104
13105 unsigned int Opcode = 0;
13106 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
13107 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
13108 (CC == ISD::SETULT || CC == ISD::SETUGT)) {
13109 Opcode = ARMISD::VMINVu;
13110 if (CC == ISD::SETUGT)
13111 std::swap(a&: TrueVal, b&: FalseVal);
13112 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
13113 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
13114 (CC == ISD::SETLT || CC == ISD::SETGT)) {
13115 Opcode = ARMISD::VMINVs;
13116 if (CC == ISD::SETGT)
13117 std::swap(a&: TrueVal, b&: FalseVal);
13118 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
13119 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
13120 (CC == ISD::SETUGT || CC == ISD::SETULT)) {
13121 Opcode = ARMISD::VMAXVu;
13122 if (CC == ISD::SETULT)
13123 std::swap(a&: TrueVal, b&: FalseVal);
13124 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
13125 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
13126 (CC == ISD::SETGT || CC == ISD::SETLT)) {
13127 Opcode = ARMISD::VMAXVs;
13128 if (CC == ISD::SETLT)
13129 std::swap(a&: TrueVal, b&: FalseVal);
13130 } else
13131 return SDValue();
13132
13133 // Normalise to the right hand side being the vector reduction
13134 switch (TrueVal->getOpcode()) {
13135 case ISD::VECREDUCE_UMIN:
13136 case ISD::VECREDUCE_SMIN:
13137 case ISD::VECREDUCE_UMAX:
13138 case ISD::VECREDUCE_SMAX:
13139 std::swap(a&: LHS, b&: RHS);
13140 std::swap(a&: TrueVal, b&: FalseVal);
13141 break;
13142 }
13143
13144 EVT VectorType = FalseVal->getOperand(Num: 0).getValueType();
13145
13146 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
13147 VectorType != MVT::v4i32)
13148 return SDValue();
13149
13150 EVT VectorScalarType = VectorType.getVectorElementType();
13151
13152 // The values being selected must also be the ones being compared
13153 if (TrueVal != LHS || FalseVal != RHS)
13154 return SDValue();
13155
13156 EVT LeftType = LHS->getValueType(ResNo: 0);
13157 EVT RightType = RHS->getValueType(ResNo: 0);
13158
13159 // The types must match the reduced type too
13160 if (LeftType != VectorScalarType || RightType != VectorScalarType)
13161 return SDValue();
13162
13163 // Legalise the scalar to an i32
13164 if (VectorScalarType != MVT::i32)
13165 LHS = DCI.DAG.getNode(Opcode: ISD::ANY_EXTEND, DL: dl, VT: MVT::i32, Operand: LHS);
13166
13167 // Generate the reduction as an i32 for legalisation purposes
13168 auto Reduction =
13169 DCI.DAG.getNode(Opcode, DL: dl, VT: MVT::i32, N1: LHS, N2: RHS->getOperand(Num: 0));
13170
13171 // The result isn't actually an i32 so truncate it back to its original type
13172 if (VectorScalarType != MVT::i32)
13173 Reduction = DCI.DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: VectorScalarType, Operand: Reduction);
13174
13175 return Reduction;
13176}
13177
13178// A special combine for the vqdmulh family of instructions. This is one of the
13179// potential set of patterns that could patch this instruction. The base pattern
13180// you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
13181// This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
13182// which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
13183// the max is unnecessary.
13184static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) {
13185 EVT VT = N->getValueType(ResNo: 0);
13186 SDValue Shft;
13187 ConstantSDNode *Clamp;
13188
13189 if (!VT.isVector() || VT.getScalarSizeInBits() > 64)
13190 return SDValue();
13191
13192 if (N->getOpcode() == ISD::SMIN) {
13193 Shft = N->getOperand(Num: 0);
13194 Clamp = isConstOrConstSplat(N: N->getOperand(Num: 1));
13195 } else if (N->getOpcode() == ISD::VSELECT) {
13196 // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
13197 SDValue Cmp = N->getOperand(Num: 0);
13198 if (Cmp.getOpcode() != ISD::SETCC ||
13199 cast<CondCodeSDNode>(Val: Cmp.getOperand(i: 2))->get() != ISD::SETLT ||
13200 Cmp.getOperand(i: 0) != N->getOperand(Num: 1) ||
13201 Cmp.getOperand(i: 1) != N->getOperand(Num: 2))
13202 return SDValue();
13203 Shft = N->getOperand(Num: 1);
13204 Clamp = isConstOrConstSplat(N: N->getOperand(Num: 2));
13205 } else
13206 return SDValue();
13207
13208 if (!Clamp)
13209 return SDValue();
13210
13211 MVT ScalarType;
13212 int ShftAmt = 0;
13213 switch (Clamp->getSExtValue()) {
13214 case (1 << 7) - 1:
13215 ScalarType = MVT::i8;
13216 ShftAmt = 7;
13217 break;
13218 case (1 << 15) - 1:
13219 ScalarType = MVT::i16;
13220 ShftAmt = 15;
13221 break;
13222 case (1ULL << 31) - 1:
13223 ScalarType = MVT::i32;
13224 ShftAmt = 31;
13225 break;
13226 default:
13227 return SDValue();
13228 }
13229
13230 if (Shft.getOpcode() != ISD::SRA)
13231 return SDValue();
13232 ConstantSDNode *N1 = isConstOrConstSplat(N: Shft.getOperand(i: 1));
13233 if (!N1 || N1->getSExtValue() != ShftAmt)
13234 return SDValue();
13235
13236 SDValue Mul = Shft.getOperand(i: 0);
13237 if (Mul.getOpcode() != ISD::MUL)
13238 return SDValue();
13239
13240 SDValue Ext0 = Mul.getOperand(i: 0);
13241 SDValue Ext1 = Mul.getOperand(i: 1);
13242 if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
13243 Ext1.getOpcode() != ISD::SIGN_EXTEND)
13244 return SDValue();
13245 EVT VecVT = Ext0.getOperand(i: 0).getValueType();
13246 if (!VecVT.isPow2VectorType() || VecVT.getVectorNumElements() == 1)
13247 return SDValue();
13248 if (Ext1.getOperand(i: 0).getValueType() != VecVT ||
13249 VecVT.getScalarType() != ScalarType ||
13250 VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
13251 return SDValue();
13252
13253 SDLoc DL(Mul);
13254 unsigned LegalLanes = 128 / (ShftAmt + 1);
13255 EVT LegalVecVT = MVT::getVectorVT(VT: ScalarType, NumElements: LegalLanes);
13256 // For types smaller than legal vectors extend to be legal and only use needed
13257 // lanes.
13258 if (VecVT.getSizeInBits() < 128) {
13259 EVT ExtVecVT =
13260 MVT::getVectorVT(VT: MVT::getIntegerVT(BitWidth: 128 / VecVT.getVectorNumElements()),
13261 NumElements: VecVT.getVectorNumElements());
13262 SDValue Inp0 =
13263 DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: ExtVecVT, Operand: Ext0.getOperand(i: 0));
13264 SDValue Inp1 =
13265 DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: ExtVecVT, Operand: Ext1.getOperand(i: 0));
13266 Inp0 = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT: LegalVecVT, Operand: Inp0);
13267 Inp1 = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT: LegalVecVT, Operand: Inp1);
13268 SDValue VQDMULH = DAG.getNode(Opcode: ARMISD::VQDMULH, DL, VT: LegalVecVT, N1: Inp0, N2: Inp1);
13269 SDValue Trunc = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT: ExtVecVT, Operand: VQDMULH);
13270 Trunc = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: VecVT, Operand: Trunc);
13271 return DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT, Operand: Trunc);
13272 }
13273
13274 // For larger types, split into legal sized chunks.
13275 assert(VecVT.getSizeInBits() % 128 == 0 && "Expected a power2 type");
13276 unsigned NumParts = VecVT.getSizeInBits() / 128;
13277 SmallVector<SDValue> Parts;
13278 for (unsigned I = 0; I < NumParts; ++I) {
13279 SDValue Inp0 =
13280 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: LegalVecVT, N1: Ext0.getOperand(i: 0),
13281 N2: DAG.getVectorIdxConstant(Val: I * LegalLanes, DL));
13282 SDValue Inp1 =
13283 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: LegalVecVT, N1: Ext1.getOperand(i: 0),
13284 N2: DAG.getVectorIdxConstant(Val: I * LegalLanes, DL));
13285 SDValue VQDMULH = DAG.getNode(Opcode: ARMISD::VQDMULH, DL, VT: LegalVecVT, N1: Inp0, N2: Inp1);
13286 Parts.push_back(Elt: VQDMULH);
13287 }
13288 return DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT,
13289 Operand: DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: VecVT, Ops: Parts));
13290}
13291
13292static SDValue PerformVSELECTCombine(SDNode *N,
13293 TargetLowering::DAGCombinerInfo &DCI,
13294 const ARMSubtarget *Subtarget) {
13295 if (!Subtarget->hasMVEIntegerOps())
13296 return SDValue();
13297
13298 if (SDValue V = PerformVQDMULHCombine(N, DAG&: DCI.DAG))
13299 return V;
13300
13301 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
13302 //
13303 // We need to re-implement this optimization here as the implementation in the
13304 // Target-Independent DAGCombiner does not handle the kind of constant we make
13305 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
13306 // good reason, allowing truncation there would break other targets).
13307 //
13308 // Currently, this is only done for MVE, as it's the only target that benefits
13309 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
13310 if (N->getOperand(Num: 0).getOpcode() != ISD::XOR)
13311 return SDValue();
13312 SDValue XOR = N->getOperand(Num: 0);
13313
13314 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
13315 // It is important to check with truncation allowed as the BUILD_VECTORs we
13316 // generate in those situations will truncate their operands.
13317 ConstantSDNode *Const =
13318 isConstOrConstSplat(N: XOR->getOperand(Num: 1), /*AllowUndefs*/ false,
13319 /*AllowTruncation*/ true);
13320 if (!Const || !Const->isOne())
13321 return SDValue();
13322
13323 // Rewrite into vselect(cond, rhs, lhs).
13324 SDValue Cond = XOR->getOperand(Num: 0);
13325 SDValue LHS = N->getOperand(Num: 1);
13326 SDValue RHS = N->getOperand(Num: 2);
13327 EVT Type = N->getValueType(ResNo: 0);
13328 return DCI.DAG.getNode(Opcode: ISD::VSELECT, DL: SDLoc(N), VT: Type, N1: Cond, N2: RHS, N3: LHS);
13329}
13330
13331// Convert vsetcc([0,1,2,..], splat(n), ult) -> vctp n
13332static SDValue PerformVSetCCToVCTPCombine(SDNode *N,
13333 TargetLowering::DAGCombinerInfo &DCI,
13334 const ARMSubtarget *Subtarget) {
13335 SDValue Op0 = N->getOperand(Num: 0);
13336 SDValue Op1 = N->getOperand(Num: 1);
13337 ISD::CondCode CC = cast<CondCodeSDNode>(Val: N->getOperand(Num: 2))->get();
13338 EVT VT = N->getValueType(ResNo: 0);
13339
13340 if (!Subtarget->hasMVEIntegerOps() ||
13341 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13342 return SDValue();
13343
13344 if (CC == ISD::SETUGE) {
13345 std::swap(a&: Op0, b&: Op1);
13346 CC = ISD::SETULT;
13347 }
13348
13349 if (CC != ISD::SETULT || VT.getScalarSizeInBits() != 1 ||
13350 Op0.getOpcode() != ISD::BUILD_VECTOR)
13351 return SDValue();
13352
13353 // Check first operand is BuildVector of 0,1,2,...
13354 for (unsigned I = 0; I < VT.getVectorNumElements(); I++) {
13355 if (!Op0.getOperand(i: I).isUndef() &&
13356 !(isa<ConstantSDNode>(Val: Op0.getOperand(i: I)) &&
13357 Op0.getConstantOperandVal(i: I) == I))
13358 return SDValue();
13359 }
13360
13361 // The second is a Splat of Op1S
13362 SDValue Op1S = DCI.DAG.getSplatValue(V: Op1);
13363 if (!Op1S)
13364 return SDValue();
13365
13366 unsigned Opc;
13367 switch (VT.getVectorNumElements()) {
13368 case 2:
13369 Opc = Intrinsic::arm_mve_vctp64;
13370 break;
13371 case 4:
13372 Opc = Intrinsic::arm_mve_vctp32;
13373 break;
13374 case 8:
13375 Opc = Intrinsic::arm_mve_vctp16;
13376 break;
13377 case 16:
13378 Opc = Intrinsic::arm_mve_vctp8;
13379 break;
13380 default:
13381 return SDValue();
13382 }
13383
13384 SDLoc DL(N);
13385 return DCI.DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT,
13386 N1: DCI.DAG.getConstant(Val: Opc, DL, VT: MVT::i32),
13387 N2: DCI.DAG.getZExtOrTrunc(Op: Op1S, DL, VT: MVT::i32));
13388}
13389
13390/// PerformADDECombine - Target-specific dag combine transform from
13391/// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
13392/// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
13393static SDValue PerformADDECombine(SDNode *N,
13394 TargetLowering::DAGCombinerInfo &DCI,
13395 const ARMSubtarget *Subtarget) {
13396 // Only ARM and Thumb2 support UMLAL/SMLAL.
13397 if (Subtarget->isThumb1Only())
13398 return PerformAddeSubeCombine(N, DCI, Subtarget);
13399
13400 // Only perform the checks after legalize when the pattern is available.
13401 if (DCI.isBeforeLegalize()) return SDValue();
13402
13403 return AddCombineTo64bitUMAAL(AddeNode: N, DCI, Subtarget);
13404}
13405
13406/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
13407/// operands N0 and N1. This is a helper for PerformADDCombine that is
13408/// called with the default operands, and if that fails, with commuted
13409/// operands.
13410static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
13411 TargetLowering::DAGCombinerInfo &DCI,
13412 const ARMSubtarget *Subtarget){
13413 // Attempt to create vpadd for this add.
13414 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
13415 return Result;
13416
13417 // Attempt to create vpaddl for this add.
13418 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
13419 return Result;
13420 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
13421 Subtarget))
13422 return Result;
13423
13424 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
13425 if (N0.getNode()->hasOneUse())
13426 if (SDValue Result = combineSelectAndUse(N, Slct: N0, OtherOp: N1, DCI))
13427 return Result;
13428 return SDValue();
13429}
13430
13431static SDValue TryDistrubutionADDVecReduce(SDNode *N, SelectionDAG &DAG) {
13432 EVT VT = N->getValueType(ResNo: 0);
13433 SDValue N0 = N->getOperand(Num: 0);
13434 SDValue N1 = N->getOperand(Num: 1);
13435 SDLoc dl(N);
13436
13437 auto IsVecReduce = [](SDValue Op) {
13438 switch (Op.getOpcode()) {
13439 case ISD::VECREDUCE_ADD:
13440 case ARMISD::VADDVs:
13441 case ARMISD::VADDVu:
13442 case ARMISD::VMLAVs:
13443 case ARMISD::VMLAVu:
13444 return true;
13445 }
13446 return false;
13447 };
13448
13449 auto DistrubuteAddAddVecReduce = [&](SDValue N0, SDValue N1) {
13450 // Distribute add(X, add(vecreduce(Y), vecreduce(Z))) ->
13451 // add(add(X, vecreduce(Y)), vecreduce(Z))
13452 // to make better use of vaddva style instructions.
13453 if (VT == MVT::i32 && N1.getOpcode() == ISD::ADD && !IsVecReduce(N0) &&
13454 IsVecReduce(N1.getOperand(i: 0)) && IsVecReduce(N1.getOperand(i: 1)) &&
13455 !isa<ConstantSDNode>(Val: N0) && N1->hasOneUse()) {
13456 SDValue Add0 = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: N0, N2: N1.getOperand(i: 0));
13457 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: Add0, N2: N1.getOperand(i: 1));
13458 }
13459 // And turn add(add(A, reduce(B)), add(C, reduce(D))) ->
13460 // add(add(add(A, C), reduce(B)), reduce(D))
13461 if (VT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
13462 N1.getOpcode() == ISD::ADD && N0->hasOneUse() && N1->hasOneUse()) {
13463 unsigned N0RedOp = 0;
13464 if (!IsVecReduce(N0.getOperand(i: N0RedOp))) {
13465 N0RedOp = 1;
13466 if (!IsVecReduce(N0.getOperand(i: N0RedOp)))
13467 return SDValue();
13468 }
13469
13470 unsigned N1RedOp = 0;
13471 if (!IsVecReduce(N1.getOperand(i: N1RedOp)))
13472 N1RedOp = 1;
13473 if (!IsVecReduce(N1.getOperand(i: N1RedOp)))
13474 return SDValue();
13475
13476 SDValue Add0 = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: N0.getOperand(i: 1 - N0RedOp),
13477 N2: N1.getOperand(i: 1 - N1RedOp));
13478 SDValue Add1 =
13479 DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: Add0, N2: N0.getOperand(i: N0RedOp));
13480 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: Add1, N2: N1.getOperand(i: N1RedOp));
13481 }
13482 return SDValue();
13483 };
13484 if (SDValue R = DistrubuteAddAddVecReduce(N0, N1))
13485 return R;
13486 if (SDValue R = DistrubuteAddAddVecReduce(N1, N0))
13487 return R;
13488
13489 // Distribute add(vecreduce(load(Y)), vecreduce(load(Z)))
13490 // Or add(add(X, vecreduce(load(Y))), vecreduce(load(Z)))
13491 // by ascending load offsets. This can help cores prefetch if the order of
13492 // loads is more predictable.
13493 auto DistrubuteVecReduceLoad = [&](SDValue N0, SDValue N1, bool IsForward) {
13494 // Check if two reductions are known to load data where one is before/after
13495 // another. Return negative if N0 loads data before N1, positive if N1 is
13496 // before N0 and 0 otherwise if nothing is known.
13497 auto IsKnownOrderedLoad = [&](SDValue N0, SDValue N1) {
13498 // Look through to the first operand of a MUL, for the VMLA case.
13499 // Currently only looks at the first operand, in the hope they are equal.
13500 if (N0.getOpcode() == ISD::MUL)
13501 N0 = N0.getOperand(i: 0);
13502 if (N1.getOpcode() == ISD::MUL)
13503 N1 = N1.getOperand(i: 0);
13504
13505 // Return true if the two operands are loads to the same object and the
13506 // offset of the first is known to be less than the offset of the second.
13507 LoadSDNode *Load0 = dyn_cast<LoadSDNode>(Val&: N0);
13508 LoadSDNode *Load1 = dyn_cast<LoadSDNode>(Val&: N1);
13509 if (!Load0 || !Load1 || Load0->getChain() != Load1->getChain() ||
13510 !Load0->isSimple() || !Load1->isSimple() || Load0->isIndexed() ||
13511 Load1->isIndexed())
13512 return 0;
13513
13514 auto BaseLocDecomp0 = BaseIndexOffset::match(N: Load0, DAG);
13515 auto BaseLocDecomp1 = BaseIndexOffset::match(N: Load1, DAG);
13516
13517 if (!BaseLocDecomp0.getBase() ||
13518 BaseLocDecomp0.getBase() != BaseLocDecomp1.getBase() ||
13519 !BaseLocDecomp0.hasValidOffset() || !BaseLocDecomp1.hasValidOffset())
13520 return 0;
13521 if (BaseLocDecomp0.getOffset() < BaseLocDecomp1.getOffset())
13522 return -1;
13523 if (BaseLocDecomp0.getOffset() > BaseLocDecomp1.getOffset())
13524 return 1;
13525 return 0;
13526 };
13527
13528 SDValue X;
13529 if (N0.getOpcode() == ISD::ADD && N0->hasOneUse()) {
13530 if (IsVecReduce(N0.getOperand(i: 0)) && IsVecReduce(N0.getOperand(i: 1))) {
13531 int IsBefore = IsKnownOrderedLoad(N0.getOperand(i: 0).getOperand(i: 0),
13532 N0.getOperand(i: 1).getOperand(i: 0));
13533 if (IsBefore < 0) {
13534 X = N0.getOperand(i: 0);
13535 N0 = N0.getOperand(i: 1);
13536 } else if (IsBefore > 0) {
13537 X = N0.getOperand(i: 1);
13538 N0 = N0.getOperand(i: 0);
13539 } else
13540 return SDValue();
13541 } else if (IsVecReduce(N0.getOperand(i: 0))) {
13542 X = N0.getOperand(i: 1);
13543 N0 = N0.getOperand(i: 0);
13544 } else if (IsVecReduce(N0.getOperand(i: 1))) {
13545 X = N0.getOperand(i: 0);
13546 N0 = N0.getOperand(i: 1);
13547 } else
13548 return SDValue();
13549 } else if (IsForward && IsVecReduce(N0) && IsVecReduce(N1) &&
13550 IsKnownOrderedLoad(N0.getOperand(i: 0), N1.getOperand(i: 0)) < 0) {
13551 // Note this is backward to how you would expect. We create
13552 // add(reduce(load + 16), reduce(load + 0)) so that the
13553 // add(reduce(load+16), X) is combined into VADDVA(X, load+16)), leaving
13554 // the X as VADDV(load + 0)
13555 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1, N2: N0);
13556 } else
13557 return SDValue();
13558
13559 if (!IsVecReduce(N0) || !IsVecReduce(N1))
13560 return SDValue();
13561
13562 if (IsKnownOrderedLoad(N1.getOperand(i: 0), N0.getOperand(i: 0)) >= 0)
13563 return SDValue();
13564
13565 // Switch from add(add(X, N0), N1) to add(add(X, N1), N0)
13566 SDValue Add0 = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: X, N2: N1);
13567 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: Add0, N2: N0);
13568 };
13569 if (SDValue R = DistrubuteVecReduceLoad(N0, N1, true))
13570 return R;
13571 if (SDValue R = DistrubuteVecReduceLoad(N1, N0, false))
13572 return R;
13573 return SDValue();
13574}
13575
13576static SDValue PerformADDVecReduce(SDNode *N, SelectionDAG &DAG,
13577 const ARMSubtarget *Subtarget) {
13578 if (!Subtarget->hasMVEIntegerOps())
13579 return SDValue();
13580
13581 if (SDValue R = TryDistrubutionADDVecReduce(N, DAG))
13582 return R;
13583
13584 EVT VT = N->getValueType(ResNo: 0);
13585 SDValue N0 = N->getOperand(Num: 0);
13586 SDValue N1 = N->getOperand(Num: 1);
13587 SDLoc dl(N);
13588
13589 if (VT != MVT::i64)
13590 return SDValue();
13591
13592 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
13593 // will look like:
13594 // t1: i32,i32 = ARMISD::VADDLVs x
13595 // t2: i64 = build_pair t1, t1:1
13596 // t3: i64 = add t2, y
13597 // Otherwise we try to push the add up above VADDLVAx, to potentially allow
13598 // the add to be simplified separately.
13599 // We also need to check for sext / zext and commutitive adds.
13600 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
13601 SDValue NB) {
13602 if (NB->getOpcode() != ISD::BUILD_PAIR)
13603 return SDValue();
13604 SDValue VecRed = NB->getOperand(Num: 0);
13605 if ((VecRed->getOpcode() != Opcode && VecRed->getOpcode() != OpcodeA) ||
13606 VecRed.getResNo() != 0 ||
13607 NB->getOperand(Num: 1) != SDValue(VecRed.getNode(), 1))
13608 return SDValue();
13609
13610 if (VecRed->getOpcode() == OpcodeA) {
13611 // add(NA, VADDLVA(Inp), Y) -> VADDLVA(add(NA, Inp), Y)
13612 SDValue Inp = DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64,
13613 N1: VecRed.getOperand(i: 0), N2: VecRed.getOperand(i: 1));
13614 NA = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i64, N1: Inp, N2: NA);
13615 }
13616
13617 SmallVector<SDValue, 4> Ops(2);
13618 std::tie(args&: Ops[0], args&: Ops[1]) = DAG.SplitScalar(N: NA, DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
13619
13620 unsigned S = VecRed->getOpcode() == OpcodeA ? 2 : 0;
13621 for (unsigned I = S, E = VecRed.getNumOperands(); I < E; I++)
13622 Ops.push_back(Elt: VecRed->getOperand(Num: I));
13623 SDValue Red =
13624 DAG.getNode(Opcode: OpcodeA, DL: dl, VTList: DAG.getVTList(VTs: {MVT::i32, MVT::i32}), Ops);
13625 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Red,
13626 N2: SDValue(Red.getNode(), 1));
13627 };
13628
13629 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
13630 return M;
13631 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
13632 return M;
13633 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
13634 return M;
13635 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
13636 return M;
13637 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
13638 return M;
13639 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
13640 return M;
13641 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
13642 return M;
13643 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
13644 return M;
13645 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
13646 return M;
13647 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
13648 return M;
13649 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
13650 return M;
13651 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
13652 return M;
13653 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
13654 return M;
13655 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
13656 return M;
13657 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
13658 return M;
13659 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
13660 return M;
13661 return SDValue();
13662}
13663
13664bool
13665ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
13666 CombineLevel Level) const {
13667 assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||
13668 N->getOpcode() == ISD::SRL) &&
13669 "Expected shift op");
13670
13671 SDValue ShiftLHS = N->getOperand(Num: 0);
13672 if (!ShiftLHS->hasOneUse())
13673 return false;
13674
13675 if (ShiftLHS.getOpcode() == ISD::SIGN_EXTEND &&
13676 !ShiftLHS.getOperand(i: 0)->hasOneUse())
13677 return false;
13678
13679 if (Level == BeforeLegalizeTypes)
13680 return true;
13681
13682 if (N->getOpcode() != ISD::SHL)
13683 return true;
13684
13685 if (Subtarget->isThumb1Only()) {
13686 // Avoid making expensive immediates by commuting shifts. (This logic
13687 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
13688 // for free.)
13689 if (N->getOpcode() != ISD::SHL)
13690 return true;
13691 SDValue N1 = N->getOperand(Num: 0);
13692 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
13693 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
13694 return true;
13695 if (auto *Const = dyn_cast<ConstantSDNode>(Val: N1->getOperand(Num: 1))) {
13696 if (Const->getAPIntValue().ult(RHS: 256))
13697 return false;
13698 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(RHS: 0) &&
13699 Const->getAPIntValue().sgt(RHS: -256))
13700 return false;
13701 }
13702 return true;
13703 }
13704
13705 // Turn off commute-with-shift transform after legalization, so it doesn't
13706 // conflict with PerformSHLSimplify. (We could try to detect when
13707 // PerformSHLSimplify would trigger more precisely, but it isn't
13708 // really necessary.)
13709 return false;
13710}
13711
13712bool ARMTargetLowering::isDesirableToCommuteXorWithShift(
13713 const SDNode *N) const {
13714 assert(N->getOpcode() == ISD::XOR &&
13715 (N->getOperand(0).getOpcode() == ISD::SHL ||
13716 N->getOperand(0).getOpcode() == ISD::SRL) &&
13717 "Expected XOR(SHIFT) pattern");
13718
13719 // Only commute if the entire NOT mask is a hidden shifted mask.
13720 auto *XorC = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
13721 auto *ShiftC = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 0).getOperand(i: 1));
13722 if (XorC && ShiftC) {
13723 unsigned MaskIdx, MaskLen;
13724 if (XorC->getAPIntValue().isShiftedMask(MaskIdx, MaskLen)) {
13725 unsigned ShiftAmt = ShiftC->getZExtValue();
13726 unsigned BitWidth = N->getValueType(ResNo: 0).getScalarSizeInBits();
13727 if (N->getOperand(Num: 0).getOpcode() == ISD::SHL)
13728 return MaskIdx == ShiftAmt && MaskLen == (BitWidth - ShiftAmt);
13729 return MaskIdx == 0 && MaskLen == (BitWidth - ShiftAmt);
13730 }
13731 }
13732
13733 return false;
13734}
13735
13736bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
13737 const SDNode *N) const {
13738 assert(((N->getOpcode() == ISD::SHL &&
13739 N->getOperand(0).getOpcode() == ISD::SRL) ||
13740 (N->getOpcode() == ISD::SRL &&
13741 N->getOperand(0).getOpcode() == ISD::SHL)) &&
13742 "Expected shift-shift mask");
13743
13744 if (!Subtarget->isThumb1Only())
13745 return true;
13746
13747 EVT VT = N->getValueType(ResNo: 0);
13748 if (VT.getScalarSizeInBits() > 32)
13749 return true;
13750
13751 return false;
13752}
13753
13754bool ARMTargetLowering::shouldFoldSelectWithIdentityConstant(
13755 unsigned BinOpcode, EVT VT, unsigned SelectOpcode, SDValue X,
13756 SDValue Y) const {
13757 return Subtarget->hasMVEIntegerOps() && isTypeLegal(VT) &&
13758 SelectOpcode == ISD::VSELECT;
13759}
13760
13761bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13762 if (!Subtarget->hasNEON()) {
13763 if (Subtarget->isThumb1Only())
13764 return VT.getScalarSizeInBits() <= 32;
13765 return true;
13766 }
13767 return VT.isScalarInteger();
13768}
13769
13770bool ARMTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
13771 EVT VT) const {
13772 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
13773 return false;
13774
13775 switch (FPVT.getSimpleVT().SimpleTy) {
13776 case MVT::f16:
13777 return Subtarget->hasVFP2Base();
13778 case MVT::f32:
13779 return Subtarget->hasVFP2Base();
13780 case MVT::f64:
13781 return Subtarget->hasFP64();
13782 case MVT::v4f32:
13783 case MVT::v8f16:
13784 return Subtarget->hasMVEFloatOps();
13785 default:
13786 return false;
13787 }
13788}
13789
13790static SDValue PerformSHLSimplify(SDNode *N,
13791 TargetLowering::DAGCombinerInfo &DCI,
13792 const ARMSubtarget *ST) {
13793 // Allow the generic combiner to identify potential bswaps.
13794 if (DCI.isBeforeLegalize())
13795 return SDValue();
13796
13797 // DAG combiner will fold:
13798 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
13799 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
13800 // Other code patterns that can be also be modified have the following form:
13801 // b + ((a << 1) | 510)
13802 // b + ((a << 1) & 510)
13803 // b + ((a << 1) ^ 510)
13804 // b + ((a << 1) + 510)
13805
13806 // Many instructions can perform the shift for free, but it requires both
13807 // the operands to be registers. If c1 << c2 is too large, a mov immediate
13808 // instruction will needed. So, unfold back to the original pattern if:
13809 // - if c1 and c2 are small enough that they don't require mov imms.
13810 // - the user(s) of the node can perform an shl
13811
13812 // No shifted operands for 16-bit instructions.
13813 if (ST->isThumb() && ST->isThumb1Only())
13814 return SDValue();
13815
13816 // Check that all the users could perform the shl themselves.
13817 for (auto *U : N->users()) {
13818 switch(U->getOpcode()) {
13819 default:
13820 return SDValue();
13821 case ISD::SUB:
13822 case ISD::ADD:
13823 case ISD::AND:
13824 case ISD::OR:
13825 case ISD::XOR:
13826 case ISD::SETCC:
13827 case ARMISD::CMP:
13828 // Check that the user isn't already using a constant because there
13829 // aren't any instructions that support an immediate operand and a
13830 // shifted operand.
13831 if (isa<ConstantSDNode>(Val: U->getOperand(Num: 0)) ||
13832 isa<ConstantSDNode>(Val: U->getOperand(Num: 1)))
13833 return SDValue();
13834
13835 // Check that it's not already using a shift.
13836 if (U->getOperand(Num: 0).getOpcode() == ISD::SHL ||
13837 U->getOperand(Num: 1).getOpcode() == ISD::SHL)
13838 return SDValue();
13839 break;
13840 }
13841 }
13842
13843 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
13844 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
13845 return SDValue();
13846
13847 if (N->getOperand(Num: 0).getOpcode() != ISD::SHL)
13848 return SDValue();
13849
13850 SDValue SHL = N->getOperand(Num: 0);
13851
13852 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
13853 auto *C2 = dyn_cast<ConstantSDNode>(Val: SHL.getOperand(i: 1));
13854 if (!C1ShlC2 || !C2)
13855 return SDValue();
13856
13857 APInt C2Int = C2->getAPIntValue();
13858 APInt C1Int = C1ShlC2->getAPIntValue();
13859 unsigned C2Width = C2Int.getBitWidth();
13860 if (C2Int.uge(RHS: C2Width))
13861 return SDValue();
13862 uint64_t C2Value = C2Int.getZExtValue();
13863
13864 // Check that performing a lshr will not lose any information.
13865 APInt Mask = APInt::getHighBitsSet(numBits: C2Width, hiBitsSet: C2Width - C2Value);
13866 if ((C1Int & Mask) != C1Int)
13867 return SDValue();
13868
13869 // Shift the first constant.
13870 C1Int.lshrInPlace(ShiftAmt: C2Int);
13871
13872 // The immediates are encoded as an 8-bit value that can be rotated.
13873 auto LargeImm = [](const APInt &Imm) {
13874 unsigned Zeros = Imm.countl_zero() + Imm.countr_zero();
13875 return Imm.getBitWidth() - Zeros > 8;
13876 };
13877
13878 if (LargeImm(C1Int) || LargeImm(C2Int))
13879 return SDValue();
13880
13881 SelectionDAG &DAG = DCI.DAG;
13882 SDLoc dl(N);
13883 SDValue X = SHL.getOperand(i: 0);
13884 SDValue BinOp = DAG.getNode(Opcode: N->getOpcode(), DL: dl, VT: MVT::i32, N1: X,
13885 N2: DAG.getConstant(Val: C1Int, DL: dl, VT: MVT::i32));
13886 // Shift left to compensate for the lshr of C1Int.
13887 SDValue Res = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT: MVT::i32, N1: BinOp, N2: SHL.getOperand(i: 1));
13888
13889 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
13890 SHL.dump(); N->dump());
13891 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
13892 return Res;
13893}
13894
13895
13896/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
13897///
13898static SDValue PerformADDCombine(SDNode *N,
13899 TargetLowering::DAGCombinerInfo &DCI,
13900 const ARMSubtarget *Subtarget) {
13901 SDValue N0 = N->getOperand(Num: 0);
13902 SDValue N1 = N->getOperand(Num: 1);
13903
13904 // Only works one way, because it needs an immediate operand.
13905 if (SDValue Result = PerformSHLSimplify(N, DCI, ST: Subtarget))
13906 return Result;
13907
13908 if (SDValue Result = PerformADDVecReduce(N, DAG&: DCI.DAG, Subtarget))
13909 return Result;
13910
13911 // First try with the default operand order.
13912 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
13913 return Result;
13914
13915 // If that didn't work, try again with the operands commuted.
13916 return PerformADDCombineWithOperands(N, N0: N1, N1: N0, DCI, Subtarget);
13917}
13918
13919// Combine (sub 0, (csinc X, Y, CC)) -> (csinv -X, Y, CC)
13920// providing -X is as cheap as X (currently, just a constant).
13921static SDValue PerformSubCSINCCombine(SDNode *N, SelectionDAG &DAG) {
13922 if (N->getValueType(ResNo: 0) != MVT::i32 || !isNullConstant(V: N->getOperand(Num: 0)))
13923 return SDValue();
13924 SDValue CSINC = N->getOperand(Num: 1);
13925 if (CSINC.getOpcode() != ARMISD::CSINC || !CSINC.hasOneUse())
13926 return SDValue();
13927
13928 ConstantSDNode *X = dyn_cast<ConstantSDNode>(Val: CSINC.getOperand(i: 0));
13929 if (!X)
13930 return SDValue();
13931
13932 return DAG.getNode(Opcode: ARMISD::CSINV, DL: SDLoc(N), VT: MVT::i32,
13933 N1: DAG.getNode(Opcode: ISD::SUB, DL: SDLoc(N), VT: MVT::i32, N1: N->getOperand(Num: 0),
13934 N2: CSINC.getOperand(i: 0)),
13935 N2: CSINC.getOperand(i: 1), N3: CSINC.getOperand(i: 2),
13936 N4: CSINC.getOperand(i: 3));
13937}
13938
13939static int getNegationCost(SDValue Op) {
13940 // Free to negate.
13941 if (isa<ConstantSDNode>(Val: Op))
13942 return 0;
13943
13944 // Will save one instruction.
13945 if (Op.getOpcode() == ISD::SUB && isNullConstant(V: Op.getOperand(i: 0)))
13946 return -1;
13947
13948 // Can freely negate by converting sra <-> srl.
13949 if (Op.getOpcode() == ISD::SRA || Op.getOpcode() == ISD::SRL) {
13950 ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 1));
13951 if (Op.hasOneUse() && ShiftAmt &&
13952 ShiftAmt->getZExtValue() == Op.getValueType().getScalarSizeInBits() - 1)
13953 return 0;
13954 }
13955
13956 // Will have to create sub.
13957 return 1;
13958}
13959
13960// Try to fold
13961//
13962// (neg (cmov X, Y)) -> (cmov (neg X), (neg Y))
13963//
13964// The folding helps cmov to be matched with csneg without generating
13965// redundant neg instruction.
13966static SDValue performNegCMovCombine(SDNode *N, SelectionDAG &DAG) {
13967 assert(N->getOpcode() == ISD::SUB);
13968 if (!isNullConstant(V: N->getOperand(Num: 0)))
13969 return SDValue();
13970
13971 SDValue CMov = N->getOperand(Num: 1);
13972 if (CMov.getOpcode() != ARMISD::CMOV || !CMov->hasOneUse())
13973 return SDValue();
13974
13975 SDValue N0 = CMov.getOperand(i: 0);
13976 SDValue N1 = CMov.getOperand(i: 1);
13977
13978 // Only perform the fold if we actually save something.
13979 if (getNegationCost(Op: N0) + getNegationCost(Op: N1) > 0)
13980 return SDValue();
13981
13982 SDLoc DL(N);
13983 EVT VT = CMov.getValueType();
13984
13985 SDValue N0N = DAG.getNegative(Val: N0, DL, VT);
13986 SDValue N1N = DAG.getNegative(Val: N1, DL, VT);
13987 return DAG.getNode(Opcode: ARMISD::CMOV, DL, VT, N1: N0N, N2: N1N, N3: CMov.getOperand(i: 2),
13988 N4: CMov.getOperand(i: 3));
13989}
13990
13991/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
13992///
13993static SDValue PerformSUBCombine(SDNode *N,
13994 TargetLowering::DAGCombinerInfo &DCI,
13995 const ARMSubtarget *Subtarget) {
13996 SDValue N0 = N->getOperand(Num: 0);
13997 SDValue N1 = N->getOperand(Num: 1);
13998
13999 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
14000 if (N1.getNode()->hasOneUse())
14001 if (SDValue Result = combineSelectAndUse(N, Slct: N1, OtherOp: N0, DCI))
14002 return Result;
14003
14004 if (SDValue R = PerformSubCSINCCombine(N, DAG&: DCI.DAG))
14005 return R;
14006
14007 if (SDValue Val = performNegCMovCombine(N, DAG&: DCI.DAG))
14008 return Val;
14009
14010 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(ResNo: 0).isVector())
14011 return SDValue();
14012
14013 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
14014 // so that we can readily pattern match more mve instructions which can use
14015 // a scalar operand.
14016 SDValue VDup = N->getOperand(Num: 1);
14017 if (VDup->getOpcode() != ARMISD::VDUP)
14018 return SDValue();
14019
14020 SDValue VMov = N->getOperand(Num: 0);
14021 if (VMov->getOpcode() == ISD::BITCAST)
14022 VMov = VMov->getOperand(Num: 0);
14023
14024 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(N: VMov))
14025 return SDValue();
14026
14027 SDLoc dl(N);
14028 SDValue Negate = DCI.DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
14029 N1: DCI.DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32),
14030 N2: VDup->getOperand(Num: 0));
14031 return DCI.DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT: N->getValueType(ResNo: 0), Operand: Negate);
14032}
14033
14034/// PerformVMULCombine
14035/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
14036/// special multiplier accumulator forwarding.
14037/// vmul d3, d0, d2
14038/// vmla d3, d1, d2
14039/// is faster than
14040/// vadd d3, d0, d1
14041/// vmul d3, d3, d2
14042// However, for (A + B) * (A + B),
14043// vadd d2, d0, d1
14044// vmul d3, d0, d2
14045// vmla d3, d1, d2
14046// is slower than
14047// vadd d2, d0, d1
14048// vmul d3, d2, d2
14049static SDValue PerformVMULCombine(SDNode *N,
14050 TargetLowering::DAGCombinerInfo &DCI,
14051 const ARMSubtarget *Subtarget) {
14052 if (!Subtarget->hasVMLxForwarding())
14053 return SDValue();
14054
14055 SelectionDAG &DAG = DCI.DAG;
14056 SDValue N0 = N->getOperand(Num: 0);
14057 SDValue N1 = N->getOperand(Num: 1);
14058 unsigned Opcode = N0.getOpcode();
14059 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14060 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
14061 Opcode = N1.getOpcode();
14062 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14063 Opcode != ISD::FADD && Opcode != ISD::FSUB)
14064 return SDValue();
14065 std::swap(a&: N0, b&: N1);
14066 }
14067
14068 if (N0 == N1)
14069 return SDValue();
14070
14071 EVT VT = N->getValueType(ResNo: 0);
14072 SDLoc DL(N);
14073 SDValue N00 = N0->getOperand(Num: 0);
14074 SDValue N01 = N0->getOperand(Num: 1);
14075 return DAG.getNode(Opcode, DL, VT,
14076 N1: DAG.getNode(Opcode: ISD::MUL, DL, VT, N1: N00, N2: N1),
14077 N2: DAG.getNode(Opcode: ISD::MUL, DL, VT, N1: N01, N2: N1));
14078}
14079
14080static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
14081 const ARMSubtarget *Subtarget) {
14082 EVT VT = N->getValueType(ResNo: 0);
14083 if (VT != MVT::v2i64)
14084 return SDValue();
14085
14086 SDValue N0 = N->getOperand(Num: 0);
14087 SDValue N1 = N->getOperand(Num: 1);
14088
14089 auto IsSignExt = [&](SDValue Op) {
14090 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
14091 return SDValue();
14092 EVT VT = cast<VTSDNode>(Val: Op->getOperand(Num: 1))->getVT();
14093 if (VT.getScalarSizeInBits() == 32)
14094 return Op->getOperand(Num: 0);
14095 return SDValue();
14096 };
14097 auto IsZeroExt = [&](SDValue Op) {
14098 // Zero extends are a little more awkward. At the point we are matching
14099 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
14100 // That might be before of after a bitcast depending on how the and is
14101 // placed. Because this has to look through bitcasts, it is currently only
14102 // supported on LE.
14103 if (!Subtarget->isLittle())
14104 return SDValue();
14105
14106 SDValue And = Op;
14107 if (And->getOpcode() == ISD::BITCAST)
14108 And = And->getOperand(Num: 0);
14109 if (And->getOpcode() != ISD::AND)
14110 return SDValue();
14111 SDValue Mask = And->getOperand(Num: 1);
14112 if (Mask->getOpcode() == ISD::BITCAST)
14113 Mask = Mask->getOperand(Num: 0);
14114
14115 if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
14116 Mask.getValueType() != MVT::v4i32)
14117 return SDValue();
14118 if (isAllOnesConstant(V: Mask->getOperand(Num: 0)) &&
14119 isNullConstant(V: Mask->getOperand(Num: 1)) &&
14120 isAllOnesConstant(V: Mask->getOperand(Num: 2)) &&
14121 isNullConstant(V: Mask->getOperand(Num: 3)))
14122 return And->getOperand(Num: 0);
14123 return SDValue();
14124 };
14125
14126 SDLoc dl(N);
14127 if (SDValue Op0 = IsSignExt(N0)) {
14128 if (SDValue Op1 = IsSignExt(N1)) {
14129 SDValue New0a = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: Op0);
14130 SDValue New1a = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: Op1);
14131 return DAG.getNode(Opcode: ARMISD::VMULLs, DL: dl, VT, N1: New0a, N2: New1a);
14132 }
14133 }
14134 if (SDValue Op0 = IsZeroExt(N0)) {
14135 if (SDValue Op1 = IsZeroExt(N1)) {
14136 SDValue New0a = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: Op0);
14137 SDValue New1a = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: Op1);
14138 return DAG.getNode(Opcode: ARMISD::VMULLu, DL: dl, VT, N1: New0a, N2: New1a);
14139 }
14140 }
14141
14142 return SDValue();
14143}
14144
14145static SDValue PerformMULCombine(SDNode *N,
14146 TargetLowering::DAGCombinerInfo &DCI,
14147 const ARMSubtarget *Subtarget) {
14148 SelectionDAG &DAG = DCI.DAG;
14149
14150 EVT VT = N->getValueType(ResNo: 0);
14151 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
14152 return PerformMVEVMULLCombine(N, DAG, Subtarget);
14153
14154 if (Subtarget->isThumb1Only())
14155 return SDValue();
14156
14157 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14158 return SDValue();
14159
14160 if (VT.is64BitVector() || VT.is128BitVector())
14161 return PerformVMULCombine(N, DCI, Subtarget);
14162 if (VT != MVT::i32)
14163 return SDValue();
14164
14165 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
14166 if (!C)
14167 return SDValue();
14168
14169 int64_t MulAmt = C->getSExtValue();
14170 unsigned ShiftAmt = llvm::countr_zero<uint64_t>(Val: MulAmt);
14171
14172 ShiftAmt = ShiftAmt & (32 - 1);
14173 SDValue V = N->getOperand(Num: 0);
14174 SDLoc DL(N);
14175
14176 SDValue Res;
14177 MulAmt >>= ShiftAmt;
14178
14179 if (MulAmt >= 0) {
14180 if (llvm::has_single_bit<uint32_t>(Value: MulAmt - 1)) {
14181 // (mul x, 2^N + 1) => (add (shl x, N), x)
14182 Res = DAG.getNode(Opcode: ISD::ADD, DL, VT,
14183 N1: V,
14184 N2: DAG.getNode(Opcode: ISD::SHL, DL, VT,
14185 N1: V,
14186 N2: DAG.getConstant(Val: Log2_32(Value: MulAmt - 1), DL,
14187 VT: MVT::i32)));
14188 } else if (llvm::has_single_bit<uint32_t>(Value: MulAmt + 1)) {
14189 // (mul x, 2^N - 1) => (sub (shl x, N), x)
14190 Res = DAG.getNode(Opcode: ISD::SUB, DL, VT,
14191 N1: DAG.getNode(Opcode: ISD::SHL, DL, VT,
14192 N1: V,
14193 N2: DAG.getConstant(Val: Log2_32(Value: MulAmt + 1), DL,
14194 VT: MVT::i32)),
14195 N2: V);
14196 } else
14197 return SDValue();
14198 } else {
14199 uint64_t MulAmtAbs = -MulAmt;
14200 if (llvm::has_single_bit<uint32_t>(Value: MulAmtAbs + 1)) {
14201 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
14202 Res = DAG.getNode(Opcode: ISD::SUB, DL, VT,
14203 N1: V,
14204 N2: DAG.getNode(Opcode: ISD::SHL, DL, VT,
14205 N1: V,
14206 N2: DAG.getConstant(Val: Log2_32(Value: MulAmtAbs + 1), DL,
14207 VT: MVT::i32)));
14208 } else if (llvm::has_single_bit<uint32_t>(Value: MulAmtAbs - 1)) {
14209 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
14210 Res = DAG.getNode(Opcode: ISD::ADD, DL, VT,
14211 N1: V,
14212 N2: DAG.getNode(Opcode: ISD::SHL, DL, VT,
14213 N1: V,
14214 N2: DAG.getConstant(Val: Log2_32(Value: MulAmtAbs - 1), DL,
14215 VT: MVT::i32)));
14216 Res = DAG.getNode(Opcode: ISD::SUB, DL, VT,
14217 N1: DAG.getConstant(Val: 0, DL, VT: MVT::i32), N2: Res);
14218 } else
14219 return SDValue();
14220 }
14221
14222 if (ShiftAmt != 0)
14223 Res = DAG.getNode(Opcode: ISD::SHL, DL, VT,
14224 N1: Res, N2: DAG.getConstant(Val: ShiftAmt, DL, VT: MVT::i32));
14225
14226 // Do not add new nodes to DAG combiner worklist.
14227 DCI.CombineTo(N, Res, AddTo: false);
14228 return SDValue();
14229}
14230
14231static SDValue CombineANDShift(SDNode *N,
14232 TargetLowering::DAGCombinerInfo &DCI,
14233 const ARMSubtarget *Subtarget) {
14234 // Allow DAGCombine to pattern-match before we touch the canonical form.
14235 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14236 return SDValue();
14237
14238 if (N->getValueType(ResNo: 0) != MVT::i32)
14239 return SDValue();
14240
14241 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
14242 if (!N1C)
14243 return SDValue();
14244
14245 uint32_t C1 = (uint32_t)N1C->getZExtValue();
14246 // Don't transform uxtb/uxth.
14247 if (C1 == 255 || C1 == 65535)
14248 return SDValue();
14249
14250 SDNode *N0 = N->getOperand(Num: 0).getNode();
14251 if (!N0->hasOneUse())
14252 return SDValue();
14253
14254 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
14255 return SDValue();
14256
14257 bool LeftShift = N0->getOpcode() == ISD::SHL;
14258
14259 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(Val: N0->getOperand(Num: 1));
14260 if (!N01C)
14261 return SDValue();
14262
14263 uint32_t C2 = (uint32_t)N01C->getZExtValue();
14264 if (!C2 || C2 >= 32)
14265 return SDValue();
14266
14267 // Clear irrelevant bits in the mask.
14268 if (LeftShift)
14269 C1 &= (-1U << C2);
14270 else
14271 C1 &= (-1U >> C2);
14272
14273 SelectionDAG &DAG = DCI.DAG;
14274 SDLoc DL(N);
14275
14276 // We have a pattern of the form "(and (shl x, c2) c1)" or
14277 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
14278 // transform to a pair of shifts, to save materializing c1.
14279
14280 // First pattern: right shift, then mask off leading bits.
14281 // FIXME: Use demanded bits?
14282 if (!LeftShift && isMask_32(Value: C1)) {
14283 uint32_t C3 = llvm::countl_zero(Val: C1);
14284 if (C2 < C3) {
14285 SDValue SHL = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
14286 N2: DAG.getConstant(Val: C3 - C2, DL, VT: MVT::i32));
14287 return DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: SHL,
14288 N2: DAG.getConstant(Val: C3, DL, VT: MVT::i32));
14289 }
14290 }
14291
14292 // First pattern, reversed: left shift, then mask off trailing bits.
14293 if (LeftShift && isMask_32(Value: ~C1)) {
14294 uint32_t C3 = llvm::countr_zero(Val: C1);
14295 if (C2 < C3) {
14296 SDValue SHL = DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
14297 N2: DAG.getConstant(Val: C3 - C2, DL, VT: MVT::i32));
14298 return DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: SHL,
14299 N2: DAG.getConstant(Val: C3, DL, VT: MVT::i32));
14300 }
14301 }
14302
14303 // Second pattern: left shift, then mask off leading bits.
14304 // FIXME: Use demanded bits?
14305 if (LeftShift && isShiftedMask_32(Value: C1)) {
14306 uint32_t Trailing = llvm::countr_zero(Val: C1);
14307 uint32_t C3 = llvm::countl_zero(Val: C1);
14308 if (Trailing == C2 && C2 + C3 < 32) {
14309 SDValue SHL = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
14310 N2: DAG.getConstant(Val: C2 + C3, DL, VT: MVT::i32));
14311 return DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: SHL,
14312 N2: DAG.getConstant(Val: C3, DL, VT: MVT::i32));
14313 }
14314 }
14315
14316 // Second pattern, reversed: right shift, then mask off trailing bits.
14317 // FIXME: Handle other patterns of known/demanded bits.
14318 if (!LeftShift && isShiftedMask_32(Value: C1)) {
14319 uint32_t Leading = llvm::countl_zero(Val: C1);
14320 uint32_t C3 = llvm::countr_zero(Val: C1);
14321 if (Leading == C2 && C2 + C3 < 32) {
14322 SDValue SHL = DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
14323 N2: DAG.getConstant(Val: C2 + C3, DL, VT: MVT::i32));
14324 return DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: SHL,
14325 N2: DAG.getConstant(Val: C3, DL, VT: MVT::i32));
14326 }
14327 }
14328
14329 // Transform "(and (shl x, c2) c1)" into "(shl (and x, c1>>c2), c2)"
14330 // if "c1 >> c2" is a cheaper immediate than "c1"
14331 if (LeftShift &&
14332 HasLowerConstantMaterializationCost(Val1: C1 >> C2, Val2: C1, Subtarget)) {
14333
14334 SDValue And = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
14335 N2: DAG.getConstant(Val: C1 >> C2, DL, VT: MVT::i32));
14336 return DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: And,
14337 N2: DAG.getConstant(Val: C2, DL, VT: MVT::i32));
14338 }
14339
14340 return SDValue();
14341}
14342
14343static SDValue PerformANDCombine(SDNode *N,
14344 TargetLowering::DAGCombinerInfo &DCI,
14345 const ARMSubtarget *Subtarget) {
14346 // Attempt to use immediate-form VBIC
14347 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Val: N->getOperand(Num: 1));
14348 SDLoc dl(N);
14349 EVT VT = N->getValueType(ResNo: 0);
14350 SelectionDAG &DAG = DCI.DAG;
14351
14352 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v2i1 ||
14353 VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)
14354 return SDValue();
14355
14356 APInt SplatBits, SplatUndef;
14357 unsigned SplatBitSize;
14358 bool HasAnyUndefs;
14359 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14360 BVN->isConstantSplat(SplatValue&: SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14361 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14362 SplatBitSize == 64) {
14363 EVT VbicVT;
14364 SDValue Val = isVMOVModifiedImm(SplatBits: (~SplatBits).getZExtValue(),
14365 SplatUndef: SplatUndef.getZExtValue(), SplatBitSize,
14366 DAG, dl, VT&: VbicVT, VectorVT: VT, type: OtherModImm);
14367 if (Val.getNode()) {
14368 SDValue Input =
14369 DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: VbicVT, Operand: N->getOperand(Num: 0));
14370 SDValue Vbic = DAG.getNode(Opcode: ARMISD::VBICIMM, DL: dl, VT: VbicVT, N1: Input, N2: Val);
14371 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Vbic);
14372 }
14373 }
14374 }
14375
14376 if (!Subtarget->isThumb1Only()) {
14377 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
14378 if (SDValue Result = combineSelectAndUseCommutative(N, AllOnes: true, DCI))
14379 return Result;
14380
14381 if (SDValue Result = PerformSHLSimplify(N, DCI, ST: Subtarget))
14382 return Result;
14383 }
14384
14385 if (Subtarget->isThumb1Only())
14386 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
14387 return Result;
14388
14389 return SDValue();
14390}
14391
14392// Try combining OR nodes to SMULWB, SMULWT.
14393static SDValue PerformORCombineToSMULWBT(SDNode *OR,
14394 TargetLowering::DAGCombinerInfo &DCI,
14395 const ARMSubtarget *Subtarget) {
14396 if (!Subtarget->hasV6Ops() ||
14397 (Subtarget->isThumb() &&
14398 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
14399 return SDValue();
14400
14401 SDValue SRL = OR->getOperand(Num: 0);
14402 SDValue SHL = OR->getOperand(Num: 1);
14403
14404 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
14405 SRL = OR->getOperand(Num: 1);
14406 SHL = OR->getOperand(Num: 0);
14407 }
14408 if (!isSRL16(Op: SRL) || !isSHL16(Op: SHL))
14409 return SDValue();
14410
14411 // The first operands to the shifts need to be the two results from the
14412 // same smul_lohi node.
14413 if ((SRL.getOperand(i: 0).getNode() != SHL.getOperand(i: 0).getNode()) ||
14414 SRL.getOperand(i: 0).getOpcode() != ISD::SMUL_LOHI)
14415 return SDValue();
14416
14417 SDNode *SMULLOHI = SRL.getOperand(i: 0).getNode();
14418 if (SRL.getOperand(i: 0) != SDValue(SMULLOHI, 0) ||
14419 SHL.getOperand(i: 0) != SDValue(SMULLOHI, 1))
14420 return SDValue();
14421
14422 // Now we have:
14423 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
14424 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
14425 // For SMUWB the 16-bit value will signed extended somehow.
14426 // For SMULWT only the SRA is required.
14427 // Check both sides of SMUL_LOHI
14428 SDValue OpS16 = SMULLOHI->getOperand(Num: 0);
14429 SDValue OpS32 = SMULLOHI->getOperand(Num: 1);
14430
14431 SelectionDAG &DAG = DCI.DAG;
14432 if (!isS16(Op: OpS16, DAG) && !isSRA16(Op: OpS16)) {
14433 OpS16 = OpS32;
14434 OpS32 = SMULLOHI->getOperand(Num: 0);
14435 }
14436
14437 SDLoc dl(OR);
14438 unsigned Opcode = 0;
14439 if (isS16(Op: OpS16, DAG))
14440 Opcode = ARMISD::SMULWB;
14441 else if (isSRA16(Op: OpS16)) {
14442 Opcode = ARMISD::SMULWT;
14443 OpS16 = OpS16->getOperand(Num: 0);
14444 }
14445 else
14446 return SDValue();
14447
14448 SDValue Res = DAG.getNode(Opcode, DL: dl, VT: MVT::i32, N1: OpS32, N2: OpS16);
14449 DAG.ReplaceAllUsesOfValueWith(From: SDValue(OR, 0), To: Res);
14450 return SDValue(OR, 0);
14451}
14452
14453static SDValue PerformORCombineToBFI(SDNode *N,
14454 TargetLowering::DAGCombinerInfo &DCI,
14455 const ARMSubtarget *Subtarget) {
14456 // BFI is only available on V6T2+
14457 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
14458 return SDValue();
14459
14460 EVT VT = N->getValueType(ResNo: 0);
14461 SDValue N0 = N->getOperand(Num: 0);
14462 SDValue N1 = N->getOperand(Num: 1);
14463 SelectionDAG &DAG = DCI.DAG;
14464 SDLoc DL(N);
14465 // 1) or (and A, mask), val => ARMbfi A, val, mask
14466 // iff (val & mask) == val
14467 //
14468 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14469 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
14470 // && mask == ~mask2
14471 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
14472 // && ~mask == mask2
14473 // (i.e., copy a bitfield value into another bitfield of the same width)
14474
14475 if (VT != MVT::i32)
14476 return SDValue();
14477
14478 SDValue N00 = N0.getOperand(i: 0);
14479
14480 // The value and the mask need to be constants so we can verify this is
14481 // actually a bitfield set. If the mask is 0xffff, we can do better
14482 // via a movt instruction, so don't use BFI in that case.
14483 SDValue MaskOp = N0.getOperand(i: 1);
14484 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Val&: MaskOp);
14485 if (!MaskC)
14486 return SDValue();
14487 unsigned Mask = MaskC->getZExtValue();
14488 if (Mask == 0xffff)
14489 return SDValue();
14490 SDValue Res;
14491 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
14492 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Val&: N1);
14493 if (N1C) {
14494 unsigned Val = N1C->getZExtValue();
14495 if ((Val & ~Mask) != Val)
14496 return SDValue();
14497
14498 if (ARM::isBitFieldInvertedMask(v: Mask)) {
14499 Val >>= llvm::countr_zero(Val: ~Mask);
14500
14501 Res = DAG.getNode(Opcode: ARMISD::BFI, DL, VT, N1: N00,
14502 N2: DAG.getConstant(Val, DL, VT: MVT::i32),
14503 N3: DAG.getConstant(Val: Mask, DL, VT: MVT::i32));
14504
14505 DCI.CombineTo(N, Res, AddTo: false);
14506 // Return value from the original node to inform the combiner than N is
14507 // now dead.
14508 return SDValue(N, 0);
14509 }
14510 } else if (N1.getOpcode() == ISD::AND) {
14511 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14512 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(Val: N1.getOperand(i: 1));
14513 if (!N11C)
14514 return SDValue();
14515 unsigned Mask2 = N11C->getZExtValue();
14516
14517 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
14518 // as is to match.
14519 if (ARM::isBitFieldInvertedMask(v: Mask) &&
14520 (Mask == ~Mask2)) {
14521 // The pack halfword instruction works better for masks that fit it,
14522 // so use that when it's available.
14523 if (Subtarget->hasDSP() &&
14524 (Mask == 0xffff || Mask == 0xffff0000))
14525 return SDValue();
14526 // 2a
14527 unsigned amt = llvm::countr_zero(Val: Mask2);
14528 Res = DAG.getNode(Opcode: ISD::SRL, DL, VT, N1: N1.getOperand(i: 0),
14529 N2: DAG.getConstant(Val: amt, DL, VT: MVT::i32));
14530 Res = DAG.getNode(Opcode: ARMISD::BFI, DL, VT, N1: N00, N2: Res,
14531 N3: DAG.getConstant(Val: Mask, DL, VT: MVT::i32));
14532 DCI.CombineTo(N, Res, AddTo: false);
14533 // Return value from the original node to inform the combiner than N is
14534 // now dead.
14535 return SDValue(N, 0);
14536 } else if (ARM::isBitFieldInvertedMask(v: ~Mask) &&
14537 (~Mask == Mask2)) {
14538 // The pack halfword instruction works better for masks that fit it,
14539 // so use that when it's available.
14540 if (Subtarget->hasDSP() &&
14541 (Mask2 == 0xffff || Mask2 == 0xffff0000))
14542 return SDValue();
14543 // 2b
14544 unsigned lsb = llvm::countr_zero(Val: Mask);
14545 Res = DAG.getNode(Opcode: ISD::SRL, DL, VT, N1: N00,
14546 N2: DAG.getConstant(Val: lsb, DL, VT: MVT::i32));
14547 Res = DAG.getNode(Opcode: ARMISD::BFI, DL, VT, N1: N1.getOperand(i: 0), N2: Res,
14548 N3: DAG.getConstant(Val: Mask2, DL, VT: MVT::i32));
14549 DCI.CombineTo(N, Res, AddTo: false);
14550 // Return value from the original node to inform the combiner than N is
14551 // now dead.
14552 return SDValue(N, 0);
14553 }
14554 }
14555
14556 if (DAG.MaskedValueIsZero(Op: N1, Mask: MaskC->getAPIntValue()) &&
14557 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(Val: N00.getOperand(i: 1)) &&
14558 ARM::isBitFieldInvertedMask(v: ~Mask)) {
14559 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
14560 // where lsb(mask) == #shamt and masked bits of B are known zero.
14561 SDValue ShAmt = N00.getOperand(i: 1);
14562 unsigned ShAmtC = ShAmt->getAsZExtVal();
14563 unsigned LSB = llvm::countr_zero(Val: Mask);
14564 if (ShAmtC != LSB)
14565 return SDValue();
14566
14567 Res = DAG.getNode(Opcode: ARMISD::BFI, DL, VT, N1, N2: N00.getOperand(i: 0),
14568 N3: DAG.getConstant(Val: ~Mask, DL, VT: MVT::i32));
14569
14570 DCI.CombineTo(N, Res, AddTo: false);
14571 // Return value from the original node to inform the combiner than N is
14572 // now dead.
14573 return SDValue(N, 0);
14574 }
14575
14576 return SDValue();
14577}
14578
14579static bool isValidMVECond(unsigned CC, bool IsFloat) {
14580 switch (CC) {
14581 case ARMCC::EQ:
14582 case ARMCC::NE:
14583 case ARMCC::LE:
14584 case ARMCC::GT:
14585 case ARMCC::GE:
14586 case ARMCC::LT:
14587 return true;
14588 case ARMCC::HS:
14589 case ARMCC::HI:
14590 return !IsFloat;
14591 default:
14592 return false;
14593 };
14594}
14595
14596static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
14597 if (N->getOpcode() == ARMISD::VCMP)
14598 return (ARMCC::CondCodes)N->getConstantOperandVal(Num: 2);
14599 else if (N->getOpcode() == ARMISD::VCMPZ)
14600 return (ARMCC::CondCodes)N->getConstantOperandVal(Num: 1);
14601 else
14602 llvm_unreachable("Not a VCMP/VCMPZ!");
14603}
14604
14605static bool CanInvertMVEVCMP(SDValue N) {
14606 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(CC: getVCMPCondCode(N));
14607 return isValidMVECond(CC, IsFloat: N->getOperand(Num: 0).getValueType().isFloatingPoint());
14608}
14609
14610static SDValue PerformORCombine_i1(SDNode *N, SelectionDAG &DAG,
14611 const ARMSubtarget *Subtarget) {
14612 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
14613 // together with predicates
14614 EVT VT = N->getValueType(ResNo: 0);
14615 SDLoc DL(N);
14616 SDValue N0 = N->getOperand(Num: 0);
14617 SDValue N1 = N->getOperand(Num: 1);
14618
14619 auto IsFreelyInvertable = [&](SDValue V) {
14620 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
14621 return CanInvertMVEVCMP(N: V);
14622 return false;
14623 };
14624
14625 // At least one operand must be freely invertable.
14626 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
14627 return SDValue();
14628
14629 SDValue NewN0 = DAG.getLogicalNOT(DL, Val: N0, VT);
14630 SDValue NewN1 = DAG.getLogicalNOT(DL, Val: N1, VT);
14631 SDValue And = DAG.getNode(Opcode: ISD::AND, DL, VT, N1: NewN0, N2: NewN1);
14632 return DAG.getLogicalNOT(DL, Val: And, VT);
14633}
14634
14635// Try to form a NEON shift-{right, left}-and-insert (VSRI/VSLI) from:
14636// (or (and X, splat (i32 C1)), (srl Y, splat (i32 C2))) -> VSRI X, Y, #C2
14637// (or (and X, splat (i32 C1)), (shl Y, splat (i32 C2))) -> VSLI X, Y, #C2
14638// where C1 is a mask that preserves the bits not written by the shift/insert,
14639// i.e. `C1 == (1 << C2) - 1`.
14640static SDValue PerformORCombineToShiftInsert(SelectionDAG &DAG, SDValue AndOp,
14641 SDValue ShiftOp, EVT VT,
14642 SDLoc dl) {
14643 // Match (and X, Mask)
14644 if (AndOp.getOpcode() != ISD::AND)
14645 return SDValue();
14646
14647 SDValue X = AndOp.getOperand(i: 0);
14648 SDValue Mask = AndOp.getOperand(i: 1);
14649
14650 ConstantSDNode *MaskC = isConstOrConstSplat(N: Mask, AllowUndefs: false, AllowTruncation: true);
14651 if (!MaskC)
14652 return SDValue();
14653 APInt MaskBits =
14654 MaskC->getAPIntValue().trunc(width: Mask.getScalarValueSizeInBits());
14655
14656 // Match shift (srl/shl Y, CntVec)
14657 int64_t Cnt = 0;
14658 bool IsShiftRight = false;
14659 SDValue Y;
14660
14661 if (ShiftOp.getOpcode() == ARMISD::VSHRuIMM) {
14662 IsShiftRight = true;
14663 Y = ShiftOp.getOperand(i: 0);
14664 Cnt = ShiftOp.getConstantOperandVal(i: 1);
14665 } else if (ShiftOp.getOpcode() == ARMISD::VSHLIMM) {
14666 Y = ShiftOp.getOperand(i: 0);
14667 Cnt = ShiftOp.getConstantOperandVal(i: 1);
14668 } else {
14669 return SDValue();
14670 }
14671
14672 unsigned ElemBits = VT.getScalarSizeInBits();
14673 APInt RequiredMask = IsShiftRight
14674 ? APInt::getHighBitsSet(numBits: ElemBits, hiBitsSet: (unsigned)Cnt)
14675 : APInt::getLowBitsSet(numBits: ElemBits, loBitsSet: (unsigned)Cnt);
14676 if (MaskBits != RequiredMask)
14677 return SDValue();
14678
14679 unsigned Opc = IsShiftRight ? ARMISD::VSRIIMM : ARMISD::VSLIIMM;
14680 return DAG.getNode(Opcode: Opc, DL: dl, VT, N1: X, N2: Y, N3: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
14681}
14682
14683/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
14684static SDValue PerformORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
14685 const ARMSubtarget *Subtarget) {
14686 // Attempt to use immediate-form VORR
14687 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Val: N->getOperand(Num: 1));
14688 SDLoc dl(N);
14689 EVT VT = N->getValueType(ResNo: 0);
14690 SelectionDAG &DAG = DCI.DAG;
14691
14692 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14693 return SDValue();
14694
14695 if (Subtarget->hasMVEIntegerOps() && (VT == MVT::v2i1 || VT == MVT::v4i1 ||
14696 VT == MVT::v8i1 || VT == MVT::v16i1))
14697 return PerformORCombine_i1(N, DAG, Subtarget);
14698
14699 APInt SplatBits, SplatUndef;
14700 unsigned SplatBitSize;
14701 bool HasAnyUndefs;
14702 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14703 BVN->isConstantSplat(SplatValue&: SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14704 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14705 SplatBitSize == 64) {
14706 EVT VorrVT;
14707 SDValue Val =
14708 isVMOVModifiedImm(SplatBits: SplatBits.getZExtValue(), SplatUndef: SplatUndef.getZExtValue(),
14709 SplatBitSize, DAG, dl, VT&: VorrVT, VectorVT: VT, type: OtherModImm);
14710 if (Val.getNode()) {
14711 SDValue Input =
14712 DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: VorrVT, Operand: N->getOperand(Num: 0));
14713 SDValue Vorr = DAG.getNode(Opcode: ARMISD::VORRIMM, DL: dl, VT: VorrVT, N1: Input, N2: Val);
14714 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Vorr);
14715 }
14716 }
14717 }
14718
14719 if (!Subtarget->isThumb1Only()) {
14720 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
14721 if (SDValue Result = combineSelectAndUseCommutative(N, AllOnes: false, DCI))
14722 return Result;
14723 if (SDValue Result = PerformORCombineToSMULWBT(OR: N, DCI, Subtarget))
14724 return Result;
14725 }
14726
14727 SDValue N0 = N->getOperand(Num: 0);
14728 SDValue N1 = N->getOperand(Num: 1);
14729
14730 // (or (and X, C1), (srl Y, C2)) -> VSRI X, Y, #C2
14731 // (or (and X, C1), (shl Y, C2)) -> VSLI X, Y, #C2
14732 if (VT.isVector() &&
14733 ((Subtarget->hasNEON() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) ||
14734 (Subtarget->hasMVEIntegerOps() &&
14735 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32)))) {
14736 if (SDValue ShiftInsert =
14737 PerformORCombineToShiftInsert(DAG, AndOp: N0, ShiftOp: N1, VT, dl))
14738 return ShiftInsert;
14739
14740 if (SDValue ShiftInsert =
14741 PerformORCombineToShiftInsert(DAG, AndOp: N1, ShiftOp: N0, VT, dl))
14742 return ShiftInsert;
14743 }
14744
14745 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
14746 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
14747 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14748
14749 // The code below optimizes (or (and X, Y), Z).
14750 // The AND operand needs to have a single user to make these optimizations
14751 // profitable.
14752 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
14753 return SDValue();
14754
14755 APInt SplatUndef;
14756 unsigned SplatBitSize;
14757 bool HasAnyUndefs;
14758
14759 APInt SplatBits0, SplatBits1;
14760 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(Val: N0->getOperand(Num: 1));
14761 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(Val: N1->getOperand(Num: 1));
14762 // Ensure that the second operand of both ands are constants
14763 if (BVN0 && BVN0->isConstantSplat(SplatValue&: SplatBits0, SplatUndef, SplatBitSize,
14764 HasAnyUndefs) && !HasAnyUndefs) {
14765 if (BVN1 && BVN1->isConstantSplat(SplatValue&: SplatBits1, SplatUndef, SplatBitSize,
14766 HasAnyUndefs) && !HasAnyUndefs) {
14767 // Ensure that the bit width of the constants are the same and that
14768 // the splat arguments are logical inverses as per the pattern we
14769 // are trying to simplify.
14770 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
14771 SplatBits0 == ~SplatBits1) {
14772 // Canonicalize the vector type to make instruction selection
14773 // simpler.
14774 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
14775 SDValue Result = DAG.getNode(Opcode: ARMISD::VBSP, DL: dl, VT: CanonicalVT,
14776 N1: N0->getOperand(Num: 1),
14777 N2: N0->getOperand(Num: 0),
14778 N3: N1->getOperand(Num: 0));
14779 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Result);
14780 }
14781 }
14782 }
14783 }
14784
14785 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
14786 // reasonable.
14787 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
14788 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
14789 return Res;
14790 }
14791
14792 if (SDValue Result = PerformSHLSimplify(N, DCI, ST: Subtarget))
14793 return Result;
14794
14795 return SDValue();
14796}
14797
14798static SDValue PerformXORCombine(SDNode *N,
14799 TargetLowering::DAGCombinerInfo &DCI,
14800 const ARMSubtarget *Subtarget) {
14801 EVT VT = N->getValueType(ResNo: 0);
14802 SelectionDAG &DAG = DCI.DAG;
14803
14804 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14805 return SDValue();
14806
14807 if (!Subtarget->isThumb1Only()) {
14808 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
14809 if (SDValue Result = combineSelectAndUseCommutative(N, AllOnes: false, DCI))
14810 return Result;
14811
14812 if (SDValue Result = PerformSHLSimplify(N, DCI, ST: Subtarget))
14813 return Result;
14814 }
14815
14816 if (Subtarget->hasMVEIntegerOps()) {
14817 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
14818 SDValue N0 = N->getOperand(Num: 0);
14819 SDValue N1 = N->getOperand(Num: 1);
14820 const TargetLowering *TLI = Subtarget->getTargetLowering();
14821 if (TLI->isConstTrueVal(N: N1) &&
14822 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
14823 if (CanInvertMVEVCMP(N: N0)) {
14824 SDLoc DL(N0);
14825 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(CC: getVCMPCondCode(N: N0));
14826
14827 SmallVector<SDValue, 4> Ops;
14828 Ops.push_back(Elt: N0->getOperand(Num: 0));
14829 if (N0->getOpcode() == ARMISD::VCMP)
14830 Ops.push_back(Elt: N0->getOperand(Num: 1));
14831 Ops.push_back(Elt: DAG.getConstant(Val: CC, DL, VT: MVT::i32));
14832 return DAG.getNode(Opcode: N0->getOpcode(), DL, VT: N0->getValueType(ResNo: 0), Ops);
14833 }
14834 }
14835 }
14836
14837 return SDValue();
14838}
14839
14840// ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
14841// and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
14842// their position in "to" (Rd).
14843static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
14844 assert(N->getOpcode() == ARMISD::BFI);
14845
14846 SDValue From = N->getOperand(Num: 1);
14847 ToMask = ~N->getConstantOperandAPInt(Num: 2);
14848 FromMask = APInt::getLowBitsSet(numBits: ToMask.getBitWidth(), loBitsSet: ToMask.popcount());
14849
14850 // If the Base came from a SHR #C, we can deduce that it is really testing bit
14851 // #C in the base of the SHR.
14852 if (From->getOpcode() == ISD::SRL &&
14853 isa<ConstantSDNode>(Val: From->getOperand(Num: 1))) {
14854 APInt Shift = From->getConstantOperandAPInt(Num: 1);
14855 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
14856 FromMask <<= Shift.getLimitedValue(Limit: 31);
14857 From = From->getOperand(Num: 0);
14858 }
14859
14860 return From;
14861}
14862
14863// If A and B contain one contiguous set of bits, does A | B == A . B?
14864//
14865// Neither A nor B must be zero.
14866static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
14867 unsigned LastActiveBitInA = A.countr_zero();
14868 unsigned FirstActiveBitInB = B.getBitWidth() - B.countl_zero() - 1;
14869 return LastActiveBitInA - 1 == FirstActiveBitInB;
14870}
14871
14872static SDValue FindBFIToCombineWith(SDNode *N) {
14873 // We have a BFI in N. Find a BFI it can combine with, if one exists.
14874 APInt ToMask, FromMask;
14875 SDValue From = ParseBFI(N, ToMask, FromMask);
14876 SDValue To = N->getOperand(Num: 0);
14877
14878 SDValue V = To;
14879 if (V.getOpcode() != ARMISD::BFI)
14880 return SDValue();
14881
14882 APInt NewToMask, NewFromMask;
14883 SDValue NewFrom = ParseBFI(N: V.getNode(), ToMask&: NewToMask, FromMask&: NewFromMask);
14884 if (NewFrom != From)
14885 return SDValue();
14886
14887 // Do the written bits conflict with any we've seen so far?
14888 if ((NewToMask & ToMask).getBoolValue())
14889 // Conflicting bits.
14890 return SDValue();
14891
14892 // Are the new bits contiguous when combined with the old bits?
14893 if (BitsProperlyConcatenate(A: ToMask, B: NewToMask) &&
14894 BitsProperlyConcatenate(A: FromMask, B: NewFromMask))
14895 return V;
14896 if (BitsProperlyConcatenate(A: NewToMask, B: ToMask) &&
14897 BitsProperlyConcatenate(A: NewFromMask, B: FromMask))
14898 return V;
14899
14900 return SDValue();
14901}
14902
14903static SDValue PerformBFICombine(SDNode *N, SelectionDAG &DAG) {
14904 SDValue N0 = N->getOperand(Num: 0);
14905 SDValue N1 = N->getOperand(Num: 1);
14906
14907 if (N1.getOpcode() == ISD::AND) {
14908 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
14909 // the bits being cleared by the AND are not demanded by the BFI.
14910 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(Val: N1.getOperand(i: 1));
14911 if (!N11C)
14912 return SDValue();
14913 unsigned InvMask = N->getConstantOperandVal(Num: 2);
14914 unsigned LSB = llvm::countr_zero(Val: ~InvMask);
14915 unsigned Width = llvm::bit_width<unsigned>(Value: ~InvMask) - LSB;
14916 assert(Width <
14917 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
14918 "undefined behavior");
14919 unsigned Mask = (1u << Width) - 1;
14920 unsigned Mask2 = N11C->getZExtValue();
14921 if ((Mask & (~Mask2)) == 0)
14922 return DAG.getNode(Opcode: ARMISD::BFI, DL: SDLoc(N), VT: N->getValueType(ResNo: 0),
14923 N1: N->getOperand(Num: 0), N2: N1.getOperand(i: 0), N3: N->getOperand(Num: 2));
14924 return SDValue();
14925 }
14926
14927 // Look for another BFI to combine with.
14928 if (SDValue CombineBFI = FindBFIToCombineWith(N)) {
14929 // We've found a BFI.
14930 APInt ToMask1, FromMask1;
14931 SDValue From1 = ParseBFI(N, ToMask&: ToMask1, FromMask&: FromMask1);
14932
14933 APInt ToMask2, FromMask2;
14934 SDValue From2 = ParseBFI(N: CombineBFI.getNode(), ToMask&: ToMask2, FromMask&: FromMask2);
14935 assert(From1 == From2);
14936 (void)From2;
14937
14938 // Create a new BFI, combining the two together.
14939 APInt NewFromMask = FromMask1 | FromMask2;
14940 APInt NewToMask = ToMask1 | ToMask2;
14941
14942 EVT VT = N->getValueType(ResNo: 0);
14943 SDLoc dl(N);
14944
14945 if (NewFromMask[0] == 0)
14946 From1 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: From1,
14947 N2: DAG.getConstant(Val: NewFromMask.countr_zero(), DL: dl, VT));
14948 return DAG.getNode(Opcode: ARMISD::BFI, DL: dl, VT, N1: CombineBFI.getOperand(i: 0), N2: From1,
14949 N3: DAG.getConstant(Val: ~NewToMask, DL: dl, VT));
14950 }
14951
14952 // Reassociate BFI(BFI (A, B, M1), C, M2) to BFI(BFI (A, C, M2), B, M1) so
14953 // that lower bit insertions are performed first, providing that M1 and M2
14954 // do no overlap. This can allow multiple BFI instructions to be combined
14955 // together by the other folds above.
14956 if (N->getOperand(Num: 0).getOpcode() == ARMISD::BFI) {
14957 APInt ToMask1 = ~N->getConstantOperandAPInt(Num: 2);
14958 APInt ToMask2 = ~N0.getConstantOperandAPInt(i: 2);
14959
14960 if (!N0.hasOneUse() || (ToMask1 & ToMask2) != 0 ||
14961 ToMask1.countl_zero() < ToMask2.countl_zero())
14962 return SDValue();
14963
14964 EVT VT = N->getValueType(ResNo: 0);
14965 SDLoc dl(N);
14966 SDValue BFI1 = DAG.getNode(Opcode: ARMISD::BFI, DL: dl, VT, N1: N0.getOperand(i: 0),
14967 N2: N->getOperand(Num: 1), N3: N->getOperand(Num: 2));
14968 return DAG.getNode(Opcode: ARMISD::BFI, DL: dl, VT, N1: BFI1, N2: N0.getOperand(i: 1),
14969 N3: N0.getOperand(i: 2));
14970 }
14971
14972 return SDValue();
14973}
14974
14975// Check that N is CMPZ(CSINC(0, 0, CC, X)),
14976// or CMPZ(CMOV(1, 0, CC, X))
14977// return X if valid.
14978static SDValue IsCMPZCSINC(SDNode *Cmp, ARMCC::CondCodes &CC) {
14979 if (Cmp->getOpcode() != ARMISD::CMPZ || !isNullConstant(V: Cmp->getOperand(Num: 1)))
14980 return SDValue();
14981 SDValue CSInc = Cmp->getOperand(Num: 0);
14982
14983 // Ignore any `And 1` nodes that may not yet have been removed. We are
14984 // looking for a value that produces 1/0, so these have no effect on the
14985 // code.
14986 while (CSInc.getOpcode() == ISD::AND &&
14987 isa<ConstantSDNode>(Val: CSInc.getOperand(i: 1)) &&
14988 CSInc.getConstantOperandVal(i: 1) == 1 && CSInc->hasOneUse())
14989 CSInc = CSInc.getOperand(i: 0);
14990
14991 if (CSInc.getOpcode() == ARMISD::CSINC &&
14992 isNullConstant(V: CSInc.getOperand(i: 0)) &&
14993 isNullConstant(V: CSInc.getOperand(i: 1)) && CSInc->hasOneUse()) {
14994 CC = (ARMCC::CondCodes)CSInc.getConstantOperandVal(i: 2);
14995 return CSInc.getOperand(i: 3);
14996 }
14997 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(V: CSInc.getOperand(i: 0)) &&
14998 isNullConstant(V: CSInc.getOperand(i: 1)) && CSInc->hasOneUse()) {
14999 CC = (ARMCC::CondCodes)CSInc.getConstantOperandVal(i: 2);
15000 return CSInc.getOperand(i: 3);
15001 }
15002 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(V: CSInc.getOperand(i: 1)) &&
15003 isNullConstant(V: CSInc.getOperand(i: 0)) && CSInc->hasOneUse()) {
15004 CC = ARMCC::getOppositeCondition(
15005 CC: (ARMCC::CondCodes)CSInc.getConstantOperandVal(i: 2));
15006 return CSInc.getOperand(i: 3);
15007 }
15008 return SDValue();
15009}
15010
15011static SDValue PerformCMPZCombine(SDNode *N, SelectionDAG &DAG) {
15012 // Given CMPZ(CSINC(C, 0, 0, EQ), 0), we can just use C directly. As in
15013 // t92: flags = ARMISD::CMPZ t74, 0
15014 // t93: i32 = ARMISD::CSINC 0, 0, 1, t92
15015 // t96: flags = ARMISD::CMPZ t93, 0
15016 // t114: i32 = ARMISD::CSINV 0, 0, 0, t96
15017 ARMCC::CondCodes Cond;
15018 if (SDValue C = IsCMPZCSINC(Cmp: N, CC&: Cond))
15019 if (Cond == ARMCC::EQ)
15020 return C;
15021 return SDValue();
15022}
15023
15024static SDValue PerformCSETCombine(SDNode *N, SelectionDAG &DAG) {
15025 // Fold away an unnecessary CMPZ/CSINC
15026 // CSXYZ A, B, C1 (CMPZ (CSINC 0, 0, C2, D), 0) ->
15027 // if C1==EQ -> CSXYZ A, B, C2, D
15028 // if C1==NE -> CSXYZ A, B, NOT(C2), D
15029 ARMCC::CondCodes Cond;
15030 if (SDValue C = IsCMPZCSINC(Cmp: N->getOperand(Num: 3).getNode(), CC&: Cond)) {
15031 if (N->getConstantOperandVal(Num: 2) == ARMCC::EQ)
15032 return DAG.getNode(Opcode: N->getOpcode(), DL: SDLoc(N), VT: MVT::i32, N1: N->getOperand(Num: 0),
15033 N2: N->getOperand(Num: 1),
15034 N3: DAG.getConstant(Val: Cond, DL: SDLoc(N), VT: MVT::i32), N4: C);
15035 if (N->getConstantOperandVal(Num: 2) == ARMCC::NE)
15036 return DAG.getNode(
15037 Opcode: N->getOpcode(), DL: SDLoc(N), VT: MVT::i32, N1: N->getOperand(Num: 0),
15038 N2: N->getOperand(Num: 1),
15039 N3: DAG.getConstant(Val: ARMCC::getOppositeCondition(CC: Cond), DL: SDLoc(N), VT: MVT::i32), N4: C);
15040 }
15041 return SDValue();
15042}
15043
15044/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
15045/// ARMISD::VMOVRRD.
15046static SDValue PerformVMOVRRDCombine(SDNode *N,
15047 TargetLowering::DAGCombinerInfo &DCI,
15048 const ARMSubtarget *Subtarget) {
15049 // vmovrrd(vmovdrr x, y) -> x,y
15050 SDValue InDouble = N->getOperand(Num: 0);
15051 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
15052 return DCI.CombineTo(N, Res0: InDouble.getOperand(i: 0), Res1: InDouble.getOperand(i: 1));
15053
15054 // vmovrrd(load f64) -> (load i32), (load i32)
15055 SDNode *InNode = InDouble.getNode();
15056 if (ISD::isNormalLoad(N: InNode) && InNode->hasOneUse() &&
15057 InNode->getValueType(ResNo: 0) == MVT::f64 &&
15058 InNode->getOperand(Num: 1).getOpcode() == ISD::FrameIndex &&
15059 !cast<LoadSDNode>(Val: InNode)->isVolatile()) {
15060 // TODO: Should this be done for non-FrameIndex operands?
15061 LoadSDNode *LD = cast<LoadSDNode>(Val: InNode);
15062
15063 SelectionDAG &DAG = DCI.DAG;
15064 SDLoc DL(LD);
15065 SDValue BasePtr = LD->getBasePtr();
15066 SDValue NewLD1 =
15067 DAG.getLoad(VT: MVT::i32, dl: DL, Chain: LD->getChain(), Ptr: BasePtr, PtrInfo: LD->getPointerInfo(),
15068 Alignment: LD->getAlign(), MMOFlags: LD->getMemOperand()->getFlags());
15069
15070 SDValue OffsetPtr = DAG.getNode(Opcode: ISD::ADD, DL, VT: MVT::i32, N1: BasePtr,
15071 N2: DAG.getConstant(Val: 4, DL, VT: MVT::i32));
15072
15073 SDValue NewLD2 = DAG.getLoad(VT: MVT::i32, dl: DL, Chain: LD->getChain(), Ptr: OffsetPtr,
15074 PtrInfo: LD->getPointerInfo().getWithOffset(O: 4),
15075 Alignment: commonAlignment(A: LD->getAlign(), Offset: 4),
15076 MMOFlags: LD->getMemOperand()->getFlags());
15077
15078 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 1), To: NewLD2.getValue(R: 1));
15079 if (DCI.DAG.getDataLayout().isBigEndian())
15080 std::swap (a&: NewLD1, b&: NewLD2);
15081 SDValue Result = DCI.CombineTo(N, Res0: NewLD1, Res1: NewLD2);
15082 return Result;
15083 }
15084
15085 // VMOVRRD(extract(..(build_vector(a, b, c, d)))) -> a,b or c,d
15086 // VMOVRRD(extract(insert_vector(insert_vector(.., a, l1), b, l2))) -> a,b
15087 if (InDouble.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15088 isa<ConstantSDNode>(Val: InDouble.getOperand(i: 1))) {
15089 SDValue BV = InDouble.getOperand(i: 0);
15090 // Look up through any nop bitcasts and vector_reg_casts. bitcasts may
15091 // change lane order under big endian.
15092 bool BVSwap = BV.getOpcode() == ISD::BITCAST;
15093 while (
15094 (BV.getOpcode() == ISD::BITCAST ||
15095 BV.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
15096 (BV.getValueType() == MVT::v2f64 || BV.getValueType() == MVT::v2i64)) {
15097 BVSwap = BV.getOpcode() == ISD::BITCAST;
15098 BV = BV.getOperand(i: 0);
15099 }
15100 if (BV.getValueType() != MVT::v4i32)
15101 return SDValue();
15102
15103 // Handle buildvectors, pulling out the correct lane depending on
15104 // endianness.
15105 unsigned Offset = InDouble.getConstantOperandVal(i: 1) == 1 ? 2 : 0;
15106 if (BV.getOpcode() == ISD::BUILD_VECTOR) {
15107 SDValue Op0 = BV.getOperand(i: Offset);
15108 SDValue Op1 = BV.getOperand(i: Offset + 1);
15109 if (!Subtarget->isLittle() && BVSwap)
15110 std::swap(a&: Op0, b&: Op1);
15111
15112 return DCI.DAG.getMergeValues(Ops: {Op0, Op1}, dl: SDLoc(N));
15113 }
15114
15115 // A chain of insert_vectors, grabbing the correct value of the chain of
15116 // inserts.
15117 SDValue Op0, Op1;
15118 while (BV.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15119 if (isa<ConstantSDNode>(Val: BV.getOperand(i: 2))) {
15120 if (BV.getConstantOperandVal(i: 2) == Offset && !Op0)
15121 Op0 = BV.getOperand(i: 1);
15122 if (BV.getConstantOperandVal(i: 2) == Offset + 1 && !Op1)
15123 Op1 = BV.getOperand(i: 1);
15124 }
15125 BV = BV.getOperand(i: 0);
15126 }
15127 if (!Subtarget->isLittle() && BVSwap)
15128 std::swap(a&: Op0, b&: Op1);
15129 if (Op0 && Op1)
15130 return DCI.DAG.getMergeValues(Ops: {Op0, Op1}, dl: SDLoc(N));
15131 }
15132
15133 return SDValue();
15134}
15135
15136/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
15137/// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
15138static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
15139 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
15140 SDValue Op0 = N->getOperand(Num: 0);
15141 SDValue Op1 = N->getOperand(Num: 1);
15142 if (Op0.getOpcode() == ISD::BITCAST)
15143 Op0 = Op0.getOperand(i: 0);
15144 if (Op1.getOpcode() == ISD::BITCAST)
15145 Op1 = Op1.getOperand(i: 0);
15146 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
15147 Op0.getNode() == Op1.getNode() &&
15148 Op0.getResNo() == 0 && Op1.getResNo() == 1)
15149 return DAG.getNode(Opcode: ISD::BITCAST, DL: SDLoc(N),
15150 VT: N->getValueType(ResNo: 0), Operand: Op0.getOperand(i: 0));
15151 return SDValue();
15152}
15153
15154static SDValue PerformVMOVhrCombine(SDNode *N,
15155 TargetLowering::DAGCombinerInfo &DCI) {
15156 SDValue Op0 = N->getOperand(Num: 0);
15157
15158 // VMOVhr (VMOVrh (X)) -> X
15159 if (Op0->getOpcode() == ARMISD::VMOVrh)
15160 return Op0->getOperand(Num: 0);
15161
15162 // FullFP16: half values are passed in S-registers, and we don't
15163 // need any of the bitcast and moves:
15164 //
15165 // t2: f32,ch1,gl1? = CopyFromReg ch, Register:f32 %0, gl?
15166 // t5: i32 = bitcast t2
15167 // t18: f16 = ARMISD::VMOVhr t5
15168 // =>
15169 // tN: f16,ch2,gl2? = CopyFromReg ch, Register::f32 %0, gl?
15170 if (Op0->getOpcode() == ISD::BITCAST) {
15171 SDValue Copy = Op0->getOperand(Num: 0);
15172 if (Copy.getValueType() == MVT::f32 &&
15173 Copy->getOpcode() == ISD::CopyFromReg) {
15174 bool HasGlue = Copy->getNumOperands() == 3;
15175 SDValue Ops[] = {Copy->getOperand(Num: 0), Copy->getOperand(Num: 1),
15176 HasGlue ? Copy->getOperand(Num: 2) : SDValue()};
15177 EVT OutTys[] = {N->getValueType(ResNo: 0), MVT::Other, MVT::Glue};
15178 SDValue NewCopy =
15179 DCI.DAG.getNode(Opcode: ISD::CopyFromReg, DL: SDLoc(N),
15180 VTList: DCI.DAG.getVTList(VTs: ArrayRef(OutTys, HasGlue ? 3 : 2)),
15181 Ops: ArrayRef(Ops, HasGlue ? 3 : 2));
15182
15183 // Update Users, Chains, and Potential Glue.
15184 DCI.DAG.ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: NewCopy.getValue(R: 0));
15185 DCI.DAG.ReplaceAllUsesOfValueWith(From: Copy.getValue(R: 1), To: NewCopy.getValue(R: 1));
15186 if (HasGlue)
15187 DCI.DAG.ReplaceAllUsesOfValueWith(From: Copy.getValue(R: 2),
15188 To: NewCopy.getValue(R: 2));
15189
15190 return NewCopy;
15191 }
15192 }
15193
15194 // fold (VMOVhr (load x)) -> (load (f16*)x)
15195 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Val&: Op0)) {
15196 if (LN0->hasOneUse() && LN0->isUnindexed() &&
15197 LN0->getMemoryVT() == MVT::i16) {
15198 SDValue Load =
15199 DCI.DAG.getLoad(VT: N->getValueType(ResNo: 0), dl: SDLoc(N), Chain: LN0->getChain(),
15200 Ptr: LN0->getBasePtr(), MMO: LN0->getMemOperand());
15201 DCI.DAG.ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: Load.getValue(R: 0));
15202 DCI.DAG.ReplaceAllUsesOfValueWith(From: Op0.getValue(R: 1), To: Load.getValue(R: 1));
15203 return Load;
15204 }
15205 }
15206
15207 // Only the bottom 16 bits of the source register are used.
15208 APInt DemandedMask = APInt::getLowBitsSet(numBits: 32, loBitsSet: 16);
15209 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15210 if (TLI.SimplifyDemandedBits(Op: Op0, DemandedBits: DemandedMask, DCI))
15211 return SDValue(N, 0);
15212
15213 return SDValue();
15214}
15215
15216static SDValue PerformVMOVrhCombine(SDNode *N, SelectionDAG &DAG) {
15217 SDValue N0 = N->getOperand(Num: 0);
15218 EVT VT = N->getValueType(ResNo: 0);
15219
15220 // fold (VMOVrh (fpconst x)) -> const x
15221 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val&: N0)) {
15222 APFloat V = C->getValueAPF();
15223 return DAG.getConstant(Val: V.bitcastToAPInt().getZExtValue(), DL: SDLoc(N), VT);
15224 }
15225
15226 // fold (VMOVrh (load x)) -> (zextload (i16*)x)
15227 if (ISD::isNormalLoad(N: N0.getNode()) && N0.hasOneUse()) {
15228 LoadSDNode *LN0 = cast<LoadSDNode>(Val&: N0);
15229
15230 SDValue Load =
15231 DAG.getExtLoad(ExtType: ISD::ZEXTLOAD, dl: SDLoc(N), VT, Chain: LN0->getChain(),
15232 Ptr: LN0->getBasePtr(), MemVT: MVT::i16, MMO: LN0->getMemOperand());
15233 DAG.ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: Load.getValue(R: 0));
15234 DAG.ReplaceAllUsesOfValueWith(From: N0.getValue(R: 1), To: Load.getValue(R: 1));
15235 return Load;
15236 }
15237
15238 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
15239 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15240 isa<ConstantSDNode>(Val: N0->getOperand(Num: 1)))
15241 return DAG.getNode(Opcode: ARMISD::VGETLANEu, DL: SDLoc(N), VT, N1: N0->getOperand(Num: 0),
15242 N2: N0->getOperand(Num: 1));
15243
15244 return SDValue();
15245}
15246
15247/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
15248/// are normal, non-volatile loads. If so, it is profitable to bitcast an
15249/// i64 vector to have f64 elements, since the value can then be loaded
15250/// directly into a VFP register.
15251static bool hasNormalLoadOperand(SDNode *N) {
15252 unsigned NumElts = N->getValueType(ResNo: 0).getVectorNumElements();
15253 for (unsigned i = 0; i < NumElts; ++i) {
15254 SDNode *Elt = N->getOperand(Num: i).getNode();
15255 if (ISD::isNormalLoad(N: Elt) && !cast<LoadSDNode>(Val: Elt)->isVolatile())
15256 return true;
15257 }
15258 return false;
15259}
15260
15261/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
15262/// ISD::BUILD_VECTOR.
15263static SDValue PerformBUILD_VECTORCombine(SDNode *N,
15264 TargetLowering::DAGCombinerInfo &DCI,
15265 const ARMSubtarget *Subtarget) {
15266 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
15267 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
15268 // into a pair of GPRs, which is fine when the value is used as a scalar,
15269 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
15270 SelectionDAG &DAG = DCI.DAG;
15271 if (N->getNumOperands() == 2)
15272 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
15273 return RV;
15274
15275 // Load i64 elements as f64 values so that type legalization does not split
15276 // them up into i32 values.
15277 EVT VT = N->getValueType(ResNo: 0);
15278 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
15279 return SDValue();
15280 SDLoc dl(N);
15281 SmallVector<SDValue, 8> Ops;
15282 unsigned NumElts = VT.getVectorNumElements();
15283 for (unsigned i = 0; i < NumElts; ++i) {
15284 SDValue V = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f64, Operand: N->getOperand(Num: i));
15285 Ops.push_back(Elt: V);
15286 // Make the DAGCombiner fold the bitcast.
15287 DCI.AddToWorklist(N: V.getNode());
15288 }
15289 EVT FloatVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::f64, NumElements: NumElts);
15290 SDValue BV = DAG.getBuildVector(VT: FloatVT, DL: dl, Ops);
15291 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: BV);
15292}
15293
15294/// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
15295static SDValue
15296PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15297 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
15298 // At that time, we may have inserted bitcasts from integer to float.
15299 // If these bitcasts have survived DAGCombine, change the lowering of this
15300 // BUILD_VECTOR in something more vector friendly, i.e., that does not
15301 // force to use floating point types.
15302
15303 // Make sure we can change the type of the vector.
15304 // This is possible iff:
15305 // 1. The vector is only used in a bitcast to a integer type. I.e.,
15306 // 1.1. Vector is used only once.
15307 // 1.2. Use is a bit convert to an integer type.
15308 // 2. The size of its operands are 32-bits (64-bits are not legal).
15309 EVT VT = N->getValueType(ResNo: 0);
15310 EVT EltVT = VT.getVectorElementType();
15311
15312 // Check 1.1. and 2.
15313 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
15314 return SDValue();
15315
15316 // By construction, the input type must be float.
15317 assert(EltVT == MVT::f32 && "Unexpected type!");
15318
15319 // Check 1.2.
15320 SDNode *Use = *N->user_begin();
15321 if (Use->getOpcode() != ISD::BITCAST ||
15322 Use->getValueType(ResNo: 0).isFloatingPoint())
15323 return SDValue();
15324
15325 // Check profitability.
15326 // Model is, if more than half of the relevant operands are bitcast from
15327 // i32, turn the build_vector into a sequence of insert_vector_elt.
15328 // Relevant operands are everything that is not statically
15329 // (i.e., at compile time) bitcasted.
15330 unsigned NumOfBitCastedElts = 0;
15331 unsigned NumElts = VT.getVectorNumElements();
15332 unsigned NumOfRelevantElts = NumElts;
15333 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
15334 SDValue Elt = N->getOperand(Num: Idx);
15335 if (Elt->getOpcode() == ISD::BITCAST) {
15336 // Assume only bit cast to i32 will go away.
15337 if (Elt->getOperand(Num: 0).getValueType() == MVT::i32)
15338 ++NumOfBitCastedElts;
15339 } else if (Elt.isUndef() || isa<ConstantSDNode>(Val: Elt))
15340 // Constants are statically casted, thus do not count them as
15341 // relevant operands.
15342 --NumOfRelevantElts;
15343 }
15344
15345 // Check if more than half of the elements require a non-free bitcast.
15346 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
15347 return SDValue();
15348
15349 SelectionDAG &DAG = DCI.DAG;
15350 // Create the new vector type.
15351 EVT VecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::i32, NumElements: NumElts);
15352 // Check if the type is legal.
15353 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15354 if (!TLI.isTypeLegal(VT: VecVT))
15355 return SDValue();
15356
15357 // Combine:
15358 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
15359 // => BITCAST INSERT_VECTOR_ELT
15360 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
15361 // (BITCAST EN), N.
15362 SDValue Vec = DAG.getUNDEF(VT: VecVT);
15363 SDLoc dl(N);
15364 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
15365 SDValue V = N->getOperand(Num: Idx);
15366 if (V.isUndef())
15367 continue;
15368 if (V.getOpcode() == ISD::BITCAST &&
15369 V->getOperand(Num: 0).getValueType() == MVT::i32)
15370 // Fold obvious case.
15371 V = V.getOperand(i: 0);
15372 else {
15373 V = DAG.getNode(Opcode: ISD::BITCAST, DL: SDLoc(V), VT: MVT::i32, Operand: V);
15374 // Make the DAGCombiner fold the bitcasts.
15375 DCI.AddToWorklist(N: V.getNode());
15376 }
15377 SDValue LaneIdx = DAG.getConstant(Val: Idx, DL: dl, VT: MVT::i32);
15378 Vec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: VecVT, N1: Vec, N2: V, N3: LaneIdx);
15379 }
15380 Vec = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Vec);
15381 // Make the DAGCombiner fold the bitcasts.
15382 DCI.AddToWorklist(N: Vec.getNode());
15383 return Vec;
15384}
15385
15386static SDValue
15387PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15388 EVT VT = N->getValueType(ResNo: 0);
15389 SDValue Op = N->getOperand(Num: 0);
15390 SDLoc dl(N);
15391
15392 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
15393 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
15394 // If the valuetypes are the same, we can remove the cast entirely.
15395 if (Op->getOperand(Num: 0).getValueType() == VT)
15396 return Op->getOperand(Num: 0);
15397 return DCI.DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT, Operand: Op->getOperand(Num: 0));
15398 }
15399
15400 // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
15401 // more VPNOT which might get folded as else predicates.
15402 if (Op.getValueType() == MVT::i32 && isBitwiseNot(V: Op)) {
15403 SDValue X =
15404 DCI.DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT, Operand: Op->getOperand(Num: 0));
15405 SDValue C = DCI.DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT,
15406 Operand: DCI.DAG.getConstant(Val: 65535, DL: dl, VT: MVT::i32));
15407 return DCI.DAG.getNode(Opcode: ISD::XOR, DL: dl, VT, N1: X, N2: C);
15408 }
15409
15410 // Only the bottom 16 bits of the source register are used.
15411 if (Op.getValueType() == MVT::i32) {
15412 APInt DemandedMask = APInt::getLowBitsSet(numBits: 32, loBitsSet: 16);
15413 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15414 if (TLI.SimplifyDemandedBits(Op, DemandedBits: DemandedMask, DCI))
15415 return SDValue(N, 0);
15416 }
15417 return SDValue();
15418}
15419
15420static SDValue PerformVECTOR_REG_CASTCombine(SDNode *N, SelectionDAG &DAG,
15421 const ARMSubtarget *ST) {
15422 EVT VT = N->getValueType(ResNo: 0);
15423 SDValue Op = N->getOperand(Num: 0);
15424 SDLoc dl(N);
15425
15426 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
15427 if (ST->isLittle())
15428 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Op);
15429
15430 // VT VECTOR_REG_CAST (VT Op) -> Op
15431 if (Op.getValueType() == VT)
15432 return Op;
15433 // VECTOR_REG_CAST undef -> undef
15434 if (Op.isUndef())
15435 return DAG.getUNDEF(VT);
15436
15437 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
15438 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
15439 // If the valuetypes are the same, we can remove the cast entirely.
15440 if (Op->getOperand(Num: 0).getValueType() == VT)
15441 return Op->getOperand(Num: 0);
15442 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Op->getOperand(Num: 0));
15443 }
15444
15445 return SDValue();
15446}
15447
15448static SDValue PerformVCMPCombine(SDNode *N, SelectionDAG &DAG,
15449 const ARMSubtarget *Subtarget) {
15450 if (!Subtarget->hasMVEIntegerOps())
15451 return SDValue();
15452
15453 EVT VT = N->getValueType(ResNo: 0);
15454 SDValue Op0 = N->getOperand(Num: 0);
15455 SDValue Op1 = N->getOperand(Num: 1);
15456 ARMCC::CondCodes Cond = (ARMCC::CondCodes)N->getConstantOperandVal(Num: 2);
15457 SDLoc dl(N);
15458
15459 // vcmp X, 0, cc -> vcmpz X, cc
15460 if (isZeroVector(N: Op1))
15461 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: Op0, N2: N->getOperand(Num: 2));
15462
15463 unsigned SwappedCond = getSwappedCondition(CC: Cond);
15464 if (isValidMVECond(CC: SwappedCond, IsFloat: VT.isFloatingPoint())) {
15465 // vcmp 0, X, cc -> vcmpz X, reversed(cc)
15466 if (isZeroVector(N: Op0))
15467 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: Op1,
15468 N2: DAG.getConstant(Val: SwappedCond, DL: dl, VT: MVT::i32));
15469 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
15470 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
15471 return DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT, N1: Op1, N2: Op0,
15472 N3: DAG.getConstant(Val: SwappedCond, DL: dl, VT: MVT::i32));
15473 }
15474
15475 return SDValue();
15476}
15477
15478/// PerformInsertEltCombine - Target-specific dag combine xforms for
15479/// ISD::INSERT_VECTOR_ELT.
15480static SDValue PerformInsertEltCombine(SDNode *N,
15481 TargetLowering::DAGCombinerInfo &DCI) {
15482 // Bitcast an i64 load inserted into a vector to f64.
15483 // Otherwise, the i64 value will be legalized to a pair of i32 values.
15484 EVT VT = N->getValueType(ResNo: 0);
15485 SDNode *Elt = N->getOperand(Num: 1).getNode();
15486 if (VT.getVectorElementType() != MVT::i64 ||
15487 !ISD::isNormalLoad(N: Elt) || cast<LoadSDNode>(Val: Elt)->isVolatile())
15488 return SDValue();
15489
15490 SelectionDAG &DAG = DCI.DAG;
15491 SDLoc dl(N);
15492 EVT FloatVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::f64,
15493 NumElements: VT.getVectorNumElements());
15494 SDValue Vec = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: FloatVT, Operand: N->getOperand(Num: 0));
15495 SDValue V = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f64, Operand: N->getOperand(Num: 1));
15496 // Make the DAGCombiner fold the bitcasts.
15497 DCI.AddToWorklist(N: Vec.getNode());
15498 DCI.AddToWorklist(N: V.getNode());
15499 SDValue InsElt = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: FloatVT,
15500 N1: Vec, N2: V, N3: N->getOperand(Num: 2));
15501 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: InsElt);
15502}
15503
15504// Convert a pair of extracts from the same base vector to a VMOVRRD. Either
15505// directly or bitcast to an integer if the original is a float vector.
15506// extract(x, n); extract(x, n+1) -> VMOVRRD(extract v2f64 x, n/2)
15507// bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD(extract x, n/2)
15508static SDValue
15509PerformExtractEltToVMOVRRD(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15510 EVT VT = N->getValueType(ResNo: 0);
15511 SDLoc dl(N);
15512
15513 if (!DCI.isAfterLegalizeDAG() || VT != MVT::i32 ||
15514 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT: MVT::f64))
15515 return SDValue();
15516
15517 SDValue Ext = SDValue(N, 0);
15518 if (Ext.getOpcode() == ISD::BITCAST &&
15519 Ext.getOperand(i: 0).getValueType() == MVT::f32)
15520 Ext = Ext.getOperand(i: 0);
15521 if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
15522 !isa<ConstantSDNode>(Val: Ext.getOperand(i: 1)) ||
15523 Ext.getConstantOperandVal(i: 1) % 2 != 0)
15524 return SDValue();
15525 if (Ext->hasOneUse() && (Ext->user_begin()->getOpcode() == ISD::SINT_TO_FP ||
15526 Ext->user_begin()->getOpcode() == ISD::UINT_TO_FP))
15527 return SDValue();
15528
15529 SDValue Op0 = Ext.getOperand(i: 0);
15530 EVT VecVT = Op0.getValueType();
15531 unsigned ResNo = Op0.getResNo();
15532 unsigned Lane = Ext.getConstantOperandVal(i: 1);
15533 if (VecVT.getVectorNumElements() != 4)
15534 return SDValue();
15535
15536 // Find another extract, of Lane + 1
15537 auto OtherIt = find_if(Range: Op0->users(), P: [&](SDNode *V) {
15538 return V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15539 isa<ConstantSDNode>(Val: V->getOperand(Num: 1)) &&
15540 V->getConstantOperandVal(Num: 1) == Lane + 1 &&
15541 V->getOperand(Num: 0).getResNo() == ResNo;
15542 });
15543 if (OtherIt == Op0->users().end())
15544 return SDValue();
15545
15546 // For float extracts, we need to be converting to a i32 for both vector
15547 // lanes.
15548 SDValue OtherExt(*OtherIt, 0);
15549 if (OtherExt.getValueType() != MVT::i32) {
15550 if (!OtherExt->hasOneUse() ||
15551 OtherExt->user_begin()->getOpcode() != ISD::BITCAST ||
15552 OtherExt->user_begin()->getValueType(ResNo: 0) != MVT::i32)
15553 return SDValue();
15554 OtherExt = SDValue(*OtherExt->user_begin(), 0);
15555 }
15556
15557 // Convert the type to a f64 and extract with a VMOVRRD.
15558 SDValue F64 = DCI.DAG.getNode(
15559 Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f64,
15560 N1: DCI.DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v2f64, Operand: Op0),
15561 N2: DCI.DAG.getConstant(Val: Ext.getConstantOperandVal(i: 1) / 2, DL: dl, VT: MVT::i32));
15562 SDValue VMOVRRD =
15563 DCI.DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl, ResultTys: {MVT::i32, MVT::i32}, Ops: F64);
15564
15565 DCI.CombineTo(N: OtherExt.getNode(), Res: SDValue(VMOVRRD.getNode(), 1));
15566 return VMOVRRD;
15567}
15568
15569static SDValue PerformExtractEltCombine(SDNode *N,
15570 TargetLowering::DAGCombinerInfo &DCI,
15571 const ARMSubtarget *ST) {
15572 SDValue Op0 = N->getOperand(Num: 0);
15573 EVT VT = N->getValueType(ResNo: 0);
15574 SDLoc dl(N);
15575
15576 // extract (vdup x) -> x
15577 if (Op0->getOpcode() == ARMISD::VDUP) {
15578 SDValue X = Op0->getOperand(Num: 0);
15579 if (VT == MVT::f16 && X.getValueType() == MVT::i32)
15580 return DCI.DAG.getNode(Opcode: ARMISD::VMOVhr, DL: dl, VT, Operand: X);
15581 if (VT == MVT::i32 && X.getValueType() == MVT::f16)
15582 return DCI.DAG.getNode(Opcode: ARMISD::VMOVrh, DL: dl, VT, Operand: X);
15583 if (VT == MVT::f32 && X.getValueType() == MVT::i32)
15584 return DCI.DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: X);
15585
15586 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
15587 X = X->getOperand(Num: 0);
15588 if (X.getValueType() == VT)
15589 return X;
15590 }
15591
15592 // extract ARM_BUILD_VECTOR -> x
15593 if (Op0->getOpcode() == ARMISD::BUILD_VECTOR &&
15594 isa<ConstantSDNode>(Val: N->getOperand(Num: 1)) &&
15595 N->getConstantOperandVal(Num: 1) < Op0.getNumOperands()) {
15596 return Op0.getOperand(i: N->getConstantOperandVal(Num: 1));
15597 }
15598
15599 // extract(bitcast(BUILD_VECTOR(VMOVDRR(a, b), ..))) -> a or b
15600 if (Op0.getValueType() == MVT::v4i32 &&
15601 isa<ConstantSDNode>(Val: N->getOperand(Num: 1)) &&
15602 Op0.getOpcode() == ISD::BITCAST &&
15603 Op0.getOperand(i: 0).getOpcode() == ISD::BUILD_VECTOR &&
15604 Op0.getOperand(i: 0).getValueType() == MVT::v2f64) {
15605 SDValue BV = Op0.getOperand(i: 0);
15606 unsigned Offset = N->getConstantOperandVal(Num: 1);
15607 SDValue MOV = BV.getOperand(i: Offset < 2 ? 0 : 1);
15608 if (MOV.getOpcode() == ARMISD::VMOVDRR)
15609 return MOV.getOperand(i: ST->isLittle() ? Offset % 2 : 1 - Offset % 2);
15610 }
15611
15612 // extract x, n; extract x, n+1 -> VMOVRRD x
15613 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
15614 return R;
15615
15616 // extract (MVETrunc(x)) -> extract x
15617 if (Op0->getOpcode() == ARMISD::MVETRUNC) {
15618 unsigned Idx = N->getConstantOperandVal(Num: 1);
15619 unsigned Vec =
15620 Idx / Op0->getOperand(Num: 0).getValueType().getVectorNumElements();
15621 unsigned SubIdx =
15622 Idx % Op0->getOperand(Num: 0).getValueType().getVectorNumElements();
15623 return DCI.DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT, N1: Op0.getOperand(i: Vec),
15624 N2: DCI.DAG.getConstant(Val: SubIdx, DL: dl, VT: MVT::i32));
15625 }
15626
15627 return SDValue();
15628}
15629
15630static SDValue PerformSignExtendInregCombine(SDNode *N, SelectionDAG &DAG) {
15631 SDValue Op = N->getOperand(Num: 0);
15632 EVT VT = N->getValueType(ResNo: 0);
15633
15634 // sext_inreg(VGETLANEu) -> VGETLANEs
15635 if (Op.getOpcode() == ARMISD::VGETLANEu &&
15636 cast<VTSDNode>(Val: N->getOperand(Num: 1))->getVT() ==
15637 Op.getOperand(i: 0).getValueType().getScalarType())
15638 return DAG.getNode(Opcode: ARMISD::VGETLANEs, DL: SDLoc(N), VT, N1: Op.getOperand(i: 0),
15639 N2: Op.getOperand(i: 1));
15640
15641 return SDValue();
15642}
15643
15644static SDValue
15645PerformInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15646 SDValue Vec = N->getOperand(Num: 0);
15647 SDValue SubVec = N->getOperand(Num: 1);
15648 uint64_t IdxVal = N->getConstantOperandVal(Num: 2);
15649 EVT VecVT = Vec.getValueType();
15650 EVT SubVT = SubVec.getValueType();
15651
15652 // Only do this for legal fixed vector types.
15653 if (!VecVT.isFixedLengthVector() ||
15654 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT: VecVT) ||
15655 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT: SubVT))
15656 return SDValue();
15657
15658 // Ignore widening patterns.
15659 if (IdxVal == 0 && Vec.isUndef())
15660 return SDValue();
15661
15662 // Subvector must be half the width and an "aligned" insertion.
15663 unsigned NumSubElts = SubVT.getVectorNumElements();
15664 if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
15665 (IdxVal != 0 && IdxVal != NumSubElts))
15666 return SDValue();
15667
15668 // Fold insert_subvector -> concat_vectors
15669 // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
15670 // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
15671 SDLoc DL(N);
15672 SDValue Lo, Hi;
15673 if (IdxVal == 0) {
15674 Lo = SubVec;
15675 Hi = DCI.DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: SubVT, N1: Vec,
15676 N2: DCI.DAG.getVectorIdxConstant(Val: NumSubElts, DL));
15677 } else {
15678 Lo = DCI.DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: SubVT, N1: Vec,
15679 N2: DCI.DAG.getVectorIdxConstant(Val: 0, DL));
15680 Hi = SubVec;
15681 }
15682 return DCI.DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: VecVT, N1: Lo, N2: Hi);
15683}
15684
15685// shuffle(MVETrunc(x, y)) -> VMOVN(x, y)
15686static SDValue PerformShuffleVMOVNCombine(ShuffleVectorSDNode *N,
15687 SelectionDAG &DAG) {
15688 SDValue Trunc = N->getOperand(Num: 0);
15689 EVT VT = Trunc.getValueType();
15690 if (Trunc.getOpcode() != ARMISD::MVETRUNC || !N->getOperand(Num: 1).isUndef())
15691 return SDValue();
15692
15693 SDLoc DL(Trunc);
15694 if (isVMOVNTruncMask(M: N->getMask(), ToVT: VT, rev: false))
15695 return DAG.getNode(
15696 Opcode: ARMISD::VMOVN, DL, VT,
15697 N1: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: Trunc.getOperand(i: 0)),
15698 N2: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: Trunc.getOperand(i: 1)),
15699 N3: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
15700 else if (isVMOVNTruncMask(M: N->getMask(), ToVT: VT, rev: true))
15701 return DAG.getNode(
15702 Opcode: ARMISD::VMOVN, DL, VT,
15703 N1: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: Trunc.getOperand(i: 1)),
15704 N2: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: Trunc.getOperand(i: 0)),
15705 N3: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
15706 return SDValue();
15707}
15708
15709/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
15710/// ISD::VECTOR_SHUFFLE.
15711static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
15712 if (SDValue R = PerformShuffleVMOVNCombine(N: cast<ShuffleVectorSDNode>(Val: N), DAG))
15713 return R;
15714
15715 // The LLVM shufflevector instruction does not require the shuffle mask
15716 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
15717 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
15718 // operands do not match the mask length, they are extended by concatenating
15719 // them with undef vectors. That is probably the right thing for other
15720 // targets, but for NEON it is better to concatenate two double-register
15721 // size vector operands into a single quad-register size vector. Do that
15722 // transformation here:
15723 // shuffle(concat(v1, undef), concat(v2, undef)) ->
15724 // shuffle(concat(v1, v2), undef)
15725 SDValue Op0 = N->getOperand(Num: 0);
15726 SDValue Op1 = N->getOperand(Num: 1);
15727 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
15728 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
15729 Op0.getNumOperands() != 2 ||
15730 Op1.getNumOperands() != 2)
15731 return SDValue();
15732 SDValue Concat0Op1 = Op0.getOperand(i: 1);
15733 SDValue Concat1Op1 = Op1.getOperand(i: 1);
15734 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
15735 return SDValue();
15736 // Skip the transformation if any of the types are illegal.
15737 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15738 EVT VT = N->getValueType(ResNo: 0);
15739 if (!TLI.isTypeLegal(VT) ||
15740 !TLI.isTypeLegal(VT: Concat0Op1.getValueType()) ||
15741 !TLI.isTypeLegal(VT: Concat1Op1.getValueType()))
15742 return SDValue();
15743
15744 SDValue NewConcat = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: SDLoc(N), VT,
15745 N1: Op0.getOperand(i: 0), N2: Op1.getOperand(i: 0));
15746 // Translate the shuffle mask.
15747 SmallVector<int, 16> NewMask;
15748 unsigned NumElts = VT.getVectorNumElements();
15749 unsigned HalfElts = NumElts/2;
15750 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Val: N);
15751 for (unsigned n = 0; n < NumElts; ++n) {
15752 int MaskElt = SVN->getMaskElt(Idx: n);
15753 int NewElt = -1;
15754 if (MaskElt < (int)HalfElts)
15755 NewElt = MaskElt;
15756 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
15757 NewElt = HalfElts + MaskElt - NumElts;
15758 NewMask.push_back(Elt: NewElt);
15759 }
15760 return DAG.getVectorShuffle(VT, dl: SDLoc(N), N1: NewConcat,
15761 N2: DAG.getUNDEF(VT), Mask: NewMask);
15762}
15763
15764/// Load/store instruction that can be merged with a base address
15765/// update
15766struct BaseUpdateTarget {
15767 SDNode *N;
15768 bool isIntrinsic;
15769 bool isStore;
15770 unsigned AddrOpIdx;
15771};
15772
15773struct BaseUpdateUser {
15774 /// Instruction that updates a pointer
15775 SDNode *N;
15776 /// Pointer increment operand
15777 SDValue Inc;
15778 /// Pointer increment value if it is a constant, or 0 otherwise
15779 unsigned ConstInc;
15780};
15781
15782static bool isValidBaseUpdate(SDNode *N, SDNode *User) {
15783 // Check that the add is independent of the load/store.
15784 // Otherwise, folding it would create a cycle. Search through Addr
15785 // as well, since the User may not be a direct user of Addr and
15786 // only share a base pointer.
15787 SmallPtrSet<const SDNode *, 32> Visited;
15788 SmallVector<const SDNode *, 16> Worklist;
15789 Worklist.push_back(Elt: N);
15790 Worklist.push_back(Elt: User);
15791 const unsigned MaxSteps = 1024;
15792 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
15793 SDNode::hasPredecessorHelper(N: User, Visited, Worklist, MaxSteps))
15794 return false;
15795 return true;
15796}
15797
15798static bool TryCombineBaseUpdate(struct BaseUpdateTarget &Target,
15799 struct BaseUpdateUser &User,
15800 bool SimpleConstIncOnly,
15801 TargetLowering::DAGCombinerInfo &DCI) {
15802 SelectionDAG &DAG = DCI.DAG;
15803 SDNode *N = Target.N;
15804 MemSDNode *MemN = cast<MemSDNode>(Val: N);
15805 SDLoc dl(N);
15806
15807 // Find the new opcode for the updating load/store.
15808 bool isLoadOp = true;
15809 bool isLaneOp = false;
15810 // Workaround for vst1x and vld1x intrinsics which do not have alignment
15811 // as an operand.
15812 bool hasAlignment = true;
15813 unsigned NewOpc = 0;
15814 unsigned NumVecs = 0;
15815 if (Target.isIntrinsic) {
15816 unsigned IntNo = N->getConstantOperandVal(Num: 1);
15817 switch (IntNo) {
15818 default:
15819 llvm_unreachable("unexpected intrinsic for Neon base update");
15820 case Intrinsic::arm_neon_vld1:
15821 NewOpc = ARMISD::VLD1_UPD;
15822 NumVecs = 1;
15823 break;
15824 case Intrinsic::arm_neon_vld2:
15825 NewOpc = ARMISD::VLD2_UPD;
15826 NumVecs = 2;
15827 break;
15828 case Intrinsic::arm_neon_vld3:
15829 NewOpc = ARMISD::VLD3_UPD;
15830 NumVecs = 3;
15831 break;
15832 case Intrinsic::arm_neon_vld4:
15833 NewOpc = ARMISD::VLD4_UPD;
15834 NumVecs = 4;
15835 break;
15836 case Intrinsic::arm_neon_vld1x2:
15837 NewOpc = ARMISD::VLD1x2_UPD;
15838 NumVecs = 2;
15839 hasAlignment = false;
15840 break;
15841 case Intrinsic::arm_neon_vld1x3:
15842 NewOpc = ARMISD::VLD1x3_UPD;
15843 NumVecs = 3;
15844 hasAlignment = false;
15845 break;
15846 case Intrinsic::arm_neon_vld1x4:
15847 NewOpc = ARMISD::VLD1x4_UPD;
15848 NumVecs = 4;
15849 hasAlignment = false;
15850 break;
15851 case Intrinsic::arm_neon_vld2dup:
15852 NewOpc = ARMISD::VLD2DUP_UPD;
15853 NumVecs = 2;
15854 break;
15855 case Intrinsic::arm_neon_vld3dup:
15856 NewOpc = ARMISD::VLD3DUP_UPD;
15857 NumVecs = 3;
15858 break;
15859 case Intrinsic::arm_neon_vld4dup:
15860 NewOpc = ARMISD::VLD4DUP_UPD;
15861 NumVecs = 4;
15862 break;
15863 case Intrinsic::arm_neon_vld2lane:
15864 NewOpc = ARMISD::VLD2LN_UPD;
15865 NumVecs = 2;
15866 isLaneOp = true;
15867 break;
15868 case Intrinsic::arm_neon_vld3lane:
15869 NewOpc = ARMISD::VLD3LN_UPD;
15870 NumVecs = 3;
15871 isLaneOp = true;
15872 break;
15873 case Intrinsic::arm_neon_vld4lane:
15874 NewOpc = ARMISD::VLD4LN_UPD;
15875 NumVecs = 4;
15876 isLaneOp = true;
15877 break;
15878 case Intrinsic::arm_neon_vst1:
15879 NewOpc = ARMISD::VST1_UPD;
15880 NumVecs = 1;
15881 isLoadOp = false;
15882 break;
15883 case Intrinsic::arm_neon_vst2:
15884 NewOpc = ARMISD::VST2_UPD;
15885 NumVecs = 2;
15886 isLoadOp = false;
15887 break;
15888 case Intrinsic::arm_neon_vst3:
15889 NewOpc = ARMISD::VST3_UPD;
15890 NumVecs = 3;
15891 isLoadOp = false;
15892 break;
15893 case Intrinsic::arm_neon_vst4:
15894 NewOpc = ARMISD::VST4_UPD;
15895 NumVecs = 4;
15896 isLoadOp = false;
15897 break;
15898 case Intrinsic::arm_neon_vst2lane:
15899 NewOpc = ARMISD::VST2LN_UPD;
15900 NumVecs = 2;
15901 isLoadOp = false;
15902 isLaneOp = true;
15903 break;
15904 case Intrinsic::arm_neon_vst3lane:
15905 NewOpc = ARMISD::VST3LN_UPD;
15906 NumVecs = 3;
15907 isLoadOp = false;
15908 isLaneOp = true;
15909 break;
15910 case Intrinsic::arm_neon_vst4lane:
15911 NewOpc = ARMISD::VST4LN_UPD;
15912 NumVecs = 4;
15913 isLoadOp = false;
15914 isLaneOp = true;
15915 break;
15916 case Intrinsic::arm_neon_vst1x2:
15917 NewOpc = ARMISD::VST1x2_UPD;
15918 NumVecs = 2;
15919 isLoadOp = false;
15920 hasAlignment = false;
15921 break;
15922 case Intrinsic::arm_neon_vst1x3:
15923 NewOpc = ARMISD::VST1x3_UPD;
15924 NumVecs = 3;
15925 isLoadOp = false;
15926 hasAlignment = false;
15927 break;
15928 case Intrinsic::arm_neon_vst1x4:
15929 NewOpc = ARMISD::VST1x4_UPD;
15930 NumVecs = 4;
15931 isLoadOp = false;
15932 hasAlignment = false;
15933 break;
15934 }
15935 } else {
15936 isLaneOp = true;
15937 switch (N->getOpcode()) {
15938 default:
15939 llvm_unreachable("unexpected opcode for Neon base update");
15940 case ARMISD::VLD1DUP:
15941 NewOpc = ARMISD::VLD1DUP_UPD;
15942 NumVecs = 1;
15943 break;
15944 case ARMISD::VLD2DUP:
15945 NewOpc = ARMISD::VLD2DUP_UPD;
15946 NumVecs = 2;
15947 break;
15948 case ARMISD::VLD3DUP:
15949 NewOpc = ARMISD::VLD3DUP_UPD;
15950 NumVecs = 3;
15951 break;
15952 case ARMISD::VLD4DUP:
15953 NewOpc = ARMISD::VLD4DUP_UPD;
15954 NumVecs = 4;
15955 break;
15956 case ISD::LOAD:
15957 NewOpc = ARMISD::VLD1_UPD;
15958 NumVecs = 1;
15959 isLaneOp = false;
15960 break;
15961 case ISD::STORE:
15962 NewOpc = ARMISD::VST1_UPD;
15963 NumVecs = 1;
15964 isLaneOp = false;
15965 isLoadOp = false;
15966 break;
15967 }
15968 }
15969
15970 // Find the size of memory referenced by the load/store.
15971 EVT VecTy;
15972 if (isLoadOp) {
15973 VecTy = N->getValueType(ResNo: 0);
15974 } else if (Target.isIntrinsic) {
15975 VecTy = N->getOperand(Num: Target.AddrOpIdx + 1).getValueType();
15976 } else {
15977 assert(Target.isStore &&
15978 "Node has to be a load, a store, or an intrinsic!");
15979 VecTy = N->getOperand(Num: 1).getValueType();
15980 }
15981
15982 bool isVLDDUPOp =
15983 NewOpc == ARMISD::VLD1DUP_UPD || NewOpc == ARMISD::VLD2DUP_UPD ||
15984 NewOpc == ARMISD::VLD3DUP_UPD || NewOpc == ARMISD::VLD4DUP_UPD;
15985
15986 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
15987 if (isLaneOp || isVLDDUPOp)
15988 NumBytes /= VecTy.getVectorNumElements();
15989
15990 if (NumBytes >= 3 * 16 && User.ConstInc != NumBytes) {
15991 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
15992 // separate instructions that make it harder to use a non-constant update.
15993 return false;
15994 }
15995
15996 if (SimpleConstIncOnly && User.ConstInc != NumBytes)
15997 return false;
15998
15999 if (!isValidBaseUpdate(N, User: User.N))
16000 return false;
16001
16002 // OK, we found an ADD we can fold into the base update.
16003 // Now, create a _UPD node, taking care of not breaking alignment.
16004
16005 EVT AlignedVecTy = VecTy;
16006 Align Alignment = MemN->getAlign();
16007
16008 // If this is a less-than-standard-aligned load/store, change the type to
16009 // match the standard alignment.
16010 // The alignment is overlooked when selecting _UPD variants; and it's
16011 // easier to introduce bitcasts here than fix that.
16012 // There are 3 ways to get to this base-update combine:
16013 // - intrinsics: they are assumed to be properly aligned (to the standard
16014 // alignment of the memory type), so we don't need to do anything.
16015 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
16016 // intrinsics, so, likewise, there's nothing to do.
16017 // - generic load/store instructions: the alignment is specified as an
16018 // explicit operand, rather than implicitly as the standard alignment
16019 // of the memory type (like the intrinsics). We need to change the
16020 // memory type to match the explicit alignment. That way, we don't
16021 // generate non-standard-aligned ARMISD::VLDx nodes.
16022 if (isa<LSBaseSDNode>(Val: N)) {
16023 if (Alignment.value() < VecTy.getScalarSizeInBits() / 8) {
16024 MVT EltTy = MVT::getIntegerVT(BitWidth: Alignment.value() * 8);
16025 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
16026 assert(!isLaneOp && "Unexpected generic load/store lane.");
16027 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
16028 AlignedVecTy = MVT::getVectorVT(VT: EltTy, NumElements: NumElts);
16029 }
16030 // Don't set an explicit alignment on regular load/stores that we want
16031 // to transform to VLD/VST 1_UPD nodes.
16032 // This matches the behavior of regular load/stores, which only get an
16033 // explicit alignment if the MMO alignment is larger than the standard
16034 // alignment of the memory type.
16035 // Intrinsics, however, always get an explicit alignment, set to the
16036 // alignment of the MMO.
16037 Alignment = Align(1);
16038 }
16039
16040 // Create the new updating load/store node.
16041 // First, create an SDVTList for the new updating node's results.
16042 EVT Tys[6];
16043 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16044 unsigned n;
16045 for (n = 0; n < NumResultVecs; ++n)
16046 Tys[n] = AlignedVecTy;
16047 Tys[n++] = MVT::i32;
16048 Tys[n] = MVT::Other;
16049 SDVTList SDTys = DAG.getVTList(VTs: ArrayRef(Tys, NumResultVecs + 2));
16050
16051 // Then, gather the new node's operands.
16052 SmallVector<SDValue, 8> Ops;
16053 Ops.push_back(Elt: N->getOperand(Num: 0)); // incoming chain
16054 Ops.push_back(Elt: N->getOperand(Num: Target.AddrOpIdx));
16055 Ops.push_back(Elt: User.Inc);
16056
16057 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(Val: N)) {
16058 // Try to match the intrinsic's signature
16059 Ops.push_back(Elt: StN->getValue());
16060 } else {
16061 // Loads (and of course intrinsics) match the intrinsics' signature,
16062 // so just add all but the alignment operand.
16063 unsigned LastOperand =
16064 hasAlignment ? N->getNumOperands() - 1 : N->getNumOperands();
16065 for (unsigned i = Target.AddrOpIdx + 1; i < LastOperand; ++i)
16066 Ops.push_back(Elt: N->getOperand(Num: i));
16067 }
16068
16069 // For all node types, the alignment operand is always the last one.
16070 Ops.push_back(Elt: DAG.getConstant(Val: Alignment.value(), DL: dl, VT: MVT::i32));
16071
16072 // If this is a non-standard-aligned STORE, the penultimate operand is the
16073 // stored value. Bitcast it to the aligned type.
16074 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
16075 SDValue &StVal = Ops[Ops.size() - 2];
16076 StVal = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: AlignedVecTy, Operand: StVal);
16077 }
16078
16079 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
16080 SDValue UpdN = DAG.getMemIntrinsicNode(Opcode: NewOpc, dl, VTList: SDTys, Ops, MemVT: LoadVT,
16081 MMO: MemN->getMemOperand());
16082
16083 // Update the uses.
16084 SmallVector<SDValue, 5> NewResults;
16085 for (unsigned i = 0; i < NumResultVecs; ++i)
16086 NewResults.push_back(Elt: SDValue(UpdN.getNode(), i));
16087
16088 // If this is an non-standard-aligned LOAD, the first result is the loaded
16089 // value. Bitcast it to the expected result type.
16090 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
16091 SDValue &LdVal = NewResults[0];
16092 LdVal = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VecTy, Operand: LdVal);
16093 }
16094
16095 NewResults.push_back(Elt: SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16096 DCI.CombineTo(N, To: NewResults);
16097 DCI.CombineTo(N: User.N, Res: SDValue(UpdN.getNode(), NumResultVecs));
16098
16099 return true;
16100}
16101
16102// If (opcode ptr inc) is and ADD-like instruction, return the
16103// increment value. Otherwise return 0.
16104static unsigned getPointerConstIncrement(unsigned Opcode, SDValue Ptr,
16105 SDValue Inc, const SelectionDAG &DAG) {
16106 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Val: Inc.getNode());
16107 if (!CInc)
16108 return 0;
16109
16110 switch (Opcode) {
16111 case ARMISD::VLD1_UPD:
16112 case ISD::ADD:
16113 return CInc->getZExtValue();
16114 case ISD::OR: {
16115 if (DAG.haveNoCommonBitsSet(A: Ptr, B: Inc)) {
16116 // (OR ptr inc) is the same as (ADD ptr inc)
16117 return CInc->getZExtValue();
16118 }
16119 return 0;
16120 }
16121 default:
16122 return 0;
16123 }
16124}
16125
16126static bool findPointerConstIncrement(SDNode *N, SDValue *Ptr, SDValue *CInc) {
16127 switch (N->getOpcode()) {
16128 case ISD::ADD:
16129 case ISD::OR: {
16130 if (isa<ConstantSDNode>(Val: N->getOperand(Num: 1))) {
16131 *Ptr = N->getOperand(Num: 0);
16132 *CInc = N->getOperand(Num: 1);
16133 return true;
16134 }
16135 return false;
16136 }
16137 case ARMISD::VLD1_UPD: {
16138 if (isa<ConstantSDNode>(Val: N->getOperand(Num: 2))) {
16139 *Ptr = N->getOperand(Num: 1);
16140 *CInc = N->getOperand(Num: 2);
16141 return true;
16142 }
16143 return false;
16144 }
16145 default:
16146 return false;
16147 }
16148}
16149
16150/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
16151/// NEON load/store intrinsics, and generic vector load/stores, to merge
16152/// base address updates.
16153/// For generic load/stores, the memory type is assumed to be a vector.
16154/// The caller is assumed to have checked legality.
16155static SDValue CombineBaseUpdate(SDNode *N,
16156 TargetLowering::DAGCombinerInfo &DCI) {
16157 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
16158 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
16159 const bool isStore = N->getOpcode() == ISD::STORE;
16160 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
16161 BaseUpdateTarget Target = {.N: N, .isIntrinsic: isIntrinsic, .isStore: isStore, .AddrOpIdx: AddrOpIdx};
16162
16163 // Limit the number of possible base-updates we look at to prevent degenerate
16164 // cases.
16165 unsigned MaxBaseUpdates = ArmMaxBaseUpdatesToCheck;
16166
16167 SDValue Addr = N->getOperand(Num: AddrOpIdx);
16168
16169 SmallVector<BaseUpdateUser, 8> BaseUpdates;
16170
16171 // Search for a use of the address operand that is an increment.
16172 for (SDUse &Use : Addr->uses()) {
16173 SDNode *User = Use.getUser();
16174 if (Use.getResNo() != Addr.getResNo() || User->getNumOperands() != 2)
16175 continue;
16176
16177 SDValue Inc = User->getOperand(Num: Use.getOperandNo() == 1 ? 0 : 1);
16178 unsigned ConstInc =
16179 getPointerConstIncrement(Opcode: User->getOpcode(), Ptr: Addr, Inc, DAG: DCI.DAG);
16180
16181 if (ConstInc || User->getOpcode() == ISD::ADD) {
16182 BaseUpdates.push_back(Elt: {.N: User, .Inc: Inc, .ConstInc: ConstInc});
16183 if (BaseUpdates.size() >= MaxBaseUpdates)
16184 break;
16185 }
16186 }
16187
16188 // If the address is a constant pointer increment itself, find
16189 // another constant increment that has the same base operand
16190 SDValue Base;
16191 SDValue CInc;
16192 if (findPointerConstIncrement(N: Addr.getNode(), Ptr: &Base, CInc: &CInc)) {
16193 unsigned Offset =
16194 getPointerConstIncrement(Opcode: Addr->getOpcode(), Ptr: Base, Inc: CInc, DAG: DCI.DAG);
16195 if (Offset) {
16196 for (SDUse &Use : Base->uses()) {
16197
16198 SDNode *User = Use.getUser();
16199 if (Use.getResNo() != Base.getResNo() || User == Addr.getNode() ||
16200 User->getNumOperands() != 2)
16201 continue;
16202
16203 SDValue UserInc = User->getOperand(Num: Use.getOperandNo() == 0 ? 1 : 0);
16204 unsigned UserOffset =
16205 getPointerConstIncrement(Opcode: User->getOpcode(), Ptr: Base, Inc: UserInc, DAG: DCI.DAG);
16206
16207 if (!UserOffset || UserOffset <= Offset)
16208 continue;
16209
16210 unsigned NewConstInc = UserOffset - Offset;
16211 SDValue NewInc = DCI.DAG.getConstant(Val: NewConstInc, DL: SDLoc(N), VT: MVT::i32);
16212 BaseUpdates.push_back(Elt: {.N: User, .Inc: NewInc, .ConstInc: NewConstInc});
16213 if (BaseUpdates.size() >= MaxBaseUpdates)
16214 break;
16215 }
16216 }
16217 }
16218
16219 // Try to fold the load/store with an update that matches memory
16220 // access size. This should work well for sequential loads.
16221 unsigned NumValidUpd = BaseUpdates.size();
16222 for (unsigned I = 0; I < NumValidUpd; I++) {
16223 BaseUpdateUser &User = BaseUpdates[I];
16224 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/true, DCI))
16225 return SDValue();
16226 }
16227
16228 // Try to fold with other users. Non-constant updates are considered
16229 // first, and constant updates are sorted to not break a sequence of
16230 // strided accesses (if there is any).
16231 llvm::stable_sort(Range&: BaseUpdates,
16232 C: [](const BaseUpdateUser &LHS, const BaseUpdateUser &RHS) {
16233 return LHS.ConstInc < RHS.ConstInc;
16234 });
16235 for (BaseUpdateUser &User : BaseUpdates) {
16236 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/false, DCI))
16237 return SDValue();
16238 }
16239 return SDValue();
16240}
16241
16242static SDValue PerformVLDCombine(SDNode *N,
16243 TargetLowering::DAGCombinerInfo &DCI) {
16244 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16245 return SDValue();
16246
16247 return CombineBaseUpdate(N, DCI);
16248}
16249
16250static SDValue PerformMVEVLDCombine(SDNode *N,
16251 TargetLowering::DAGCombinerInfo &DCI) {
16252 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16253 return SDValue();
16254
16255 SelectionDAG &DAG = DCI.DAG;
16256 SDValue Addr = N->getOperand(Num: 2);
16257 MemSDNode *MemN = cast<MemSDNode>(Val: N);
16258 SDLoc dl(N);
16259
16260 // For the stores, where there are multiple intrinsics we only actually want
16261 // to post-inc the last of the them.
16262 unsigned IntNo = N->getConstantOperandVal(Num: 1);
16263 if (IntNo == Intrinsic::arm_mve_vst2q && N->getConstantOperandVal(Num: 5) != 1)
16264 return SDValue();
16265 if (IntNo == Intrinsic::arm_mve_vst4q && N->getConstantOperandVal(Num: 7) != 3)
16266 return SDValue();
16267
16268 // Search for a use of the address operand that is an increment.
16269 for (SDUse &Use : Addr->uses()) {
16270 SDNode *User = Use.getUser();
16271 if (User->getOpcode() != ISD::ADD || Use.getResNo() != Addr.getResNo())
16272 continue;
16273
16274 // Check that the add is independent of the load/store. Otherwise, folding
16275 // it would create a cycle. We can avoid searching through Addr as it's a
16276 // predecessor to both.
16277 SmallPtrSet<const SDNode *, 32> Visited;
16278 SmallVector<const SDNode *, 16> Worklist;
16279 Visited.insert(Ptr: Addr.getNode());
16280 Worklist.push_back(Elt: N);
16281 Worklist.push_back(Elt: User);
16282 const unsigned MaxSteps = 1024;
16283 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
16284 SDNode::hasPredecessorHelper(N: User, Visited, Worklist, MaxSteps))
16285 continue;
16286
16287 // Find the new opcode for the updating load/store.
16288 bool isLoadOp = true;
16289 unsigned NewOpc = 0;
16290 unsigned NumVecs = 0;
16291 switch (IntNo) {
16292 default:
16293 llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
16294 case Intrinsic::arm_mve_vld2q:
16295 NewOpc = ARMISD::VLD2_UPD;
16296 NumVecs = 2;
16297 break;
16298 case Intrinsic::arm_mve_vld4q:
16299 NewOpc = ARMISD::VLD4_UPD;
16300 NumVecs = 4;
16301 break;
16302 case Intrinsic::arm_mve_vst2q:
16303 NewOpc = ARMISD::VST2_UPD;
16304 NumVecs = 2;
16305 isLoadOp = false;
16306 break;
16307 case Intrinsic::arm_mve_vst4q:
16308 NewOpc = ARMISD::VST4_UPD;
16309 NumVecs = 4;
16310 isLoadOp = false;
16311 break;
16312 }
16313
16314 // Find the size of memory referenced by the load/store.
16315 EVT VecTy;
16316 if (isLoadOp) {
16317 VecTy = N->getValueType(ResNo: 0);
16318 } else {
16319 VecTy = N->getOperand(Num: 3).getValueType();
16320 }
16321
16322 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16323
16324 // If the increment is a constant, it must match the memory ref size.
16325 SDValue Inc = User->getOperand(Num: User->getOperand(Num: 0) == Addr ? 1 : 0);
16326 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Val: Inc.getNode());
16327 if (!CInc || CInc->getZExtValue() != NumBytes)
16328 continue;
16329
16330 // Create the new updating load/store node.
16331 // First, create an SDVTList for the new updating node's results.
16332 EVT Tys[6];
16333 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16334 unsigned n;
16335 for (n = 0; n < NumResultVecs; ++n)
16336 Tys[n] = VecTy;
16337 Tys[n++] = MVT::i32;
16338 Tys[n] = MVT::Other;
16339 SDVTList SDTys = DAG.getVTList(VTs: ArrayRef(Tys, NumResultVecs + 2));
16340
16341 // Then, gather the new node's operands.
16342 SmallVector<SDValue, 8> Ops;
16343 Ops.push_back(Elt: N->getOperand(Num: 0)); // incoming chain
16344 Ops.push_back(Elt: N->getOperand(Num: 2)); // ptr
16345 Ops.push_back(Elt: Inc);
16346
16347 for (unsigned i = 3; i < N->getNumOperands(); ++i)
16348 Ops.push_back(Elt: N->getOperand(Num: i));
16349
16350 SDValue UpdN = DAG.getMemIntrinsicNode(Opcode: NewOpc, dl, VTList: SDTys, Ops, MemVT: VecTy,
16351 MMO: MemN->getMemOperand());
16352
16353 // Update the uses.
16354 SmallVector<SDValue, 5> NewResults;
16355 for (unsigned i = 0; i < NumResultVecs; ++i)
16356 NewResults.push_back(Elt: SDValue(UpdN.getNode(), i));
16357
16358 NewResults.push_back(Elt: SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16359 DCI.CombineTo(N, To: NewResults);
16360 DCI.CombineTo(N: User, Res: SDValue(UpdN.getNode(), NumResultVecs));
16361
16362 break;
16363 }
16364
16365 return SDValue();
16366}
16367
16368/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
16369/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
16370/// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
16371/// return true.
16372static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
16373 SelectionDAG &DAG = DCI.DAG;
16374 EVT VT = N->getValueType(ResNo: 0);
16375 // vldN-dup instructions only support 64-bit vectors for N > 1.
16376 if (!VT.is64BitVector())
16377 return false;
16378
16379 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
16380 SDNode *VLD = N->getOperand(Num: 0).getNode();
16381 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
16382 return false;
16383 unsigned NumVecs = 0;
16384 unsigned NewOpc = 0;
16385 unsigned IntNo = VLD->getConstantOperandVal(Num: 1);
16386 if (IntNo == Intrinsic::arm_neon_vld2lane) {
16387 NumVecs = 2;
16388 NewOpc = ARMISD::VLD2DUP;
16389 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
16390 NumVecs = 3;
16391 NewOpc = ARMISD::VLD3DUP;
16392 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
16393 NumVecs = 4;
16394 NewOpc = ARMISD::VLD4DUP;
16395 } else {
16396 return false;
16397 }
16398
16399 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
16400 // numbers match the load.
16401 unsigned VLDLaneNo = VLD->getConstantOperandVal(Num: NumVecs + 3);
16402 for (SDUse &Use : VLD->uses()) {
16403 // Ignore uses of the chain result.
16404 if (Use.getResNo() == NumVecs)
16405 continue;
16406 SDNode *User = Use.getUser();
16407 if (User->getOpcode() != ARMISD::VDUPLANE ||
16408 VLDLaneNo != User->getConstantOperandVal(Num: 1))
16409 return false;
16410 }
16411
16412 // Create the vldN-dup node.
16413 EVT Tys[5];
16414 unsigned n;
16415 for (n = 0; n < NumVecs; ++n)
16416 Tys[n] = VT;
16417 Tys[n] = MVT::Other;
16418 SDVTList SDTys = DAG.getVTList(VTs: ArrayRef(Tys, NumVecs + 1));
16419 SDValue Ops[] = { VLD->getOperand(Num: 0), VLD->getOperand(Num: 2) };
16420 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(Val: VLD);
16421 SDValue VLDDup = DAG.getMemIntrinsicNode(Opcode: NewOpc, dl: SDLoc(VLD), VTList: SDTys,
16422 Ops, MemVT: VLDMemInt->getMemoryVT(),
16423 MMO: VLDMemInt->getMemOperand());
16424
16425 // Update the uses.
16426 for (SDUse &Use : VLD->uses()) {
16427 unsigned ResNo = Use.getResNo();
16428 // Ignore uses of the chain result.
16429 if (ResNo == NumVecs)
16430 continue;
16431 DCI.CombineTo(N: Use.getUser(), Res: SDValue(VLDDup.getNode(), ResNo));
16432 }
16433
16434 // Now the vldN-lane intrinsic is dead except for its chain result.
16435 // Update uses of the chain.
16436 std::vector<SDValue> VLDDupResults;
16437 for (unsigned n = 0; n < NumVecs; ++n)
16438 VLDDupResults.push_back(x: SDValue(VLDDup.getNode(), n));
16439 VLDDupResults.push_back(x: SDValue(VLDDup.getNode(), NumVecs));
16440 DCI.CombineTo(N: VLD, To: VLDDupResults);
16441
16442 return true;
16443}
16444
16445/// PerformVDUPLANECombine - Target-specific dag combine xforms for
16446/// ARMISD::VDUPLANE.
16447static SDValue PerformVDUPLANECombine(SDNode *N,
16448 TargetLowering::DAGCombinerInfo &DCI,
16449 const ARMSubtarget *Subtarget) {
16450 SDValue Op = N->getOperand(Num: 0);
16451 EVT VT = N->getValueType(ResNo: 0);
16452
16453 // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
16454 if (Subtarget->hasMVEIntegerOps()) {
16455 EVT ExtractVT = VT.getVectorElementType();
16456 // We need to ensure we are creating a legal type.
16457 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT: ExtractVT))
16458 ExtractVT = MVT::i32;
16459 SDValue Extract = DCI.DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: SDLoc(N), VT: ExtractVT,
16460 N1: N->getOperand(Num: 0), N2: N->getOperand(Num: 1));
16461 return DCI.DAG.getNode(Opcode: ARMISD::VDUP, DL: SDLoc(N), VT, Operand: Extract);
16462 }
16463
16464 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
16465 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
16466 if (CombineVLDDUP(N, DCI))
16467 return SDValue(N, 0);
16468
16469 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
16470 // redundant. Ignore bit_converts for now; element sizes are checked below.
16471 while (Op.getOpcode() == ISD::BITCAST)
16472 Op = Op.getOperand(i: 0);
16473 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
16474 return SDValue();
16475
16476 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
16477 unsigned EltSize = Op.getScalarValueSizeInBits();
16478 // The canonical VMOV for a zero vector uses a 32-bit element size.
16479 unsigned Imm = Op.getConstantOperandVal(i: 0);
16480 unsigned EltBits;
16481 if (ARM_AM::decodeVMOVModImm(ModImm: Imm, EltBits) == 0)
16482 EltSize = 8;
16483 if (EltSize > VT.getScalarSizeInBits())
16484 return SDValue();
16485
16486 return DCI.DAG.getNode(Opcode: ISD::BITCAST, DL: SDLoc(N), VT, Operand: Op);
16487}
16488
16489/// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
16490static SDValue PerformVDUPCombine(SDNode *N, SelectionDAG &DAG,
16491 const ARMSubtarget *Subtarget) {
16492 SDValue Op = N->getOperand(Num: 0);
16493 SDLoc dl(N);
16494
16495 if (Subtarget->hasMVEIntegerOps()) {
16496 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
16497 // need to come from a GPR.
16498 if (Op.getValueType() == MVT::f32)
16499 return DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT: N->getValueType(ResNo: 0),
16500 Operand: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op));
16501 else if (Op.getValueType() == MVT::f16)
16502 return DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT: N->getValueType(ResNo: 0),
16503 Operand: DAG.getNode(Opcode: ARMISD::VMOVrh, DL: dl, VT: MVT::i32, Operand: Op));
16504 }
16505
16506 if (!Subtarget->hasNEON())
16507 return SDValue();
16508
16509 // Match VDUP(LOAD) -> VLD1DUP.
16510 // We match this pattern here rather than waiting for isel because the
16511 // transform is only legal for unindexed loads.
16512 LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: Op.getNode());
16513 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
16514 LD->getMemoryVT() == N->getValueType(ResNo: 0).getVectorElementType()) {
16515 SDValue Ops[] = {LD->getOperand(Num: 0), LD->getOperand(Num: 1),
16516 DAG.getConstant(Val: LD->getAlign().value(), DL: SDLoc(N), VT: MVT::i32)};
16517 SDVTList SDTys = DAG.getVTList(VT1: N->getValueType(ResNo: 0), VT2: MVT::Other);
16518 SDValue VLDDup =
16519 DAG.getMemIntrinsicNode(Opcode: ARMISD::VLD1DUP, dl: SDLoc(N), VTList: SDTys, Ops,
16520 MemVT: LD->getMemoryVT(), MMO: LD->getMemOperand());
16521 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 1), To: VLDDup.getValue(R: 1));
16522 return VLDDup;
16523 }
16524
16525 return SDValue();
16526}
16527
16528static SDValue PerformLOADCombine(SDNode *N,
16529 TargetLowering::DAGCombinerInfo &DCI,
16530 const ARMSubtarget *Subtarget) {
16531 EVT VT = N->getValueType(ResNo: 0);
16532
16533 // If this is a legal vector load, try to combine it into a VLD1_UPD.
16534 if (Subtarget->hasNEON() && ISD::isNormalLoad(N) && VT.isVector() &&
16535 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16536 return CombineBaseUpdate(N, DCI);
16537
16538 return SDValue();
16539}
16540
16541// Optimize trunc store (of multiple scalars) to shuffle and store. First,
16542// pack all of the elements in one place. Next, store to memory in fewer
16543// chunks.
16544static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
16545 SelectionDAG &DAG) {
16546 SDValue StVal = St->getValue();
16547 EVT VT = StVal.getValueType();
16548 if (!St->isTruncatingStore() || !VT.isVector())
16549 return SDValue();
16550 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16551 EVT StVT = St->getMemoryVT();
16552 unsigned NumElems = VT.getVectorNumElements();
16553 assert(StVT != VT && "Cannot truncate to the same type");
16554 unsigned FromEltSz = VT.getScalarSizeInBits();
16555 unsigned ToEltSz = StVT.getScalarSizeInBits();
16556
16557 // From, To sizes and ElemCount must be pow of two
16558 if (!isPowerOf2_32(Value: NumElems * FromEltSz * ToEltSz))
16559 return SDValue();
16560
16561 // We are going to use the original vector elt for storing.
16562 // Accumulated smaller vector elements must be a multiple of the store size.
16563 if (0 != (NumElems * FromEltSz) % ToEltSz)
16564 return SDValue();
16565
16566 unsigned SizeRatio = FromEltSz / ToEltSz;
16567 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
16568
16569 // Create a type on which we perform the shuffle.
16570 EVT WideVecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: StVT.getScalarType(),
16571 NumElements: NumElems * SizeRatio);
16572 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16573
16574 SDLoc DL(St);
16575 SDValue WideVec = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: WideVecVT, Operand: StVal);
16576 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16577 for (unsigned i = 0; i < NumElems; ++i)
16578 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
16579 : i * SizeRatio;
16580
16581 // Can't shuffle using an illegal type.
16582 if (!TLI.isTypeLegal(VT: WideVecVT))
16583 return SDValue();
16584
16585 SDValue Shuff = DAG.getVectorShuffle(
16586 VT: WideVecVT, dl: DL, N1: WideVec, N2: DAG.getUNDEF(VT: WideVec.getValueType()), Mask: ShuffleVec);
16587 // At this point all of the data is stored at the bottom of the
16588 // register. We now need to save it to mem.
16589
16590 // Find the largest store unit
16591 MVT StoreType = MVT::i8;
16592 for (MVT Tp : MVT::integer_valuetypes()) {
16593 if (TLI.isTypeLegal(VT: Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
16594 StoreType = Tp;
16595 }
16596 // Didn't find a legal store type.
16597 if (!TLI.isTypeLegal(VT: StoreType))
16598 return SDValue();
16599
16600 // Bitcast the original vector into a vector of store-size units
16601 EVT StoreVecVT =
16602 EVT::getVectorVT(Context&: *DAG.getContext(), VT: StoreType,
16603 NumElements: VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
16604 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16605 SDValue ShuffWide = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: StoreVecVT, Operand: Shuff);
16606 SmallVector<SDValue, 8> Chains;
16607 SDValue Increment = DAG.getConstant(Val: StoreType.getSizeInBits() / 8, DL,
16608 VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
16609 SDValue BasePtr = St->getBasePtr();
16610
16611 // Perform one or more big stores into memory.
16612 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
16613 for (unsigned I = 0; I < E; I++) {
16614 SDValue SubVec = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: StoreType,
16615 N1: ShuffWide, N2: DAG.getIntPtrConstant(Val: I, DL));
16616 SDValue Ch =
16617 DAG.getStore(Chain: St->getChain(), dl: DL, Val: SubVec, Ptr: BasePtr, PtrInfo: St->getPointerInfo(),
16618 Alignment: St->getAlign(), MMOFlags: St->getMemOperand()->getFlags());
16619 BasePtr =
16620 DAG.getNode(Opcode: ISD::ADD, DL, VT: BasePtr.getValueType(), N1: BasePtr, N2: Increment);
16621 Chains.push_back(Elt: Ch);
16622 }
16623 return DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Chains);
16624}
16625
16626// Try taking a single vector store from an fpround (which would otherwise turn
16627// into an expensive buildvector) and splitting it into a series of narrowing
16628// stores.
16629static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
16630 SelectionDAG &DAG) {
16631 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16632 return SDValue();
16633 SDValue Trunc = St->getValue();
16634 if (Trunc->getOpcode() != ISD::FP_ROUND)
16635 return SDValue();
16636 EVT FromVT = Trunc->getOperand(Num: 0).getValueType();
16637 EVT ToVT = Trunc.getValueType();
16638 if (!ToVT.isVector())
16639 return SDValue();
16640 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
16641 EVT ToEltVT = ToVT.getVectorElementType();
16642 EVT FromEltVT = FromVT.getVectorElementType();
16643
16644 if (FromEltVT != MVT::f32 || ToEltVT != MVT::f16)
16645 return SDValue();
16646
16647 unsigned NumElements = 4;
16648 if (FromVT.getVectorNumElements() % NumElements != 0)
16649 return SDValue();
16650
16651 // Test if the Trunc will be convertible to a VMOVN with a shuffle, and if so
16652 // use the VMOVN over splitting the store. We are looking for patterns of:
16653 // !rev: 0 N 1 N+1 2 N+2 ...
16654 // rev: N 0 N+1 1 N+2 2 ...
16655 // The shuffle may either be a single source (in which case N = NumElts/2) or
16656 // two inputs extended with concat to the same size (in which case N =
16657 // NumElts).
16658 auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) {
16659 ArrayRef<int> M = SVN->getMask();
16660 unsigned NumElts = ToVT.getVectorNumElements();
16661 if (SVN->getOperand(Num: 1).isUndef())
16662 NumElts /= 2;
16663
16664 unsigned Off0 = Rev ? NumElts : 0;
16665 unsigned Off1 = Rev ? 0 : NumElts;
16666
16667 for (unsigned I = 0; I < NumElts; I += 2) {
16668 if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2))
16669 return false;
16670 if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2))
16671 return false;
16672 }
16673
16674 return true;
16675 };
16676
16677 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Val: Trunc.getOperand(i: 0)))
16678 if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true))
16679 return SDValue();
16680
16681 LLVMContext &C = *DAG.getContext();
16682 SDLoc DL(St);
16683 // Details about the old store
16684 SDValue Ch = St->getChain();
16685 SDValue BasePtr = St->getBasePtr();
16686 Align Alignment = St->getBaseAlign();
16687 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16688 AAMDNodes AAInfo = St->getAAInfo();
16689
16690 // We split the store into slices of NumElements. fp16 trunc stores are vcvt
16691 // and then stored as truncating integer stores.
16692 EVT NewFromVT = EVT::getVectorVT(Context&: C, VT: FromEltVT, NumElements);
16693 EVT NewToVT = EVT::getVectorVT(
16694 Context&: C, VT: EVT::getIntegerVT(Context&: C, BitWidth: ToEltVT.getSizeInBits()), NumElements);
16695
16696 SmallVector<SDValue, 4> Stores;
16697 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
16698 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
16699 SDValue NewPtr =
16700 DAG.getObjectPtrOffset(SL: DL, Ptr: BasePtr, Offset: TypeSize::getFixed(ExactSize: NewOffset));
16701
16702 SDValue Extract =
16703 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: NewFromVT, N1: Trunc.getOperand(i: 0),
16704 N2: DAG.getConstant(Val: i * NumElements, DL, VT: MVT::i32));
16705
16706 SDValue FPTrunc =
16707 DAG.getNode(Opcode: ARMISD::VCVTN, DL, VT: MVT::v8f16, N1: DAG.getUNDEF(VT: MVT::v8f16),
16708 N2: Extract, N3: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
16709 Extract = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT: MVT::v4i32, Operand: FPTrunc);
16710
16711 SDValue Store = DAG.getTruncStore(
16712 Chain: Ch, dl: DL, Val: Extract, Ptr: NewPtr, PtrInfo: St->getPointerInfo().getWithOffset(O: NewOffset),
16713 SVT: NewToVT, Alignment, MMOFlags, AAInfo);
16714 Stores.push_back(Elt: Store);
16715 }
16716 return DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Stores);
16717}
16718
16719// Try taking a single vector store from an MVETRUNC (which would otherwise turn
16720// into an expensive buildvector) and splitting it into a series of narrowing
16721// stores.
16722static SDValue PerformSplittingMVETruncToNarrowingStores(StoreSDNode *St,
16723 SelectionDAG &DAG) {
16724 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16725 return SDValue();
16726 SDValue Trunc = St->getValue();
16727 if (Trunc->getOpcode() != ARMISD::MVETRUNC)
16728 return SDValue();
16729 EVT FromVT = Trunc->getOperand(Num: 0).getValueType();
16730 EVT ToVT = Trunc.getValueType();
16731
16732 LLVMContext &C = *DAG.getContext();
16733 SDLoc DL(St);
16734 // Details about the old store
16735 SDValue Ch = St->getChain();
16736 SDValue BasePtr = St->getBasePtr();
16737 Align Alignment = St->getBaseAlign();
16738 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16739 AAMDNodes AAInfo = St->getAAInfo();
16740
16741 EVT NewToVT = EVT::getVectorVT(Context&: C, VT: ToVT.getVectorElementType(),
16742 NumElements: FromVT.getVectorNumElements());
16743
16744 SmallVector<SDValue, 4> Stores;
16745 for (unsigned i = 0; i < Trunc.getNumOperands(); i++) {
16746 unsigned NewOffset =
16747 i * FromVT.getVectorNumElements() * ToVT.getScalarSizeInBits() / 8;
16748 SDValue NewPtr =
16749 DAG.getObjectPtrOffset(SL: DL, Ptr: BasePtr, Offset: TypeSize::getFixed(ExactSize: NewOffset));
16750
16751 SDValue Extract = Trunc.getOperand(i);
16752 SDValue Store = DAG.getTruncStore(
16753 Chain: Ch, dl: DL, Val: Extract, Ptr: NewPtr, PtrInfo: St->getPointerInfo().getWithOffset(O: NewOffset),
16754 SVT: NewToVT, Alignment, MMOFlags, AAInfo);
16755 Stores.push_back(Elt: Store);
16756 }
16757 return DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Stores);
16758}
16759
16760// Given a floating point store from an extracted vector, with an integer
16761// VGETLANE that already exists, store the existing VGETLANEu directly. This can
16762// help reduce fp register pressure, doesn't require the fp extract and allows
16763// use of more integer post-inc stores not available with vstr.
16764static SDValue PerformExtractFpToIntStores(StoreSDNode *St, SelectionDAG &DAG) {
16765 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16766 return SDValue();
16767 SDValue Extract = St->getValue();
16768 EVT VT = Extract.getValueType();
16769 // For now only uses f16. This may be useful for f32 too, but that will
16770 // be bitcast(extract), not the VGETLANEu we currently check here.
16771 if (VT != MVT::f16 || Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16772 return SDValue();
16773
16774 SDNode *GetLane =
16775 DAG.getNodeIfExists(Opcode: ARMISD::VGETLANEu, VTList: DAG.getVTList(VT: MVT::i32),
16776 Ops: {Extract.getOperand(i: 0), Extract.getOperand(i: 1)});
16777 if (!GetLane)
16778 return SDValue();
16779
16780 LLVMContext &C = *DAG.getContext();
16781 SDLoc DL(St);
16782 // Create a new integer store to replace the existing floating point version.
16783 SDValue Ch = St->getChain();
16784 SDValue BasePtr = St->getBasePtr();
16785 Align Alignment = St->getBaseAlign();
16786 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16787 AAMDNodes AAInfo = St->getAAInfo();
16788 EVT NewToVT = EVT::getIntegerVT(Context&: C, BitWidth: VT.getSizeInBits());
16789 SDValue Store = DAG.getTruncStore(Chain: Ch, dl: DL, Val: SDValue(GetLane, 0), Ptr: BasePtr,
16790 PtrInfo: St->getPointerInfo(), SVT: NewToVT, Alignment,
16791 MMOFlags, AAInfo);
16792
16793 return Store;
16794}
16795
16796/// PerformSTORECombine - Target-specific dag combine xforms for
16797/// ISD::STORE.
16798static SDValue PerformSTORECombine(SDNode *N,
16799 TargetLowering::DAGCombinerInfo &DCI,
16800 const ARMSubtarget *Subtarget) {
16801 StoreSDNode *St = cast<StoreSDNode>(Val: N);
16802 if (St->isVolatile())
16803 return SDValue();
16804 SDValue StVal = St->getValue();
16805 EVT VT = StVal.getValueType();
16806
16807 if (Subtarget->hasNEON())
16808 if (SDValue Store = PerformTruncatingStoreCombine(St, DAG&: DCI.DAG))
16809 return Store;
16810
16811 if (Subtarget->hasMVEFloatOps())
16812 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DAG&: DCI.DAG))
16813 return NewToken;
16814
16815 if (Subtarget->hasMVEIntegerOps()) {
16816 if (SDValue NewChain = PerformExtractFpToIntStores(St, DAG&: DCI.DAG))
16817 return NewChain;
16818 if (SDValue NewToken =
16819 PerformSplittingMVETruncToNarrowingStores(St, DAG&: DCI.DAG))
16820 return NewToken;
16821 }
16822
16823 if (!ISD::isNormalStore(N: St))
16824 return SDValue();
16825
16826 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
16827 // ARM stores of arguments in the same cache line.
16828 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
16829 StVal.getNode()->hasOneUse()) {
16830 SelectionDAG &DAG = DCI.DAG;
16831 bool isBigEndian = DAG.getDataLayout().isBigEndian();
16832 SDLoc DL(St);
16833 SDValue BasePtr = St->getBasePtr();
16834 SDValue NewST1 = DAG.getStore(
16835 Chain: St->getChain(), dl: DL, Val: StVal.getNode()->getOperand(Num: isBigEndian ? 1 : 0),
16836 Ptr: BasePtr, PtrInfo: St->getPointerInfo(), Alignment: St->getBaseAlign(),
16837 MMOFlags: St->getMemOperand()->getFlags());
16838
16839 SDValue OffsetPtr = DAG.getNode(Opcode: ISD::ADD, DL, VT: MVT::i32, N1: BasePtr,
16840 N2: DAG.getConstant(Val: 4, DL, VT: MVT::i32));
16841 return DAG.getStore(Chain: NewST1.getValue(R: 0), dl: DL,
16842 Val: StVal.getNode()->getOperand(Num: isBigEndian ? 0 : 1),
16843 Ptr: OffsetPtr, PtrInfo: St->getPointerInfo().getWithOffset(O: 4),
16844 Alignment: St->getBaseAlign(), MMOFlags: St->getMemOperand()->getFlags());
16845 }
16846
16847 if (StVal.getValueType() == MVT::i64 &&
16848 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16849
16850 // Bitcast an i64 store extracted from a vector to f64.
16851 // Otherwise, the i64 value will be legalized to a pair of i32 values.
16852 SelectionDAG &DAG = DCI.DAG;
16853 SDLoc dl(StVal);
16854 SDValue IntVec = StVal.getOperand(i: 0);
16855 EVT FloatVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::f64,
16856 NumElements: IntVec.getValueType().getVectorNumElements());
16857 SDValue Vec = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: FloatVT, Operand: IntVec);
16858 SDValue ExtElt = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f64,
16859 N1: Vec, N2: StVal.getOperand(i: 1));
16860 dl = SDLoc(N);
16861 SDValue V = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i64, Operand: ExtElt);
16862 // Make the DAGCombiner fold the bitcasts.
16863 DCI.AddToWorklist(N: Vec.getNode());
16864 DCI.AddToWorklist(N: ExtElt.getNode());
16865 DCI.AddToWorklist(N: V.getNode());
16866 return DAG.getStore(Chain: St->getChain(), dl, Val: V, Ptr: St->getBasePtr(),
16867 PtrInfo: St->getPointerInfo(), Alignment: St->getAlign(),
16868 MMOFlags: St->getMemOperand()->getFlags(), AAInfo: St->getAAInfo());
16869 }
16870
16871 // If this is a legal vector store, try to combine it into a VST1_UPD.
16872 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
16873 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16874 return CombineBaseUpdate(N, DCI);
16875
16876 return SDValue();
16877}
16878
16879/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
16880/// can replace combinations of VMUL and VCVT (floating-point to integer)
16881/// when the VMUL has a constant operand that is a power of 2.
16882///
16883/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
16884/// vmul.f32 d16, d17, d16
16885/// vcvt.s32.f32 d16, d16
16886/// becomes:
16887/// vcvt.s32.f32 d16, d16, #3
16888static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
16889 const ARMSubtarget *Subtarget) {
16890 if (!Subtarget->hasNEON())
16891 return SDValue();
16892
16893 SDValue Op = N->getOperand(Num: 0);
16894 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
16895 Op.getOpcode() != ISD::FMUL)
16896 return SDValue();
16897
16898 SDValue ConstVec = Op->getOperand(Num: 1);
16899 if (!isa<BuildVectorSDNode>(Val: ConstVec))
16900 return SDValue();
16901
16902 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
16903 uint32_t FloatBits = FloatTy.getSizeInBits();
16904 MVT IntTy = N->getSimpleValueType(ResNo: 0).getVectorElementType();
16905 uint32_t IntBits = IntTy.getSizeInBits();
16906 unsigned NumLanes = Op.getValueType().getVectorNumElements();
16907 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
16908 // These instructions only exist converting from f32 to i32. We can handle
16909 // smaller integers by generating an extra truncate, but larger ones would
16910 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
16911 // these instructions only support v2i32/v4i32 types.
16912 return SDValue();
16913 }
16914
16915 BitVector UndefElements;
16916 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Val&: ConstVec);
16917 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(UndefElements: &UndefElements, BitWidth: 33);
16918 if (C == -1 || C == 0 || C > 32)
16919 return SDValue();
16920
16921 SDLoc dl(N);
16922 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
16923 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
16924 Intrinsic::arm_neon_vcvtfp2fxu;
16925 SDValue FixConv = DAG.getNode(
16926 Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
16927 N1: DAG.getConstant(Val: IntrinsicOpcode, DL: dl, VT: MVT::i32), N2: Op->getOperand(Num: 0),
16928 N3: DAG.getConstant(Val: C, DL: dl, VT: MVT::i32));
16929
16930 if (IntBits < FloatBits)
16931 FixConv = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: N->getValueType(ResNo: 0), Operand: FixConv);
16932
16933 return FixConv;
16934}
16935
16936static SDValue PerformFAddVSelectCombine(SDNode *N, SelectionDAG &DAG,
16937 const ARMSubtarget *Subtarget) {
16938 if (!Subtarget->hasMVEFloatOps())
16939 return SDValue();
16940
16941 // Turn (fadd x, (vselect c, y, -0.0)) into (vselect c, (fadd x, y), x)
16942 // The second form can be more easily turned into a predicated vadd, and
16943 // possibly combined into a fma to become a predicated vfma.
16944 SDValue Op0 = N->getOperand(Num: 0);
16945 SDValue Op1 = N->getOperand(Num: 1);
16946 EVT VT = N->getValueType(ResNo: 0);
16947 SDLoc DL(N);
16948
16949 // The identity element for a fadd is -0.0 or +0.0 when the nsz flag is set,
16950 // which these VMOV's represent.
16951 auto isIdentitySplat = [&](SDValue Op, bool NSZ) {
16952 if (Op.getOpcode() != ISD::BITCAST ||
16953 Op.getOperand(i: 0).getOpcode() != ARMISD::VMOVIMM)
16954 return false;
16955 uint64_t ImmVal = Op.getOperand(i: 0).getConstantOperandVal(i: 0);
16956 if (VT == MVT::v4f32 && (ImmVal == 1664 || (ImmVal == 0 && NSZ)))
16957 return true;
16958 if (VT == MVT::v8f16 && (ImmVal == 2688 || (ImmVal == 0 && NSZ)))
16959 return true;
16960 return false;
16961 };
16962
16963 if (Op0.getOpcode() == ISD::VSELECT && Op1.getOpcode() != ISD::VSELECT)
16964 std::swap(a&: Op0, b&: Op1);
16965
16966 if (Op1.getOpcode() != ISD::VSELECT)
16967 return SDValue();
16968
16969 SDNodeFlags FaddFlags = N->getFlags();
16970 bool NSZ = FaddFlags.hasNoSignedZeros();
16971 if (!isIdentitySplat(Op1.getOperand(i: 2), NSZ))
16972 return SDValue();
16973
16974 SDValue FAdd =
16975 DAG.getNode(Opcode: ISD::FADD, DL, VT, N1: Op0, N2: Op1.getOperand(i: 1), Flags: FaddFlags);
16976 return DAG.getNode(Opcode: ISD::VSELECT, DL, VT, N1: Op1.getOperand(i: 0), N2: FAdd, N3: Op0, Flags: FaddFlags);
16977}
16978
16979static SDValue PerformFADDVCMLACombine(SDNode *N, SelectionDAG &DAG) {
16980 SDValue LHS = N->getOperand(Num: 0);
16981 SDValue RHS = N->getOperand(Num: 1);
16982 EVT VT = N->getValueType(ResNo: 0);
16983 SDLoc DL(N);
16984
16985 if (!N->getFlags().hasAllowReassociation())
16986 return SDValue();
16987
16988 // Combine fadd(a, vcmla(b, c, d)) -> vcmla(fadd(a, b), b, c)
16989 auto ReassocComplex = [&](SDValue A, SDValue B) {
16990 if (A.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
16991 return SDValue();
16992 unsigned Opc = A.getConstantOperandVal(i: 0);
16993 if (Opc != Intrinsic::arm_mve_vcmlaq)
16994 return SDValue();
16995 SDValue VCMLA = DAG.getNode(
16996 Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT, N1: A.getOperand(i: 0), N2: A.getOperand(i: 1),
16997 N3: DAG.getNode(Opcode: ISD::FADD, DL, VT, N1: A.getOperand(i: 2), N2: B, Flags: N->getFlags()),
16998 N4: A.getOperand(i: 3), N5: A.getOperand(i: 4));
16999 VCMLA->setFlags(A->getFlags());
17000 return VCMLA;
17001 };
17002 if (SDValue R = ReassocComplex(LHS, RHS))
17003 return R;
17004 if (SDValue R = ReassocComplex(RHS, LHS))
17005 return R;
17006
17007 return SDValue();
17008}
17009
17010static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17011 const ARMSubtarget *Subtarget) {
17012 if (SDValue S = PerformFAddVSelectCombine(N, DAG, Subtarget))
17013 return S;
17014 if (SDValue S = PerformFADDVCMLACombine(N, DAG))
17015 return S;
17016 return SDValue();
17017}
17018
17019/// PerformVMulVCTPCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
17020/// can replace combinations of VCVT (integer to floating-point) and VMUL
17021/// when the VMUL has a constant operand that is a power of 2.
17022///
17023/// Example (assume d17 = <float 0.125, float 0.125>):
17024/// vcvt.f32.s32 d16, d16
17025/// vmul.f32 d16, d16, d17
17026/// becomes:
17027/// vcvt.f32.s32 d16, d16, #3
17028static SDValue PerformVMulVCTPCombine(SDNode *N, SelectionDAG &DAG,
17029 const ARMSubtarget *Subtarget) {
17030 if (!Subtarget->hasNEON())
17031 return SDValue();
17032
17033 SDValue Op = N->getOperand(Num: 0);
17034 unsigned OpOpcode = Op.getNode()->getOpcode();
17035 if (!N->getValueType(ResNo: 0).isVector() || !N->getValueType(ResNo: 0).isSimple() ||
17036 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
17037 return SDValue();
17038
17039 SDValue ConstVec = N->getOperand(Num: 1);
17040 if (!isa<BuildVectorSDNode>(Val: ConstVec))
17041 return SDValue();
17042
17043 MVT FloatTy = N->getSimpleValueType(ResNo: 0).getVectorElementType();
17044 uint32_t FloatBits = FloatTy.getSizeInBits();
17045 MVT IntTy = Op.getOperand(i: 0).getSimpleValueType().getVectorElementType();
17046 uint32_t IntBits = IntTy.getSizeInBits();
17047 unsigned NumLanes = Op.getValueType().getVectorNumElements();
17048 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
17049 // These instructions only exist converting from i32 to f32. We can handle
17050 // smaller integers by generating an extra extend, but larger ones would
17051 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
17052 // these instructions only support v2i32/v4i32 types.
17053 return SDValue();
17054 }
17055
17056 ConstantFPSDNode *CN = isConstOrConstSplatFP(N: ConstVec, AllowUndefs: true);
17057 APFloat Recip(0.0f);
17058 if (!CN || !CN->getValueAPF().getExactInverse(Inv: &Recip))
17059 return SDValue();
17060
17061 bool IsExact;
17062 APSInt IntVal(33);
17063 if (Recip.convertToInteger(Result&: IntVal, RM: APFloat::rmTowardZero, IsExact: &IsExact) !=
17064 APFloat::opOK ||
17065 !IsExact)
17066 return SDValue();
17067
17068 int32_t C = IntVal.exactLogBase2();
17069 if (C == -1 || C == 0 || C > 32)
17070 return SDValue();
17071
17072 SDLoc DL(N);
17073 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
17074 SDValue ConvInput = Op.getOperand(i: 0);
17075 if (IntBits < FloatBits)
17076 ConvInput = DAG.getNode(Opcode: isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
17077 VT: NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, Operand: ConvInput);
17078
17079 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp
17080 : Intrinsic::arm_neon_vcvtfxu2fp;
17081 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT: Op.getValueType(),
17082 N1: DAG.getConstant(Val: IntrinsicOpcode, DL, VT: MVT::i32), N2: ConvInput,
17083 N3: DAG.getConstant(Val: C, DL, VT: MVT::i32));
17084}
17085
17086static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
17087 const ARMSubtarget *ST) {
17088 if (!ST->hasMVEIntegerOps())
17089 return SDValue();
17090
17091 assert(N->getOpcode() == ISD::VECREDUCE_ADD);
17092 EVT ResVT = N->getValueType(ResNo: 0);
17093 SDValue N0 = N->getOperand(Num: 0);
17094 SDLoc dl(N);
17095
17096 // Try to turn vecreduce_add(add(x, y)) into vecreduce(x) + vecreduce(y)
17097 if (ResVT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
17098 (N0.getValueType() == MVT::v4i32 || N0.getValueType() == MVT::v8i16 ||
17099 N0.getValueType() == MVT::v16i8)) {
17100 SDValue Red0 = DAG.getNode(Opcode: ISD::VECREDUCE_ADD, DL: dl, VT: ResVT, Operand: N0.getOperand(i: 0));
17101 SDValue Red1 = DAG.getNode(Opcode: ISD::VECREDUCE_ADD, DL: dl, VT: ResVT, Operand: N0.getOperand(i: 1));
17102 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: ResVT, N1: Red0, N2: Red1);
17103 }
17104
17105 // We are looking for something that will have illegal types if left alone,
17106 // but that we can convert to a single instruction under MVE. For example
17107 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
17108 // or
17109 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
17110
17111 // The legal cases are:
17112 // VADDV u/s 8/16/32
17113 // VMLAV u/s 8/16/32
17114 // VADDLV u/s 32
17115 // VMLALV u/s 16/32
17116
17117 // If the input vector is smaller than legal (v4i8/v4i16 for example) we can
17118 // extend it and use v4i32 instead.
17119 auto ExtTypeMatches = [](SDValue A, ArrayRef<MVT> ExtTypes) {
17120 EVT AVT = A.getValueType();
17121 return any_of(Range&: ExtTypes, P: [&](MVT Ty) {
17122 return AVT.getVectorNumElements() == Ty.getVectorNumElements() &&
17123 AVT.bitsLE(VT: Ty);
17124 });
17125 };
17126 auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) {
17127 EVT AVT = A.getValueType();
17128 if (!AVT.is128BitVector())
17129 A = DAG.getNode(
17130 Opcode: ExtendCode, DL: dl,
17131 VT: AVT.changeVectorElementType(
17132 Context&: *DAG.getContext(),
17133 EltVT: MVT::getIntegerVT(BitWidth: 128 / AVT.getVectorMinNumElements())),
17134 Operand: A);
17135 return A;
17136 };
17137 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
17138 if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
17139 return SDValue();
17140 SDValue A = N0->getOperand(Num: 0);
17141 if (ExtTypeMatches(A, ExtTypes))
17142 return ExtendIfNeeded(A, ExtendCode);
17143 return SDValue();
17144 };
17145 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
17146 ArrayRef<MVT> ExtTypes, SDValue &Mask) {
17147 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17148 !ISD::isBuildVectorAllZeros(N: N0->getOperand(Num: 2).getNode()))
17149 return SDValue();
17150 Mask = N0->getOperand(Num: 0);
17151 SDValue Ext = N0->getOperand(Num: 1);
17152 if (Ext->getOpcode() != ExtendCode)
17153 return SDValue();
17154 SDValue A = Ext->getOperand(Num: 0);
17155 if (ExtTypeMatches(A, ExtTypes))
17156 return ExtendIfNeeded(A, ExtendCode);
17157 return SDValue();
17158 };
17159 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17160 SDValue &A, SDValue &B) {
17161 // For a vmla we are trying to match a larger pattern:
17162 // ExtA = sext/zext A
17163 // ExtB = sext/zext B
17164 // Mul = mul ExtA, ExtB
17165 // vecreduce.add Mul
17166 // There might also be en extra extend between the mul and the addreduce, so
17167 // long as the bitwidth is high enough to make them equivalent (for example
17168 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
17169 if (ResVT != RetTy)
17170 return false;
17171 SDValue Mul = N0;
17172 if (Mul->getOpcode() == ExtendCode &&
17173 Mul->getOperand(Num: 0).getScalarValueSizeInBits() * 2 >=
17174 ResVT.getScalarSizeInBits())
17175 Mul = Mul->getOperand(Num: 0);
17176 if (Mul->getOpcode() != ISD::MUL)
17177 return false;
17178 SDValue ExtA = Mul->getOperand(Num: 0);
17179 SDValue ExtB = Mul->getOperand(Num: 1);
17180 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17181 return false;
17182 A = ExtA->getOperand(Num: 0);
17183 B = ExtB->getOperand(Num: 0);
17184 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17185 A = ExtendIfNeeded(A, ExtendCode);
17186 B = ExtendIfNeeded(B, ExtendCode);
17187 return true;
17188 }
17189 return false;
17190 };
17191 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17192 SDValue &A, SDValue &B, SDValue &Mask) {
17193 // Same as the pattern above with a select for the zero predicated lanes
17194 // ExtA = sext/zext A
17195 // ExtB = sext/zext B
17196 // Mul = mul ExtA, ExtB
17197 // N0 = select Mask, Mul, 0
17198 // vecreduce.add N0
17199 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17200 !ISD::isBuildVectorAllZeros(N: N0->getOperand(Num: 2).getNode()))
17201 return false;
17202 Mask = N0->getOperand(Num: 0);
17203 SDValue Mul = N0->getOperand(Num: 1);
17204 if (Mul->getOpcode() == ExtendCode &&
17205 Mul->getOperand(Num: 0).getScalarValueSizeInBits() * 2 >=
17206 ResVT.getScalarSizeInBits())
17207 Mul = Mul->getOperand(Num: 0);
17208 if (Mul->getOpcode() != ISD::MUL)
17209 return false;
17210 SDValue ExtA = Mul->getOperand(Num: 0);
17211 SDValue ExtB = Mul->getOperand(Num: 1);
17212 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17213 return false;
17214 A = ExtA->getOperand(Num: 0);
17215 B = ExtB->getOperand(Num: 0);
17216 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17217 A = ExtendIfNeeded(A, ExtendCode);
17218 B = ExtendIfNeeded(B, ExtendCode);
17219 return true;
17220 }
17221 return false;
17222 };
17223 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
17224 // Split illegal MVT::v16i8->i64 vector reductions into two legal v8i16->i64
17225 // reductions. The operands are extended with MVEEXT, but as they are
17226 // reductions the lane orders do not matter. MVEEXT may be combined with
17227 // loads to produce two extending loads, or else they will be expanded to
17228 // VREV/VMOVL.
17229 EVT VT = Ops[0].getValueType();
17230 if (VT == MVT::v16i8) {
17231 assert((Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) &&
17232 "Unexpected illegal long reduction opcode");
17233 bool IsUnsigned = Opcode == ARMISD::VMLALVu;
17234
17235 SDValue Ext0 =
17236 DAG.getNode(Opcode: IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, DL: dl,
17237 VTList: DAG.getVTList(VT1: MVT::v8i16, VT2: MVT::v8i16), N: Ops[0]);
17238 SDValue Ext1 =
17239 DAG.getNode(Opcode: IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, DL: dl,
17240 VTList: DAG.getVTList(VT1: MVT::v8i16, VT2: MVT::v8i16), N: Ops[1]);
17241
17242 SDValue MLA0 = DAG.getNode(Opcode, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
17243 N1: Ext0, N2: Ext1);
17244 SDValue MLA1 =
17245 DAG.getNode(Opcode: IsUnsigned ? ARMISD::VMLALVAu : ARMISD::VMLALVAs, DL: dl,
17246 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N1: MLA0, N2: MLA0.getValue(R: 1),
17247 N3: Ext0.getValue(R: 1), N4: Ext1.getValue(R: 1));
17248 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: MLA1, N2: MLA1.getValue(R: 1));
17249 }
17250 SDValue Node = DAG.getNode(Opcode, DL: dl, ResultTys: {MVT::i32, MVT::i32}, Ops);
17251 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Node,
17252 N2: SDValue(Node.getNode(), 1));
17253 };
17254
17255 SDValue A, B;
17256 SDValue Mask;
17257 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17258 return DAG.getNode(Opcode: ARMISD::VMLAVs, DL: dl, VT: ResVT, N1: A, N2: B);
17259 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17260 return DAG.getNode(Opcode: ARMISD::VMLAVu, DL: dl, VT: ResVT, N1: A, N2: B);
17261 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17262 A, B))
17263 return Create64bitNode(ARMISD::VMLALVs, {A, B});
17264 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17265 A, B))
17266 return Create64bitNode(ARMISD::VMLALVu, {A, B});
17267 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
17268 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17269 Operand: DAG.getNode(Opcode: ARMISD::VMLAVs, DL: dl, VT: MVT::i32, N1: A, N2: B));
17270 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
17271 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17272 Operand: DAG.getNode(Opcode: ARMISD::VMLAVu, DL: dl, VT: MVT::i32, N1: A, N2: B));
17273
17274 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17275 Mask))
17276 return DAG.getNode(Opcode: ARMISD::VMLAVps, DL: dl, VT: ResVT, N1: A, N2: B, N3: Mask);
17277 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17278 Mask))
17279 return DAG.getNode(Opcode: ARMISD::VMLAVpu, DL: dl, VT: ResVT, N1: A, N2: B, N3: Mask);
17280 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17281 Mask))
17282 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
17283 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17284 Mask))
17285 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
17286 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
17287 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17288 Operand: DAG.getNode(Opcode: ARMISD::VMLAVps, DL: dl, VT: MVT::i32, N1: A, N2: B, N3: Mask));
17289 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
17290 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17291 Operand: DAG.getNode(Opcode: ARMISD::VMLAVpu, DL: dl, VT: MVT::i32, N1: A, N2: B, N3: Mask));
17292
17293 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
17294 return DAG.getNode(Opcode: ARMISD::VADDVs, DL: dl, VT: ResVT, Operand: A);
17295 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
17296 return DAG.getNode(Opcode: ARMISD::VADDVu, DL: dl, VT: ResVT, Operand: A);
17297 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
17298 return Create64bitNode(ARMISD::VADDLVs, {A});
17299 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
17300 return Create64bitNode(ARMISD::VADDLVu, {A});
17301 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
17302 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17303 Operand: DAG.getNode(Opcode: ARMISD::VADDVs, DL: dl, VT: MVT::i32, Operand: A));
17304 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
17305 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17306 Operand: DAG.getNode(Opcode: ARMISD::VADDVu, DL: dl, VT: MVT::i32, Operand: A));
17307
17308 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17309 return DAG.getNode(Opcode: ARMISD::VADDVps, DL: dl, VT: ResVT, N1: A, N2: Mask);
17310 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17311 return DAG.getNode(Opcode: ARMISD::VADDVpu, DL: dl, VT: ResVT, N1: A, N2: Mask);
17312 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
17313 return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
17314 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
17315 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
17316 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
17317 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17318 Operand: DAG.getNode(Opcode: ARMISD::VADDVps, DL: dl, VT: MVT::i32, N1: A, N2: Mask));
17319 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
17320 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17321 Operand: DAG.getNode(Opcode: ARMISD::VADDVpu, DL: dl, VT: MVT::i32, N1: A, N2: Mask));
17322
17323 // Some complications. We can get a case where the two inputs of the mul are
17324 // the same, then the output sext will have been helpfully converted to a
17325 // zext. Turn it back.
17326 SDValue Op = N0;
17327 if (Op->getOpcode() == ISD::VSELECT)
17328 Op = Op->getOperand(Num: 1);
17329 if (Op->getOpcode() == ISD::ZERO_EXTEND &&
17330 Op->getOperand(Num: 0)->getOpcode() == ISD::MUL) {
17331 SDValue Mul = Op->getOperand(Num: 0);
17332 if (Mul->getOperand(Num: 0) == Mul->getOperand(Num: 1) &&
17333 Mul->getOperand(Num: 0)->getOpcode() == ISD::SIGN_EXTEND) {
17334 SDValue Ext = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: N0->getValueType(ResNo: 0), Operand: Mul);
17335 if (Op != N0)
17336 Ext = DAG.getNode(Opcode: ISD::VSELECT, DL: dl, VT: N0->getValueType(ResNo: 0),
17337 N1: N0->getOperand(Num: 0), N2: Ext, N3: N0->getOperand(Num: 2));
17338 return DAG.getNode(Opcode: ISD::VECREDUCE_ADD, DL: dl, VT: ResVT, Operand: Ext);
17339 }
17340 }
17341
17342 return SDValue();
17343}
17344
17345// Looks for vaddv(shuffle) or vmlav(shuffle, shuffle), with a shuffle where all
17346// the lanes are used. Due to the reduction being commutative the shuffle can be
17347// removed.
17348static SDValue PerformReduceShuffleCombine(SDNode *N, SelectionDAG &DAG) {
17349 unsigned VecOp = N->getOperand(Num: 0).getValueType().isVector() ? 0 : 2;
17350 auto *Shuf = dyn_cast<ShuffleVectorSDNode>(Val: N->getOperand(Num: VecOp));
17351 if (!Shuf || !Shuf->getOperand(Num: 1).isUndef())
17352 return SDValue();
17353
17354 // Check all elements are used once in the mask.
17355 ArrayRef<int> Mask = Shuf->getMask();
17356 APInt SetElts(Mask.size(), 0);
17357 for (int E : Mask) {
17358 if (E < 0 || E >= (int)Mask.size())
17359 return SDValue();
17360 SetElts.setBit(E);
17361 }
17362 if (!SetElts.isAllOnes())
17363 return SDValue();
17364
17365 if (N->getNumOperands() != VecOp + 1) {
17366 auto *Shuf2 = dyn_cast<ShuffleVectorSDNode>(Val: N->getOperand(Num: VecOp + 1));
17367 if (!Shuf2 || !Shuf2->getOperand(Num: 1).isUndef() || Shuf2->getMask() != Mask)
17368 return SDValue();
17369 }
17370
17371 SmallVector<SDValue> Ops;
17372 for (SDValue Op : N->ops()) {
17373 if (Op.getValueType().isVector())
17374 Ops.push_back(Elt: Op.getOperand(i: 0));
17375 else
17376 Ops.push_back(Elt: Op);
17377 }
17378 return DAG.getNode(Opcode: N->getOpcode(), DL: SDLoc(N), VTList: N->getVTList(), Ops);
17379}
17380
17381static SDValue PerformVMOVNCombine(SDNode *N,
17382 TargetLowering::DAGCombinerInfo &DCI) {
17383 SDValue Op0 = N->getOperand(Num: 0);
17384 SDValue Op1 = N->getOperand(Num: 1);
17385 unsigned IsTop = N->getConstantOperandVal(Num: 2);
17386
17387 // VMOVNT a undef -> a
17388 // VMOVNB a undef -> a
17389 // VMOVNB undef a -> a
17390 if (Op1->isUndef())
17391 return Op0;
17392 if (Op0->isUndef() && !IsTop)
17393 return Op1;
17394
17395 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
17396 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
17397 if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
17398 Op1->getOpcode() == ARMISD::VQMOVNu) &&
17399 Op1->getConstantOperandVal(Num: 2) == 0)
17400 return DCI.DAG.getNode(Opcode: Op1->getOpcode(), DL: SDLoc(Op1), VT: N->getValueType(ResNo: 0),
17401 N1: Op0, N2: Op1->getOperand(Num: 1), N3: N->getOperand(Num: 2));
17402
17403 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
17404 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
17405 // into the top or bottom lanes.
17406 unsigned NumElts = N->getValueType(ResNo: 0).getVectorNumElements();
17407 APInt Op1DemandedElts = APInt::getSplat(NewLen: NumElts, V: APInt::getLowBitsSet(numBits: 2, loBitsSet: 1));
17408 APInt Op0DemandedElts =
17409 IsTop ? Op1DemandedElts
17410 : APInt::getSplat(NewLen: NumElts, V: APInt::getHighBitsSet(numBits: 2, hiBitsSet: 1));
17411
17412 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17413 if (TLI.SimplifyDemandedVectorElts(Op: Op0, DemandedElts: Op0DemandedElts, DCI))
17414 return SDValue(N, 0);
17415 if (TLI.SimplifyDemandedVectorElts(Op: Op1, DemandedElts: Op1DemandedElts, DCI))
17416 return SDValue(N, 0);
17417
17418 return SDValue();
17419}
17420
17421static SDValue PerformVQMOVNCombine(SDNode *N,
17422 TargetLowering::DAGCombinerInfo &DCI) {
17423 SDValue Op0 = N->getOperand(Num: 0);
17424 unsigned IsTop = N->getConstantOperandVal(Num: 2);
17425
17426 unsigned NumElts = N->getValueType(ResNo: 0).getVectorNumElements();
17427 APInt Op0DemandedElts =
17428 APInt::getSplat(NewLen: NumElts, V: IsTop ? APInt::getLowBitsSet(numBits: 2, loBitsSet: 1)
17429 : APInt::getHighBitsSet(numBits: 2, hiBitsSet: 1));
17430
17431 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17432 if (TLI.SimplifyDemandedVectorElts(Op: Op0, DemandedElts: Op0DemandedElts, DCI))
17433 return SDValue(N, 0);
17434 return SDValue();
17435}
17436
17437static SDValue PerformVQDMULHCombine(SDNode *N,
17438 TargetLowering::DAGCombinerInfo &DCI) {
17439 EVT VT = N->getValueType(ResNo: 0);
17440 SDValue LHS = N->getOperand(Num: 0);
17441 SDValue RHS = N->getOperand(Num: 1);
17442
17443 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(Val&: LHS);
17444 auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(Val&: RHS);
17445 // Turn VQDMULH(shuffle, shuffle) -> shuffle(VQDMULH)
17446 if (Shuf0 && Shuf1 && Shuf0->getMask().equals(RHS: Shuf1->getMask()) &&
17447 LHS.getOperand(i: 1).isUndef() && RHS.getOperand(i: 1).isUndef() &&
17448 (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
17449 SDLoc DL(N);
17450 SDValue NewBinOp = DCI.DAG.getNode(Opcode: N->getOpcode(), DL, VT,
17451 N1: LHS.getOperand(i: 0), N2: RHS.getOperand(i: 0));
17452 SDValue UndefV = LHS.getOperand(i: 1);
17453 return DCI.DAG.getVectorShuffle(VT, dl: DL, N1: NewBinOp, N2: UndefV, Mask: Shuf0->getMask());
17454 }
17455 return SDValue();
17456}
17457
17458static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
17459 SDLoc DL(N);
17460 SDValue Op0 = N->getOperand(Num: 0);
17461 SDValue Op1 = N->getOperand(Num: 1);
17462
17463 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
17464 // uses of the intrinsics.
17465 if (auto C = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 2))) {
17466 int ShiftAmt = C->getSExtValue();
17467 if (ShiftAmt == 0) {
17468 SDValue Merge = DAG.getMergeValues(Ops: {Op0, Op1}, dl: DL);
17469 DAG.ReplaceAllUsesWith(From: N, To: Merge.getNode());
17470 return SDValue();
17471 }
17472
17473 if (ShiftAmt >= -32 && ShiftAmt < 0) {
17474 unsigned NewOpcode =
17475 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
17476 SDValue NewShift = DAG.getNode(Opcode: NewOpcode, DL, VTList: N->getVTList(), N1: Op0, N2: Op1,
17477 N3: DAG.getConstant(Val: -ShiftAmt, DL, VT: MVT::i32));
17478 DAG.ReplaceAllUsesWith(From: N, To: NewShift.getNode());
17479 return NewShift;
17480 }
17481 }
17482
17483 return SDValue();
17484}
17485
17486/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
17487SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
17488 DAGCombinerInfo &DCI) const {
17489 SelectionDAG &DAG = DCI.DAG;
17490 unsigned IntNo = N->getConstantOperandVal(Num: 0);
17491 switch (IntNo) {
17492 default:
17493 // Don't do anything for most intrinsics.
17494 break;
17495
17496 // Vector shifts: check for immediate versions and lower them.
17497 // Note: This is done during DAG combining instead of DAG legalizing because
17498 // the build_vectors for 64-bit vector element shift counts are generally
17499 // not legal, and it is hard to see their values after they get legalized to
17500 // loads from a constant pool.
17501 case Intrinsic::arm_neon_vshifts:
17502 case Intrinsic::arm_neon_vshiftu:
17503 case Intrinsic::arm_neon_vrshifts:
17504 case Intrinsic::arm_neon_vrshiftu:
17505 case Intrinsic::arm_neon_vrshiftn:
17506 case Intrinsic::arm_neon_vqshifts:
17507 case Intrinsic::arm_neon_vqshiftu:
17508 case Intrinsic::arm_neon_vqshiftsu:
17509 case Intrinsic::arm_neon_vqshiftns:
17510 case Intrinsic::arm_neon_vqshiftnu:
17511 case Intrinsic::arm_neon_vqshiftnsu:
17512 case Intrinsic::arm_neon_vqrshiftns:
17513 case Intrinsic::arm_neon_vqrshiftnu:
17514 case Intrinsic::arm_neon_vqrshiftnsu: {
17515 EVT VT = N->getOperand(Num: 1).getValueType();
17516 int64_t Cnt;
17517 unsigned VShiftOpc = 0;
17518
17519 switch (IntNo) {
17520 case Intrinsic::arm_neon_vshifts:
17521 case Intrinsic::arm_neon_vshiftu:
17522 if (isVShiftLImm(Op: N->getOperand(Num: 2), VT, isLong: false, Cnt)) {
17523 VShiftOpc = ARMISD::VSHLIMM;
17524 break;
17525 }
17526 if (isVShiftRImm(Op: N->getOperand(Num: 2), VT, isNarrow: false, isIntrinsic: true, Cnt)) {
17527 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
17528 : ARMISD::VSHRuIMM);
17529 break;
17530 }
17531 return SDValue();
17532
17533 case Intrinsic::arm_neon_vrshifts:
17534 case Intrinsic::arm_neon_vrshiftu:
17535 if (isVShiftRImm(Op: N->getOperand(Num: 2), VT, isNarrow: false, isIntrinsic: true, Cnt))
17536 break;
17537 return SDValue();
17538
17539 case Intrinsic::arm_neon_vqshifts:
17540 case Intrinsic::arm_neon_vqshiftu:
17541 if (isVShiftLImm(Op: N->getOperand(Num: 2), VT, isLong: false, Cnt))
17542 break;
17543 return SDValue();
17544
17545 case Intrinsic::arm_neon_vqshiftsu:
17546 if (isVShiftLImm(Op: N->getOperand(Num: 2), VT, isLong: false, Cnt))
17547 break;
17548 llvm_unreachable("invalid shift count for vqshlu intrinsic");
17549
17550 case Intrinsic::arm_neon_vrshiftn:
17551 case Intrinsic::arm_neon_vqshiftns:
17552 case Intrinsic::arm_neon_vqshiftnu:
17553 case Intrinsic::arm_neon_vqshiftnsu:
17554 case Intrinsic::arm_neon_vqrshiftns:
17555 case Intrinsic::arm_neon_vqrshiftnu:
17556 case Intrinsic::arm_neon_vqrshiftnsu:
17557 // Narrowing shifts require an immediate right shift.
17558 if (isVShiftRImm(Op: N->getOperand(Num: 2), VT, isNarrow: true, isIntrinsic: true, Cnt))
17559 break;
17560 llvm_unreachable("invalid shift count for narrowing vector shift "
17561 "intrinsic");
17562
17563 default:
17564 llvm_unreachable("unhandled vector shift");
17565 }
17566
17567 switch (IntNo) {
17568 case Intrinsic::arm_neon_vshifts:
17569 case Intrinsic::arm_neon_vshiftu:
17570 // Opcode already set above.
17571 break;
17572 case Intrinsic::arm_neon_vrshifts:
17573 VShiftOpc = ARMISD::VRSHRsIMM;
17574 break;
17575 case Intrinsic::arm_neon_vrshiftu:
17576 VShiftOpc = ARMISD::VRSHRuIMM;
17577 break;
17578 case Intrinsic::arm_neon_vrshiftn:
17579 VShiftOpc = ARMISD::VRSHRNIMM;
17580 break;
17581 case Intrinsic::arm_neon_vqshifts:
17582 VShiftOpc = ARMISD::VQSHLsIMM;
17583 break;
17584 case Intrinsic::arm_neon_vqshiftu:
17585 VShiftOpc = ARMISD::VQSHLuIMM;
17586 break;
17587 case Intrinsic::arm_neon_vqshiftsu:
17588 VShiftOpc = ARMISD::VQSHLsuIMM;
17589 break;
17590 case Intrinsic::arm_neon_vqshiftns:
17591 VShiftOpc = ARMISD::VQSHRNsIMM;
17592 break;
17593 case Intrinsic::arm_neon_vqshiftnu:
17594 VShiftOpc = ARMISD::VQSHRNuIMM;
17595 break;
17596 case Intrinsic::arm_neon_vqshiftnsu:
17597 VShiftOpc = ARMISD::VQSHRNsuIMM;
17598 break;
17599 case Intrinsic::arm_neon_vqrshiftns:
17600 VShiftOpc = ARMISD::VQRSHRNsIMM;
17601 break;
17602 case Intrinsic::arm_neon_vqrshiftnu:
17603 VShiftOpc = ARMISD::VQRSHRNuIMM;
17604 break;
17605 case Intrinsic::arm_neon_vqrshiftnsu:
17606 VShiftOpc = ARMISD::VQRSHRNsuIMM;
17607 break;
17608 }
17609
17610 SDLoc dl(N);
17611 return DAG.getNode(Opcode: VShiftOpc, DL: dl, VT: N->getValueType(ResNo: 0),
17612 N1: N->getOperand(Num: 1), N2: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
17613 }
17614
17615 case Intrinsic::arm_neon_vshiftins: {
17616 EVT VT = N->getOperand(Num: 1).getValueType();
17617 int64_t Cnt;
17618 unsigned VShiftOpc = 0;
17619
17620 if (isVShiftLImm(Op: N->getOperand(Num: 3), VT, isLong: false, Cnt))
17621 VShiftOpc = ARMISD::VSLIIMM;
17622 else if (isVShiftRImm(Op: N->getOperand(Num: 3), VT, isNarrow: false, isIntrinsic: true, Cnt))
17623 VShiftOpc = ARMISD::VSRIIMM;
17624 else {
17625 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
17626 }
17627
17628 SDLoc dl(N);
17629 return DAG.getNode(Opcode: VShiftOpc, DL: dl, VT: N->getValueType(ResNo: 0),
17630 N1: N->getOperand(Num: 1), N2: N->getOperand(Num: 2),
17631 N3: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
17632 }
17633
17634 case Intrinsic::arm_neon_vqrshifts:
17635 case Intrinsic::arm_neon_vqrshiftu:
17636 // No immediate versions of these to check for.
17637 break;
17638
17639 case Intrinsic::arm_neon_vbsl: {
17640 SDLoc dl(N);
17641 return DAG.getNode(Opcode: ARMISD::VBSP, DL: dl, VT: N->getValueType(ResNo: 0), N1: N->getOperand(Num: 1),
17642 N2: N->getOperand(Num: 2), N3: N->getOperand(Num: 3));
17643 }
17644 case Intrinsic::arm_mve_vqdmlah:
17645 case Intrinsic::arm_mve_vqdmlash:
17646 case Intrinsic::arm_mve_vqrdmlah:
17647 case Intrinsic::arm_mve_vqrdmlash:
17648 case Intrinsic::arm_mve_vmla_n_predicated:
17649 case Intrinsic::arm_mve_vmlas_n_predicated:
17650 case Intrinsic::arm_mve_vqdmlah_predicated:
17651 case Intrinsic::arm_mve_vqdmlash_predicated:
17652 case Intrinsic::arm_mve_vqrdmlah_predicated:
17653 case Intrinsic::arm_mve_vqrdmlash_predicated: {
17654 // These intrinsics all take an i32 scalar operand which is narrowed to the
17655 // size of a single lane of the vector type they return. So we don't need
17656 // any bits of that operand above that point, which allows us to eliminate
17657 // uxth/sxth.
17658 unsigned BitWidth = N->getValueType(ResNo: 0).getScalarSizeInBits();
17659 APInt DemandedMask = APInt::getLowBitsSet(numBits: 32, loBitsSet: BitWidth);
17660 if (SimplifyDemandedBits(Op: N->getOperand(Num: 3), DemandedBits: DemandedMask, DCI))
17661 return SDValue();
17662 break;
17663 }
17664
17665 case Intrinsic::arm_mve_minv:
17666 case Intrinsic::arm_mve_maxv:
17667 case Intrinsic::arm_mve_minav:
17668 case Intrinsic::arm_mve_maxav:
17669 case Intrinsic::arm_mve_minv_predicated:
17670 case Intrinsic::arm_mve_maxv_predicated:
17671 case Intrinsic::arm_mve_minav_predicated:
17672 case Intrinsic::arm_mve_maxav_predicated: {
17673 // These intrinsics all take an i32 scalar operand which is narrowed to the
17674 // size of a single lane of the vector type they take as the other input.
17675 unsigned BitWidth = N->getOperand(Num: 2)->getValueType(ResNo: 0).getScalarSizeInBits();
17676 APInt DemandedMask = APInt::getLowBitsSet(numBits: 32, loBitsSet: BitWidth);
17677 if (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI))
17678 return SDValue();
17679 break;
17680 }
17681
17682 case Intrinsic::arm_mve_addv: {
17683 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
17684 // which allow PerformADDVecReduce to turn it into VADDLV when possible.
17685 bool Unsigned = N->getConstantOperandVal(Num: 2);
17686 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
17687 return DAG.getNode(Opcode: Opc, DL: SDLoc(N), VTList: N->getVTList(), N: N->getOperand(Num: 1));
17688 }
17689
17690 case Intrinsic::arm_mve_addlv:
17691 case Intrinsic::arm_mve_addlv_predicated: {
17692 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
17693 // which recombines the two outputs into an i64
17694 bool Unsigned = N->getConstantOperandVal(Num: 2);
17695 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
17696 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
17697 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
17698
17699 SmallVector<SDValue, 4> Ops;
17700 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
17701 if (i != 2) // skip the unsigned flag
17702 Ops.push_back(Elt: N->getOperand(Num: i));
17703
17704 SDLoc dl(N);
17705 SDValue val = DAG.getNode(Opcode: Opc, DL: dl, ResultTys: {MVT::i32, MVT::i32}, Ops);
17706 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: val.getValue(R: 0),
17707 N2: val.getValue(R: 1));
17708 }
17709 }
17710
17711 return SDValue();
17712}
17713
17714/// PerformShiftCombine - Checks for immediate versions of vector shifts and
17715/// lowers them. As with the vector shift intrinsics, this is done during DAG
17716/// combining instead of DAG legalizing because the build_vectors for 64-bit
17717/// vector element shift counts are generally not legal, and it is hard to see
17718/// their values after they get legalized to loads from a constant pool.
17719static SDValue PerformShiftCombine(SDNode *N,
17720 TargetLowering::DAGCombinerInfo &DCI,
17721 const ARMSubtarget *ST) {
17722 SelectionDAG &DAG = DCI.DAG;
17723 EVT VT = N->getValueType(ResNo: 0);
17724
17725 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
17726 N->getOperand(Num: 0)->getOpcode() == ISD::AND &&
17727 N->getOperand(Num: 0)->hasOneUse()) {
17728 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17729 return SDValue();
17730 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
17731 // usually show up because instcombine prefers to canonicalize it to
17732 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
17733 // out of GEP lowering in some cases.
17734 SDValue N0 = N->getOperand(Num: 0);
17735 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
17736 if (!ShiftAmtNode)
17737 return SDValue();
17738 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
17739 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(Val: N0->getOperand(Num: 1));
17740 if (!AndMaskNode)
17741 return SDValue();
17742 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
17743 // Don't transform uxtb/uxth.
17744 if (AndMask == 255 || AndMask == 65535)
17745 return SDValue();
17746 if (isMask_32(Value: AndMask)) {
17747 uint32_t MaskedBits = llvm::countl_zero(Val: AndMask);
17748 if (MaskedBits > ShiftAmt) {
17749 SDLoc DL(N);
17750 SDValue SHL = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
17751 N2: DAG.getConstant(Val: MaskedBits, DL, VT: MVT::i32));
17752 return DAG.getNode(
17753 Opcode: ISD::SRL, DL, VT: MVT::i32, N1: SHL,
17754 N2: DAG.getConstant(Val: MaskedBits - ShiftAmt, DL, VT: MVT::i32));
17755 }
17756 }
17757 }
17758
17759 // Nothing to be done for scalar shifts.
17760 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17761 if (!VT.isVector() || !TLI.isTypeLegal(VT))
17762 return SDValue();
17763 if (ST->hasMVEIntegerOps())
17764 return SDValue();
17765
17766 int64_t Cnt;
17767
17768 switch (N->getOpcode()) {
17769 default: llvm_unreachable("unexpected shift opcode");
17770
17771 case ISD::SHL:
17772 if (isVShiftLImm(Op: N->getOperand(Num: 1), VT, isLong: false, Cnt)) {
17773 SDLoc dl(N);
17774 return DAG.getNode(Opcode: ARMISD::VSHLIMM, DL: dl, VT, N1: N->getOperand(Num: 0),
17775 N2: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
17776 }
17777 break;
17778
17779 case ISD::SRA:
17780 case ISD::SRL:
17781 if (isVShiftRImm(Op: N->getOperand(Num: 1), VT, isNarrow: false, isIntrinsic: false, Cnt)) {
17782 unsigned VShiftOpc =
17783 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
17784 SDLoc dl(N);
17785 return DAG.getNode(Opcode: VShiftOpc, DL: dl, VT, N1: N->getOperand(Num: 0),
17786 N2: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
17787 }
17788 }
17789 return SDValue();
17790}
17791
17792// Look for a sign/zero/fpextend extend of a larger than legal load. This can be
17793// split into multiple extending loads, which are simpler to deal with than an
17794// arbitrary extend. For fp extends we use an integer extending load and a VCVTL
17795// to convert the type to an f32.
17796static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
17797 SDValue N0 = N->getOperand(Num: 0);
17798 if (N0.getOpcode() != ISD::LOAD)
17799 return SDValue();
17800 LoadSDNode *LD = cast<LoadSDNode>(Val: N0.getNode());
17801 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
17802 LD->getExtensionType() != ISD::NON_EXTLOAD)
17803 return SDValue();
17804 EVT FromVT = LD->getValueType(ResNo: 0);
17805 EVT ToVT = N->getValueType(ResNo: 0);
17806 if (!ToVT.isVector())
17807 return SDValue();
17808 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
17809 EVT ToEltVT = ToVT.getVectorElementType();
17810 EVT FromEltVT = FromVT.getVectorElementType();
17811
17812 unsigned NumElements = 0;
17813 if (ToEltVT == MVT::i32 && FromEltVT == MVT::i8)
17814 NumElements = 4;
17815 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
17816 NumElements = 4;
17817 if (NumElements == 0 ||
17818 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
17819 FromVT.getVectorNumElements() % NumElements != 0 ||
17820 !isPowerOf2_32(Value: NumElements))
17821 return SDValue();
17822
17823 LLVMContext &C = *DAG.getContext();
17824 SDLoc DL(LD);
17825 // Details about the old load
17826 SDValue Ch = LD->getChain();
17827 SDValue BasePtr = LD->getBasePtr();
17828 Align Alignment = LD->getBaseAlign();
17829 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
17830 AAMDNodes AAInfo = LD->getAAInfo();
17831
17832 ISD::LoadExtType NewExtType =
17833 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
17834 SDValue Offset = DAG.getUNDEF(VT: BasePtr.getValueType());
17835 EVT NewFromVT = EVT::getVectorVT(
17836 Context&: C, VT: EVT::getIntegerVT(Context&: C, BitWidth: FromEltVT.getScalarSizeInBits()), NumElements);
17837 EVT NewToVT = EVT::getVectorVT(
17838 Context&: C, VT: EVT::getIntegerVT(Context&: C, BitWidth: ToEltVT.getScalarSizeInBits()), NumElements);
17839
17840 SmallVector<SDValue, 4> Loads;
17841 SmallVector<SDValue, 4> Chains;
17842 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
17843 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
17844 SDValue NewPtr =
17845 DAG.getObjectPtrOffset(SL: DL, Ptr: BasePtr, Offset: TypeSize::getFixed(ExactSize: NewOffset));
17846
17847 SDValue NewLoad =
17848 DAG.getLoad(AM: ISD::UNINDEXED, ExtType: NewExtType, VT: NewToVT, dl: DL, Chain: Ch, Ptr: NewPtr, Offset,
17849 PtrInfo: LD->getPointerInfo().getWithOffset(O: NewOffset), MemVT: NewFromVT,
17850 Alignment, MMOFlags, AAInfo);
17851 Loads.push_back(Elt: NewLoad);
17852 Chains.push_back(Elt: SDValue(NewLoad.getNode(), 1));
17853 }
17854
17855 // Float truncs need to extended with VCVTB's into their floating point types.
17856 if (FromEltVT == MVT::f16) {
17857 SmallVector<SDValue, 4> Extends;
17858
17859 for (unsigned i = 0; i < Loads.size(); i++) {
17860 SDValue LoadBC =
17861 DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT: MVT::v8f16, Operand: Loads[i]);
17862 SDValue FPExt = DAG.getNode(Opcode: ARMISD::VCVTL, DL, VT: MVT::v4f32, N1: LoadBC,
17863 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
17864 Extends.push_back(Elt: FPExt);
17865 }
17866
17867 Loads = Extends;
17868 }
17869
17870 SDValue NewChain = DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Chains);
17871 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 1), To: NewChain);
17872 return DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: ToVT, Ops: Loads);
17873}
17874
17875/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
17876/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
17877static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
17878 const ARMSubtarget *ST) {
17879 SDValue N0 = N->getOperand(Num: 0);
17880
17881 // Check for sign- and zero-extensions of vector extract operations of 8- and
17882 // 16-bit vector elements. NEON and MVE support these directly. They are
17883 // handled during DAG combining because type legalization will promote them
17884 // to 32-bit types and it is messy to recognize the operations after that.
17885 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
17886 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17887 SDValue Vec = N0.getOperand(i: 0);
17888 SDValue Lane = N0.getOperand(i: 1);
17889 EVT VT = N->getValueType(ResNo: 0);
17890 EVT EltVT = N0.getValueType();
17891 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17892
17893 if (VT == MVT::i32 &&
17894 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
17895 TLI.isTypeLegal(VT: Vec.getValueType()) &&
17896 isa<ConstantSDNode>(Val: Lane)) {
17897
17898 unsigned Opc = 0;
17899 switch (N->getOpcode()) {
17900 default: llvm_unreachable("unexpected opcode");
17901 case ISD::SIGN_EXTEND:
17902 Opc = ARMISD::VGETLANEs;
17903 break;
17904 case ISD::ZERO_EXTEND:
17905 case ISD::ANY_EXTEND:
17906 Opc = ARMISD::VGETLANEu;
17907 break;
17908 }
17909 return DAG.getNode(Opcode: Opc, DL: SDLoc(N), VT, N1: Vec, N2: Lane);
17910 }
17911 }
17912
17913 if (ST->hasMVEIntegerOps())
17914 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
17915 return NewLoad;
17916
17917 return SDValue();
17918}
17919
17920static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG,
17921 const ARMSubtarget *ST) {
17922 if (ST->hasMVEFloatOps())
17923 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
17924 return NewLoad;
17925
17926 return SDValue();
17927}
17928
17929// Lower smin(smax(x, C1), C2) to ssat or usat, if they have saturating
17930// constant bounds.
17931static SDValue PerformMinMaxToSatCombine(SDValue Op, SelectionDAG &DAG,
17932 const ARMSubtarget *Subtarget) {
17933 if ((Subtarget->isThumb() || !Subtarget->hasV6Ops()) &&
17934 !Subtarget->isThumb2())
17935 return SDValue();
17936
17937 EVT VT = Op.getValueType();
17938 SDValue Op0 = Op.getOperand(i: 0);
17939
17940 if (VT != MVT::i32 ||
17941 (Op0.getOpcode() != ISD::SMIN && Op0.getOpcode() != ISD::SMAX) ||
17942 !isa<ConstantSDNode>(Val: Op.getOperand(i: 1)) ||
17943 !isa<ConstantSDNode>(Val: Op0.getOperand(i: 1)))
17944 return SDValue();
17945
17946 SDValue Min = Op;
17947 SDValue Max = Op0;
17948 SDValue Input = Op0.getOperand(i: 0);
17949 if (Min.getOpcode() == ISD::SMAX)
17950 std::swap(a&: Min, b&: Max);
17951
17952 APInt MinC = Min.getConstantOperandAPInt(i: 1);
17953 APInt MaxC = Max.getConstantOperandAPInt(i: 1);
17954
17955 if (Min.getOpcode() != ISD::SMIN || Max.getOpcode() != ISD::SMAX ||
17956 !(MinC + 1).isPowerOf2())
17957 return SDValue();
17958
17959 SDLoc DL(Op);
17960 if (MinC == ~MaxC)
17961 return DAG.getNode(Opcode: ARMISD::SSAT, DL, VT, N1: Input,
17962 N2: DAG.getConstant(Val: MinC.countr_one(), DL, VT));
17963 if (MaxC == 0)
17964 return DAG.getNode(Opcode: ARMISD::USAT, DL, VT, N1: Input,
17965 N2: DAG.getConstant(Val: MinC.countr_one(), DL, VT));
17966
17967 return SDValue();
17968}
17969
17970/// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
17971/// saturates.
17972static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
17973 const ARMSubtarget *ST) {
17974 EVT VT = N->getValueType(ResNo: 0);
17975 SDValue N0 = N->getOperand(Num: 0);
17976
17977 if (VT == MVT::i32)
17978 return PerformMinMaxToSatCombine(Op: SDValue(N, 0), DAG, Subtarget: ST);
17979
17980 if (!ST->hasMVEIntegerOps())
17981 return SDValue();
17982
17983 if (SDValue V = PerformVQDMULHCombine(N, DAG))
17984 return V;
17985
17986 if (VT != MVT::v4i32 && VT != MVT::v8i16)
17987 return SDValue();
17988
17989 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
17990 // Check one is a smin and the other is a smax
17991 if (Min->getOpcode() != ISD::SMIN)
17992 std::swap(a&: Min, b&: Max);
17993 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
17994 return false;
17995
17996 APInt SaturateC;
17997 if (VT == MVT::v4i32)
17998 SaturateC = APInt(32, (1 << 15) - 1, true);
17999 else //if (VT == MVT::v8i16)
18000 SaturateC = APInt(16, (1 << 7) - 1, true);
18001
18002 APInt MinC, MaxC;
18003 if (!ISD::isConstantSplatVector(N: Min->getOperand(Num: 1).getNode(), SplatValue&: MinC) ||
18004 MinC != SaturateC)
18005 return false;
18006 if (!ISD::isConstantSplatVector(N: Max->getOperand(Num: 1).getNode(), SplatValue&: MaxC) ||
18007 MaxC != ~SaturateC)
18008 return false;
18009 return true;
18010 };
18011
18012 if (IsSignedSaturate(N, N0.getNode())) {
18013 SDLoc DL(N);
18014 MVT ExtVT, HalfVT;
18015 if (VT == MVT::v4i32) {
18016 HalfVT = MVT::v8i16;
18017 ExtVT = MVT::v4i16;
18018 } else { // if (VT == MVT::v8i16)
18019 HalfVT = MVT::v16i8;
18020 ExtVT = MVT::v8i8;
18021 }
18022
18023 // Create a VQMOVNB with undef top lanes, then signed extended into the top
18024 // half. That extend will hopefully be removed if only the bottom bits are
18025 // demanded (though a truncating store, for example).
18026 SDValue VQMOVN =
18027 DAG.getNode(Opcode: ARMISD::VQMOVNs, DL, VT: HalfVT, N1: DAG.getUNDEF(VT: HalfVT),
18028 N2: N0->getOperand(Num: 0), N3: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
18029 SDValue Bitcast = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: VQMOVN);
18030 return DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL, VT, N1: Bitcast,
18031 N2: DAG.getValueType(ExtVT));
18032 }
18033
18034 auto IsUnsignedSaturate = [&](SDNode *Min) {
18035 // For unsigned, we just need to check for <= 0xffff
18036 if (Min->getOpcode() != ISD::UMIN)
18037 return false;
18038
18039 APInt SaturateC;
18040 if (VT == MVT::v4i32)
18041 SaturateC = APInt(32, (1 << 16) - 1, true);
18042 else //if (VT == MVT::v8i16)
18043 SaturateC = APInt(16, (1 << 8) - 1, true);
18044
18045 APInt MinC;
18046 if (!ISD::isConstantSplatVector(N: Min->getOperand(Num: 1).getNode(), SplatValue&: MinC) ||
18047 MinC != SaturateC)
18048 return false;
18049 return true;
18050 };
18051
18052 if (IsUnsignedSaturate(N)) {
18053 SDLoc DL(N);
18054 MVT HalfVT;
18055 unsigned ExtConst;
18056 if (VT == MVT::v4i32) {
18057 HalfVT = MVT::v8i16;
18058 ExtConst = 0x0000FFFF;
18059 } else { //if (VT == MVT::v8i16)
18060 HalfVT = MVT::v16i8;
18061 ExtConst = 0x00FF;
18062 }
18063
18064 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
18065 // an AND. That extend will hopefully be removed if only the bottom bits are
18066 // demanded (though a truncating store, for example).
18067 SDValue VQMOVN =
18068 DAG.getNode(Opcode: ARMISD::VQMOVNu, DL, VT: HalfVT, N1: DAG.getUNDEF(VT: HalfVT), N2: N0,
18069 N3: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
18070 SDValue Bitcast = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: VQMOVN);
18071 return DAG.getNode(Opcode: ISD::AND, DL, VT, N1: Bitcast,
18072 N2: DAG.getConstant(Val: ExtConst, DL, VT));
18073 }
18074
18075 return SDValue();
18076}
18077
18078static const APInt *isPowerOf2Constant(SDValue V) {
18079 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: V);
18080 if (!C)
18081 return nullptr;
18082 const APInt *CV = &C->getAPIntValue();
18083 return CV->isPowerOf2() ? CV : nullptr;
18084}
18085
18086SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
18087 // If we have a CMOV, OR and AND combination such as:
18088 // if (x & CN)
18089 // y |= CM;
18090 //
18091 // And:
18092 // * CN is a single bit;
18093 // * All bits covered by CM are known zero in y
18094 //
18095 // Then we can convert this into a sequence of BFI instructions. This will
18096 // always be a win if CM is a single bit, will always be no worse than the
18097 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
18098 // three bits (due to the extra IT instruction).
18099
18100 SDValue Op0 = CMOV->getOperand(Num: 0);
18101 SDValue Op1 = CMOV->getOperand(Num: 1);
18102 auto CC = CMOV->getConstantOperandAPInt(Num: 2).getLimitedValue();
18103 SDValue CmpZ = CMOV->getOperand(Num: 3);
18104
18105 // The compare must be against zero.
18106 if (!isNullConstant(V: CmpZ->getOperand(Num: 1)))
18107 return SDValue();
18108
18109 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
18110 SDValue And = CmpZ->getOperand(Num: 0);
18111 if (And->getOpcode() != ISD::AND)
18112 return SDValue();
18113 const APInt *AndC = isPowerOf2Constant(V: And->getOperand(Num: 1));
18114 if (!AndC)
18115 return SDValue();
18116 SDValue X = And->getOperand(Num: 0);
18117
18118 if (CC == ARMCC::EQ) {
18119 // We're performing an "equal to zero" compare. Swap the operands so we
18120 // canonicalize on a "not equal to zero" compare.
18121 std::swap(a&: Op0, b&: Op1);
18122 } else {
18123 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
18124 }
18125
18126 if (Op1->getOpcode() != ISD::OR)
18127 return SDValue();
18128
18129 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Val: Op1->getOperand(Num: 1));
18130 if (!OrC)
18131 return SDValue();
18132 SDValue Y = Op1->getOperand(Num: 0);
18133
18134 if (Op0 != Y)
18135 return SDValue();
18136
18137 // Now, is it profitable to continue?
18138 APInt OrCI = OrC->getAPIntValue();
18139 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
18140 if (OrCI.popcount() > Heuristic)
18141 return SDValue();
18142
18143 // Lastly, can we determine that the bits defined by OrCI
18144 // are zero in Y?
18145 KnownBits Known = DAG.computeKnownBits(Op: Y);
18146 if ((OrCI & Known.Zero) != OrCI)
18147 return SDValue();
18148
18149 // OK, we can do the combine.
18150 SDValue V = Y;
18151 SDLoc dl(X);
18152 EVT VT = X.getValueType();
18153 unsigned BitInX = AndC->logBase2();
18154
18155 if (BitInX != 0) {
18156 // We must shift X first.
18157 X = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: X,
18158 N2: DAG.getConstant(Val: BitInX, DL: dl, VT));
18159 }
18160
18161 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
18162 BitInY < NumActiveBits; ++BitInY) {
18163 if (OrCI[BitInY] == 0)
18164 continue;
18165 APInt Mask(VT.getSizeInBits(), 0);
18166 Mask.setBit(BitInY);
18167 V = DAG.getNode(Opcode: ARMISD::BFI, DL: dl, VT, N1: V, N2: X,
18168 // Confusingly, the operand is an *inverted* mask.
18169 N3: DAG.getConstant(Val: ~Mask, DL: dl, VT));
18170 }
18171
18172 return V;
18173}
18174
18175// Given N, the value controlling the conditional branch, search for the loop
18176// intrinsic, returning it, along with how the value is used. We need to handle
18177// patterns such as the following:
18178// (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
18179// (brcond (setcc (loop.decrement), 0, eq), exit)
18180// (brcond (setcc (loop.decrement), 0, ne), header)
18181static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
18182 bool &Negate) {
18183 switch (N->getOpcode()) {
18184 default:
18185 break;
18186 case ISD::XOR: {
18187 if (!isa<ConstantSDNode>(Val: N.getOperand(i: 1)))
18188 return SDValue();
18189 if (!cast<ConstantSDNode>(Val: N.getOperand(i: 1))->isOne())
18190 return SDValue();
18191 Negate = !Negate;
18192 return SearchLoopIntrinsic(N: N.getOperand(i: 0), CC, Imm, Negate);
18193 }
18194 case ISD::SETCC: {
18195 auto *Const = dyn_cast<ConstantSDNode>(Val: N.getOperand(i: 1));
18196 if (!Const)
18197 return SDValue();
18198 if (Const->isZero())
18199 Imm = 0;
18200 else if (Const->isOne())
18201 Imm = 1;
18202 else
18203 return SDValue();
18204 CC = cast<CondCodeSDNode>(Val: N.getOperand(i: 2))->get();
18205 return SearchLoopIntrinsic(N: N->getOperand(Num: 0), CC, Imm, Negate);
18206 }
18207 case ISD::INTRINSIC_W_CHAIN: {
18208 unsigned IntOp = N.getConstantOperandVal(i: 1);
18209 if (IntOp != Intrinsic::test_start_loop_iterations &&
18210 IntOp != Intrinsic::loop_decrement_reg)
18211 return SDValue();
18212 return N;
18213 }
18214 }
18215 return SDValue();
18216}
18217
18218static SDValue PerformHWLoopCombine(SDNode *N,
18219 TargetLowering::DAGCombinerInfo &DCI,
18220 const ARMSubtarget *ST) {
18221
18222 // The hwloop intrinsics that we're interested are used for control-flow,
18223 // either for entering or exiting the loop:
18224 // - test.start.loop.iterations will test whether its operand is zero. If it
18225 // is zero, the proceeding branch should not enter the loop.
18226 // - loop.decrement.reg also tests whether its operand is zero. If it is
18227 // zero, the proceeding branch should not branch back to the beginning of
18228 // the loop.
18229 // So here, we need to check that how the brcond is using the result of each
18230 // of the intrinsics to ensure that we're branching to the right place at the
18231 // right time.
18232
18233 ISD::CondCode CC;
18234 SDValue Cond;
18235 int Imm = 1;
18236 bool Negate = false;
18237 SDValue Chain = N->getOperand(Num: 0);
18238 SDValue Dest;
18239
18240 if (N->getOpcode() == ISD::BRCOND) {
18241 CC = ISD::SETEQ;
18242 Cond = N->getOperand(Num: 1);
18243 Dest = N->getOperand(Num: 2);
18244 } else {
18245 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
18246 CC = cast<CondCodeSDNode>(Val: N->getOperand(Num: 1))->get();
18247 Cond = N->getOperand(Num: 2);
18248 Dest = N->getOperand(Num: 4);
18249 if (auto *Const = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 3))) {
18250 if (!Const->isOne() && !Const->isZero())
18251 return SDValue();
18252 Imm = Const->getZExtValue();
18253 } else
18254 return SDValue();
18255 }
18256
18257 SDValue Int = SearchLoopIntrinsic(N: Cond, CC, Imm, Negate);
18258 if (!Int)
18259 return SDValue();
18260
18261 if (Negate)
18262 CC = ISD::getSetCCInverse(Operation: CC, /* Integer inverse */ Type: MVT::i32);
18263
18264 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
18265 return (CC == ISD::SETEQ && Imm == 0) ||
18266 (CC == ISD::SETNE && Imm == 1) ||
18267 (CC == ISD::SETLT && Imm == 1) ||
18268 (CC == ISD::SETULT && Imm == 1);
18269 };
18270
18271 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
18272 return (CC == ISD::SETEQ && Imm == 1) ||
18273 (CC == ISD::SETNE && Imm == 0) ||
18274 (CC == ISD::SETGT && Imm == 0) ||
18275 (CC == ISD::SETUGT && Imm == 0) ||
18276 (CC == ISD::SETGE && Imm == 1) ||
18277 (CC == ISD::SETUGE && Imm == 1);
18278 };
18279
18280 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
18281 "unsupported condition");
18282
18283 SDLoc dl(Int);
18284 SelectionDAG &DAG = DCI.DAG;
18285 SDValue Elements = Int.getOperand(i: 2);
18286 unsigned IntOp = Int->getConstantOperandVal(Num: 1);
18287 assert((N->hasOneUse() && N->user_begin()->getOpcode() == ISD::BR) &&
18288 "expected single br user");
18289 SDNode *Br = *N->user_begin();
18290 SDValue OtherTarget = Br->getOperand(Num: 1);
18291
18292 // Update the unconditional branch to branch to the given Dest.
18293 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
18294 SDValue NewBrOps[] = { Br->getOperand(Num: 0), Dest };
18295 SDValue NewBr = DAG.getNode(Opcode: ISD::BR, DL: SDLoc(Br), VT: MVT::Other, Ops: NewBrOps);
18296 DAG.ReplaceAllUsesOfValueWith(From: SDValue(Br, 0), To: NewBr);
18297 };
18298
18299 if (IntOp == Intrinsic::test_start_loop_iterations) {
18300 SDValue Res;
18301 SDValue Setup = DAG.getNode(Opcode: ARMISD::WLSSETUP, DL: dl, VT: MVT::i32, Operand: Elements);
18302 // We expect this 'instruction' to branch when the counter is zero.
18303 if (IsTrueIfZero(CC, Imm)) {
18304 SDValue Ops[] = {Chain, Setup, Dest};
18305 Res = DAG.getNode(Opcode: ARMISD::WLS, DL: dl, VT: MVT::Other, Ops);
18306 } else {
18307 // The logic is the reverse of what we need for WLS, so find the other
18308 // basic block target: the target of the proceeding br.
18309 UpdateUncondBr(Br, Dest, DAG);
18310
18311 SDValue Ops[] = {Chain, Setup, OtherTarget};
18312 Res = DAG.getNode(Opcode: ARMISD::WLS, DL: dl, VT: MVT::Other, Ops);
18313 }
18314 // Update LR count to the new value
18315 DAG.ReplaceAllUsesOfValueWith(From: Int.getValue(R: 0), To: Setup);
18316 // Update chain
18317 DAG.ReplaceAllUsesOfValueWith(From: Int.getValue(R: 2), To: Int.getOperand(i: 0));
18318 return Res;
18319 } else {
18320 SDValue Size =
18321 DAG.getTargetConstant(Val: Int.getConstantOperandVal(i: 3), DL: dl, VT: MVT::i32);
18322 SDValue Args[] = { Int.getOperand(i: 0), Elements, Size, };
18323 SDValue LoopDec = DAG.getNode(Opcode: ARMISD::LOOP_DEC, DL: dl,
18324 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), Ops: Args);
18325 DAG.ReplaceAllUsesWith(From: Int.getNode(), To: LoopDec.getNode());
18326
18327 // We expect this instruction to branch when the count is not zero.
18328 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
18329
18330 // Update the unconditional branch to target the loop preheader if we've
18331 // found the condition has been reversed.
18332 if (Target == OtherTarget)
18333 UpdateUncondBr(Br, Dest, DAG);
18334
18335 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
18336 N1: SDValue(LoopDec.getNode(), 1), N2: Chain);
18337
18338 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
18339 return DAG.getNode(Opcode: ARMISD::LE, DL: dl, VT: MVT::Other, Ops: EndArgs);
18340 }
18341 return SDValue();
18342}
18343
18344/// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
18345SDValue
18346ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
18347 SDValue Cmp = N->getOperand(Num: 3);
18348 if (Cmp.getOpcode() != ARMISD::CMPZ)
18349 // Only looking at NE cases.
18350 return SDValue();
18351
18352 SDLoc dl(N);
18353 SDValue LHS = Cmp.getOperand(i: 0);
18354 SDValue RHS = Cmp.getOperand(i: 1);
18355 SDValue Chain = N->getOperand(Num: 0);
18356 SDValue BB = N->getOperand(Num: 1);
18357 SDValue ARMcc = N->getOperand(Num: 2);
18358 ARMCC::CondCodes CC = (ARMCC::CondCodes)ARMcc->getAsZExtVal();
18359
18360 // (brcond Chain BB ne (cmpz (and (cmov 0 1 CC Flags) 1) 0))
18361 // -> (brcond Chain BB CC Flags)
18362 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
18363 LHS->getOperand(Num: 0)->getOpcode() == ARMISD::CMOV &&
18364 LHS->getOperand(Num: 0)->hasOneUse() &&
18365 isNullConstant(V: LHS->getOperand(Num: 0)->getOperand(Num: 0)) &&
18366 isOneConstant(V: LHS->getOperand(Num: 0)->getOperand(Num: 1)) &&
18367 isOneConstant(V: LHS->getOperand(Num: 1)) && isNullConstant(V: RHS)) {
18368 return DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, N1: Chain, N2: BB,
18369 N3: LHS->getOperand(Num: 0)->getOperand(Num: 2),
18370 N4: LHS->getOperand(Num: 0)->getOperand(Num: 3));
18371 }
18372
18373 return SDValue();
18374}
18375
18376/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
18377SDValue
18378ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
18379 SDLoc dl(N);
18380 EVT VT = N->getValueType(ResNo: 0);
18381 SDValue FalseVal = N->getOperand(Num: 0);
18382 SDValue TrueVal = N->getOperand(Num: 1);
18383 SDValue ARMcc = N->getOperand(Num: 2);
18384 SDValue Cmp = N->getOperand(Num: 3);
18385
18386 // Try to form CSINV etc.
18387 unsigned Opcode;
18388 bool InvertCond;
18389 if (SDValue CSetOp =
18390 matchCSET(Opcode, InvertCond, TrueVal, FalseVal, Subtarget)) {
18391 if (InvertCond) {
18392 ARMCC::CondCodes CondCode =
18393 (ARMCC::CondCodes)cast<const ConstantSDNode>(Val&: ARMcc)->getZExtValue();
18394 CondCode = ARMCC::getOppositeCondition(CC: CondCode);
18395 ARMcc = DAG.getConstant(Val: CondCode, DL: SDLoc(ARMcc), VT: MVT::i32);
18396 }
18397 return DAG.getNode(Opcode, DL: dl, VT, N1: CSetOp, N2: CSetOp, N3: ARMcc, N4: Cmp);
18398 }
18399
18400 if (Cmp.getOpcode() != ARMISD::CMPZ)
18401 // Only looking at EQ and NE cases.
18402 return SDValue();
18403
18404 SDValue LHS = Cmp.getOperand(i: 0);
18405 SDValue RHS = Cmp.getOperand(i: 1);
18406 ARMCC::CondCodes CC = (ARMCC::CondCodes)ARMcc->getAsZExtVal();
18407
18408 // BFI is only available on V6T2+.
18409 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
18410 SDValue R = PerformCMOVToBFICombine(CMOV: N, DAG);
18411 if (R)
18412 return R;
18413 }
18414
18415 // Simplify
18416 // mov r1, r0
18417 // cmp r1, x
18418 // mov r0, y
18419 // moveq r0, x
18420 // to
18421 // cmp r0, x
18422 // movne r0, y
18423 //
18424 // mov r1, r0
18425 // cmp r1, x
18426 // mov r0, x
18427 // movne r0, y
18428 // to
18429 // cmp r0, x
18430 // movne r0, y
18431 /// FIXME: Turn this into a target neutral optimization?
18432 SDValue Res;
18433 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
18434 Res = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: LHS, N2: TrueVal, N3: ARMcc, N4: Cmp);
18435 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
18436 SDValue ARMcc;
18437 SDValue NewCmp = getARMCmp(LHS, RHS, CC: ISD::SETNE, ARMcc, DAG, dl);
18438 Res = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: LHS, N2: FalseVal, N3: ARMcc, N4: NewCmp);
18439 }
18440
18441 // (cmov F T ne (cmpz (cmov 0 1 CC Flags) 0))
18442 // -> (cmov F T CC Flags)
18443 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse() &&
18444 isNullConstant(V: LHS->getOperand(Num: 0)) && isOneConstant(V: LHS->getOperand(Num: 1)) &&
18445 isNullConstant(V: RHS)) {
18446 return DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: FalseVal, N2: TrueVal,
18447 N3: LHS->getOperand(Num: 2), N4: LHS->getOperand(Num: 3));
18448 }
18449
18450 if (!VT.isInteger())
18451 return SDValue();
18452
18453 // Fold away an unnecessary CMPZ/CMOV
18454 // CMOV A, B, C1, (CMPZ (CMOV 1, 0, C2, D), 0) ->
18455 // if C1==EQ -> CMOV A, B, C2, D
18456 // if C1==NE -> CMOV A, B, NOT(C2), D
18457 if (N->getConstantOperandVal(Num: 2) == ARMCC::EQ ||
18458 N->getConstantOperandVal(Num: 2) == ARMCC::NE) {
18459 ARMCC::CondCodes Cond;
18460 if (SDValue C = IsCMPZCSINC(Cmp: N->getOperand(Num: 3).getNode(), CC&: Cond)) {
18461 if (N->getConstantOperandVal(Num: 2) == ARMCC::NE)
18462 Cond = ARMCC::getOppositeCondition(CC: Cond);
18463 return DAG.getNode(Opcode: N->getOpcode(), DL: SDLoc(N), VT: MVT::i32, N1: N->getOperand(Num: 0),
18464 N2: N->getOperand(Num: 1),
18465 N3: DAG.getConstant(Val: Cond, DL: SDLoc(N), VT: MVT::i32), N4: C);
18466 }
18467 }
18468
18469 // Materialize a boolean comparison for integers so we can avoid branching.
18470 if (isNullConstant(V: FalseVal)) {
18471 if (CC == ARMCC::EQ && isOneConstant(V: TrueVal)) {
18472 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
18473 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
18474 // right 5 bits will make that 32 be 1, otherwise it will be 0.
18475 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
18476 SDValue Sub = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: LHS, N2: RHS);
18477 Res = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: DAG.getNode(Opcode: ISD::CTLZ, DL: dl, VT, Operand: Sub),
18478 N2: DAG.getConstant(Val: 5, DL: dl, VT: MVT::i32));
18479 } else {
18480 // CMOV 0, 1, ==, (CMPZ x, y) ->
18481 // (UADDO_CARRY (SUB x, y), t:0, t:1)
18482 // where t = (USUBO_CARRY 0, (SUB x, y), 0)
18483 //
18484 // The USUBO_CARRY computes 0 - (x - y) and this will give a borrow when
18485 // x != y. In other words, a carry C == 1 when x == y, C == 0
18486 // otherwise.
18487 // The final UADDO_CARRY computes
18488 // x - y + (0 - (x - y)) + C == C
18489 SDValue Sub = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: LHS, N2: RHS);
18490 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::i32);
18491 SDValue Neg = DAG.getNode(Opcode: ISD::USUBO, DL: dl, VTList: VTs, N1: FalseVal, N2: Sub);
18492 // ISD::USUBO_CARRY returns a borrow but we want the carry here
18493 // actually.
18494 SDValue Carry =
18495 DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
18496 N1: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32), N2: Neg.getValue(R: 1));
18497 Res = DAG.getNode(Opcode: ISD::UADDO_CARRY, DL: dl, VTList: VTs, N1: Sub, N2: Neg, N3: Carry);
18498 }
18499 } else if (CC == ARMCC::NE && !isNullConstant(V: RHS) &&
18500 (!Subtarget->isThumb1Only() || isPowerOf2Constant(V: TrueVal))) {
18501 // This seems pointless but will allow us to combine it further below.
18502 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
18503 SDValue Sub =
18504 DAG.getNode(Opcode: ARMISD::SUBC, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: MVT::i32), N1: LHS, N2: RHS);
18505 Res = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: Sub, N2: TrueVal, N3: ARMcc,
18506 N4: Sub.getValue(R: 1));
18507 FalseVal = Sub;
18508 }
18509 } else if (isNullConstant(V: TrueVal)) {
18510 if (CC == ARMCC::EQ && !isNullConstant(V: RHS) &&
18511 (!Subtarget->isThumb1Only() || isPowerOf2Constant(V: FalseVal))) {
18512 // This seems pointless but will allow us to combine it further below
18513 // Note that we change == for != as this is the dual for the case above.
18514 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
18515 SDValue Sub =
18516 DAG.getNode(Opcode: ARMISD::SUBC, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: MVT::i32), N1: LHS, N2: RHS);
18517 Res = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: Sub, N2: FalseVal,
18518 N3: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32),
18519 N4: Sub.getValue(R: 1));
18520 FalseVal = Sub;
18521 }
18522 }
18523
18524 // On Thumb1, the DAG above may be further combined if z is a power of 2
18525 // (z == 2 ^ K).
18526 // CMOV (SUBC x, y), z, !=, (SUBC x, y):1 ->
18527 // t1 = (USUBO (SUB x, y), 1)
18528 // t2 = (USUBO_CARRY (SUB x, y), t1:0, t1:1)
18529 // Result = if K != 0 then (SHL t2:0, K) else t2:0
18530 //
18531 // This also handles the special case of comparing against zero; it's
18532 // essentially, the same pattern, except there's no SUBC:
18533 // CMOV x, z, !=, (CMPZ x, 0) ->
18534 // t1 = (USUBO x, 1)
18535 // t2 = (USUBO_CARRY x, t1:0, t1:1)
18536 // Result = if K != 0 then (SHL t2:0, K) else t2:0
18537 const APInt *TrueConst;
18538 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
18539 ((FalseVal.getOpcode() == ARMISD::SUBC && FalseVal.getOperand(i: 0) == LHS &&
18540 FalseVal.getOperand(i: 1) == RHS) ||
18541 (FalseVal == LHS && isNullConstant(V: RHS))) &&
18542 (TrueConst = isPowerOf2Constant(V: TrueVal))) {
18543 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::i32);
18544 unsigned ShiftAmount = TrueConst->logBase2();
18545 if (ShiftAmount)
18546 TrueVal = DAG.getConstant(Val: 1, DL: dl, VT);
18547 SDValue Subc = DAG.getNode(Opcode: ISD::USUBO, DL: dl, VTList: VTs, N1: FalseVal, N2: TrueVal);
18548 Res = DAG.getNode(Opcode: ISD::USUBO_CARRY, DL: dl, VTList: VTs, N1: FalseVal, N2: Subc,
18549 N3: Subc.getValue(R: 1));
18550
18551 if (ShiftAmount)
18552 Res = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: Res,
18553 N2: DAG.getConstant(Val: ShiftAmount, DL: dl, VT: MVT::i32));
18554 }
18555
18556 if (Res.getNode()) {
18557 KnownBits Known = DAG.computeKnownBits(Op: SDValue(N,0));
18558 // Capture demanded bits information that would be otherwise lost.
18559 if (Known.Zero == 0xfffffffe)
18560 Res = DAG.getNode(Opcode: ISD::AssertZext, DL: dl, VT: MVT::i32, N1: Res,
18561 N2: DAG.getValueType(MVT::i1));
18562 else if (Known.Zero == 0xffffff00)
18563 Res = DAG.getNode(Opcode: ISD::AssertZext, DL: dl, VT: MVT::i32, N1: Res,
18564 N2: DAG.getValueType(MVT::i8));
18565 else if (Known.Zero == 0xffff0000)
18566 Res = DAG.getNode(Opcode: ISD::AssertZext, DL: dl, VT: MVT::i32, N1: Res,
18567 N2: DAG.getValueType(MVT::i16));
18568 }
18569
18570 return Res;
18571}
18572
18573static SDValue PerformBITCASTCombine(SDNode *N,
18574 TargetLowering::DAGCombinerInfo &DCI,
18575 const ARMSubtarget *ST) {
18576 SelectionDAG &DAG = DCI.DAG;
18577 SDValue Src = N->getOperand(Num: 0);
18578 EVT DstVT = N->getValueType(ResNo: 0);
18579
18580 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
18581 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
18582 EVT SrcVT = Src.getValueType();
18583 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
18584 return DAG.getNode(Opcode: ARMISD::VDUP, DL: SDLoc(N), VT: DstVT, Operand: Src.getOperand(i: 0));
18585 }
18586
18587 // We may have a bitcast of something that has already had this bitcast
18588 // combine performed on it, so skip past any VECTOR_REG_CASTs.
18589 if (Src.getOpcode() == ARMISD::VECTOR_REG_CAST &&
18590 Src.getOperand(i: 0).getValueType().getScalarSizeInBits() <=
18591 Src.getValueType().getScalarSizeInBits())
18592 Src = Src.getOperand(i: 0);
18593
18594 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
18595 // would be generated is at least the width of the element type.
18596 EVT SrcVT = Src.getValueType();
18597 if ((Src.getOpcode() == ARMISD::VMOVIMM ||
18598 Src.getOpcode() == ARMISD::VMVNIMM ||
18599 Src.getOpcode() == ARMISD::VMOVFPIMM) &&
18600 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
18601 DAG.getDataLayout().isBigEndian())
18602 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: SDLoc(N), VT: DstVT, Operand: Src);
18603
18604 // bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD x
18605 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
18606 return R;
18607
18608 return SDValue();
18609}
18610
18611// Some combines for the MVETrunc truncations legalizer helper. Also lowers the
18612// node into stack operations after legalizeOps.
18613SDValue ARMTargetLowering::PerformMVETruncCombine(
18614 SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
18615 SelectionDAG &DAG = DCI.DAG;
18616 EVT VT = N->getValueType(ResNo: 0);
18617 SDLoc DL(N);
18618
18619 // MVETrunc(Undef, Undef) -> Undef
18620 if (all_of(Range: N->ops(), P: [](SDValue Op) { return Op.isUndef(); }))
18621 return DAG.getUNDEF(VT);
18622
18623 // MVETrunc(MVETrunc a b, MVETrunc c, d) -> MVETrunc
18624 if (N->getNumOperands() == 2 &&
18625 N->getOperand(Num: 0).getOpcode() == ARMISD::MVETRUNC &&
18626 N->getOperand(Num: 1).getOpcode() == ARMISD::MVETRUNC)
18627 return DAG.getNode(Opcode: ARMISD::MVETRUNC, DL, VT, N1: N->getOperand(Num: 0).getOperand(i: 0),
18628 N2: N->getOperand(Num: 0).getOperand(i: 1),
18629 N3: N->getOperand(Num: 1).getOperand(i: 0),
18630 N4: N->getOperand(Num: 1).getOperand(i: 1));
18631
18632 // MVETrunc(shuffle, shuffle) -> VMOVN
18633 if (N->getNumOperands() == 2 &&
18634 N->getOperand(Num: 0).getOpcode() == ISD::VECTOR_SHUFFLE &&
18635 N->getOperand(Num: 1).getOpcode() == ISD::VECTOR_SHUFFLE) {
18636 auto *S0 = cast<ShuffleVectorSDNode>(Val: N->getOperand(Num: 0).getNode());
18637 auto *S1 = cast<ShuffleVectorSDNode>(Val: N->getOperand(Num: 1).getNode());
18638
18639 if (S0->getOperand(Num: 0) == S1->getOperand(Num: 0) &&
18640 S0->getOperand(Num: 1) == S1->getOperand(Num: 1)) {
18641 // Construct complete shuffle mask
18642 SmallVector<int, 8> Mask(S0->getMask());
18643 Mask.append(in_start: S1->getMask().begin(), in_end: S1->getMask().end());
18644
18645 if (isVMOVNTruncMask(M: Mask, ToVT: VT, rev: false))
18646 return DAG.getNode(
18647 Opcode: ARMISD::VMOVN, DL, VT,
18648 N1: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: S0->getOperand(Num: 0)),
18649 N2: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: S0->getOperand(Num: 1)),
18650 N3: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
18651 if (isVMOVNTruncMask(M: Mask, ToVT: VT, rev: true))
18652 return DAG.getNode(
18653 Opcode: ARMISD::VMOVN, DL, VT,
18654 N1: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: S0->getOperand(Num: 1)),
18655 N2: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: S0->getOperand(Num: 0)),
18656 N3: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
18657 }
18658 }
18659
18660 // For MVETrunc of a buildvector or shuffle, it can be beneficial to lower the
18661 // truncate to a buildvector to allow the generic optimisations to kick in.
18662 if (all_of(Range: N->ops(), P: [](SDValue Op) {
18663 return Op.getOpcode() == ISD::BUILD_VECTOR ||
18664 Op.getOpcode() == ISD::VECTOR_SHUFFLE ||
18665 (Op.getOpcode() == ISD::BITCAST &&
18666 Op.getOperand(i: 0).getOpcode() == ISD::BUILD_VECTOR);
18667 })) {
18668 SmallVector<SDValue, 8> Extracts;
18669 for (unsigned Op = 0; Op < N->getNumOperands(); Op++) {
18670 SDValue O = N->getOperand(Num: Op);
18671 for (unsigned i = 0; i < O.getValueType().getVectorNumElements(); i++) {
18672 SDValue Ext = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i32, N1: O,
18673 N2: DAG.getConstant(Val: i, DL, VT: MVT::i32));
18674 Extracts.push_back(Elt: Ext);
18675 }
18676 }
18677 return DAG.getBuildVector(VT, DL, Ops: Extracts);
18678 }
18679
18680 // If we are late in the legalization process and nothing has optimised
18681 // the trunc to anything better, lower it to a stack store and reload,
18682 // performing the truncation whilst keeping the lanes in the correct order:
18683 // VSTRH.32 a, stack; VSTRH.32 b, stack+8; VLDRW.32 stack;
18684 if (!DCI.isAfterLegalizeDAG())
18685 return SDValue();
18686
18687 SDValue StackPtr = DAG.CreateStackTemporary(Bytes: TypeSize::getFixed(ExactSize: 16), Alignment: Align(4));
18688 int SPFI = cast<FrameIndexSDNode>(Val: StackPtr.getNode())->getIndex();
18689 int NumIns = N->getNumOperands();
18690 assert((NumIns == 2 || NumIns == 4) &&
18691 "Expected 2 or 4 inputs to an MVETrunc");
18692 EVT StoreVT = VT.getHalfNumVectorElementsVT(Context&: *DAG.getContext());
18693 if (N->getNumOperands() == 4)
18694 StoreVT = StoreVT.getHalfNumVectorElementsVT(Context&: *DAG.getContext());
18695
18696 SmallVector<SDValue> Chains;
18697 for (int I = 0; I < NumIns; I++) {
18698 SDValue Ptr = DAG.getNode(
18699 Opcode: ISD::ADD, DL, VT: StackPtr.getValueType(), N1: StackPtr,
18700 N2: DAG.getConstant(Val: I * 16 / NumIns, DL, VT: StackPtr.getValueType()));
18701 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
18702 MF&: DAG.getMachineFunction(), FI: SPFI, Offset: I * 16 / NumIns);
18703 SDValue Ch = DAG.getTruncStore(Chain: DAG.getEntryNode(), dl: DL, Val: N->getOperand(Num: I),
18704 Ptr, PtrInfo: MPI, SVT: StoreVT, Alignment: Align(4));
18705 Chains.push_back(Elt: Ch);
18706 }
18707
18708 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Chains);
18709 MachinePointerInfo MPI =
18710 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI, Offset: 0);
18711 return DAG.getLoad(VT, dl: DL, Chain, Ptr: StackPtr, PtrInfo: MPI, Alignment: Align(4));
18712}
18713
18714// Take a MVEEXT(load x) and split that into (extload x, extload x+8)
18715static SDValue PerformSplittingMVEEXTToWideningLoad(SDNode *N,
18716 SelectionDAG &DAG) {
18717 SDValue N0 = N->getOperand(Num: 0);
18718 LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: N0.getNode());
18719 if (!LD || !LD->isSimple() || !N0.hasOneUse() || LD->isIndexed())
18720 return SDValue();
18721
18722 EVT FromVT = LD->getMemoryVT();
18723 EVT ToVT = N->getValueType(ResNo: 0);
18724 if (!ToVT.isVector())
18725 return SDValue();
18726 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2);
18727 EVT ToEltVT = ToVT.getVectorElementType();
18728 EVT FromEltVT = FromVT.getVectorElementType();
18729
18730 unsigned NumElements = 0;
18731 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
18732 NumElements = 4;
18733 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
18734 NumElements = 8;
18735 assert(NumElements != 0);
18736
18737 ISD::LoadExtType NewExtType =
18738 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
18739 if (LD->getExtensionType() != ISD::NON_EXTLOAD &&
18740 LD->getExtensionType() != ISD::EXTLOAD &&
18741 LD->getExtensionType() != NewExtType)
18742 return SDValue();
18743
18744 LLVMContext &C = *DAG.getContext();
18745 SDLoc DL(LD);
18746 // Details about the old load
18747 SDValue Ch = LD->getChain();
18748 SDValue BasePtr = LD->getBasePtr();
18749 Align Alignment = LD->getBaseAlign();
18750 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
18751 AAMDNodes AAInfo = LD->getAAInfo();
18752
18753 SDValue Offset = DAG.getUNDEF(VT: BasePtr.getValueType());
18754 EVT NewFromVT = EVT::getVectorVT(
18755 Context&: C, VT: EVT::getIntegerVT(Context&: C, BitWidth: FromEltVT.getScalarSizeInBits()), NumElements);
18756 EVT NewToVT = EVT::getVectorVT(
18757 Context&: C, VT: EVT::getIntegerVT(Context&: C, BitWidth: ToEltVT.getScalarSizeInBits()), NumElements);
18758
18759 SmallVector<SDValue, 4> Loads;
18760 SmallVector<SDValue, 4> Chains;
18761 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
18762 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
18763 SDValue NewPtr =
18764 DAG.getObjectPtrOffset(SL: DL, Ptr: BasePtr, Offset: TypeSize::getFixed(ExactSize: NewOffset));
18765
18766 SDValue NewLoad =
18767 DAG.getLoad(AM: ISD::UNINDEXED, ExtType: NewExtType, VT: NewToVT, dl: DL, Chain: Ch, Ptr: NewPtr, Offset,
18768 PtrInfo: LD->getPointerInfo().getWithOffset(O: NewOffset), MemVT: NewFromVT,
18769 Alignment, MMOFlags, AAInfo);
18770 Loads.push_back(Elt: NewLoad);
18771 Chains.push_back(Elt: SDValue(NewLoad.getNode(), 1));
18772 }
18773
18774 SDValue NewChain = DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Chains);
18775 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 1), To: NewChain);
18776 return DAG.getMergeValues(Ops: Loads, dl: DL);
18777}
18778
18779// Perform combines for MVEEXT. If it has not be optimized to anything better
18780// before lowering, it gets converted to stack store and extloads performing the
18781// extend whilst still keeping the same lane ordering.
18782SDValue ARMTargetLowering::PerformMVEExtCombine(
18783 SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
18784 SelectionDAG &DAG = DCI.DAG;
18785 EVT VT = N->getValueType(ResNo: 0);
18786 SDLoc DL(N);
18787 assert(N->getNumValues() == 2 && "Expected MVEEXT with 2 elements");
18788 assert((VT == MVT::v4i32 || VT == MVT::v8i16) && "Unexpected MVEEXT type");
18789
18790 EVT ExtVT = N->getOperand(Num: 0).getValueType().getHalfNumVectorElementsVT(
18791 Context&: *DAG.getContext());
18792 auto Extend = [&](SDValue V) {
18793 SDValue VVT = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: V);
18794 return N->getOpcode() == ARMISD::MVESEXT
18795 ? DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL, VT, N1: VVT,
18796 N2: DAG.getValueType(ExtVT))
18797 : DAG.getZeroExtendInReg(Op: VVT, DL, VT: ExtVT);
18798 };
18799
18800 // MVEEXT(VDUP) -> SIGN_EXTEND_INREG(VDUP)
18801 if (N->getOperand(Num: 0).getOpcode() == ARMISD::VDUP) {
18802 SDValue Ext = Extend(N->getOperand(Num: 0));
18803 return DAG.getMergeValues(Ops: {Ext, Ext}, dl: DL);
18804 }
18805
18806 // MVEEXT(shuffle) -> SIGN_EXTEND_INREG/ZERO_EXTEND_INREG
18807 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Val: N->getOperand(Num: 0))) {
18808 ArrayRef<int> Mask = SVN->getMask();
18809 assert(Mask.size() == 2 * VT.getVectorNumElements());
18810 assert(Mask.size() == SVN->getValueType(0).getVectorNumElements());
18811 unsigned Rev = VT == MVT::v4i32 ? ARMISD::VREV32 : ARMISD::VREV16;
18812 SDValue Op0 = SVN->getOperand(Num: 0);
18813 SDValue Op1 = SVN->getOperand(Num: 1);
18814
18815 auto CheckInregMask = [&](int Start, int Offset) {
18816 for (int Idx = 0, E = VT.getVectorNumElements(); Idx < E; ++Idx)
18817 if (Mask[Start + Idx] >= 0 && Mask[Start + Idx] != Idx * 2 + Offset)
18818 return false;
18819 return true;
18820 };
18821 SDValue V0 = SDValue(N, 0);
18822 SDValue V1 = SDValue(N, 1);
18823 if (CheckInregMask(0, 0))
18824 V0 = Extend(Op0);
18825 else if (CheckInregMask(0, 1))
18826 V0 = Extend(DAG.getNode(Opcode: Rev, DL, VT: SVN->getValueType(ResNo: 0), Operand: Op0));
18827 else if (CheckInregMask(0, Mask.size()))
18828 V0 = Extend(Op1);
18829 else if (CheckInregMask(0, Mask.size() + 1))
18830 V0 = Extend(DAG.getNode(Opcode: Rev, DL, VT: SVN->getValueType(ResNo: 0), Operand: Op1));
18831
18832 if (CheckInregMask(VT.getVectorNumElements(), Mask.size()))
18833 V1 = Extend(Op1);
18834 else if (CheckInregMask(VT.getVectorNumElements(), Mask.size() + 1))
18835 V1 = Extend(DAG.getNode(Opcode: Rev, DL, VT: SVN->getValueType(ResNo: 0), Operand: Op1));
18836 else if (CheckInregMask(VT.getVectorNumElements(), 0))
18837 V1 = Extend(Op0);
18838 else if (CheckInregMask(VT.getVectorNumElements(), 1))
18839 V1 = Extend(DAG.getNode(Opcode: Rev, DL, VT: SVN->getValueType(ResNo: 0), Operand: Op0));
18840
18841 if (V0.getNode() != N || V1.getNode() != N)
18842 return DAG.getMergeValues(Ops: {V0, V1}, dl: DL);
18843 }
18844
18845 // MVEEXT(load) -> extload, extload
18846 if (N->getOperand(Num: 0)->getOpcode() == ISD::LOAD)
18847 if (SDValue L = PerformSplittingMVEEXTToWideningLoad(N, DAG))
18848 return L;
18849
18850 if (!DCI.isAfterLegalizeDAG())
18851 return SDValue();
18852
18853 // Lower to a stack store and reload:
18854 // VSTRW.32 a, stack; VLDRH.32 stack; VLDRH.32 stack+8;
18855 SDValue StackPtr = DAG.CreateStackTemporary(Bytes: TypeSize::getFixed(ExactSize: 16), Alignment: Align(4));
18856 int SPFI = cast<FrameIndexSDNode>(Val: StackPtr.getNode())->getIndex();
18857 int NumOuts = N->getNumValues();
18858 assert((NumOuts == 2 || NumOuts == 4) &&
18859 "Expected 2 or 4 outputs to an MVEEXT");
18860 EVT LoadVT = N->getOperand(Num: 0).getValueType().getHalfNumVectorElementsVT(
18861 Context&: *DAG.getContext());
18862 if (N->getNumOperands() == 4)
18863 LoadVT = LoadVT.getHalfNumVectorElementsVT(Context&: *DAG.getContext());
18864
18865 MachinePointerInfo MPI =
18866 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI, Offset: 0);
18867 SDValue Chain = DAG.getStore(Chain: DAG.getEntryNode(), dl: DL, Val: N->getOperand(Num: 0),
18868 Ptr: StackPtr, PtrInfo: MPI, Alignment: Align(4));
18869
18870 SmallVector<SDValue> Loads;
18871 for (int I = 0; I < NumOuts; I++) {
18872 SDValue Ptr = DAG.getNode(
18873 Opcode: ISD::ADD, DL, VT: StackPtr.getValueType(), N1: StackPtr,
18874 N2: DAG.getConstant(Val: I * 16 / NumOuts, DL, VT: StackPtr.getValueType()));
18875 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
18876 MF&: DAG.getMachineFunction(), FI: SPFI, Offset: I * 16 / NumOuts);
18877 SDValue Load = DAG.getExtLoad(
18878 ExtType: N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD, dl: DL,
18879 VT, Chain, Ptr, PtrInfo: MPI, MemVT: LoadVT, Alignment: Align(4));
18880 Loads.push_back(Elt: Load);
18881 }
18882
18883 return DAG.getMergeValues(Ops: Loads, dl: DL);
18884}
18885
18886SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
18887 DAGCombinerInfo &DCI) const {
18888 switch (N->getOpcode()) {
18889 default: break;
18890 case ISD::SELECT_CC:
18891 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget);
18892 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget);
18893 case ISD::SETCC: return PerformVSetCCToVCTPCombine(N, DCI, Subtarget);
18894 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
18895 case ARMISD::UMLAL: return PerformUMLALCombine(N, DAG&: DCI.DAG, Subtarget);
18896 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
18897 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget);
18898 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
18899 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
18900 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
18901 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
18902 case ISD::BRCOND:
18903 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, ST: Subtarget);
18904 case ARMISD::ADDC:
18905 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
18906 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
18907 case ARMISD::BFI: return PerformBFICombine(N, DAG&: DCI.DAG);
18908 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
18909 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DAG&: DCI.DAG);
18910 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI);
18911 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DAG&: DCI.DAG);
18912 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
18913 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
18914 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
18915 case ISD::EXTRACT_VECTOR_ELT:
18916 return PerformExtractEltCombine(N, DCI, ST: Subtarget);
18917 case ISD::SIGN_EXTEND_INREG: return PerformSignExtendInregCombine(N, DAG&: DCI.DAG);
18918 case ISD::INSERT_SUBVECTOR: return PerformInsertSubvectorCombine(N, DCI);
18919 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DAG&: DCI.DAG);
18920 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
18921 case ARMISD::VDUP: return PerformVDUPCombine(N, DAG&: DCI.DAG, Subtarget);
18922 case ISD::FP_TO_SINT:
18923 case ISD::FP_TO_UINT:
18924 return PerformVCVTCombine(N, DAG&: DCI.DAG, Subtarget);
18925 case ISD::FADD:
18926 return PerformFADDCombine(N, DAG&: DCI.DAG, Subtarget);
18927 case ISD::FMUL:
18928 return PerformVMulVCTPCombine(N, DAG&: DCI.DAG, Subtarget);
18929 case ISD::INTRINSIC_WO_CHAIN:
18930 return PerformIntrinsicCombine(N, DCI);
18931 case ISD::SHL:
18932 case ISD::SRA:
18933 case ISD::SRL:
18934 return PerformShiftCombine(N, DCI, ST: Subtarget);
18935 case ISD::SIGN_EXTEND:
18936 case ISD::ZERO_EXTEND:
18937 case ISD::ANY_EXTEND:
18938 return PerformExtendCombine(N, DAG&: DCI.DAG, ST: Subtarget);
18939 case ISD::FP_EXTEND:
18940 return PerformFPExtendCombine(N, DAG&: DCI.DAG, ST: Subtarget);
18941 case ISD::SMIN:
18942 case ISD::UMIN:
18943 case ISD::SMAX:
18944 case ISD::UMAX:
18945 return PerformMinMaxCombine(N, DAG&: DCI.DAG, ST: Subtarget);
18946 case ARMISD::CMOV:
18947 return PerformCMOVCombine(N, DAG&: DCI.DAG);
18948 case ARMISD::BRCOND:
18949 return PerformBRCONDCombine(N, DAG&: DCI.DAG);
18950 case ARMISD::CMPZ:
18951 return PerformCMPZCombine(N, DAG&: DCI.DAG);
18952 case ARMISD::CSINC:
18953 case ARMISD::CSINV:
18954 case ARMISD::CSNEG:
18955 return PerformCSETCombine(N, DAG&: DCI.DAG);
18956 case ISD::LOAD:
18957 return PerformLOADCombine(N, DCI, Subtarget);
18958 case ARMISD::VLD1DUP:
18959 case ARMISD::VLD2DUP:
18960 case ARMISD::VLD3DUP:
18961 case ARMISD::VLD4DUP:
18962 return PerformVLDCombine(N, DCI);
18963 case ARMISD::BUILD_VECTOR:
18964 return PerformARMBUILD_VECTORCombine(N, DCI);
18965 case ISD::BITCAST:
18966 return PerformBITCASTCombine(N, DCI, ST: Subtarget);
18967 case ARMISD::PREDICATE_CAST:
18968 return PerformPREDICATE_CASTCombine(N, DCI);
18969 case ARMISD::VECTOR_REG_CAST:
18970 return PerformVECTOR_REG_CASTCombine(N, DAG&: DCI.DAG, ST: Subtarget);
18971 case ARMISD::MVETRUNC:
18972 return PerformMVETruncCombine(N, DCI);
18973 case ARMISD::MVESEXT:
18974 case ARMISD::MVEZEXT:
18975 return PerformMVEExtCombine(N, DCI);
18976 case ARMISD::VCMP:
18977 return PerformVCMPCombine(N, DAG&: DCI.DAG, Subtarget);
18978 case ISD::VECREDUCE_ADD:
18979 return PerformVECREDUCE_ADDCombine(N, DAG&: DCI.DAG, ST: Subtarget);
18980 case ARMISD::VADDVs:
18981 case ARMISD::VADDVu:
18982 case ARMISD::VADDLVs:
18983 case ARMISD::VADDLVu:
18984 case ARMISD::VADDLVAs:
18985 case ARMISD::VADDLVAu:
18986 case ARMISD::VMLAVs:
18987 case ARMISD::VMLAVu:
18988 case ARMISD::VMLALVs:
18989 case ARMISD::VMLALVu:
18990 case ARMISD::VMLALVAs:
18991 case ARMISD::VMLALVAu:
18992 return PerformReduceShuffleCombine(N, DAG&: DCI.DAG);
18993 case ARMISD::VMOVN:
18994 return PerformVMOVNCombine(N, DCI);
18995 case ARMISD::VQMOVNs:
18996 case ARMISD::VQMOVNu:
18997 return PerformVQMOVNCombine(N, DCI);
18998 case ARMISD::VQDMULH:
18999 return PerformVQDMULHCombine(N, DCI);
19000 case ARMISD::ASRL:
19001 case ARMISD::LSRL:
19002 case ARMISD::LSLL:
19003 return PerformLongShiftCombine(N, DAG&: DCI.DAG);
19004 case ARMISD::SMULWB: {
19005 unsigned BitWidth = N->getValueType(ResNo: 0).getSizeInBits();
19006 APInt DemandedMask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: 16);
19007 if (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI))
19008 return SDValue();
19009 break;
19010 }
19011 case ARMISD::SMULWT: {
19012 unsigned BitWidth = N->getValueType(ResNo: 0).getSizeInBits();
19013 APInt DemandedMask = APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: 16);
19014 if (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI))
19015 return SDValue();
19016 break;
19017 }
19018 case ARMISD::SMLALBB:
19019 case ARMISD::QADD16b:
19020 case ARMISD::QSUB16b:
19021 case ARMISD::UQADD16b:
19022 case ARMISD::UQSUB16b: {
19023 unsigned BitWidth = N->getValueType(ResNo: 0).getSizeInBits();
19024 APInt DemandedMask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: 16);
19025 if ((SimplifyDemandedBits(Op: N->getOperand(Num: 0), DemandedBits: DemandedMask, DCI)) ||
19026 (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI)))
19027 return SDValue();
19028 break;
19029 }
19030 case ARMISD::SMLALBT: {
19031 unsigned LowWidth = N->getOperand(Num: 0).getValueType().getSizeInBits();
19032 APInt LowMask = APInt::getLowBitsSet(numBits: LowWidth, loBitsSet: 16);
19033 unsigned HighWidth = N->getOperand(Num: 1).getValueType().getSizeInBits();
19034 APInt HighMask = APInt::getHighBitsSet(numBits: HighWidth, hiBitsSet: 16);
19035 if ((SimplifyDemandedBits(Op: N->getOperand(Num: 0), DemandedBits: LowMask, DCI)) ||
19036 (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: HighMask, DCI)))
19037 return SDValue();
19038 break;
19039 }
19040 case ARMISD::SMLALTB: {
19041 unsigned HighWidth = N->getOperand(Num: 0).getValueType().getSizeInBits();
19042 APInt HighMask = APInt::getHighBitsSet(numBits: HighWidth, hiBitsSet: 16);
19043 unsigned LowWidth = N->getOperand(Num: 1).getValueType().getSizeInBits();
19044 APInt LowMask = APInt::getLowBitsSet(numBits: LowWidth, loBitsSet: 16);
19045 if ((SimplifyDemandedBits(Op: N->getOperand(Num: 0), DemandedBits: HighMask, DCI)) ||
19046 (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: LowMask, DCI)))
19047 return SDValue();
19048 break;
19049 }
19050 case ARMISD::SMLALTT: {
19051 unsigned BitWidth = N->getValueType(ResNo: 0).getSizeInBits();
19052 APInt DemandedMask = APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: 16);
19053 if ((SimplifyDemandedBits(Op: N->getOperand(Num: 0), DemandedBits: DemandedMask, DCI)) ||
19054 (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI)))
19055 return SDValue();
19056 break;
19057 }
19058 case ARMISD::QADD8b:
19059 case ARMISD::QSUB8b:
19060 case ARMISD::UQADD8b:
19061 case ARMISD::UQSUB8b: {
19062 unsigned BitWidth = N->getValueType(ResNo: 0).getSizeInBits();
19063 APInt DemandedMask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: 8);
19064 if ((SimplifyDemandedBits(Op: N->getOperand(Num: 0), DemandedBits: DemandedMask, DCI)) ||
19065 (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI)))
19066 return SDValue();
19067 break;
19068 }
19069 case ARMISD::VBSP:
19070 if (N->getOperand(Num: 1) == N->getOperand(Num: 2))
19071 return N->getOperand(Num: 1);
19072 return SDValue();
19073 case ISD::INTRINSIC_VOID:
19074 case ISD::INTRINSIC_W_CHAIN:
19075 switch (N->getConstantOperandVal(Num: 1)) {
19076 case Intrinsic::arm_neon_vld1:
19077 case Intrinsic::arm_neon_vld1x2:
19078 case Intrinsic::arm_neon_vld1x3:
19079 case Intrinsic::arm_neon_vld1x4:
19080 case Intrinsic::arm_neon_vld2:
19081 case Intrinsic::arm_neon_vld3:
19082 case Intrinsic::arm_neon_vld4:
19083 case Intrinsic::arm_neon_vld2lane:
19084 case Intrinsic::arm_neon_vld3lane:
19085 case Intrinsic::arm_neon_vld4lane:
19086 case Intrinsic::arm_neon_vld2dup:
19087 case Intrinsic::arm_neon_vld3dup:
19088 case Intrinsic::arm_neon_vld4dup:
19089 case Intrinsic::arm_neon_vst1:
19090 case Intrinsic::arm_neon_vst1x2:
19091 case Intrinsic::arm_neon_vst1x3:
19092 case Intrinsic::arm_neon_vst1x4:
19093 case Intrinsic::arm_neon_vst2:
19094 case Intrinsic::arm_neon_vst3:
19095 case Intrinsic::arm_neon_vst4:
19096 case Intrinsic::arm_neon_vst2lane:
19097 case Intrinsic::arm_neon_vst3lane:
19098 case Intrinsic::arm_neon_vst4lane:
19099 return PerformVLDCombine(N, DCI);
19100 case Intrinsic::arm_mve_vld2q:
19101 case Intrinsic::arm_mve_vld4q:
19102 case Intrinsic::arm_mve_vst2q:
19103 case Intrinsic::arm_mve_vst4q:
19104 return PerformMVEVLDCombine(N, DCI);
19105 default: break;
19106 }
19107 break;
19108 }
19109 return SDValue();
19110}
19111
19112bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
19113 EVT VT) const {
19114 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
19115}
19116
19117bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
19118 Align Alignment,
19119 MachineMemOperand::Flags,
19120 unsigned *Fast) const {
19121 // Depends what it gets converted into if the type is weird.
19122 if (!VT.isSimple())
19123 return false;
19124
19125 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
19126 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
19127 auto Ty = VT.getSimpleVT().SimpleTy;
19128
19129 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
19130 // Unaligned access can use (for example) LRDB, LRDH, LDR
19131 if (AllowsUnaligned) {
19132 if (Fast)
19133 *Fast = Subtarget->hasV7Ops();
19134 return true;
19135 }
19136 }
19137
19138 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
19139 // For any little-endian targets with neon, we can support unaligned ld/st
19140 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
19141 // A big-endian target may also explicitly support unaligned accesses
19142 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
19143 if (Fast)
19144 *Fast = 1;
19145 return true;
19146 }
19147 }
19148
19149 if (!Subtarget->hasMVEIntegerOps())
19150 return false;
19151
19152 // These are for predicates
19153 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1 ||
19154 Ty == MVT::v2i1)) {
19155 if (Fast)
19156 *Fast = 1;
19157 return true;
19158 }
19159
19160 // These are for truncated stores/narrowing loads. They are fine so long as
19161 // the alignment is at least the size of the item being loaded
19162 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
19163 Alignment >= VT.getScalarSizeInBits() / 8) {
19164 if (Fast)
19165 *Fast = true;
19166 return true;
19167 }
19168
19169 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
19170 // VSTRW.U32 all store the vector register in exactly the same format, and
19171 // differ only in the range of their immediate offset field and the required
19172 // alignment. So there is always a store that can be used, regardless of
19173 // actual type.
19174 //
19175 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
19176 // VREV64.8) pair and get the same effect. This will likely be better than
19177 // aligning the vector through the stack.
19178 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
19179 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
19180 Ty == MVT::v2f64) {
19181 if (Fast)
19182 *Fast = 1;
19183 return true;
19184 }
19185
19186 return false;
19187}
19188
19189EVT ARMTargetLowering::getOptimalMemOpType(
19190 LLVMContext &Context, const MemOp &Op,
19191 const AttributeList &FuncAttributes) const {
19192 // See if we can use NEON instructions for this...
19193 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
19194 !FuncAttributes.hasFnAttr(Kind: Attribute::NoImplicitFloat)) {
19195 unsigned Fast;
19196 if (Op.size() >= 16 &&
19197 (Op.isAligned(AlignCheck: Align(16)) ||
19198 (allowsMisalignedMemoryAccesses(VT: MVT::v2f64, 0, Alignment: Align(1),
19199 MachineMemOperand::MONone, Fast: &Fast) &&
19200 Fast))) {
19201 return MVT::v2f64;
19202 } else if (Op.size() >= 8 &&
19203 (Op.isAligned(AlignCheck: Align(8)) ||
19204 (allowsMisalignedMemoryAccesses(
19205 VT: MVT::f64, 0, Alignment: Align(1), MachineMemOperand::MONone, Fast: &Fast) &&
19206 Fast))) {
19207 return MVT::f64;
19208 }
19209 }
19210
19211 // Let the target-independent logic figure it out.
19212 return MVT::Other;
19213}
19214
19215// 64-bit integers are split into their high and low parts and held in two
19216// different registers, so the trunc is free since the low register can just
19217// be used.
19218bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
19219 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
19220 return false;
19221 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
19222 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
19223 return (SrcBits == 64 && DestBits == 32);
19224}
19225
19226bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
19227 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
19228 !DstVT.isInteger())
19229 return false;
19230 unsigned SrcBits = SrcVT.getSizeInBits();
19231 unsigned DestBits = DstVT.getSizeInBits();
19232 return (SrcBits == 64 && DestBits == 32);
19233}
19234
19235bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19236 if (Val.getOpcode() != ISD::LOAD)
19237 return false;
19238
19239 EVT VT1 = Val.getValueType();
19240 if (!VT1.isSimple() || !VT1.isInteger() ||
19241 !VT2.isSimple() || !VT2.isInteger())
19242 return false;
19243
19244 switch (VT1.getSimpleVT().SimpleTy) {
19245 default: break;
19246 case MVT::i1:
19247 case MVT::i8:
19248 case MVT::i16:
19249 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
19250 return true;
19251 }
19252
19253 return false;
19254}
19255
19256bool ARMTargetLowering::isFNegFree(EVT VT) const {
19257 if (!VT.isSimple())
19258 return false;
19259
19260 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
19261 // negate values directly (fneg is free). So, we don't want to let the DAG
19262 // combiner rewrite fneg into xors and some other instructions. For f16 and
19263 // FullFP16 argument passing, some bitcast nodes may be introduced,
19264 // triggering this DAG combine rewrite, so we are avoiding that with this.
19265 switch (VT.getSimpleVT().SimpleTy) {
19266 default: break;
19267 case MVT::f16:
19268 return Subtarget->hasFullFP16();
19269 }
19270
19271 return false;
19272}
19273
19274Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
19275 if (!Subtarget->hasMVEIntegerOps())
19276 return nullptr;
19277 Type *SVIType = SVI->getType();
19278 Type *ScalarType = SVIType->getScalarType();
19279
19280 if (ScalarType->isFloatTy())
19281 return Type::getInt32Ty(C&: SVIType->getContext());
19282 if (ScalarType->isHalfTy())
19283 return Type::getInt16Ty(C&: SVIType->getContext());
19284 return nullptr;
19285}
19286
19287bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
19288 EVT VT = ExtVal.getValueType();
19289
19290 if (!isTypeLegal(VT))
19291 return false;
19292
19293 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(Val: ExtVal.getOperand(i: 0))) {
19294 if (Ld->isExpandingLoad())
19295 return false;
19296 }
19297
19298 if (Subtarget->hasMVEIntegerOps())
19299 return true;
19300
19301 // Don't create a loadext if we can fold the extension into a wide/long
19302 // instruction.
19303 // If there's more than one user instruction, the loadext is desirable no
19304 // matter what. There can be two uses by the same instruction.
19305 if (ExtVal->use_empty() ||
19306 !ExtVal->user_begin()->isOnlyUserOf(N: ExtVal.getNode()))
19307 return true;
19308
19309 SDNode *U = *ExtVal->user_begin();
19310 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
19311 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
19312 return false;
19313
19314 return true;
19315}
19316
19317bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19318 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19319 return false;
19320
19321 if (!isTypeLegal(VT: EVT::getEVT(Ty: Ty1)))
19322 return false;
19323
19324 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19325
19326 // Assuming the caller doesn't have a zeroext or signext return parameter,
19327 // truncation all the way down to i1 is valid.
19328 return true;
19329}
19330
19331/// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
19332/// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
19333/// expanded to FMAs when this method returns true, otherwise fmuladd is
19334/// expanded to fmul + fadd.
19335///
19336/// ARM supports both fused and unfused multiply-add operations; we already
19337/// lower a pair of fmul and fadd to the latter so it's not clear that there
19338/// would be a gain or that the gain would be worthwhile enough to risk
19339/// correctness bugs.
19340///
19341/// For MVE, we set this to true as it helps simplify the need for some
19342/// patterns (and we don't have the non-fused floating point instruction).
19343bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
19344 EVT VT) const {
19345 if (Subtarget->useSoftFloat())
19346 return false;
19347
19348 if (!VT.isSimple())
19349 return false;
19350
19351 switch (VT.getSimpleVT().SimpleTy) {
19352 case MVT::v4f32:
19353 case MVT::v8f16:
19354 return Subtarget->hasMVEFloatOps();
19355 case MVT::f16:
19356 return Subtarget->useFPVFMx16();
19357 case MVT::f32:
19358 return Subtarget->useFPVFMx();
19359 case MVT::f64:
19360 return Subtarget->useFPVFMx64();
19361 default:
19362 break;
19363 }
19364
19365 return false;
19366}
19367
19368static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
19369 if (V < 0)
19370 return false;
19371
19372 unsigned Scale = 1;
19373 switch (VT.getSimpleVT().SimpleTy) {
19374 case MVT::i1:
19375 case MVT::i8:
19376 // Scale == 1;
19377 break;
19378 case MVT::i16:
19379 // Scale == 2;
19380 Scale = 2;
19381 break;
19382 default:
19383 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
19384 // Scale == 4;
19385 Scale = 4;
19386 break;
19387 }
19388
19389 if ((V & (Scale - 1)) != 0)
19390 return false;
19391 return isUInt<5>(x: V / Scale);
19392}
19393
19394static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
19395 const ARMSubtarget *Subtarget) {
19396 if (!VT.isInteger() && !VT.isFloatingPoint())
19397 return false;
19398 if (VT.isVector() && Subtarget->hasNEON())
19399 return false;
19400 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
19401 !Subtarget->hasMVEFloatOps())
19402 return false;
19403
19404 bool IsNeg = false;
19405 if (V < 0) {
19406 IsNeg = true;
19407 V = -V;
19408 }
19409
19410 unsigned NumBytes = std::max(a: (unsigned)VT.getSizeInBits() / 8, b: 1U);
19411
19412 // MVE: size * imm7
19413 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
19414 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
19415 case MVT::i32:
19416 case MVT::f32:
19417 return isShiftedUInt<7,2>(x: V);
19418 case MVT::i16:
19419 case MVT::f16:
19420 return isShiftedUInt<7,1>(x: V);
19421 case MVT::i8:
19422 return isUInt<7>(x: V);
19423 default:
19424 return false;
19425 }
19426 }
19427
19428 // half VLDR: 2 * imm8
19429 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
19430 return isShiftedUInt<8, 1>(x: V);
19431 // VLDR and LDRD: 4 * imm8
19432 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
19433 return isShiftedUInt<8, 2>(x: V);
19434
19435 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
19436 // + imm12 or - imm8
19437 if (IsNeg)
19438 return isUInt<8>(x: V);
19439 return isUInt<12>(x: V);
19440 }
19441
19442 return false;
19443}
19444
19445/// isLegalAddressImmediate - Return true if the integer value can be used
19446/// as the offset of the target addressing mode for load / store of the
19447/// given type.
19448static bool isLegalAddressImmediate(int64_t V, EVT VT,
19449 const ARMSubtarget *Subtarget) {
19450 if (V == 0)
19451 return true;
19452
19453 if (!VT.isSimple())
19454 return false;
19455
19456 if (Subtarget->isThumb1Only())
19457 return isLegalT1AddressImmediate(V, VT);
19458 else if (Subtarget->isThumb2())
19459 return isLegalT2AddressImmediate(V, VT, Subtarget);
19460
19461 // ARM mode.
19462 if (V < 0)
19463 V = - V;
19464 switch (VT.getSimpleVT().SimpleTy) {
19465 default: return false;
19466 case MVT::i1:
19467 case MVT::i8:
19468 case MVT::i32:
19469 // +- imm12
19470 return isUInt<12>(x: V);
19471 case MVT::i16:
19472 // +- imm8
19473 return isUInt<8>(x: V);
19474 case MVT::f32:
19475 case MVT::f64:
19476 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
19477 return false;
19478 return isShiftedUInt<8, 2>(x: V);
19479 }
19480}
19481
19482bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
19483 EVT VT) const {
19484 int Scale = AM.Scale;
19485 if (Scale < 0)
19486 return false;
19487
19488 switch (VT.getSimpleVT().SimpleTy) {
19489 default: return false;
19490 case MVT::i1:
19491 case MVT::i8:
19492 case MVT::i16:
19493 case MVT::i32:
19494 if (Scale == 1)
19495 return true;
19496 // r + r << imm
19497 Scale = Scale & ~1;
19498 return Scale == 2 || Scale == 4 || Scale == 8;
19499 case MVT::i64:
19500 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
19501 // version in Thumb mode.
19502 // r + r
19503 if (Scale == 1)
19504 return true;
19505 // r * 2 (this can be lowered to r + r).
19506 if (!AM.HasBaseReg && Scale == 2)
19507 return true;
19508 return false;
19509 case MVT::isVoid:
19510 // Note, we allow "void" uses (basically, uses that aren't loads or
19511 // stores), because arm allows folding a scale into many arithmetic
19512 // operations. This should be made more precise and revisited later.
19513
19514 // Allow r << imm, but the imm has to be a multiple of two.
19515 if (Scale & 1) return false;
19516 return isPowerOf2_32(Value: Scale);
19517 }
19518}
19519
19520bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
19521 EVT VT) const {
19522 const int Scale = AM.Scale;
19523
19524 // Negative scales are not supported in Thumb1.
19525 if (Scale < 0)
19526 return false;
19527
19528 // Thumb1 addressing modes do not support register scaling excepting the
19529 // following cases:
19530 // 1. Scale == 1 means no scaling.
19531 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
19532 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
19533}
19534
19535/// isLegalAddressingMode - Return true if the addressing mode represented
19536/// by AM is legal for this target, for a load/store of the specified type.
19537bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
19538 const AddrMode &AM, Type *Ty,
19539 unsigned AS, Instruction *I) const {
19540 EVT VT = getValueType(DL, Ty, AllowUnknown: true);
19541 if (!isLegalAddressImmediate(V: AM.BaseOffs, VT, Subtarget))
19542 return false;
19543
19544 // Can never fold addr of global into load/store.
19545 if (AM.BaseGV)
19546 return false;
19547
19548 switch (AM.Scale) {
19549 case 0: // no scale reg, must be "r+i" or "r", or "i".
19550 break;
19551 default:
19552 // ARM doesn't support any R+R*scale+imm addr modes.
19553 if (AM.BaseOffs)
19554 return false;
19555
19556 if (!VT.isSimple())
19557 return false;
19558
19559 if (Subtarget->isThumb1Only())
19560 return isLegalT1ScaledAddressingMode(AM, VT);
19561
19562 if (Subtarget->isThumb2())
19563 return isLegalT2ScaledAddressingMode(AM, VT);
19564
19565 int Scale = AM.Scale;
19566 switch (VT.getSimpleVT().SimpleTy) {
19567 default: return false;
19568 case MVT::i1:
19569 case MVT::i8:
19570 case MVT::i32:
19571 if (Scale < 0) Scale = -Scale;
19572 if (Scale == 1)
19573 return true;
19574 // r + r << imm
19575 return isPowerOf2_32(Value: Scale & ~1);
19576 case MVT::i16:
19577 case MVT::i64:
19578 // r +/- r
19579 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
19580 return true;
19581 // r * 2 (this can be lowered to r + r).
19582 if (!AM.HasBaseReg && Scale == 2)
19583 return true;
19584 return false;
19585
19586 case MVT::isVoid:
19587 // Note, we allow "void" uses (basically, uses that aren't loads or
19588 // stores), because arm allows folding a scale into many arithmetic
19589 // operations. This should be made more precise and revisited later.
19590
19591 // Allow r << imm, but the imm has to be a multiple of two.
19592 if (Scale & 1) return false;
19593 return isPowerOf2_32(Value: Scale);
19594 }
19595 }
19596 return true;
19597}
19598
19599/// isLegalICmpImmediate - Return true if the specified immediate is legal
19600/// icmp immediate, that is the target has icmp instructions which can compare
19601/// a register against the immediate without having to materialize the
19602/// immediate into a register.
19603bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19604 // Thumb2 and ARM modes can use cmn for negative immediates.
19605 if (!Subtarget->isThumb())
19606 return ARM_AM::getSOImmVal(Arg: (uint32_t)Imm) != -1 ||
19607 ARM_AM::getSOImmVal(Arg: -(uint32_t)Imm) != -1;
19608 if (Subtarget->isThumb2())
19609 return ARM_AM::getT2SOImmVal(Arg: (uint32_t)Imm) != -1 ||
19610 ARM_AM::getT2SOImmVal(Arg: -(uint32_t)Imm) != -1;
19611 // Thumb1 doesn't have cmn, and only 8-bit immediates.
19612 return Imm >= 0 && Imm <= 255;
19613}
19614
19615/// isLegalAddImmediate - Return true if the specified immediate is a legal add
19616/// *or sub* immediate, that is the target has add or sub instructions which can
19617/// add a register with the immediate without having to materialize the
19618/// immediate into a register.
19619bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
19620 // Same encoding for add/sub, just flip the sign.
19621 uint64_t AbsImm = AbsoluteValue(X: Imm);
19622 if (!Subtarget->isThumb())
19623 return ARM_AM::getSOImmVal(Arg: AbsImm) != -1;
19624 if (Subtarget->isThumb2())
19625 return ARM_AM::getT2SOImmVal(Arg: AbsImm) != -1;
19626 // Thumb1 only has 8-bit unsigned immediate.
19627 return AbsImm <= 255;
19628}
19629
19630// Return false to prevent folding
19631// (mul (add r, c0), c1) -> (add (mul r, c1), c0*c1) in DAGCombine,
19632// if the folding leads to worse code.
19633bool ARMTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
19634 SDValue ConstNode) const {
19635 // Let the DAGCombiner decide for vector types and large types.
19636 const EVT VT = AddNode.getValueType();
19637 if (VT.isVector() || VT.getScalarSizeInBits() > 32)
19638 return true;
19639
19640 // It is worse if c0 is legal add immediate, while c1*c0 is not
19641 // and has to be composed by at least two instructions.
19642 const ConstantSDNode *C0Node = cast<ConstantSDNode>(Val: AddNode.getOperand(i: 1));
19643 const ConstantSDNode *C1Node = cast<ConstantSDNode>(Val&: ConstNode);
19644 const int64_t C0 = C0Node->getSExtValue();
19645 APInt CA = C0Node->getAPIntValue() * C1Node->getAPIntValue();
19646 if (!isLegalAddImmediate(Imm: C0) || isLegalAddImmediate(Imm: CA.getSExtValue()))
19647 return true;
19648 if (ConstantMaterializationCost(Val: (unsigned)CA.getZExtValue(), Subtarget) > 1)
19649 return false;
19650
19651 // Default to true and let the DAGCombiner decide.
19652 return true;
19653}
19654
19655static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
19656 bool isSEXTLoad, SDValue &Base,
19657 SDValue &Offset, bool &isInc,
19658 SelectionDAG &DAG) {
19659 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19660 return false;
19661
19662 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
19663 // AddressingMode 3
19664 Base = Ptr->getOperand(Num: 0);
19665 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Val: Ptr->getOperand(Num: 1))) {
19666 int RHSC = (int)RHS->getZExtValue();
19667 if (RHSC < 0 && RHSC > -256) {
19668 assert(Ptr->getOpcode() == ISD::ADD);
19669 isInc = false;
19670 Offset = DAG.getConstant(Val: -RHSC, DL: SDLoc(Ptr), VT: RHS->getValueType(ResNo: 0));
19671 return true;
19672 }
19673 }
19674 isInc = (Ptr->getOpcode() == ISD::ADD);
19675 Offset = Ptr->getOperand(Num: 1);
19676 return true;
19677 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
19678 // AddressingMode 2
19679 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Val: Ptr->getOperand(Num: 1))) {
19680 int RHSC = (int)RHS->getZExtValue();
19681 if (RHSC < 0 && RHSC > -0x1000) {
19682 assert(Ptr->getOpcode() == ISD::ADD);
19683 isInc = false;
19684 Offset = DAG.getConstant(Val: -RHSC, DL: SDLoc(Ptr), VT: RHS->getValueType(ResNo: 0));
19685 Base = Ptr->getOperand(Num: 0);
19686 return true;
19687 }
19688 }
19689
19690 if (Ptr->getOpcode() == ISD::ADD) {
19691 isInc = true;
19692 ARM_AM::ShiftOpc ShOpcVal=
19693 ARM_AM::getShiftOpcForNode(Opcode: Ptr->getOperand(Num: 0).getOpcode());
19694 if (ShOpcVal != ARM_AM::no_shift) {
19695 Base = Ptr->getOperand(Num: 1);
19696 Offset = Ptr->getOperand(Num: 0);
19697 } else {
19698 Base = Ptr->getOperand(Num: 0);
19699 Offset = Ptr->getOperand(Num: 1);
19700 }
19701 return true;
19702 }
19703
19704 isInc = (Ptr->getOpcode() == ISD::ADD);
19705 Base = Ptr->getOperand(Num: 0);
19706 Offset = Ptr->getOperand(Num: 1);
19707 return true;
19708 }
19709
19710 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
19711 return false;
19712}
19713
19714static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
19715 bool isSEXTLoad, SDValue &Base,
19716 SDValue &Offset, bool &isInc,
19717 SelectionDAG &DAG) {
19718 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19719 return false;
19720
19721 Base = Ptr->getOperand(Num: 0);
19722 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Val: Ptr->getOperand(Num: 1))) {
19723 int RHSC = (int)RHS->getZExtValue();
19724 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
19725 assert(Ptr->getOpcode() == ISD::ADD);
19726 isInc = false;
19727 Offset = DAG.getConstant(Val: -RHSC, DL: SDLoc(Ptr), VT: RHS->getValueType(ResNo: 0));
19728 return true;
19729 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
19730 isInc = Ptr->getOpcode() == ISD::ADD;
19731 Offset = DAG.getConstant(Val: RHSC, DL: SDLoc(Ptr), VT: RHS->getValueType(ResNo: 0));
19732 return true;
19733 }
19734 }
19735
19736 return false;
19737}
19738
19739static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
19740 bool isSEXTLoad, bool IsMasked, bool isLE,
19741 SDValue &Base, SDValue &Offset,
19742 bool &isInc, SelectionDAG &DAG) {
19743 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19744 return false;
19745 if (!isa<ConstantSDNode>(Val: Ptr->getOperand(Num: 1)))
19746 return false;
19747
19748 // We allow LE non-masked loads to change the type (for example use a vldrb.8
19749 // as opposed to a vldrw.32). This can allow extra addressing modes or
19750 // alignments for what is otherwise an equivalent instruction.
19751 bool CanChangeType = isLE && !IsMasked;
19752
19753 ConstantSDNode *RHS = cast<ConstantSDNode>(Val: Ptr->getOperand(Num: 1));
19754 int RHSC = (int)RHS->getZExtValue();
19755
19756 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
19757 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
19758 assert(Ptr->getOpcode() == ISD::ADD);
19759 isInc = false;
19760 Offset = DAG.getConstant(Val: -RHSC, DL: SDLoc(Ptr), VT: RHS->getValueType(ResNo: 0));
19761 return true;
19762 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
19763 isInc = Ptr->getOpcode() == ISD::ADD;
19764 Offset = DAG.getConstant(Val: RHSC, DL: SDLoc(Ptr), VT: RHS->getValueType(ResNo: 0));
19765 return true;
19766 }
19767 return false;
19768 };
19769
19770 // Try to find a matching instruction based on s/zext, Alignment, Offset and
19771 // (in BE/masked) type.
19772 Base = Ptr->getOperand(Num: 0);
19773 if (VT == MVT::v4i16) {
19774 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
19775 return true;
19776 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
19777 if (IsInRange(RHSC, 0x80, 1))
19778 return true;
19779 } else if (Alignment >= 4 &&
19780 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
19781 IsInRange(RHSC, 0x80, 4))
19782 return true;
19783 else if (Alignment >= 2 &&
19784 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
19785 IsInRange(RHSC, 0x80, 2))
19786 return true;
19787 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
19788 return true;
19789 return false;
19790}
19791
19792/// getPreIndexedAddressParts - returns true by value, base pointer and
19793/// offset pointer and addressing mode by reference if the node's address
19794/// can be legally represented as pre-indexed load / store address.
19795bool
19796ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
19797 SDValue &Offset,
19798 ISD::MemIndexedMode &AM,
19799 SelectionDAG &DAG) const {
19800 if (Subtarget->isThumb1Only())
19801 return false;
19802
19803 EVT VT;
19804 SDValue Ptr;
19805 Align Alignment;
19806 unsigned AS = 0;
19807 bool isSEXTLoad = false;
19808 bool IsMasked = false;
19809 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: N)) {
19810 Ptr = LD->getBasePtr();
19811 VT = LD->getMemoryVT();
19812 Alignment = LD->getAlign();
19813 AS = LD->getAddressSpace();
19814 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19815 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Val: N)) {
19816 Ptr = ST->getBasePtr();
19817 VT = ST->getMemoryVT();
19818 Alignment = ST->getAlign();
19819 AS = ST->getAddressSpace();
19820 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Val: N)) {
19821 Ptr = LD->getBasePtr();
19822 VT = LD->getMemoryVT();
19823 Alignment = LD->getAlign();
19824 AS = LD->getAddressSpace();
19825 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19826 IsMasked = true;
19827 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Val: N)) {
19828 Ptr = ST->getBasePtr();
19829 VT = ST->getMemoryVT();
19830 Alignment = ST->getAlign();
19831 AS = ST->getAddressSpace();
19832 IsMasked = true;
19833 } else
19834 return false;
19835
19836 unsigned Fast = 0;
19837 if (!allowsMisalignedMemoryAccesses(VT, AS, Alignment,
19838 MachineMemOperand::MONone, Fast: &Fast)) {
19839 // Only generate post-increment or pre-increment forms when a real
19840 // hardware instruction exists for them. Do not emit postinc/preinc
19841 // if the operation will end up as a libcall.
19842 return false;
19843 }
19844
19845 bool isInc;
19846 bool isLegal = false;
19847 if (VT.isVector())
19848 isLegal = Subtarget->hasMVEIntegerOps() &&
19849 getMVEIndexedAddressParts(
19850 Ptr: Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
19851 isLE: Subtarget->isLittle(), Base, Offset, isInc, DAG);
19852 else {
19853 if (Subtarget->isThumb2())
19854 isLegal = getT2IndexedAddressParts(Ptr: Ptr.getNode(), VT, isSEXTLoad, Base,
19855 Offset, isInc, DAG);
19856 else
19857 isLegal = getARMIndexedAddressParts(Ptr: Ptr.getNode(), VT, isSEXTLoad, Base,
19858 Offset, isInc, DAG);
19859 }
19860 if (!isLegal)
19861 return false;
19862
19863 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
19864 return true;
19865}
19866
19867/// getPostIndexedAddressParts - returns true by value, base pointer and
19868/// offset pointer and addressing mode by reference if this node can be
19869/// combined with a load / store to form a post-indexed load / store.
19870bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
19871 SDValue &Base,
19872 SDValue &Offset,
19873 ISD::MemIndexedMode &AM,
19874 SelectionDAG &DAG) const {
19875 EVT VT;
19876 SDValue Ptr;
19877 Align Alignment;
19878 bool isSEXTLoad = false, isNonExt;
19879 bool IsMasked = false;
19880 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: N)) {
19881 VT = LD->getMemoryVT();
19882 Ptr = LD->getBasePtr();
19883 Alignment = LD->getAlign();
19884 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19885 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19886 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Val: N)) {
19887 VT = ST->getMemoryVT();
19888 Ptr = ST->getBasePtr();
19889 Alignment = ST->getAlign();
19890 isNonExt = !ST->isTruncatingStore();
19891 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Val: N)) {
19892 VT = LD->getMemoryVT();
19893 Ptr = LD->getBasePtr();
19894 Alignment = LD->getAlign();
19895 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19896 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19897 IsMasked = true;
19898 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Val: N)) {
19899 VT = ST->getMemoryVT();
19900 Ptr = ST->getBasePtr();
19901 Alignment = ST->getAlign();
19902 isNonExt = !ST->isTruncatingStore();
19903 IsMasked = true;
19904 } else
19905 return false;
19906
19907 if (Subtarget->isThumb1Only()) {
19908 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
19909 // must be non-extending/truncating, i32, with an offset of 4.
19910 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
19911 if (Op->getOpcode() != ISD::ADD || !isNonExt)
19912 return false;
19913 auto *RHS = dyn_cast<ConstantSDNode>(Val: Op->getOperand(Num: 1));
19914 if (!RHS || RHS->getZExtValue() != 4)
19915 return false;
19916 if (Alignment < Align(4))
19917 return false;
19918
19919 Offset = Op->getOperand(Num: 1);
19920 Base = Op->getOperand(Num: 0);
19921 AM = ISD::POST_INC;
19922 return true;
19923 }
19924
19925 bool isInc;
19926 bool isLegal = false;
19927 if (VT.isVector())
19928 isLegal = Subtarget->hasMVEIntegerOps() &&
19929 getMVEIndexedAddressParts(Ptr: Op, VT, Alignment, isSEXTLoad, IsMasked,
19930 isLE: Subtarget->isLittle(), Base, Offset,
19931 isInc, DAG);
19932 else {
19933 if (Subtarget->isThumb2())
19934 isLegal = getT2IndexedAddressParts(Ptr: Op, VT, isSEXTLoad, Base, Offset,
19935 isInc, DAG);
19936 else
19937 isLegal = getARMIndexedAddressParts(Ptr: Op, VT, isSEXTLoad, Base, Offset,
19938 isInc, DAG);
19939 }
19940 if (!isLegal)
19941 return false;
19942
19943 if (Ptr != Base) {
19944 // Swap base ptr and offset to catch more post-index load / store when
19945 // it's legal. In Thumb2 mode, offset must be an immediate.
19946 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
19947 !Subtarget->isThumb2())
19948 std::swap(a&: Base, b&: Offset);
19949
19950 // Post-indexed load / store update the base pointer.
19951 if (Ptr != Base)
19952 return false;
19953 }
19954
19955 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
19956 return true;
19957}
19958
19959void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19960 KnownBits &Known,
19961 const APInt &DemandedElts,
19962 const SelectionDAG &DAG,
19963 unsigned Depth) const {
19964 unsigned BitWidth = Known.getBitWidth();
19965 Known.resetAll();
19966 switch (Op.getOpcode()) {
19967 default: break;
19968 case ARMISD::ADDC:
19969 case ARMISD::ADDE:
19970 case ARMISD::SUBC:
19971 case ARMISD::SUBE:
19972 // Special cases when we convert a carry to a boolean.
19973 if (Op.getResNo() == 0) {
19974 SDValue LHS = Op.getOperand(i: 0);
19975 SDValue RHS = Op.getOperand(i: 1);
19976 // (ADDE 0, 0, C) will give us a single bit.
19977 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(V: LHS) &&
19978 isNullConstant(V: RHS)) {
19979 Known.Zero |= APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - 1);
19980 return;
19981 }
19982 }
19983 break;
19984 case ARMISD::CMOV: {
19985 // Bits are known zero/one if known on the LHS and RHS.
19986 Known = DAG.computeKnownBits(Op: Op.getOperand(i: 0), Depth: Depth+1);
19987 if (Known.isUnknown())
19988 return;
19989
19990 KnownBits KnownRHS = DAG.computeKnownBits(Op: Op.getOperand(i: 1), Depth: Depth+1);
19991 Known = Known.intersectWith(RHS: KnownRHS);
19992 return;
19993 }
19994 case ISD::INTRINSIC_W_CHAIN: {
19995 Intrinsic::ID IntID =
19996 static_cast<Intrinsic::ID>(Op->getConstantOperandVal(Num: 1));
19997 switch (IntID) {
19998 default: return;
19999 case Intrinsic::arm_ldaex:
20000 case Intrinsic::arm_ldrex: {
20001 EVT VT = cast<MemIntrinsicSDNode>(Val: Op)->getMemoryVT();
20002 unsigned MemBits = VT.getScalarSizeInBits();
20003 Known.Zero |= APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - MemBits);
20004 return;
20005 }
20006 }
20007 }
20008 case ARMISD::BFI: {
20009 // Conservatively, we can recurse down the first operand
20010 // and just mask out all affected bits.
20011 Known = DAG.computeKnownBits(Op: Op.getOperand(i: 0), Depth: Depth + 1);
20012
20013 // The operand to BFI is already a mask suitable for removing the bits it
20014 // sets.
20015 const APInt &Mask = Op.getConstantOperandAPInt(i: 2);
20016 Known.Zero &= Mask;
20017 Known.One &= Mask;
20018 return;
20019 }
20020 case ARMISD::VGETLANEs:
20021 case ARMISD::VGETLANEu: {
20022 const SDValue &SrcSV = Op.getOperand(i: 0);
20023 EVT VecVT = SrcSV.getValueType();
20024 assert(VecVT.isVector() && "VGETLANE expected a vector type");
20025 const unsigned NumSrcElts = VecVT.getVectorNumElements();
20026 ConstantSDNode *Pos = cast<ConstantSDNode>(Val: Op.getOperand(i: 1).getNode());
20027 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
20028 "VGETLANE index out of bounds");
20029 unsigned Idx = Pos->getZExtValue();
20030 APInt DemandedElt = APInt::getOneBitSet(numBits: NumSrcElts, BitNo: Idx);
20031 Known = DAG.computeKnownBits(Op: SrcSV, DemandedElts: DemandedElt, Depth: Depth + 1);
20032
20033 EVT VT = Op.getValueType();
20034 const unsigned DstSz = VT.getScalarSizeInBits();
20035 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
20036 (void)SrcSz;
20037 assert(SrcSz == Known.getBitWidth());
20038 assert(DstSz > SrcSz);
20039 if (Op.getOpcode() == ARMISD::VGETLANEs)
20040 Known = Known.sext(BitWidth: DstSz);
20041 else {
20042 Known = Known.zext(BitWidth: DstSz);
20043 }
20044 assert(DstSz == Known.getBitWidth());
20045 break;
20046 }
20047 case ARMISD::VMOVrh: {
20048 KnownBits KnownOp = DAG.computeKnownBits(Op: Op->getOperand(Num: 0), Depth: Depth + 1);
20049 assert(KnownOp.getBitWidth() == 16);
20050 Known = KnownOp.zext(BitWidth: 32);
20051 break;
20052 }
20053 case ARMISD::CSINC:
20054 case ARMISD::CSINV:
20055 case ARMISD::CSNEG: {
20056 KnownBits KnownOp0 = DAG.computeKnownBits(Op: Op->getOperand(Num: 0), Depth: Depth + 1);
20057 KnownBits KnownOp1 = DAG.computeKnownBits(Op: Op->getOperand(Num: 1), Depth: Depth + 1);
20058
20059 // The result is either:
20060 // CSINC: KnownOp0 or KnownOp1 + 1
20061 // CSINV: KnownOp0 or ~KnownOp1
20062 // CSNEG: KnownOp0 or KnownOp1 * -1
20063 if (Op.getOpcode() == ARMISD::CSINC)
20064 KnownOp1 =
20065 KnownBits::add(LHS: KnownOp1, RHS: KnownBits::makeConstant(C: APInt(32, 1)));
20066 else if (Op.getOpcode() == ARMISD::CSINV)
20067 std::swap(a&: KnownOp1.Zero, b&: KnownOp1.One);
20068 else if (Op.getOpcode() == ARMISD::CSNEG)
20069 KnownOp1 = KnownBits::mul(LHS: KnownOp1,
20070 RHS: KnownBits::makeConstant(C: APInt::getAllOnes(numBits: 32)));
20071
20072 Known = KnownOp0.intersectWith(RHS: KnownOp1);
20073 break;
20074 }
20075 case ARMISD::VORRIMM:
20076 case ARMISD::VBICIMM: {
20077 unsigned Encoded = Op.getConstantOperandVal(i: 1);
20078 unsigned DecEltBits = 0;
20079 uint64_t DecodedVal = ARM_AM::decodeVMOVModImm(ModImm: Encoded, EltBits&: DecEltBits);
20080
20081 unsigned EltBits = Op.getScalarValueSizeInBits();
20082 if (EltBits != DecEltBits) {
20083 // Be conservative: only update Known when EltBits == DecEltBits.
20084 // This is believed to always be true for VORRIMM/VBICIMM today, but if
20085 // that changes in the future, doing nothing here is safer than risking
20086 // subtle bugs.
20087 break;
20088 }
20089
20090 KnownBits KnownLHS = DAG.computeKnownBits(Op: Op.getOperand(i: 0), Depth: Depth + 1);
20091 bool IsVORR = Op.getOpcode() == ARMISD::VORRIMM;
20092 APInt Imm(DecEltBits, DecodedVal);
20093
20094 Known.One = IsVORR ? (KnownLHS.One | Imm) : (KnownLHS.One & ~Imm);
20095 Known.Zero = IsVORR ? (KnownLHS.Zero & ~Imm) : (KnownLHS.Zero | Imm);
20096 break;
20097 }
20098 }
20099}
20100
20101bool ARMTargetLowering::targetShrinkDemandedConstant(
20102 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
20103 TargetLoweringOpt &TLO) const {
20104 // Delay optimization, so we don't have to deal with illegal types, or block
20105 // optimizations.
20106 if (!TLO.LegalOps)
20107 return false;
20108
20109 // Only optimize AND for now.
20110 if (Op.getOpcode() != ISD::AND)
20111 return false;
20112
20113 EVT VT = Op.getValueType();
20114
20115 // Ignore vectors.
20116 if (VT.isVector())
20117 return false;
20118
20119 assert(VT == MVT::i32 && "Unexpected integer type");
20120
20121 // Make sure the RHS really is a constant.
20122 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 1));
20123 if (!C)
20124 return false;
20125
20126 unsigned Mask = C->getZExtValue();
20127
20128 unsigned Demanded = DemandedBits.getZExtValue();
20129 unsigned ShrunkMask = Mask & Demanded;
20130 unsigned ExpandedMask = Mask | ~Demanded;
20131
20132 // If the mask is all zeros, let the target-independent code replace the
20133 // result with zero.
20134 if (ShrunkMask == 0)
20135 return false;
20136
20137 // If the mask is all ones, erase the AND. (Currently, the target-independent
20138 // code won't do this, so we have to do it explicitly to avoid an infinite
20139 // loop in obscure cases.)
20140 if (ExpandedMask == ~0U)
20141 return TLO.CombineTo(O: Op, N: Op.getOperand(i: 0));
20142
20143 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
20144 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
20145 };
20146 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
20147 if (NewMask == Mask)
20148 return true;
20149 SDLoc DL(Op);
20150 SDValue NewC = TLO.DAG.getConstant(Val: NewMask, DL, VT);
20151 SDValue NewOp = TLO.DAG.getNode(Opcode: ISD::AND, DL, VT, N1: Op.getOperand(i: 0), N2: NewC);
20152 return TLO.CombineTo(O: Op, N: NewOp);
20153 };
20154
20155 // Prefer uxtb mask.
20156 if (IsLegalMask(0xFF))
20157 return UseMask(0xFF);
20158
20159 // Prefer uxth mask.
20160 if (IsLegalMask(0xFFFF))
20161 return UseMask(0xFFFF);
20162
20163 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
20164 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
20165 if (ShrunkMask < 256)
20166 return UseMask(ShrunkMask);
20167
20168 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
20169 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
20170 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
20171 return UseMask(ExpandedMask);
20172
20173 // Potential improvements:
20174 //
20175 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
20176 // We could try to prefer Thumb1 immediates which can be lowered to a
20177 // two-instruction sequence.
20178 // We could try to recognize more legal ARM/Thumb2 immediates here.
20179
20180 return false;
20181}
20182
20183bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
20184 SDValue Op, const APInt &OriginalDemandedBits,
20185 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
20186 unsigned Depth) const {
20187 unsigned Opc = Op.getOpcode();
20188
20189 switch (Opc) {
20190 case ARMISD::ASRL:
20191 case ARMISD::LSRL: {
20192 // If this is result 0 and the other result is unused, see if the demand
20193 // bits allow us to shrink this long shift into a standard small shift in
20194 // the opposite direction.
20195 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(Value: 1) &&
20196 isa<ConstantSDNode>(Val: Op->getOperand(Num: 2))) {
20197 unsigned ShAmt = Op->getConstantOperandVal(Num: 2);
20198 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(RHS: APInt::getAllOnes(numBits: 32)
20199 << (32 - ShAmt)))
20200 return TLO.CombineTo(
20201 O: Op, N: TLO.DAG.getNode(
20202 Opcode: ISD::SHL, DL: SDLoc(Op), VT: MVT::i32, N1: Op.getOperand(i: 1),
20203 N2: TLO.DAG.getConstant(Val: 32 - ShAmt, DL: SDLoc(Op), VT: MVT::i32)));
20204 }
20205 break;
20206 }
20207 case ARMISD::VBICIMM: {
20208 SDValue Op0 = Op.getOperand(i: 0);
20209 unsigned ModImm = Op.getConstantOperandVal(i: 1);
20210 unsigned EltBits = 0;
20211 uint64_t Mask = ARM_AM::decodeVMOVModImm(ModImm, EltBits);
20212 if ((OriginalDemandedBits & Mask) == 0)
20213 return TLO.CombineTo(O: Op, N: Op0);
20214 }
20215 }
20216
20217 return TargetLowering::SimplifyDemandedBitsForTargetNode(
20218 Op, DemandedBits: OriginalDemandedBits, DemandedElts: OriginalDemandedElts, Known, TLO, Depth);
20219}
20220
20221//===----------------------------------------------------------------------===//
20222// ARM Inline Assembly Support
20223//===----------------------------------------------------------------------===//
20224
20225const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
20226 // At this point, we have to lower this constraint to something else, so we
20227 // lower it to an "r" or "w". However, by doing this we will force the result
20228 // to be in register, while the X constraint is much more permissive.
20229 //
20230 // Although we are correct (we are free to emit anything, without
20231 // constraints), we might break use cases that would expect us to be more
20232 // efficient and emit something else.
20233 if (!Subtarget->hasVFP2Base())
20234 return "r";
20235 if (ConstraintVT.isFloatingPoint())
20236 return "w";
20237 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
20238 (ConstraintVT.getSizeInBits() == 64 ||
20239 ConstraintVT.getSizeInBits() == 128))
20240 return "w";
20241
20242 return "r";
20243}
20244
20245/// getConstraintType - Given a constraint letter, return the type of
20246/// constraint it is for this target.
20247ARMTargetLowering::ConstraintType
20248ARMTargetLowering::getConstraintType(StringRef Constraint) const {
20249 unsigned S = Constraint.size();
20250 if (S == 1) {
20251 switch (Constraint[0]) {
20252 default: break;
20253 case 'l': return C_RegisterClass;
20254 case 'w': return C_RegisterClass;
20255 case 'h': return C_RegisterClass;
20256 case 'x': return C_RegisterClass;
20257 case 't': return C_RegisterClass;
20258 case 'j': return C_Immediate; // Constant for movw.
20259 // An address with a single base register. Due to the way we
20260 // currently handle addresses it is the same as an 'r' memory constraint.
20261 case 'Q': return C_Memory;
20262 }
20263 } else if (S == 2) {
20264 switch (Constraint[0]) {
20265 default: break;
20266 case 'T': return C_RegisterClass;
20267 // All 'U+' constraints are addresses.
20268 case 'U': return C_Memory;
20269 }
20270 }
20271 return TargetLowering::getConstraintType(Constraint);
20272}
20273
20274/// Examine constraint type and operand type and determine a weight value.
20275/// This object must already have been set up with the operand type
20276/// and the current alternative constraint selected.
20277TargetLowering::ConstraintWeight
20278ARMTargetLowering::getSingleConstraintMatchWeight(
20279 AsmOperandInfo &info, const char *constraint) const {
20280 ConstraintWeight weight = CW_Invalid;
20281 Value *CallOperandVal = info.CallOperandVal;
20282 // If we don't have a value, we can't do a match,
20283 // but allow it at the lowest weight.
20284 if (!CallOperandVal)
20285 return CW_Default;
20286 Type *type = CallOperandVal->getType();
20287 // Look at the constraint type.
20288 switch (*constraint) {
20289 default:
20290 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20291 break;
20292 case 'l':
20293 if (type->isIntegerTy()) {
20294 if (Subtarget->isThumb())
20295 weight = CW_SpecificReg;
20296 else
20297 weight = CW_Register;
20298 }
20299 break;
20300 case 'w':
20301 if (type->isFloatingPointTy())
20302 weight = CW_Register;
20303 break;
20304 }
20305 return weight;
20306}
20307
20308static bool isIncompatibleReg(const MCPhysReg &PR, MVT VT) {
20309 if (PR == 0 || VT == MVT::Other)
20310 return false;
20311 if (ARM::SPRRegClass.contains(Reg: PR))
20312 return VT != MVT::f32 && VT != MVT::f16 && VT != MVT::i32;
20313 if (ARM::DPRRegClass.contains(Reg: PR))
20314 return VT != MVT::f64 && !VT.is64BitVector();
20315 return false;
20316}
20317
20318using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
20319
20320RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
20321 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
20322 switch (Constraint.size()) {
20323 case 1:
20324 // GCC ARM Constraint Letters
20325 switch (Constraint[0]) {
20326 case 'l': // Low regs or general regs.
20327 if (Subtarget->isThumb())
20328 return RCPair(0U, &ARM::tGPRRegClass);
20329 return RCPair(0U, &ARM::GPRRegClass);
20330 case 'h': // High regs or no regs.
20331 if (Subtarget->isThumb())
20332 return RCPair(0U, &ARM::hGPRRegClass);
20333 break;
20334 case 'r':
20335 if (Subtarget->isThumb1Only())
20336 return RCPair(0U, &ARM::tGPRRegClass);
20337 return RCPair(0U, &ARM::GPRRegClass);
20338 case 'w':
20339 if (VT == MVT::Other)
20340 break;
20341 if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
20342 return RCPair(0U, &ARM::SPRRegClass);
20343 if (VT.getSizeInBits() == 64)
20344 return RCPair(0U, &ARM::DPRRegClass);
20345 if (VT.getSizeInBits() == 128)
20346 return RCPair(0U, &ARM::QPRRegClass);
20347 break;
20348 case 'x':
20349 if (VT == MVT::Other)
20350 break;
20351 if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
20352 return RCPair(0U, &ARM::SPR_8RegClass);
20353 if (VT.getSizeInBits() == 64)
20354 return RCPair(0U, &ARM::DPR_8RegClass);
20355 if (VT.getSizeInBits() == 128)
20356 return RCPair(0U, &ARM::QPR_8RegClass);
20357 break;
20358 case 't':
20359 if (VT == MVT::Other)
20360 break;
20361 if (VT == MVT::f32 || VT == MVT::i32 || VT == MVT::f16 || VT == MVT::bf16)
20362 return RCPair(0U, &ARM::SPRRegClass);
20363 if (VT.getSizeInBits() == 64)
20364 return RCPair(0U, &ARM::DPR_VFP2RegClass);
20365 if (VT.getSizeInBits() == 128)
20366 return RCPair(0U, &ARM::QPR_VFP2RegClass);
20367 break;
20368 }
20369 break;
20370
20371 case 2:
20372 if (Constraint[0] == 'T') {
20373 switch (Constraint[1]) {
20374 default:
20375 break;
20376 case 'e':
20377 return RCPair(0U, &ARM::tGPREvenRegClass);
20378 case 'o':
20379 return RCPair(0U, &ARM::tGPROddRegClass);
20380 }
20381 }
20382 break;
20383
20384 default:
20385 break;
20386 }
20387
20388 if (StringRef("{cc}").equals_insensitive(RHS: Constraint))
20389 return std::make_pair(x: unsigned(ARM::CPSR), y: &ARM::CCRRegClass);
20390
20391 // r14 is an alias of lr.
20392 if (StringRef("{r14}").equals_insensitive(RHS: Constraint))
20393 return std::make_pair(x: unsigned(ARM::LR), y: getRegClassFor(VT: MVT::i32));
20394
20395 auto RCP = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20396 if (isIncompatibleReg(PR: RCP.first, VT))
20397 return {0, nullptr};
20398 return RCP;
20399}
20400
20401/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20402/// vector. If it is invalid, don't add anything to Ops.
20403void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20404 StringRef Constraint,
20405 std::vector<SDValue> &Ops,
20406 SelectionDAG &DAG) const {
20407 SDValue Result;
20408
20409 // Currently only support length 1 constraints.
20410 if (Constraint.size() != 1)
20411 return;
20412
20413 char ConstraintLetter = Constraint[0];
20414 switch (ConstraintLetter) {
20415 default: break;
20416 case 'j':
20417 case 'I': case 'J': case 'K': case 'L':
20418 case 'M': case 'N': case 'O':
20419 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: Op);
20420 if (!C)
20421 return;
20422
20423 int64_t CVal64 = C->getSExtValue();
20424 int CVal = (int) CVal64;
20425 // None of these constraints allow values larger than 32 bits. Check
20426 // that the value fits in an int.
20427 if (CVal != CVal64)
20428 return;
20429
20430 switch (ConstraintLetter) {
20431 case 'j':
20432 // Constant suitable for movw, must be between 0 and
20433 // 65535.
20434 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
20435 if (CVal >= 0 && CVal <= 65535)
20436 break;
20437 return;
20438 case 'I':
20439 if (Subtarget->isThumb1Only()) {
20440 // This must be a constant between 0 and 255, for ADD
20441 // immediates.
20442 if (CVal >= 0 && CVal <= 255)
20443 break;
20444 } else if (Subtarget->isThumb2()) {
20445 // A constant that can be used as an immediate value in a
20446 // data-processing instruction.
20447 if (ARM_AM::getT2SOImmVal(Arg: CVal) != -1)
20448 break;
20449 } else {
20450 // A constant that can be used as an immediate value in a
20451 // data-processing instruction.
20452 if (ARM_AM::getSOImmVal(Arg: CVal) != -1)
20453 break;
20454 }
20455 return;
20456
20457 case 'J':
20458 if (Subtarget->isThumb1Only()) {
20459 // This must be a constant between -255 and -1, for negated ADD
20460 // immediates. This can be used in GCC with an "n" modifier that
20461 // prints the negated value, for use with SUB instructions. It is
20462 // not useful otherwise but is implemented for compatibility.
20463 if (CVal >= -255 && CVal <= -1)
20464 break;
20465 } else {
20466 // This must be a constant between -4095 and 4095. This is suitable
20467 // for use as the immediate offset field in LDR and STR instructions
20468 // such as LDR r0,[r1,#offset].
20469 if (CVal >= -4095 && CVal <= 4095)
20470 break;
20471 }
20472 return;
20473
20474 case 'K':
20475 if (Subtarget->isThumb1Only()) {
20476 // A 32-bit value where only one byte has a nonzero value. Exclude
20477 // zero to match GCC. This constraint is used by GCC internally for
20478 // constants that can be loaded with a move/shift combination.
20479 // It is not useful otherwise but is implemented for compatibility.
20480 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(V: CVal))
20481 break;
20482 } else if (Subtarget->isThumb2()) {
20483 // A constant whose bitwise inverse can be used as an immediate
20484 // value in a data-processing instruction. This can be used in GCC
20485 // with a "B" modifier that prints the inverted value, for use with
20486 // BIC and MVN instructions. It is not useful otherwise but is
20487 // implemented for compatibility.
20488 if (ARM_AM::getT2SOImmVal(Arg: ~CVal) != -1)
20489 break;
20490 } else {
20491 // A constant whose bitwise inverse can be used as an immediate
20492 // value in a data-processing instruction. This can be used in GCC
20493 // with a "B" modifier that prints the inverted value, for use with
20494 // BIC and MVN instructions. It is not useful otherwise but is
20495 // implemented for compatibility.
20496 if (ARM_AM::getSOImmVal(Arg: ~CVal) != -1)
20497 break;
20498 }
20499 return;
20500
20501 case 'L':
20502 if (Subtarget->isThumb1Only()) {
20503 // This must be a constant between -7 and 7,
20504 // for 3-operand ADD/SUB immediate instructions.
20505 if (CVal >= -7 && CVal < 7)
20506 break;
20507 } else if (Subtarget->isThumb2()) {
20508 // A constant whose negation can be used as an immediate value in a
20509 // data-processing instruction. This can be used in GCC with an "n"
20510 // modifier that prints the negated value, for use with SUB
20511 // instructions. It is not useful otherwise but is implemented for
20512 // compatibility.
20513 if (ARM_AM::getT2SOImmVal(Arg: -CVal) != -1)
20514 break;
20515 } else {
20516 // A constant whose negation can be used as an immediate value in a
20517 // data-processing instruction. This can be used in GCC with an "n"
20518 // modifier that prints the negated value, for use with SUB
20519 // instructions. It is not useful otherwise but is implemented for
20520 // compatibility.
20521 if (ARM_AM::getSOImmVal(Arg: -CVal) != -1)
20522 break;
20523 }
20524 return;
20525
20526 case 'M':
20527 if (Subtarget->isThumb1Only()) {
20528 // This must be a multiple of 4 between 0 and 1020, for
20529 // ADD sp + immediate.
20530 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
20531 break;
20532 } else {
20533 // A power of two or a constant between 0 and 32. This is used in
20534 // GCC for the shift amount on shifted register operands, but it is
20535 // useful in general for any shift amounts.
20536 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
20537 break;
20538 }
20539 return;
20540
20541 case 'N':
20542 if (Subtarget->isThumb1Only()) {
20543 // This must be a constant between 0 and 31, for shift amounts.
20544 if (CVal >= 0 && CVal <= 31)
20545 break;
20546 }
20547 return;
20548
20549 case 'O':
20550 if (Subtarget->isThumb1Only()) {
20551 // This must be a multiple of 4 between -508 and 508, for
20552 // ADD/SUB sp = sp + immediate.
20553 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
20554 break;
20555 }
20556 return;
20557 }
20558 Result = DAG.getSignedTargetConstant(Val: CVal, DL: SDLoc(Op), VT: Op.getValueType());
20559 break;
20560 }
20561
20562 if (Result.getNode()) {
20563 Ops.push_back(x: Result);
20564 return;
20565 }
20566 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20567}
20568
20569static RTLIB::Libcall getDivRemLibcall(
20570 const SDNode *N, MVT::SimpleValueType SVT) {
20571 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
20572 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
20573 "Unhandled Opcode in getDivRemLibcall");
20574 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20575 N->getOpcode() == ISD::SREM;
20576 RTLIB::Libcall LC;
20577 switch (SVT) {
20578 default: llvm_unreachable("Unexpected request for libcall!");
20579 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
20580 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
20581 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
20582 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
20583 }
20584 return LC;
20585}
20586
20587static TargetLowering::ArgListTy getDivRemArgList(
20588 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
20589 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
20590 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
20591 "Unhandled Opcode in getDivRemArgList");
20592 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20593 N->getOpcode() == ISD::SREM;
20594 TargetLowering::ArgListTy Args;
20595 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
20596 EVT ArgVT = N->getOperand(Num: i).getValueType();
20597 Type *ArgTy = ArgVT.getTypeForEVT(Context&: *Context);
20598 TargetLowering::ArgListEntry Entry(N->getOperand(Num: i), ArgTy);
20599 Entry.IsSExt = isSigned;
20600 Entry.IsZExt = !isSigned;
20601 Args.push_back(x: Entry);
20602 }
20603 if (Subtarget->getTargetTriple().isOSWindows() && Args.size() >= 2)
20604 std::swap(a&: Args[0], b&: Args[1]);
20605 return Args;
20606}
20607
20608SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
20609 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
20610 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
20611 Subtarget->isTargetFuchsia() || Subtarget->isTargetWindows()) &&
20612 "Register-based DivRem lowering only");
20613 unsigned Opcode = Op->getOpcode();
20614 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
20615 "Invalid opcode for Div/Rem lowering");
20616 bool isSigned = (Opcode == ISD::SDIVREM);
20617 EVT VT = Op->getValueType(ResNo: 0);
20618 SDLoc dl(Op);
20619
20620 if (VT == MVT::i64 && isa<ConstantSDNode>(Val: Op.getOperand(i: 1))) {
20621 SmallVector<SDValue> Result;
20622 if (expandDIVREMByConstant(N: Op.getNode(), Result, HiLoVT: MVT::i32, DAG)) {
20623 SDValue Res0 =
20624 DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT, N1: Result[0], N2: Result[1]);
20625 SDValue Res1 =
20626 DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT, N1: Result[2], N2: Result[3]);
20627 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl, VTList: Op->getVTList(),
20628 Ops: {Res0, Res1});
20629 }
20630 }
20631
20632 Type *Ty = VT.getTypeForEVT(Context&: *DAG.getContext());
20633
20634 // If the target has hardware divide, use divide + multiply + subtract:
20635 // div = a / b
20636 // rem = a - b * div
20637 // return {div, rem}
20638 // This should be lowered into UDIV/SDIV + MLS later on.
20639 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
20640 : Subtarget->hasDivideInARMMode();
20641 if (hasDivide && Op->getValueType(ResNo: 0).isSimple() &&
20642 Op->getSimpleValueType(ResNo: 0) == MVT::i32) {
20643 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
20644 const SDValue Dividend = Op->getOperand(Num: 0);
20645 const SDValue Divisor = Op->getOperand(Num: 1);
20646 SDValue Div = DAG.getNode(Opcode: DivOpcode, DL: dl, VT, N1: Dividend, N2: Divisor);
20647 SDValue Mul = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT, N1: Div, N2: Divisor);
20648 SDValue Rem = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: Dividend, N2: Mul);
20649
20650 SDValue Values[2] = {Div, Rem};
20651 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT), Ops: Values);
20652 }
20653
20654 RTLIB::Libcall LC = getDivRemLibcall(N: Op.getNode(),
20655 SVT: VT.getSimpleVT().SimpleTy);
20656 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(Call: LC);
20657
20658 SDValue InChain = DAG.getEntryNode();
20659
20660 TargetLowering::ArgListTy Args = getDivRemArgList(N: Op.getNode(),
20661 Context: DAG.getContext(),
20662 Subtarget);
20663
20664 SDValue Callee =
20665 DAG.getExternalSymbol(LCImpl, VT: getPointerTy(DL: DAG.getDataLayout()));
20666
20667 Type *RetTy = StructType::get(elt1: Ty, elts: Ty);
20668
20669 if (getTM().getTargetTriple().isOSWindows())
20670 InChain = WinDBZCheckDenominator(DAG, N: Op.getNode(), InChain);
20671
20672 TargetLowering::CallLoweringInfo CLI(DAG);
20673 CLI.setDebugLoc(dl)
20674 .setChain(InChain)
20675 .setCallee(CC: DAG.getLibcalls().getLibcallImplCallingConv(Call: LCImpl), ResultType: RetTy,
20676 Target: Callee, ArgsList: std::move(Args))
20677 .setInRegister()
20678 .setSExtResult(isSigned)
20679 .setZExtResult(!isSigned);
20680
20681 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
20682 return CallInfo.first;
20683}
20684
20685// Lowers REM using divmod helpers
20686// see RTABI section 4.2/4.3
20687SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
20688 EVT VT = N->getValueType(ResNo: 0);
20689
20690 if (VT == MVT::i64 && isa<ConstantSDNode>(Val: N->getOperand(Num: 1))) {
20691 SmallVector<SDValue> Result;
20692 if (expandDIVREMByConstant(N, Result, HiLoVT: MVT::i32, DAG))
20693 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: SDLoc(N), VT: N->getValueType(ResNo: 0),
20694 N1: Result[0], N2: Result[1]);
20695 }
20696
20697 // Build return types (div and rem)
20698 std::vector<Type*> RetTyParams;
20699 Type *RetTyElement;
20700
20701 switch (VT.getSimpleVT().SimpleTy) {
20702 default: llvm_unreachable("Unexpected request for libcall!");
20703 case MVT::i8: RetTyElement = Type::getInt8Ty(C&: *DAG.getContext()); break;
20704 case MVT::i16: RetTyElement = Type::getInt16Ty(C&: *DAG.getContext()); break;
20705 case MVT::i32: RetTyElement = Type::getInt32Ty(C&: *DAG.getContext()); break;
20706 case MVT::i64: RetTyElement = Type::getInt64Ty(C&: *DAG.getContext()); break;
20707 }
20708
20709 RetTyParams.push_back(x: RetTyElement);
20710 RetTyParams.push_back(x: RetTyElement);
20711 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
20712 Type *RetTy = StructType::get(Context&: *DAG.getContext(), Elements: ret);
20713
20714 RTLIB::Libcall LC = getDivRemLibcall(N, SVT: N->getValueType(ResNo: 0).getSimpleVT().
20715 SimpleTy);
20716 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(Call: LC);
20717 SDValue InChain = DAG.getEntryNode();
20718 TargetLowering::ArgListTy Args = getDivRemArgList(N, Context: DAG.getContext(),
20719 Subtarget);
20720 bool isSigned = N->getOpcode() == ISD::SREM;
20721
20722 SDValue Callee =
20723 DAG.getExternalSymbol(LCImpl, VT: getPointerTy(DL: DAG.getDataLayout()));
20724
20725 if (getTM().getTargetTriple().isOSWindows())
20726 InChain = WinDBZCheckDenominator(DAG, N, InChain);
20727
20728 // Lower call
20729 CallLoweringInfo CLI(DAG);
20730 CLI.setChain(InChain)
20731 .setCallee(CC: DAG.getLibcalls().getLibcallImplCallingConv(Call: LCImpl), ResultType: RetTy,
20732 Target: Callee, ArgsList: std::move(Args))
20733 .setSExtResult(isSigned)
20734 .setZExtResult(!isSigned)
20735 .setDebugLoc(SDLoc(N));
20736 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
20737
20738 // Return second (rem) result operand (first contains div)
20739 SDNode *ResNode = CallResult.first.getNode();
20740 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
20741 return ResNode->getOperand(Num: 1);
20742}
20743
20744SDValue
20745ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
20746 assert(getTM().getTargetTriple().isOSWindows() &&
20747 "unsupported target platform");
20748 SDLoc DL(Op);
20749
20750 // Get the inputs.
20751 SDValue Chain = Op.getOperand(i: 0);
20752 SDValue Size = Op.getOperand(i: 1);
20753
20754 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
20755 Kind: "no-stack-arg-probe")) {
20756 MaybeAlign Align =
20757 cast<ConstantSDNode>(Val: Op.getOperand(i: 2))->getMaybeAlignValue();
20758 SDValue SP = DAG.getCopyFromReg(Chain, dl: DL, Reg: ARM::SP, VT: MVT::i32);
20759 Chain = SP.getValue(R: 1);
20760 SP = DAG.getNode(Opcode: ISD::SUB, DL, VT: MVT::i32, N1: SP, N2: Size);
20761 if (Align)
20762 SP = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: SP.getValue(R: 0),
20763 N2: DAG.getSignedConstant(Val: -Align->value(), DL, VT: MVT::i32));
20764 Chain = DAG.getCopyToReg(Chain, dl: DL, Reg: ARM::SP, N: SP);
20765 SDValue Ops[2] = { SP, Chain };
20766 return DAG.getMergeValues(Ops, dl: DL);
20767 }
20768
20769 SDValue Words = DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: Size,
20770 N2: DAG.getConstant(Val: 2, DL, VT: MVT::i32));
20771
20772 SDValue Glue;
20773 Chain = DAG.getCopyToReg(Chain, dl: DL, Reg: ARM::R4, N: Words, Glue);
20774 Glue = Chain.getValue(R: 1);
20775
20776 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
20777 Chain = DAG.getNode(Opcode: ARMISD::WIN__CHKSTK, DL, VTList: NodeTys, N1: Chain, N2: Glue);
20778
20779 SDValue NewSP = DAG.getCopyFromReg(Chain, dl: DL, Reg: ARM::SP, VT: MVT::i32);
20780 Chain = NewSP.getValue(R: 1);
20781
20782 SDValue Ops[2] = { NewSP, Chain };
20783 return DAG.getMergeValues(Ops, dl: DL);
20784}
20785
20786SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
20787 bool IsStrict = Op->isStrictFPOpcode();
20788 SDValue SrcVal = Op.getOperand(i: IsStrict ? 1 : 0);
20789 const unsigned DstSz = Op.getValueType().getSizeInBits();
20790 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
20791 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
20792 "Unexpected type for custom-lowering FP_EXTEND");
20793
20794 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
20795 "With both FP DP and 16, any FP conversion is legal!");
20796
20797 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
20798 "With FP16, 16 to 32 conversion is legal!");
20799
20800 // Converting from 32 -> 64 is valid if we have FP64.
20801 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
20802 // FIXME: Remove this when we have strict fp instruction selection patterns
20803 if (IsStrict) {
20804 SDLoc Loc(Op);
20805 SDValue Result = DAG.getNode(Opcode: ISD::FP_EXTEND,
20806 DL: Loc, VT: Op.getValueType(), Operand: SrcVal);
20807 return DAG.getMergeValues(Ops: {Result, Op.getOperand(i: 0)}, dl: Loc);
20808 }
20809 return Op;
20810 }
20811
20812 // Either we are converting from 16 -> 64, without FP16 and/or
20813 // FP.double-precision or without Armv8-fp. So we must do it in two
20814 // steps.
20815 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
20816 // without FP16. So we must do a function call.
20817 SDLoc Loc(Op);
20818 RTLIB::Libcall LC;
20819 MakeLibCallOptions CallOptions;
20820 SDValue Chain = IsStrict ? Op.getOperand(i: 0) : SDValue();
20821 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
20822 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
20823 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
20824 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
20825 if (Supported) {
20826 if (IsStrict) {
20827 SrcVal = DAG.getNode(Opcode: ISD::STRICT_FP_EXTEND, DL: Loc,
20828 ResultTys: {DstVT, MVT::Other}, Ops: {Chain, SrcVal});
20829 Chain = SrcVal.getValue(R: 1);
20830 } else {
20831 SrcVal = DAG.getNode(Opcode: ISD::FP_EXTEND, DL: Loc, VT: DstVT, Operand: SrcVal);
20832 }
20833 } else {
20834 LC = RTLIB::getFPEXT(OpVT: SrcVT, RetVT: DstVT);
20835 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
20836 "Unexpected type for custom-lowering FP_EXTEND");
20837 std::tie(args&: SrcVal, args&: Chain) = makeLibCall(DAG, LC, RetVT: DstVT, Ops: SrcVal, CallOptions,
20838 dl: Loc, Chain);
20839 }
20840 }
20841
20842 return IsStrict ? DAG.getMergeValues(Ops: {SrcVal, Chain}, dl: Loc) : SrcVal;
20843}
20844
20845SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
20846 bool IsStrict = Op->isStrictFPOpcode();
20847
20848 SDValue SrcVal = Op.getOperand(i: IsStrict ? 1 : 0);
20849 EVT SrcVT = SrcVal.getValueType();
20850 EVT DstVT = Op.getValueType();
20851 const unsigned DstSz = Op.getValueType().getSizeInBits();
20852 const unsigned SrcSz = SrcVT.getSizeInBits();
20853 (void)DstSz;
20854 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
20855 "Unexpected type for custom-lowering FP_ROUND");
20856
20857 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
20858 "With both FP DP and 16, any FP conversion is legal!");
20859
20860 SDLoc Loc(Op);
20861
20862 // Instruction from 32 -> 16 if hasFP16 is valid
20863 if (SrcSz == 32 && Subtarget->hasFP16())
20864 return Op;
20865
20866 // Lib call from 32 -> 16 / 64 -> [32, 16]
20867 RTLIB::Libcall LC = RTLIB::getFPROUND(OpVT: SrcVT, RetVT: DstVT);
20868 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
20869 "Unexpected type for custom-lowering FP_ROUND");
20870 MakeLibCallOptions CallOptions;
20871 SDValue Chain = IsStrict ? Op.getOperand(i: 0) : SDValue();
20872 SDValue Result;
20873 std::tie(args&: Result, args&: Chain) = makeLibCall(DAG, LC, RetVT: DstVT, Ops: SrcVal, CallOptions,
20874 dl: Loc, Chain);
20875 return IsStrict ? DAG.getMergeValues(Ops: {Result, Chain}, dl: Loc) : Result;
20876}
20877
20878bool
20879ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
20880 // The ARM target isn't yet aware of offsets.
20881 return false;
20882}
20883
20884bool ARM::isBitFieldInvertedMask(unsigned v) {
20885 if (v == 0xffffffff)
20886 return false;
20887
20888 // there can be 1's on either or both "outsides", all the "inside"
20889 // bits must be 0's
20890 return isShiftedMask_32(Value: ~v);
20891}
20892
20893/// isFPImmLegal - Returns true if the target can instruction select the
20894/// specified FP immediate natively. If false, the legalizer will
20895/// materialize the FP immediate as a load from a constant pool.
20896bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
20897 bool ForCodeSize) const {
20898 if (!Subtarget->hasVFP3Base())
20899 return false;
20900 if (VT == MVT::f16 && Subtarget->hasFullFP16())
20901 return ARM_AM::getFP16Imm(FPImm: Imm) != -1;
20902 if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
20903 ARM_AM::getFP32FP16Imm(FPImm: Imm) != -1)
20904 return true;
20905 if (VT == MVT::f32)
20906 return ARM_AM::getFP32Imm(FPImm: Imm) != -1;
20907 if (VT == MVT::f64 && Subtarget->hasFP64())
20908 return ARM_AM::getFP64Imm(FPImm: Imm) != -1;
20909 return false;
20910}
20911
20912/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
20913/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
20914/// specified in the intrinsic calls.
20915void ARMTargetLowering::getTgtMemIntrinsic(
20916 SmallVectorImpl<IntrinsicInfo> &Infos, const CallBase &I,
20917 MachineFunction &MF, unsigned Intrinsic) const {
20918 IntrinsicInfo Info;
20919 switch (Intrinsic) {
20920 case Intrinsic::arm_neon_vld1:
20921 case Intrinsic::arm_neon_vld2:
20922 case Intrinsic::arm_neon_vld3:
20923 case Intrinsic::arm_neon_vld4:
20924 case Intrinsic::arm_neon_vld2lane:
20925 case Intrinsic::arm_neon_vld3lane:
20926 case Intrinsic::arm_neon_vld4lane:
20927 case Intrinsic::arm_neon_vld2dup:
20928 case Intrinsic::arm_neon_vld3dup:
20929 case Intrinsic::arm_neon_vld4dup: {
20930 Info.opc = ISD::INTRINSIC_W_CHAIN;
20931 // Conservatively set memVT to the entire set of vectors loaded.
20932 auto &DL = I.getDataLayout();
20933 uint64_t NumElts = DL.getTypeSizeInBits(Ty: I.getType()) / 64;
20934 Info.memVT = EVT::getVectorVT(Context&: I.getType()->getContext(), VT: MVT::i64, NumElements: NumElts);
20935 Info.ptrVal = I.getArgOperand(i: 0);
20936 Info.offset = 0;
20937 Value *AlignArg = I.getArgOperand(i: I.arg_size() - 1);
20938 Info.align = cast<ConstantInt>(Val: AlignArg)->getMaybeAlignValue();
20939 // volatile loads with NEON intrinsics not supported
20940 Info.flags = MachineMemOperand::MOLoad;
20941 Infos.push_back(Elt: Info);
20942 return;
20943 }
20944 case Intrinsic::arm_neon_vld1x2:
20945 case Intrinsic::arm_neon_vld1x3:
20946 case Intrinsic::arm_neon_vld1x4: {
20947 Info.opc = ISD::INTRINSIC_W_CHAIN;
20948 // Conservatively set memVT to the entire set of vectors loaded.
20949 auto &DL = I.getDataLayout();
20950 uint64_t NumElts = DL.getTypeSizeInBits(Ty: I.getType()) / 64;
20951 Info.memVT = EVT::getVectorVT(Context&: I.getType()->getContext(), VT: MVT::i64, NumElements: NumElts);
20952 Info.ptrVal = I.getArgOperand(i: I.arg_size() - 1);
20953 Info.offset = 0;
20954 Info.align = I.getParamAlign(ArgNo: I.arg_size() - 1).valueOrOne();
20955 // volatile loads with NEON intrinsics not supported
20956 Info.flags = MachineMemOperand::MOLoad;
20957 Infos.push_back(Elt: Info);
20958 return;
20959 }
20960 case Intrinsic::arm_neon_vst1:
20961 case Intrinsic::arm_neon_vst2:
20962 case Intrinsic::arm_neon_vst3:
20963 case Intrinsic::arm_neon_vst4:
20964 case Intrinsic::arm_neon_vst2lane:
20965 case Intrinsic::arm_neon_vst3lane:
20966 case Intrinsic::arm_neon_vst4lane: {
20967 Info.opc = ISD::INTRINSIC_VOID;
20968 // Conservatively set memVT to the entire set of vectors stored.
20969 auto &DL = I.getDataLayout();
20970 unsigned NumElts = 0;
20971 for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
20972 Type *ArgTy = I.getArgOperand(i: ArgI)->getType();
20973 if (!ArgTy->isVectorTy())
20974 break;
20975 NumElts += DL.getTypeSizeInBits(Ty: ArgTy) / 64;
20976 }
20977 Info.memVT = EVT::getVectorVT(Context&: I.getType()->getContext(), VT: MVT::i64, NumElements: NumElts);
20978 Info.ptrVal = I.getArgOperand(i: 0);
20979 Info.offset = 0;
20980 Value *AlignArg = I.getArgOperand(i: I.arg_size() - 1);
20981 Info.align = cast<ConstantInt>(Val: AlignArg)->getMaybeAlignValue();
20982 // volatile stores with NEON intrinsics not supported
20983 Info.flags = MachineMemOperand::MOStore;
20984 Infos.push_back(Elt: Info);
20985 return;
20986 }
20987 case Intrinsic::arm_neon_vst1x2:
20988 case Intrinsic::arm_neon_vst1x3:
20989 case Intrinsic::arm_neon_vst1x4: {
20990 Info.opc = ISD::INTRINSIC_VOID;
20991 // Conservatively set memVT to the entire set of vectors stored.
20992 auto &DL = I.getDataLayout();
20993 unsigned NumElts = 0;
20994 for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
20995 Type *ArgTy = I.getArgOperand(i: ArgI)->getType();
20996 if (!ArgTy->isVectorTy())
20997 break;
20998 NumElts += DL.getTypeSizeInBits(Ty: ArgTy) / 64;
20999 }
21000 Info.memVT = EVT::getVectorVT(Context&: I.getType()->getContext(), VT: MVT::i64, NumElements: NumElts);
21001 Info.ptrVal = I.getArgOperand(i: 0);
21002 Info.offset = 0;
21003 Info.align = I.getParamAlign(ArgNo: 0).valueOrOne();
21004 // volatile stores with NEON intrinsics not supported
21005 Info.flags = MachineMemOperand::MOStore;
21006 Infos.push_back(Elt: Info);
21007 return;
21008 }
21009 case Intrinsic::arm_mve_vld2q:
21010 case Intrinsic::arm_mve_vld4q: {
21011 Info.opc = ISD::INTRINSIC_W_CHAIN;
21012 // Conservatively set memVT to the entire set of vectors loaded.
21013 Type *VecTy = cast<StructType>(Val: I.getType())->getElementType(N: 1);
21014 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
21015 Info.memVT = EVT::getVectorVT(Context&: VecTy->getContext(), VT: MVT::i64, NumElements: Factor * 2);
21016 Info.ptrVal = I.getArgOperand(i: 0);
21017 Info.offset = 0;
21018 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
21019 // volatile loads with MVE intrinsics not supported
21020 Info.flags = MachineMemOperand::MOLoad;
21021 Infos.push_back(Elt: Info);
21022 return;
21023 }
21024 case Intrinsic::arm_mve_vst2q:
21025 case Intrinsic::arm_mve_vst4q: {
21026 Info.opc = ISD::INTRINSIC_VOID;
21027 // Conservatively set memVT to the entire set of vectors stored.
21028 Type *VecTy = I.getArgOperand(i: 1)->getType();
21029 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
21030 Info.memVT = EVT::getVectorVT(Context&: VecTy->getContext(), VT: MVT::i64, NumElements: Factor * 2);
21031 Info.ptrVal = I.getArgOperand(i: 0);
21032 Info.offset = 0;
21033 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
21034 // volatile stores with MVE intrinsics not supported
21035 Info.flags = MachineMemOperand::MOStore;
21036 Infos.push_back(Elt: Info);
21037 return;
21038 }
21039 case Intrinsic::arm_mve_vldr_gather_base:
21040 case Intrinsic::arm_mve_vldr_gather_base_predicated: {
21041 Info.opc = ISD::INTRINSIC_W_CHAIN;
21042 Info.ptrVal = nullptr;
21043 Info.memVT = MVT::getVT(Ty: I.getType());
21044 Info.align = Align(1);
21045 Info.flags |= MachineMemOperand::MOLoad;
21046 Infos.push_back(Elt: Info);
21047 return;
21048 }
21049 case Intrinsic::arm_mve_vldr_gather_base_wb:
21050 case Intrinsic::arm_mve_vldr_gather_base_wb_predicated: {
21051 Info.opc = ISD::INTRINSIC_W_CHAIN;
21052 Info.ptrVal = nullptr;
21053 Info.memVT = MVT::getVT(Ty: I.getType()->getContainedType(i: 0));
21054 Info.align = Align(1);
21055 Info.flags |= MachineMemOperand::MOLoad;
21056 Infos.push_back(Elt: Info);
21057 return;
21058 }
21059 case Intrinsic::arm_mve_vldr_gather_offset:
21060 case Intrinsic::arm_mve_vldr_gather_offset_predicated: {
21061 Info.opc = ISD::INTRINSIC_W_CHAIN;
21062 Info.ptrVal = nullptr;
21063 MVT DataVT = MVT::getVT(Ty: I.getType());
21064 unsigned MemSize = cast<ConstantInt>(Val: I.getArgOperand(i: 2))->getZExtValue();
21065 Info.memVT = MVT::getVectorVT(VT: MVT::getIntegerVT(BitWidth: MemSize),
21066 NumElements: DataVT.getVectorNumElements());
21067 Info.align = Align(1);
21068 Info.flags |= MachineMemOperand::MOLoad;
21069 Infos.push_back(Elt: Info);
21070 return;
21071 }
21072 case Intrinsic::arm_mve_vstr_scatter_base:
21073 case Intrinsic::arm_mve_vstr_scatter_base_predicated: {
21074 Info.opc = ISD::INTRINSIC_VOID;
21075 Info.ptrVal = nullptr;
21076 Info.memVT = MVT::getVT(Ty: I.getArgOperand(i: 2)->getType());
21077 Info.align = Align(1);
21078 Info.flags |= MachineMemOperand::MOStore;
21079 Infos.push_back(Elt: Info);
21080 return;
21081 }
21082 case Intrinsic::arm_mve_vstr_scatter_base_wb:
21083 case Intrinsic::arm_mve_vstr_scatter_base_wb_predicated: {
21084 Info.opc = ISD::INTRINSIC_W_CHAIN;
21085 Info.ptrVal = nullptr;
21086 Info.memVT = MVT::getVT(Ty: I.getArgOperand(i: 2)->getType());
21087 Info.align = Align(1);
21088 Info.flags |= MachineMemOperand::MOStore;
21089 Infos.push_back(Elt: Info);
21090 return;
21091 }
21092 case Intrinsic::arm_mve_vstr_scatter_offset:
21093 case Intrinsic::arm_mve_vstr_scatter_offset_predicated: {
21094 Info.opc = ISD::INTRINSIC_VOID;
21095 Info.ptrVal = nullptr;
21096 MVT DataVT = MVT::getVT(Ty: I.getArgOperand(i: 2)->getType());
21097 unsigned MemSize = cast<ConstantInt>(Val: I.getArgOperand(i: 3))->getZExtValue();
21098 Info.memVT = MVT::getVectorVT(VT: MVT::getIntegerVT(BitWidth: MemSize),
21099 NumElements: DataVT.getVectorNumElements());
21100 Info.align = Align(1);
21101 Info.flags |= MachineMemOperand::MOStore;
21102 Infos.push_back(Elt: Info);
21103 return;
21104 }
21105 case Intrinsic::arm_ldaex:
21106 case Intrinsic::arm_ldrex: {
21107 auto &DL = I.getDataLayout();
21108 Type *ValTy = I.getParamElementType(ArgNo: 0);
21109 Info.opc = ISD::INTRINSIC_W_CHAIN;
21110 Info.memVT = MVT::getVT(Ty: ValTy);
21111 Info.ptrVal = I.getArgOperand(i: 0);
21112 Info.offset = 0;
21113 Info.align = DL.getABITypeAlign(Ty: ValTy);
21114 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
21115 Infos.push_back(Elt: Info);
21116 return;
21117 }
21118 case Intrinsic::arm_stlex:
21119 case Intrinsic::arm_strex: {
21120 auto &DL = I.getDataLayout();
21121 Type *ValTy = I.getParamElementType(ArgNo: 1);
21122 Info.opc = ISD::INTRINSIC_W_CHAIN;
21123 Info.memVT = MVT::getVT(Ty: ValTy);
21124 Info.ptrVal = I.getArgOperand(i: 1);
21125 Info.offset = 0;
21126 Info.align = DL.getABITypeAlign(Ty: ValTy);
21127 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
21128 Infos.push_back(Elt: Info);
21129 return;
21130 }
21131 case Intrinsic::arm_stlexd:
21132 case Intrinsic::arm_strexd:
21133 Info.opc = ISD::INTRINSIC_W_CHAIN;
21134 Info.memVT = MVT::i64;
21135 Info.ptrVal = I.getArgOperand(i: 2);
21136 Info.offset = 0;
21137 Info.align = Align(8);
21138 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
21139 Infos.push_back(Elt: Info);
21140 return;
21141
21142 case Intrinsic::arm_ldaexd:
21143 case Intrinsic::arm_ldrexd:
21144 Info.opc = ISD::INTRINSIC_W_CHAIN;
21145 Info.memVT = MVT::i64;
21146 Info.ptrVal = I.getArgOperand(i: 0);
21147 Info.offset = 0;
21148 Info.align = Align(8);
21149 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
21150 Infos.push_back(Elt: Info);
21151 return;
21152
21153 default:
21154 break;
21155 }
21156}
21157
21158/// Returns true if it is beneficial to convert a load of a constant
21159/// to just the constant itself.
21160bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
21161 Type *Ty) const {
21162 assert(Ty->isIntegerTy());
21163
21164 unsigned Bits = Ty->getPrimitiveSizeInBits();
21165 if (Bits == 0 || Bits > 32)
21166 return false;
21167 return true;
21168}
21169
21170bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
21171 unsigned Index) const {
21172 if (!isOperationLegalOrCustom(Op: ISD::EXTRACT_SUBVECTOR, VT: ResVT))
21173 return false;
21174
21175 return (Index == 0 || Index == ResVT.getVectorNumElements());
21176}
21177
21178Instruction *ARMTargetLowering::makeDMB(IRBuilderBase &Builder,
21179 ARM_MB::MemBOpt Domain) const {
21180 // First, if the target has no DMB, see what fallback we can use.
21181 if (!Subtarget->hasDataBarrier()) {
21182 // Some ARMv6 cpus can support data barriers with an mcr instruction.
21183 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
21184 // here.
21185 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
21186 Value* args[6] = {Builder.getInt32(C: 15), Builder.getInt32(C: 0),
21187 Builder.getInt32(C: 0), Builder.getInt32(C: 7),
21188 Builder.getInt32(C: 10), Builder.getInt32(C: 5)};
21189 return Builder.CreateIntrinsic(ID: Intrinsic::arm_mcr, Args: args);
21190 } else {
21191 // Instead of using barriers, atomic accesses on these subtargets use
21192 // libcalls.
21193 llvm_unreachable("makeDMB on a target so old that it has no barriers");
21194 }
21195 } else {
21196 // Only a full system barrier exists in the M-class architectures.
21197 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
21198 Constant *CDomain = Builder.getInt32(C: Domain);
21199 return Builder.CreateIntrinsic(ID: Intrinsic::arm_dmb, Args: CDomain);
21200 }
21201}
21202
21203// Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
21204Instruction *ARMTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
21205 Instruction *Inst,
21206 AtomicOrdering Ord) const {
21207 switch (Ord) {
21208 case AtomicOrdering::NotAtomic:
21209 case AtomicOrdering::Unordered:
21210 llvm_unreachable("Invalid fence: unordered/non-atomic");
21211 case AtomicOrdering::Monotonic:
21212 case AtomicOrdering::Acquire:
21213 return nullptr; // Nothing to do
21214 case AtomicOrdering::SequentiallyConsistent:
21215 if (!Inst->hasAtomicStore())
21216 return nullptr; // Nothing to do
21217 [[fallthrough]];
21218 case AtomicOrdering::Release:
21219 case AtomicOrdering::AcquireRelease:
21220 if (Subtarget->preferISHSTBarriers())
21221 return makeDMB(Builder, Domain: ARM_MB::ISHST);
21222 // FIXME: add a comment with a link to documentation justifying this.
21223 else
21224 return makeDMB(Builder, Domain: ARM_MB::ISH);
21225 }
21226 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
21227}
21228
21229Instruction *ARMTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
21230 Instruction *Inst,
21231 AtomicOrdering Ord) const {
21232 switch (Ord) {
21233 case AtomicOrdering::NotAtomic:
21234 case AtomicOrdering::Unordered:
21235 llvm_unreachable("Invalid fence: unordered/not-atomic");
21236 case AtomicOrdering::Monotonic:
21237 case AtomicOrdering::Release:
21238 return nullptr; // Nothing to do
21239 case AtomicOrdering::Acquire:
21240 case AtomicOrdering::AcquireRelease:
21241 case AtomicOrdering::SequentiallyConsistent:
21242 return makeDMB(Builder, Domain: ARM_MB::ISH);
21243 }
21244 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
21245}
21246
21247// Loads and stores less than 64-bits are already atomic; ones above that
21248// are doomed anyway, so defer to the default libcall and blame the OS when
21249// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21250// anything for those.
21251TargetLoweringBase::AtomicExpansionKind
21252ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
21253 bool has64BitAtomicStore;
21254 if (Subtarget->isMClass())
21255 has64BitAtomicStore = false;
21256 else if (Subtarget->isThumb())
21257 has64BitAtomicStore = Subtarget->hasV7Ops();
21258 else
21259 has64BitAtomicStore = Subtarget->hasV6Ops();
21260
21261 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
21262 return Size == 64 && has64BitAtomicStore ? AtomicExpansionKind::Expand
21263 : AtomicExpansionKind::None;
21264}
21265
21266// Loads and stores less than 64-bits are already atomic; ones above that
21267// are doomed anyway, so defer to the default libcall and blame the OS when
21268// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21269// anything for those.
21270// FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
21271// guarantee, see DDI0406C ARM architecture reference manual,
21272// sections A8.8.72-74 LDRD)
21273TargetLowering::AtomicExpansionKind
21274ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
21275 bool has64BitAtomicLoad;
21276 if (Subtarget->isMClass())
21277 has64BitAtomicLoad = false;
21278 else if (Subtarget->isThumb())
21279 has64BitAtomicLoad = Subtarget->hasV7Ops();
21280 else
21281 has64BitAtomicLoad = Subtarget->hasV6Ops();
21282
21283 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
21284 return (Size == 64 && has64BitAtomicLoad) ? AtomicExpansionKind::LLOnly
21285 : AtomicExpansionKind::None;
21286}
21287
21288// For the real atomic operations, we have ldrex/strex up to 32 bits,
21289// and up to 64 bits on the non-M profiles
21290TargetLowering::AtomicExpansionKind
21291ARMTargetLowering::shouldExpandAtomicRMWInIR(const AtomicRMWInst *AI) const {
21292 if (AI->isFloatingPointOperation())
21293 return AtomicExpansionKind::CmpXChg;
21294
21295 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
21296 bool hasAtomicRMW;
21297 if (Subtarget->isMClass())
21298 hasAtomicRMW = Subtarget->hasV8MBaselineOps();
21299 else if (Subtarget->isThumb())
21300 hasAtomicRMW = Subtarget->hasV7Ops();
21301 else
21302 hasAtomicRMW = Subtarget->hasV6Ops();
21303 if (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) {
21304 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
21305 // implement atomicrmw without spilling. If the target address is also on
21306 // the stack and close enough to the spill slot, this can lead to a
21307 // situation where the monitor always gets cleared and the atomic operation
21308 // can never succeed. So at -O0 lower this operation to a CAS loop.
21309 if (getTargetMachine().getOptLevel() == CodeGenOptLevel::None)
21310 return AtomicExpansionKind::CmpXChg;
21311 return AtomicExpansionKind::LLSC;
21312 }
21313 return AtomicExpansionKind::None;
21314}
21315
21316// Similar to shouldExpandAtomicRMWInIR, ldrex/strex can be used up to 32
21317// bits, and up to 64 bits on the non-M profiles.
21318TargetLowering::AtomicExpansionKind
21319ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
21320 const AtomicCmpXchgInst *AI) const {
21321 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
21322 // implement cmpxchg without spilling. If the address being exchanged is also
21323 // on the stack and close enough to the spill slot, this can lead to a
21324 // situation where the monitor always gets cleared and the atomic operation
21325 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
21326 unsigned Size = AI->getOperand(i_nocapture: 1)->getType()->getPrimitiveSizeInBits();
21327 bool HasAtomicCmpXchg;
21328 if (Subtarget->isMClass())
21329 HasAtomicCmpXchg = Subtarget->hasV8MBaselineOps();
21330 else if (Subtarget->isThumb())
21331 HasAtomicCmpXchg = Subtarget->hasV7Ops();
21332 else
21333 HasAtomicCmpXchg = Subtarget->hasV6Ops();
21334 if (getTargetMachine().getOptLevel() != CodeGenOptLevel::None &&
21335 HasAtomicCmpXchg && Size <= (Subtarget->isMClass() ? 32U : 64U))
21336 return AtomicExpansionKind::LLSC;
21337 return AtomicExpansionKind::None;
21338}
21339
21340bool ARMTargetLowering::shouldInsertFencesForAtomic(
21341 const Instruction *I) const {
21342 return InsertFencesForAtomic;
21343}
21344
21345bool ARMTargetLowering::useLoadStackGuardNode(const Module &M) const {
21346 // ROPI/RWPI are not supported currently.
21347 return !Subtarget->isROPI() && !Subtarget->isRWPI();
21348}
21349
21350void ARMTargetLowering::insertSSPDeclarations(
21351 Module &M, const LibcallLoweringInfo &Libcalls) const {
21352 // MSVC CRT provides functionalities for stack protection.
21353 RTLIB::LibcallImpl SecurityCheckCookieLibcall =
21354 Libcalls.getLibcallImpl(Call: RTLIB::SECURITY_CHECK_COOKIE);
21355
21356 RTLIB::LibcallImpl SecurityCookieVar =
21357 Libcalls.getLibcallImpl(Call: RTLIB::STACK_CHECK_GUARD);
21358 if (SecurityCheckCookieLibcall != RTLIB::Unsupported &&
21359 SecurityCookieVar != RTLIB::Unsupported) {
21360 // MSVC CRT has a global variable holding security cookie.
21361 M.getOrInsertGlobal(Name: getLibcallImplName(Call: SecurityCookieVar),
21362 Ty: PointerType::getUnqual(C&: M.getContext()));
21363
21364 // MSVC CRT has a function to validate security cookie.
21365 FunctionCallee SecurityCheckCookie =
21366 M.getOrInsertFunction(Name: getLibcallImplName(Call: SecurityCheckCookieLibcall),
21367 RetTy: Type::getVoidTy(C&: M.getContext()),
21368 Args: PointerType::getUnqual(C&: M.getContext()));
21369 if (Function *F = dyn_cast<Function>(Val: SecurityCheckCookie.getCallee()))
21370 F->addParamAttr(ArgNo: 0, Kind: Attribute::AttrKind::InReg);
21371 }
21372
21373 TargetLowering::insertSSPDeclarations(M, Libcalls);
21374}
21375
21376bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
21377 unsigned &Cost) const {
21378 // If we do not have NEON, vector types are not natively supported.
21379 if (!Subtarget->hasNEON())
21380 return false;
21381
21382 // Floating point values and vector values map to the same register file.
21383 // Therefore, although we could do a store extract of a vector type, this is
21384 // better to leave at float as we have more freedom in the addressing mode for
21385 // those.
21386 if (VectorTy->isFPOrFPVectorTy())
21387 return false;
21388
21389 // If the index is unknown at compile time, this is very expensive to lower
21390 // and it is not possible to combine the store with the extract.
21391 if (!isa<ConstantInt>(Val: Idx))
21392 return false;
21393
21394 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
21395 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedValue();
21396 // We can do a store + vector extract on any vector that fits perfectly in a D
21397 // or Q register.
21398 if (BitWidth == 64 || BitWidth == 128) {
21399 Cost = 0;
21400 return true;
21401 }
21402 return false;
21403}
21404
21405bool ARMTargetLowering::canCreateUndefOrPoisonForTargetNode(
21406 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
21407 bool PoisonOnly, bool ConsiderFlags, unsigned Depth) const {
21408 unsigned Opcode = Op.getOpcode();
21409 switch (Opcode) {
21410 case ARMISD::VORRIMM:
21411 case ARMISD::VBICIMM:
21412 return false;
21413 }
21414 return TargetLowering::canCreateUndefOrPoisonForTargetNode(
21415 Op, DemandedElts, DAG, PoisonOnly, ConsiderFlags, Depth);
21416}
21417
21418bool ARMTargetLowering::isCheapToSpeculateCttz(Type *Ty) const {
21419 return Subtarget->hasV5TOps() && !Subtarget->isThumb1Only();
21420}
21421
21422bool ARMTargetLowering::isCheapToSpeculateCtlz(Type *Ty) const {
21423 return Subtarget->hasV5TOps() && !Subtarget->isThumb1Only();
21424}
21425
21426bool ARMTargetLowering::isMaskAndCmp0FoldingBeneficial(
21427 const Instruction &AndI) const {
21428 if (!Subtarget->hasV7Ops())
21429 return false;
21430
21431 // Sink the `and` instruction only if the mask would fit into a modified
21432 // immediate operand.
21433 ConstantInt *Mask = dyn_cast<ConstantInt>(Val: AndI.getOperand(i: 1));
21434 if (!Mask || Mask->getValue().getBitWidth() > 32u)
21435 return false;
21436 auto MaskVal = unsigned(Mask->getValue().getZExtValue());
21437 return (Subtarget->isThumb2() ? ARM_AM::getT2SOImmVal(Arg: MaskVal)
21438 : ARM_AM::getSOImmVal(Arg: MaskVal)) != -1;
21439}
21440
21441TargetLowering::ShiftLegalizationStrategy
21442ARMTargetLowering::preferredShiftLegalizationStrategy(
21443 SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
21444 if (Subtarget->hasMinSize() && !getTM().getTargetTriple().isOSWindows())
21445 return ShiftLegalizationStrategy::LowerToLibcall;
21446 return TargetLowering::preferredShiftLegalizationStrategy(DAG, N,
21447 ExpansionFactor);
21448}
21449
21450Value *ARMTargetLowering::emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
21451 Value *Addr,
21452 AtomicOrdering Ord) const {
21453 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21454 bool IsAcquire = isAcquireOrStronger(AO: Ord);
21455
21456 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
21457 // intrinsic must return {i32, i32} and we have to recombine them into a
21458 // single i64 here.
21459 if (ValueTy->getPrimitiveSizeInBits() == 64) {
21460 Intrinsic::ID Int =
21461 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
21462
21463 Value *LoHi =
21464 Builder.CreateIntrinsic(ID: Int, Args: Addr, /*FMFSource=*/nullptr, Name: "lohi");
21465
21466 Value *Lo = Builder.CreateExtractValue(Agg: LoHi, Idxs: 0, Name: "lo");
21467 Value *Hi = Builder.CreateExtractValue(Agg: LoHi, Idxs: 1, Name: "hi");
21468 if (!Subtarget->isLittle())
21469 std::swap (a&: Lo, b&: Hi);
21470 Lo = Builder.CreateZExt(V: Lo, DestTy: ValueTy, Name: "lo64");
21471 Hi = Builder.CreateZExt(V: Hi, DestTy: ValueTy, Name: "hi64");
21472 return Builder.CreateOr(
21473 LHS: Lo, RHS: Builder.CreateShl(LHS: Hi, RHS: ConstantInt::get(Ty: ValueTy, V: 32)), Name: "val64");
21474 }
21475
21476 Type *Tys[] = { Addr->getType() };
21477 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
21478 CallInst *CI = Builder.CreateIntrinsic(ID: Int, Types: Tys, Args: Addr);
21479
21480 CI->addParamAttr(
21481 ArgNo: 0, Attr: Attribute::get(Context&: M->getContext(), Kind: Attribute::ElementType, Ty: ValueTy));
21482 return Builder.CreateTruncOrBitCast(V: CI, DestTy: ValueTy);
21483}
21484
21485void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
21486 IRBuilderBase &Builder) const {
21487 if (!Subtarget->hasV7Ops())
21488 return;
21489 Builder.CreateIntrinsic(ID: Intrinsic::arm_clrex, Args: {});
21490}
21491
21492Value *ARMTargetLowering::emitStoreConditional(IRBuilderBase &Builder,
21493 Value *Val, Value *Addr,
21494 AtomicOrdering Ord) const {
21495 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21496 bool IsRelease = isReleaseOrStronger(AO: Ord);
21497
21498 // Since the intrinsics must have legal type, the i64 intrinsics take two
21499 // parameters: "i32, i32". We must marshal Val into the appropriate form
21500 // before the call.
21501 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
21502 Intrinsic::ID Int =
21503 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
21504 Type *Int32Ty = Type::getInt32Ty(C&: M->getContext());
21505
21506 Value *Lo = Builder.CreateTrunc(V: Val, DestTy: Int32Ty, Name: "lo");
21507 Value *Hi = Builder.CreateTrunc(V: Builder.CreateLShr(LHS: Val, RHS: 32), DestTy: Int32Ty, Name: "hi");
21508 if (!Subtarget->isLittle())
21509 std::swap(a&: Lo, b&: Hi);
21510 return Builder.CreateIntrinsic(ID: Int, Args: {Lo, Hi, Addr});
21511 }
21512
21513 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
21514 Type *Tys[] = { Addr->getType() };
21515 Function *Strex = Intrinsic::getOrInsertDeclaration(M, id: Int, OverloadTys: Tys);
21516
21517 CallInst *CI = Builder.CreateCall(
21518 Callee: Strex, Args: {Builder.CreateZExtOrBitCast(
21519 V: Val, DestTy: Strex->getFunctionType()->getParamType(i: 0)),
21520 Addr});
21521 CI->addParamAttr(ArgNo: 1, Attr: Attribute::get(Context&: M->getContext(), Kind: Attribute::ElementType,
21522 Ty: Val->getType()));
21523 return CI;
21524}
21525
21526
21527bool ARMTargetLowering::alignLoopsWithOptSize() const {
21528 return Subtarget->isMClass();
21529}
21530
21531/// A helper function for determining the number of interleaved accesses we
21532/// will generate when lowering accesses of the given type.
21533unsigned
21534ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
21535 const DataLayout &DL) const {
21536 return (DL.getTypeSizeInBits(Ty: VecTy) + 127) / 128;
21537}
21538
21539bool ARMTargetLowering::isLegalInterleavedAccessType(
21540 unsigned Factor, FixedVectorType *VecTy, Align Alignment,
21541 const DataLayout &DL) const {
21542
21543 unsigned VecSize = DL.getTypeSizeInBits(Ty: VecTy);
21544 unsigned ElSize = DL.getTypeSizeInBits(Ty: VecTy->getElementType());
21545
21546 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
21547 return false;
21548
21549 // Ensure the vector doesn't have f16 elements. Even though we could do an
21550 // i16 vldN, we can't hold the f16 vectors and will end up converting via
21551 // f32.
21552 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
21553 return false;
21554 if (Subtarget->hasMVEIntegerOps() && Factor == 3)
21555 return false;
21556
21557 // Ensure the number of vector elements is greater than 1.
21558 if (VecTy->getNumElements() < 2)
21559 return false;
21560
21561 // Ensure the element type is legal.
21562 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
21563 return false;
21564 // And the alignment if high enough under MVE.
21565 if (Subtarget->hasMVEIntegerOps() && Alignment < ElSize / 8)
21566 return false;
21567
21568 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
21569 // 128 will be split into multiple interleaved accesses.
21570 if (Subtarget->hasNEON() && VecSize == 64)
21571 return true;
21572 return VecSize % 128 == 0;
21573}
21574
21575unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
21576 if (Subtarget->hasNEON())
21577 return 4;
21578 if (Subtarget->hasMVEIntegerOps())
21579 return MVEMaxSupportedInterleaveFactor;
21580 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
21581}
21582
21583/// Lower an interleaved load into a vldN intrinsic.
21584///
21585/// E.g. Lower an interleaved load (Factor = 2):
21586/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
21587/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
21588/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
21589///
21590/// Into:
21591/// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
21592/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
21593/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
21594bool ARMTargetLowering::lowerInterleavedLoad(
21595 Instruction *Load, Value *Mask, ArrayRef<ShuffleVectorInst *> Shuffles,
21596 ArrayRef<unsigned> Indices, unsigned Factor, const APInt &GapMask) const {
21597 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
21598 "Invalid interleave factor");
21599 assert(!Shuffles.empty() && "Empty shufflevector input");
21600 assert(Shuffles.size() == Indices.size() &&
21601 "Unmatched number of shufflevectors and indices");
21602
21603 auto *LI = dyn_cast<LoadInst>(Val: Load);
21604 if (!LI)
21605 return false;
21606 assert(!Mask && GapMask.popcount() == Factor && "Unexpected mask on a load");
21607
21608 auto *VecTy = cast<FixedVectorType>(Val: Shuffles[0]->getType());
21609 Type *EltTy = VecTy->getElementType();
21610
21611 const DataLayout &DL = LI->getDataLayout();
21612 Align Alignment = LI->getAlign();
21613
21614 // Skip if we do not have NEON and skip illegal vector types. We can
21615 // "legalize" wide vector types into multiple interleaved accesses as long as
21616 // the vector types are divisible by 128.
21617 if (!isLegalInterleavedAccessType(Factor, VecTy, Alignment, DL))
21618 return false;
21619
21620 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
21621
21622 // A pointer vector can not be the return type of the ldN intrinsics. Need to
21623 // load integer vectors first and then convert to pointer vectors.
21624 if (EltTy->isPointerTy())
21625 VecTy = FixedVectorType::get(ElementType: DL.getIntPtrType(EltTy), FVTy: VecTy);
21626
21627 IRBuilder<> Builder(LI);
21628
21629 // The base address of the load.
21630 Value *BaseAddr = LI->getPointerOperand();
21631
21632 if (NumLoads > 1) {
21633 // If we're going to generate more than one load, reset the sub-vector type
21634 // to something legal.
21635 VecTy = FixedVectorType::get(ElementType: VecTy->getElementType(),
21636 NumElts: VecTy->getNumElements() / NumLoads);
21637 }
21638
21639 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
21640
21641 auto createLoadIntrinsic = [&](Value *BaseAddr) {
21642 if (Subtarget->hasNEON()) {
21643 Type *PtrTy = Builder.getPtrTy(AddrSpace: LI->getPointerAddressSpace());
21644 Type *Tys[] = {VecTy, PtrTy};
21645 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
21646 Intrinsic::arm_neon_vld3,
21647 Intrinsic::arm_neon_vld4};
21648
21649 SmallVector<Value *, 2> Ops;
21650 Ops.push_back(Elt: BaseAddr);
21651 Ops.push_back(Elt: Builder.getInt32(C: LI->getAlign().value()));
21652
21653 return Builder.CreateIntrinsic(ID: LoadInts[Factor - 2], Types: Tys, Args: Ops,
21654 /*FMFSource=*/nullptr, Name: "vldN");
21655 } else {
21656 assert((Factor == 2 || Factor == 4) &&
21657 "expected interleave factor of 2 or 4 for MVE");
21658 Intrinsic::ID LoadInts =
21659 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
21660 Type *PtrTy = Builder.getPtrTy(AddrSpace: LI->getPointerAddressSpace());
21661 Type *Tys[] = {VecTy, PtrTy};
21662
21663 SmallVector<Value *, 2> Ops;
21664 Ops.push_back(Elt: BaseAddr);
21665 return Builder.CreateIntrinsic(ID: LoadInts, Types: Tys, Args: Ops, /*FMFSource=*/nullptr,
21666 Name: "vldN");
21667 }
21668 };
21669
21670 // Holds sub-vectors extracted from the load intrinsic return values. The
21671 // sub-vectors are associated with the shufflevector instructions they will
21672 // replace.
21673 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
21674
21675 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
21676 // If we're generating more than one load, compute the base address of
21677 // subsequent loads as an offset from the previous.
21678 if (LoadCount > 0)
21679 BaseAddr = Builder.CreateConstGEP1_32(Ty: VecTy->getElementType(), Ptr: BaseAddr,
21680 Idx0: VecTy->getNumElements() * Factor);
21681
21682 CallInst *VldN = createLoadIntrinsic(BaseAddr);
21683
21684 // Replace uses of each shufflevector with the corresponding vector loaded
21685 // by ldN.
21686 for (unsigned i = 0; i < Shuffles.size(); i++) {
21687 ShuffleVectorInst *SV = Shuffles[i];
21688 unsigned Index = Indices[i];
21689
21690 Value *SubVec = Builder.CreateExtractValue(Agg: VldN, Idxs: Index);
21691
21692 // Convert the integer vector to pointer vector if the element is pointer.
21693 if (EltTy->isPointerTy())
21694 SubVec = Builder.CreateIntToPtr(
21695 V: SubVec,
21696 DestTy: FixedVectorType::get(ElementType: SV->getType()->getElementType(), FVTy: VecTy));
21697
21698 SubVecs[SV].push_back(Elt: SubVec);
21699 }
21700 }
21701
21702 // Replace uses of the shufflevector instructions with the sub-vectors
21703 // returned by the load intrinsic. If a shufflevector instruction is
21704 // associated with more than one sub-vector, those sub-vectors will be
21705 // concatenated into a single wide vector.
21706 for (ShuffleVectorInst *SVI : Shuffles) {
21707 auto &SubVec = SubVecs[SVI];
21708 auto *WideVec =
21709 SubVec.size() > 1 ? concatenateVectors(Builder, Vecs: SubVec) : SubVec[0];
21710 SVI->replaceAllUsesWith(V: WideVec);
21711 }
21712
21713 return true;
21714}
21715
21716/// Lower an interleaved store into a vstN intrinsic.
21717///
21718/// E.g. Lower an interleaved store (Factor = 3):
21719/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
21720/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
21721/// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
21722///
21723/// Into:
21724/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
21725/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
21726/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
21727/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
21728///
21729/// Note that the new shufflevectors will be removed and we'll only generate one
21730/// vst3 instruction in CodeGen.
21731///
21732/// Example for a more general valid mask (Factor 3). Lower:
21733/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
21734/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
21735/// store <12 x i32> %i.vec, <12 x i32>* %ptr
21736///
21737/// Into:
21738/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
21739/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
21740/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
21741/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
21742bool ARMTargetLowering::lowerInterleavedStore(Instruction *Store,
21743 Value *LaneMask,
21744 ShuffleVectorInst *SVI,
21745 unsigned Factor,
21746 const APInt &GapMask) const {
21747 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
21748 "Invalid interleave factor");
21749 auto *SI = dyn_cast<StoreInst>(Val: Store);
21750 if (!SI)
21751 return false;
21752 assert(!LaneMask && GapMask.popcount() == Factor &&
21753 "Unexpected mask on store");
21754
21755 auto *VecTy = cast<FixedVectorType>(Val: SVI->getType());
21756 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
21757
21758 unsigned LaneLen = VecTy->getNumElements() / Factor;
21759 Type *EltTy = VecTy->getElementType();
21760 auto *SubVecTy = FixedVectorType::get(ElementType: EltTy, NumElts: LaneLen);
21761
21762 const DataLayout &DL = SI->getDataLayout();
21763 Align Alignment = SI->getAlign();
21764
21765 // Skip if we do not have NEON and skip illegal vector types. We can
21766 // "legalize" wide vector types into multiple interleaved accesses as long as
21767 // the vector types are divisible by 128.
21768 if (!isLegalInterleavedAccessType(Factor, VecTy: SubVecTy, Alignment, DL))
21769 return false;
21770
21771 unsigned NumStores = getNumInterleavedAccesses(VecTy: SubVecTy, DL);
21772
21773 Value *Op0 = SVI->getOperand(i_nocapture: 0);
21774 Value *Op1 = SVI->getOperand(i_nocapture: 1);
21775 IRBuilder<> Builder(SI);
21776
21777 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
21778 // vectors to integer vectors.
21779 if (EltTy->isPointerTy()) {
21780 Type *IntTy = DL.getIntPtrType(EltTy);
21781
21782 // Convert to the corresponding integer vector.
21783 auto *IntVecTy =
21784 FixedVectorType::get(ElementType: IntTy, FVTy: cast<FixedVectorType>(Val: Op0->getType()));
21785 Op0 = Builder.CreatePtrToInt(V: Op0, DestTy: IntVecTy);
21786 Op1 = Builder.CreatePtrToInt(V: Op1, DestTy: IntVecTy);
21787
21788 SubVecTy = FixedVectorType::get(ElementType: IntTy, NumElts: LaneLen);
21789 }
21790
21791 // The base address of the store.
21792 Value *BaseAddr = SI->getPointerOperand();
21793
21794 if (NumStores > 1) {
21795 // If we're going to generate more than one store, reset the lane length
21796 // and sub-vector type to something legal.
21797 LaneLen /= NumStores;
21798 SubVecTy = FixedVectorType::get(ElementType: SubVecTy->getElementType(), NumElts: LaneLen);
21799 }
21800
21801 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
21802
21803 auto Mask = SVI->getShuffleMask();
21804
21805 auto createStoreIntrinsic = [&](Value *BaseAddr,
21806 SmallVectorImpl<Value *> &Shuffles) {
21807 if (Subtarget->hasNEON()) {
21808 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
21809 Intrinsic::arm_neon_vst3,
21810 Intrinsic::arm_neon_vst4};
21811 Type *PtrTy = Builder.getPtrTy(AddrSpace: SI->getPointerAddressSpace());
21812 Type *Tys[] = {PtrTy, SubVecTy};
21813
21814 SmallVector<Value *, 6> Ops;
21815 Ops.push_back(Elt: BaseAddr);
21816 append_range(C&: Ops, R&: Shuffles);
21817 Ops.push_back(Elt: Builder.getInt32(C: SI->getAlign().value()));
21818 Builder.CreateIntrinsic(ID: StoreInts[Factor - 2], Types: Tys, Args: Ops);
21819 } else {
21820 assert((Factor == 2 || Factor == 4) &&
21821 "expected interleave factor of 2 or 4 for MVE");
21822 Intrinsic::ID StoreInts =
21823 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
21824 Type *PtrTy = Builder.getPtrTy(AddrSpace: SI->getPointerAddressSpace());
21825 Type *Tys[] = {PtrTy, SubVecTy};
21826
21827 SmallVector<Value *, 6> Ops;
21828 Ops.push_back(Elt: BaseAddr);
21829 append_range(C&: Ops, R&: Shuffles);
21830 for (unsigned F = 0; F < Factor; F++) {
21831 Ops.push_back(Elt: Builder.getInt32(C: F));
21832 Builder.CreateIntrinsic(ID: StoreInts, Types: Tys, Args: Ops);
21833 Ops.pop_back();
21834 }
21835 }
21836 };
21837
21838 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
21839 // If we generating more than one store, we compute the base address of
21840 // subsequent stores as an offset from the previous.
21841 if (StoreCount > 0)
21842 BaseAddr = Builder.CreateConstGEP1_32(Ty: SubVecTy->getElementType(),
21843 Ptr: BaseAddr, Idx0: LaneLen * Factor);
21844
21845 SmallVector<Value *, 4> Shuffles;
21846
21847 // Split the shufflevector operands into sub vectors for the new vstN call.
21848 for (unsigned i = 0; i < Factor; i++) {
21849 unsigned IdxI = StoreCount * LaneLen * Factor + i;
21850 if (Mask[IdxI] >= 0) {
21851 Shuffles.push_back(Elt: Builder.CreateShuffleVector(
21852 V1: Op0, V2: Op1, Mask: createSequentialMask(Start: Mask[IdxI], NumInts: LaneLen, NumUndefs: 0)));
21853 } else {
21854 unsigned StartMask = 0;
21855 for (unsigned j = 1; j < LaneLen; j++) {
21856 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
21857 if (Mask[IdxJ * Factor + IdxI] >= 0) {
21858 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
21859 break;
21860 }
21861 }
21862 // Note: If all elements in a chunk are undefs, StartMask=0!
21863 // Note: Filling undef gaps with random elements is ok, since
21864 // those elements were being written anyway (with undefs).
21865 // In the case of all undefs we're defaulting to using elems from 0
21866 // Note: StartMask cannot be negative, it's checked in
21867 // isReInterleaveMask
21868 Shuffles.push_back(Elt: Builder.CreateShuffleVector(
21869 V1: Op0, V2: Op1, Mask: createSequentialMask(Start: StartMask, NumInts: LaneLen, NumUndefs: 0)));
21870 }
21871 }
21872
21873 createStoreIntrinsic(BaseAddr, Shuffles);
21874 }
21875 return true;
21876}
21877
21878enum HABaseType {
21879 HA_UNKNOWN = 0,
21880 HA_FLOAT,
21881 HA_DOUBLE,
21882 HA_VECT64,
21883 HA_VECT128
21884};
21885
21886static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
21887 uint64_t &Members) {
21888 if (auto *ST = dyn_cast<StructType>(Val: Ty)) {
21889 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
21890 uint64_t SubMembers = 0;
21891 if (!isHomogeneousAggregate(Ty: ST->getElementType(N: i), Base, Members&: SubMembers))
21892 return false;
21893 Members += SubMembers;
21894 }
21895 } else if (auto *AT = dyn_cast<ArrayType>(Val: Ty)) {
21896 uint64_t SubMembers = 0;
21897 if (!isHomogeneousAggregate(Ty: AT->getElementType(), Base, Members&: SubMembers))
21898 return false;
21899 Members += SubMembers * AT->getNumElements();
21900 } else if (Ty->isFloatTy()) {
21901 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
21902 return false;
21903 Members = 1;
21904 Base = HA_FLOAT;
21905 } else if (Ty->isDoubleTy()) {
21906 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
21907 return false;
21908 Members = 1;
21909 Base = HA_DOUBLE;
21910 } else if (auto *VT = dyn_cast<VectorType>(Val: Ty)) {
21911 Members = 1;
21912 switch (Base) {
21913 case HA_FLOAT:
21914 case HA_DOUBLE:
21915 return false;
21916 case HA_VECT64:
21917 return VT->getPrimitiveSizeInBits().getFixedValue() == 64;
21918 case HA_VECT128:
21919 return VT->getPrimitiveSizeInBits().getFixedValue() == 128;
21920 case HA_UNKNOWN:
21921 switch (VT->getPrimitiveSizeInBits().getFixedValue()) {
21922 case 64:
21923 Base = HA_VECT64;
21924 return true;
21925 case 128:
21926 Base = HA_VECT128;
21927 return true;
21928 default:
21929 return false;
21930 }
21931 }
21932 }
21933
21934 return (Members > 0 && Members <= 4);
21935}
21936
21937/// Return the correct alignment for the current calling convention.
21938Align ARMTargetLowering::getABIAlignmentForCallingConv(
21939 Type *ArgTy, const DataLayout &DL) const {
21940 const Align ABITypeAlign = DL.getABITypeAlign(Ty: ArgTy);
21941 if (!ArgTy->isVectorTy())
21942 return ABITypeAlign;
21943
21944 // Avoid over-aligning vector parameters. It would require realigning the
21945 // stack and waste space for no real benefit.
21946 MaybeAlign StackAlign = DL.getStackAlignment();
21947 assert(StackAlign && "data layout string is missing stack alignment");
21948 return std::min(a: ABITypeAlign, b: *StackAlign);
21949}
21950
21951/// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
21952/// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
21953/// passing according to AAPCS rules.
21954bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
21955 Type *Ty, CallingConv::ID CallConv, bool isVarArg,
21956 const DataLayout &DL) const {
21957 if (getEffectiveCallingConv(CC: CallConv, isVarArg) !=
21958 CallingConv::ARM_AAPCS_VFP)
21959 return false;
21960
21961 HABaseType Base = HA_UNKNOWN;
21962 uint64_t Members = 0;
21963 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
21964 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
21965
21966 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
21967 return IsHA || IsIntArray;
21968}
21969
21970Register ARMTargetLowering::getExceptionPointerRegister(
21971 const Constant *PersonalityFn) const {
21972 // Platforms which do not use SjLj EH may return values in these registers
21973 // via the personality function.
21974 ExceptionHandling EM = getTargetMachine().getExceptionModel();
21975 return EM == ExceptionHandling::SjLj ? Register() : ARM::R0;
21976}
21977
21978Register ARMTargetLowering::getExceptionSelectorRegister(
21979 const Constant *PersonalityFn) const {
21980 // Platforms which do not use SjLj EH may return values in these registers
21981 // via the personality function.
21982 ExceptionHandling EM = getTargetMachine().getExceptionModel();
21983 return EM == ExceptionHandling::SjLj ? Register() : ARM::R1;
21984}
21985
21986void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
21987 // Update IsSplitCSR in ARMFunctionInfo.
21988 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
21989 AFI->setIsSplitCSR(true);
21990}
21991
21992void ARMTargetLowering::insertCopiesSplitCSR(
21993 MachineBasicBlock *Entry,
21994 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
21995 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
21996 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(MF: Entry->getParent());
21997 if (!IStart)
21998 return;
21999
22000 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22001 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
22002 MachineBasicBlock::iterator MBBI = Entry->begin();
22003 for (const MCPhysReg *I = IStart; *I; ++I) {
22004 const TargetRegisterClass *RC = nullptr;
22005 if (ARM::GPRRegClass.contains(Reg: *I))
22006 RC = &ARM::GPRRegClass;
22007 else if (ARM::DPRRegClass.contains(Reg: *I))
22008 RC = &ARM::DPRRegClass;
22009 else
22010 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
22011
22012 Register NewVR = MRI->createVirtualRegister(RegClass: RC);
22013 // Create copy from CSR to a virtual register.
22014 // FIXME: this currently does not emit CFI pseudo-instructions, it works
22015 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
22016 // nounwind. If we want to generalize this later, we may need to emit
22017 // CFI pseudo-instructions.
22018 assert(Entry->getParent()->getFunction().hasFnAttribute(
22019 Attribute::NoUnwind) &&
22020 "Function should be nounwind in insertCopiesSplitCSR!");
22021 Entry->addLiveIn(PhysReg: *I);
22022 BuildMI(BB&: *Entry, I: MBBI, MIMD: DebugLoc(), MCID: TII->get(Opcode: TargetOpcode::COPY), DestReg: NewVR)
22023 .addReg(RegNo: *I);
22024
22025 // Insert the copy-back instructions right before the terminator.
22026 for (auto *Exit : Exits)
22027 BuildMI(BB&: *Exit, I: Exit->getFirstTerminator(), MIMD: DebugLoc(),
22028 MCID: TII->get(Opcode: TargetOpcode::COPY), DestReg: *I)
22029 .addReg(RegNo: NewVR);
22030 }
22031}
22032
22033void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
22034 MF.getFrameInfo().computeMaxCallFrameSize(MF);
22035 TargetLoweringBase::finalizeLowering(MF);
22036}
22037
22038bool ARMTargetLowering::isComplexDeinterleavingSupported() const {
22039 return Subtarget->hasMVEIntegerOps();
22040}
22041
22042bool ARMTargetLowering::isComplexDeinterleavingOperationSupported(
22043 ComplexDeinterleavingOperation Operation, Type *Ty) const {
22044 auto *VTy = dyn_cast<FixedVectorType>(Val: Ty);
22045 if (!VTy)
22046 return false;
22047
22048 auto *ScalarTy = VTy->getScalarType();
22049 unsigned NumElements = VTy->getNumElements();
22050
22051 unsigned VTyWidth = VTy->getScalarSizeInBits() * NumElements;
22052 if (VTyWidth < 128 || !llvm::isPowerOf2_32(Value: VTyWidth))
22053 return false;
22054
22055 // Both VCADD and VCMUL/VCMLA support the same types, F16 and F32
22056 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy())
22057 return Subtarget->hasMVEFloatOps();
22058
22059 if (Operation != ComplexDeinterleavingOperation::CAdd)
22060 return false;
22061
22062 return Subtarget->hasMVEIntegerOps() &&
22063 (ScalarTy->isIntegerTy(Bitwidth: 8) || ScalarTy->isIntegerTy(Bitwidth: 16) ||
22064 ScalarTy->isIntegerTy(Bitwidth: 32));
22065}
22066
22067ArrayRef<MCPhysReg> ARMTargetLowering::getRoundingControlRegisters() const {
22068 static const MCPhysReg RCRegs[] = {ARM::FPSCR_RM};
22069 return RCRegs;
22070}
22071
22072Value *ARMTargetLowering::createComplexDeinterleavingIR(
22073 IRBuilderBase &B, ComplexDeinterleavingOperation OperationType,
22074 ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
22075 Value *Accumulator) const {
22076
22077 FixedVectorType *Ty = cast<FixedVectorType>(Val: InputA->getType());
22078
22079 unsigned TyWidth = Ty->getScalarSizeInBits() * Ty->getNumElements();
22080
22081 assert(TyWidth >= 128 && "Width of vector type must be at least 128 bits");
22082
22083 if (TyWidth > 128) {
22084 int Stride = Ty->getNumElements() / 2;
22085 auto SplitSeq = llvm::seq<int>(Begin: 0, End: Ty->getNumElements());
22086 auto SplitSeqVec = llvm::to_vector(Range&: SplitSeq);
22087 ArrayRef<int> LowerSplitMask(&SplitSeqVec[0], Stride);
22088 ArrayRef<int> UpperSplitMask(&SplitSeqVec[Stride], Stride);
22089
22090 auto *LowerSplitA = B.CreateShuffleVector(V: InputA, Mask: LowerSplitMask);
22091 auto *LowerSplitB = B.CreateShuffleVector(V: InputB, Mask: LowerSplitMask);
22092 auto *UpperSplitA = B.CreateShuffleVector(V: InputA, Mask: UpperSplitMask);
22093 auto *UpperSplitB = B.CreateShuffleVector(V: InputB, Mask: UpperSplitMask);
22094 Value *LowerSplitAcc = nullptr;
22095 Value *UpperSplitAcc = nullptr;
22096
22097 if (Accumulator) {
22098 LowerSplitAcc = B.CreateShuffleVector(V: Accumulator, Mask: LowerSplitMask);
22099 UpperSplitAcc = B.CreateShuffleVector(V: Accumulator, Mask: UpperSplitMask);
22100 }
22101
22102 auto *LowerSplitInt = createComplexDeinterleavingIR(
22103 B, OperationType, Rotation, InputA: LowerSplitA, InputB: LowerSplitB, Accumulator: LowerSplitAcc);
22104 auto *UpperSplitInt = createComplexDeinterleavingIR(
22105 B, OperationType, Rotation, InputA: UpperSplitA, InputB: UpperSplitB, Accumulator: UpperSplitAcc);
22106
22107 ArrayRef<int> JoinMask(&SplitSeqVec[0], Ty->getNumElements());
22108 return B.CreateShuffleVector(V1: LowerSplitInt, V2: UpperSplitInt, Mask: JoinMask);
22109 }
22110
22111 auto *IntTy = Type::getInt32Ty(C&: B.getContext());
22112
22113 ConstantInt *ConstRotation = nullptr;
22114 if (OperationType == ComplexDeinterleavingOperation::CMulPartial) {
22115 ConstRotation = ConstantInt::get(Ty: IntTy, V: (int)Rotation);
22116
22117 if (Accumulator)
22118 return B.CreateIntrinsic(ID: Intrinsic::arm_mve_vcmlaq, Types: Ty,
22119 Args: {ConstRotation, Accumulator, InputB, InputA});
22120 return B.CreateIntrinsic(ID: Intrinsic::arm_mve_vcmulq, Types: Ty,
22121 Args: {ConstRotation, InputB, InputA});
22122 }
22123
22124 if (OperationType == ComplexDeinterleavingOperation::CAdd) {
22125 // 1 means the value is not halved.
22126 auto *ConstHalving = ConstantInt::get(Ty: IntTy, V: 1);
22127
22128 if (Rotation == ComplexDeinterleavingRotation::Rotation_90)
22129 ConstRotation = ConstantInt::get(Ty: IntTy, V: 0);
22130 else if (Rotation == ComplexDeinterleavingRotation::Rotation_270)
22131 ConstRotation = ConstantInt::get(Ty: IntTy, V: 1);
22132
22133 if (!ConstRotation)
22134 return nullptr; // Invalid rotation for arm_mve_vcaddq
22135
22136 return B.CreateIntrinsic(ID: Intrinsic::arm_mve_vcaddq, Types: Ty,
22137 Args: {ConstHalving, ConstRotation, InputA, InputB});
22138 }
22139
22140 return nullptr;
22141}
22142