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: dyn_cast<GlobalValue>(Val: GV),
3209 DL: dl, VT: PtrVT);
3210 return LowerGlobalAddress(Op: GA, DAG);
3211 }
3212
3213 // The 16-bit ADR instruction can only encode offsets that are multiples of 4,
3214 // so we need to align to at least 4 bytes when we don't have 32-bit ADR.
3215 Align CPAlign = CP->getAlign();
3216 if (Subtarget->isThumb1Only())
3217 CPAlign = std::max(a: CPAlign, b: Align(4));
3218 if (CP->isMachineConstantPoolEntry())
3219 Res =
3220 DAG.getTargetConstantPool(C: CP->getMachineCPVal(), VT: PtrVT, Align: CPAlign);
3221 else
3222 Res = DAG.getTargetConstantPool(C: CP->getConstVal(), VT: PtrVT, Align: CPAlign);
3223 return DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: Res);
3224}
3225
3226unsigned ARMTargetLowering::getJumpTableEncoding() const {
3227 // If we don't have a 32-bit pc-relative branch instruction then the jump
3228 // table consists of block addresses. Usually this is inline, but for
3229 // execute-only it must be placed out-of-line.
3230 if (Subtarget->genExecuteOnly() && !Subtarget->hasV8MBaselineOps())
3231 return MachineJumpTableInfo::EK_BlockAddress;
3232 return MachineJumpTableInfo::EK_Inline;
3233}
3234
3235SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3236 SelectionDAG &DAG) const {
3237 MachineFunction &MF = DAG.getMachineFunction();
3238 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3239 unsigned ARMPCLabelIndex = 0;
3240 SDLoc DL(Op);
3241 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3242 const BlockAddress *BA = cast<BlockAddressSDNode>(Val&: Op)->getBlockAddress();
3243 SDValue CPAddr;
3244 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3245 if (!IsPositionIndependent) {
3246 CPAddr = DAG.getTargetConstantPool(C: BA, VT: PtrVT, Align: Align(4));
3247 } else {
3248 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3249 ARMPCLabelIndex = AFI->createPICLabelUId();
3250 ARMConstantPoolValue *CPV =
3251 ARMConstantPoolConstant::Create(C: BA, ID: ARMPCLabelIndex,
3252 Kind: ARMCP::CPBlockAddress, PCAdj);
3253 CPAddr = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3254 }
3255 CPAddr = DAG.getNode(Opcode: ARMISD::Wrapper, DL, VT: PtrVT, Operand: CPAddr);
3256 SDValue Result = DAG.getLoad(
3257 VT: PtrVT, dl: DL, Chain: DAG.getEntryNode(), Ptr: CPAddr,
3258 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3259 if (!IsPositionIndependent)
3260 return Result;
3261 SDValue PICLabel = DAG.getConstant(Val: ARMPCLabelIndex, DL, VT: MVT::i32);
3262 return DAG.getNode(Opcode: ARMISD::PIC_ADD, DL, VT: PtrVT, N1: Result, N2: PICLabel);
3263}
3264
3265/// Convert a TLS address reference into the correct sequence of loads
3266/// and calls to compute the variable's address for Darwin, and return an
3267/// SDValue containing the final node.
3268
3269/// Darwin only has one TLS scheme which must be capable of dealing with the
3270/// fully general situation, in the worst case. This means:
3271/// + "extern __thread" declaration.
3272/// + Defined in a possibly unknown dynamic library.
3273///
3274/// The general system is that each __thread variable has a [3 x i32] descriptor
3275/// which contains information used by the runtime to calculate the address. The
3276/// only part of this the compiler needs to know about is the first word, which
3277/// contains a function pointer that must be called with the address of the
3278/// entire descriptor in "r0".
3279///
3280/// Since this descriptor may be in a different unit, in general access must
3281/// proceed along the usual ARM rules. A common sequence to produce is:
3282///
3283/// movw rT1, :lower16:_var$non_lazy_ptr
3284/// movt rT1, :upper16:_var$non_lazy_ptr
3285/// ldr r0, [rT1]
3286/// ldr rT2, [r0]
3287/// blx rT2
3288/// [...address now in r0...]
3289SDValue
3290ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3291 SelectionDAG &DAG) const {
3292 assert(getTargetMachine().getTargetTriple().isOSDarwin() &&
3293 "This function expects a Darwin target");
3294 SDLoc DL(Op);
3295
3296 // First step is to get the address of the actua global symbol. This is where
3297 // the TLS descriptor lives.
3298 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3299
3300 // The first entry in the descriptor is a function pointer that we must call
3301 // to obtain the address of the variable.
3302 SDValue Chain = DAG.getEntryNode();
3303 SDValue FuncTLVGet = DAG.getLoad(
3304 VT: MVT::i32, dl: DL, Chain, Ptr: DescAddr,
3305 PtrInfo: MachinePointerInfo::getGOT(MF&: DAG.getMachineFunction()), Alignment: Align(4),
3306 MMOFlags: MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3307 MachineMemOperand::MOInvariant);
3308 Chain = FuncTLVGet.getValue(R: 1);
3309
3310 MachineFunction &F = DAG.getMachineFunction();
3311 MachineFrameInfo &MFI = F.getFrameInfo();
3312 MFI.setAdjustsStack(true);
3313
3314 // TLS calls preserve all registers except those that absolutely must be
3315 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3316 // silly).
3317 auto TRI =
3318 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3319 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3320 const uint32_t *Mask = ARI->getTLSCallPreservedMask(MF: DAG.getMachineFunction());
3321
3322 // Finally, we can make the call. This is just a degenerate version of a
3323 // normal AArch64 call node: r0 takes the address of the descriptor, and
3324 // returns the address of the variable in this thread.
3325 Chain = DAG.getCopyToReg(Chain, dl: DL, Reg: ARM::R0, N: DescAddr, Glue: SDValue());
3326 Chain =
3327 DAG.getNode(Opcode: ARMISD::CALL, DL, VTList: DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue),
3328 N1: Chain, N2: FuncTLVGet, N3: DAG.getRegister(Reg: ARM::R0, VT: MVT::i32),
3329 N4: DAG.getRegisterMask(RegMask: Mask), N5: Chain.getValue(R: 1));
3330 return DAG.getCopyFromReg(Chain, dl: DL, Reg: ARM::R0, VT: MVT::i32, Glue: Chain.getValue(R: 1));
3331}
3332
3333SDValue
3334ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3335 SelectionDAG &DAG) const {
3336 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3337 "Windows specific TLS lowering");
3338
3339 SDValue Chain = DAG.getEntryNode();
3340 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3341 SDLoc DL(Op);
3342
3343 // Load the current TEB (thread environment block)
3344 SDValue Ops[] = {Chain,
3345 DAG.getTargetConstant(Val: Intrinsic::arm_mrc, DL, VT: MVT::i32),
3346 DAG.getTargetConstant(Val: 15, DL, VT: MVT::i32),
3347 DAG.getTargetConstant(Val: 0, DL, VT: MVT::i32),
3348 DAG.getTargetConstant(Val: 13, DL, VT: MVT::i32),
3349 DAG.getTargetConstant(Val: 0, DL, VT: MVT::i32),
3350 DAG.getTargetConstant(Val: 2, DL, VT: MVT::i32)};
3351 SDValue CurrentTEB = DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL,
3352 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), Ops);
3353
3354 SDValue TEB = CurrentTEB.getValue(R: 0);
3355 Chain = CurrentTEB.getValue(R: 1);
3356
3357 // Load the ThreadLocalStoragePointer from the TEB
3358 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3359 SDValue TLSArray =
3360 DAG.getNode(Opcode: ISD::ADD, DL, VT: PtrVT, N1: TEB, N2: DAG.getIntPtrConstant(Val: 0x2c, DL));
3361 TLSArray = DAG.getLoad(VT: PtrVT, dl: DL, Chain, Ptr: TLSArray, PtrInfo: MachinePointerInfo());
3362
3363 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3364 // offset into the TLSArray.
3365
3366 // Load the TLS index from the C runtime
3367 SDValue TLSIndex =
3368 DAG.getTargetExternalSymbol(Sym: "_tls_index", VT: PtrVT, TargetFlags: ARMII::MO_NO_FLAG);
3369 TLSIndex = DAG.getNode(Opcode: ARMISD::Wrapper, DL, VT: PtrVT, Operand: TLSIndex);
3370 TLSIndex = DAG.getLoad(VT: PtrVT, dl: DL, Chain, Ptr: TLSIndex, PtrInfo: MachinePointerInfo());
3371
3372 SDValue Slot = DAG.getNode(Opcode: ISD::SHL, DL, VT: PtrVT, N1: TLSIndex,
3373 N2: DAG.getConstant(Val: 2, DL, VT: MVT::i32));
3374 SDValue TLS = DAG.getLoad(VT: PtrVT, dl: DL, Chain,
3375 Ptr: DAG.getNode(Opcode: ISD::ADD, DL, VT: PtrVT, N1: TLSArray, N2: Slot),
3376 PtrInfo: MachinePointerInfo());
3377
3378 // Get the offset of the start of the .tls section (section base)
3379 const auto *GA = cast<GlobalAddressSDNode>(Val&: Op);
3380 auto *CPV = ARMConstantPoolConstant::Create(GV: GA->getGlobal(), Modifier: ARMCP::SECREL);
3381 SDValue Offset = DAG.getLoad(
3382 VT: PtrVT, dl: DL, Chain,
3383 Ptr: DAG.getNode(Opcode: ARMISD::Wrapper, DL, VT: MVT::i32,
3384 Operand: DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4))),
3385 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3386
3387 return DAG.getNode(Opcode: ISD::ADD, DL, VT: PtrVT, N1: TLS, N2: Offset);
3388}
3389
3390// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3391SDValue
3392ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3393 SelectionDAG &DAG) const {
3394 SDLoc dl(GA);
3395 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3396 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3397 MachineFunction &MF = DAG.getMachineFunction();
3398 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3399 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3400 ARMConstantPoolValue *CPV =
3401 ARMConstantPoolConstant::Create(C: GA->getGlobal(), ID: ARMPCLabelIndex,
3402 Kind: ARMCP::CPValue, PCAdj, Modifier: ARMCP::TLSGD, AddCurrentAddress: true);
3403 SDValue Argument = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3404 Argument = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: Argument);
3405 Argument = DAG.getLoad(
3406 VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: Argument,
3407 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3408 SDValue Chain = Argument.getValue(R: 1);
3409
3410 SDValue PICLabel = DAG.getConstant(Val: ARMPCLabelIndex, DL: dl, VT: MVT::i32);
3411 Argument = DAG.getNode(Opcode: ARMISD::PIC_ADD, DL: dl, VT: PtrVT, N1: Argument, N2: PICLabel);
3412
3413 // call __tls_get_addr.
3414 ArgListTy Args;
3415 Args.emplace_back(args&: Argument, args: Type::getInt32Ty(C&: *DAG.getContext()));
3416
3417 // FIXME: is there useful debug info available here?
3418 TargetLowering::CallLoweringInfo CLI(DAG);
3419 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3420 CC: CallingConv::C, ResultType: Type::getInt32Ty(C&: *DAG.getContext()),
3421 Target: DAG.getExternalSymbol(Sym: "__tls_get_addr", VT: PtrVT), ArgsList: std::move(Args));
3422
3423 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3424 return CallResult.first;
3425}
3426
3427// Lower ISD::GlobalTLSAddress using the "initial exec" or
3428// "local exec" model.
3429SDValue
3430ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3431 SelectionDAG &DAG,
3432 TLSModel::Model model) const {
3433 const GlobalValue *GV = GA->getGlobal();
3434 SDLoc dl(GA);
3435 SDValue Offset;
3436 SDValue Chain = DAG.getEntryNode();
3437 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3438 // Get the Thread Pointer
3439 SDValue ThreadPointer = DAG.getNode(Opcode: ARMISD::THREAD_POINTER, DL: dl, VT: PtrVT);
3440
3441 if (model == TLSModel::InitialExec) {
3442 MachineFunction &MF = DAG.getMachineFunction();
3443 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3444 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3445 // Initial exec model.
3446 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3447 ARMConstantPoolValue *CPV =
3448 ARMConstantPoolConstant::Create(C: GA->getGlobal(), ID: ARMPCLabelIndex,
3449 Kind: ARMCP::CPValue, PCAdj, Modifier: ARMCP::GOTTPOFF,
3450 AddCurrentAddress: true);
3451 Offset = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3452 Offset = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: Offset);
3453 Offset = DAG.getLoad(
3454 VT: PtrVT, dl, Chain, Ptr: Offset,
3455 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3456 Chain = Offset.getValue(R: 1);
3457
3458 SDValue PICLabel = DAG.getConstant(Val: ARMPCLabelIndex, DL: dl, VT: MVT::i32);
3459 Offset = DAG.getNode(Opcode: ARMISD::PIC_ADD, DL: dl, VT: PtrVT, N1: Offset, N2: PICLabel);
3460
3461 Offset = DAG.getLoad(
3462 VT: PtrVT, dl, Chain, Ptr: Offset,
3463 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3464 } else {
3465 // local exec model
3466 assert(model == TLSModel::LocalExec);
3467 ARMConstantPoolValue *CPV =
3468 ARMConstantPoolConstant::Create(GV, Modifier: ARMCP::TPOFF);
3469 Offset = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3470 Offset = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: Offset);
3471 Offset = DAG.getLoad(
3472 VT: PtrVT, dl, Chain, Ptr: Offset,
3473 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3474 }
3475
3476 // The address of the thread local variable is the add of the thread
3477 // pointer with the offset of the variable.
3478 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PtrVT, N1: ThreadPointer, N2: Offset);
3479}
3480
3481SDValue
3482ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3483 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Val&: Op);
3484 if (DAG.getTarget().useEmulatedTLS())
3485 return LowerToTLSEmulatedModel(GA, DAG);
3486
3487 const Triple &TT = getTargetMachine().getTargetTriple();
3488 if (TT.isOSDarwin())
3489 return LowerGlobalTLSAddressDarwin(Op, DAG);
3490
3491 if (TT.isOSWindows())
3492 return LowerGlobalTLSAddressWindows(Op, DAG);
3493
3494 // TODO: implement the "local dynamic" model
3495 assert(TT.isOSBinFormatELF() && "Only ELF implemented here");
3496 TLSModel::Model model = getTargetMachine().getTLSModel(GV: GA->getGlobal());
3497
3498 switch (model) {
3499 case TLSModel::GeneralDynamic:
3500 case TLSModel::LocalDynamic:
3501 return LowerToTLSGeneralDynamicModel(GA, DAG);
3502 case TLSModel::InitialExec:
3503 case TLSModel::LocalExec:
3504 return LowerToTLSExecModels(GA, DAG, model);
3505 }
3506 llvm_unreachable("bogus TLS model");
3507}
3508
3509/// Return true if all users of V are within function F, looking through
3510/// ConstantExprs.
3511static bool allUsersAreInFunction(const Value *V, const Function *F) {
3512 SmallVector<const User*,4> Worklist(V->users());
3513 while (!Worklist.empty()) {
3514 auto *U = Worklist.pop_back_val();
3515 if (isa<ConstantExpr>(Val: U)) {
3516 append_range(C&: Worklist, R: U->users());
3517 continue;
3518 }
3519
3520 auto *I = dyn_cast<Instruction>(Val: U);
3521 if (!I || I->getParent()->getParent() != F)
3522 return false;
3523 }
3524 return true;
3525}
3526
3527static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3528 const GlobalValue *GV, SelectionDAG &DAG,
3529 EVT PtrVT, const SDLoc &dl) {
3530 // If we're creating a pool entry for a constant global with unnamed address,
3531 // and the global is small enough, we can emit it inline into the constant pool
3532 // to save ourselves an indirection.
3533 //
3534 // This is a win if the constant is only used in one function (so it doesn't
3535 // need to be duplicated) or duplicating the constant wouldn't increase code
3536 // size (implying the constant is no larger than 4 bytes).
3537 const Function &F = DAG.getMachineFunction().getFunction();
3538
3539 // We rely on this decision to inline being idempotent and unrelated to the
3540 // use-site. We know that if we inline a variable at one use site, we'll
3541 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3542 // doesn't know about this optimization, so bail out if it's enabled else
3543 // we could decide to inline here (and thus never emit the GV) but require
3544 // the GV from fast-isel generated code.
3545 if (!EnableConstpoolPromotion ||
3546 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3547 return SDValue();
3548
3549 auto *GVar = dyn_cast<GlobalVariable>(Val: GV);
3550 if (!GVar || !GVar->hasInitializer() ||
3551 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3552 !GVar->hasLocalLinkage())
3553 return SDValue();
3554
3555 // If we inline a value that contains relocations, we move the relocations
3556 // from .data to .text. This is not allowed in position-independent code.
3557 auto *Init = GVar->getInitializer();
3558 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3559 Init->needsDynamicRelocation())
3560 return SDValue();
3561
3562 // The constant islands pass can only really deal with alignment requests
3563 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3564 // any type wanting greater alignment requirements than 4 bytes. We also
3565 // can only promote constants that are multiples of 4 bytes in size or
3566 // are paddable to a multiple of 4. Currently we only try and pad constants
3567 // that are strings for simplicity.
3568 auto *CDAInit = dyn_cast<ConstantDataArray>(Val: Init);
3569 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Ty: Init->getType());
3570 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GV: GVar);
3571 unsigned RequiredPadding = 4 - (Size % 4);
3572 bool PaddingPossible =
3573 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3574 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3575 Size == 0)
3576 return SDValue();
3577
3578 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3579 MachineFunction &MF = DAG.getMachineFunction();
3580 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3581
3582 // We can't bloat the constant pool too much, else the ConstantIslands pass
3583 // may fail to converge. If we haven't promoted this global yet (it may have
3584 // multiple uses), and promoting it would increase the constant pool size (Sz
3585 // > 4), ensure we have space to do so up to MaxTotal.
3586 if (!AFI->getGlobalsPromotedToConstantPool().count(Ptr: GVar) && Size > 4)
3587 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3588 ConstpoolPromotionMaxTotal)
3589 return SDValue();
3590
3591 // This is only valid if all users are in a single function; we can't clone
3592 // the constant in general. The LLVM IR unnamed_addr allows merging
3593 // constants, but not cloning them.
3594 //
3595 // We could potentially allow cloning if we could prove all uses of the
3596 // constant in the current function don't care about the address, like
3597 // printf format strings. But that isn't implemented for now.
3598 if (!allUsersAreInFunction(V: GVar, F: &F))
3599 return SDValue();
3600
3601 // We're going to inline this global. Pad it out if needed.
3602 if (RequiredPadding != 4) {
3603 StringRef S = CDAInit->getAsString();
3604
3605 SmallVector<uint8_t,16> V(S.size());
3606 std::copy(first: S.bytes_begin(), last: S.bytes_end(), result: V.begin());
3607 while (RequiredPadding--)
3608 V.push_back(Elt: 0);
3609 Init = ConstantDataArray::get(Context&: *DAG.getContext(), Elts&: V);
3610 }
3611
3612 auto CPVal = ARMConstantPoolConstant::Create(GV: GVar, Initializer: Init);
3613 SDValue CPAddr = DAG.getTargetConstantPool(C: CPVal, VT: PtrVT, Align: Align(4));
3614 if (!AFI->getGlobalsPromotedToConstantPool().count(Ptr: GVar)) {
3615 AFI->markGlobalAsPromotedToConstantPool(GV: GVar);
3616 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3617 PaddedSize - 4);
3618 }
3619 ++NumConstpoolPromoted;
3620 return DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: CPAddr);
3621}
3622
3623bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3624 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Val: GV))
3625 if (!(GV = GA->getAliaseeObject()))
3626 return false;
3627 if (const auto *V = dyn_cast<GlobalVariable>(Val: GV))
3628 return V->isConstant();
3629 return isa<Function>(Val: GV);
3630}
3631
3632SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3633 SelectionDAG &DAG) const {
3634 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3635 default: llvm_unreachable("unknown object format");
3636 case Triple::COFF:
3637 return LowerGlobalAddressWindows(Op, DAG);
3638 case Triple::ELF:
3639 return LowerGlobalAddressELF(Op, DAG);
3640 case Triple::MachO:
3641 return LowerGlobalAddressDarwin(Op, DAG);
3642 }
3643}
3644
3645SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3646 SelectionDAG &DAG) const {
3647 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3648 SDLoc dl(Op);
3649 const GlobalValue *GV = cast<GlobalAddressSDNode>(Val&: Op)->getGlobal();
3650 bool IsRO = isReadOnly(GV);
3651
3652 // promoteToConstantPool only if not generating XO text section
3653 if (GV->isDSOLocal() && !Subtarget->genExecuteOnly())
3654 if (SDValue V = promoteToConstantPool(TLI: this, GV, DAG, PtrVT, dl))
3655 return V;
3656
3657 if (isPositionIndependent()) {
3658 SDValue G = DAG.getTargetGlobalAddress(
3659 GV, DL: dl, VT: PtrVT, offset: 0, TargetFlags: GV->isDSOLocal() ? 0 : ARMII::MO_GOT);
3660 SDValue Result = DAG.getNode(Opcode: ARMISD::WrapperPIC, DL: dl, VT: PtrVT, Operand: G);
3661 if (!GV->isDSOLocal())
3662 Result =
3663 DAG.getLoad(VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: Result,
3664 PtrInfo: MachinePointerInfo::getGOT(MF&: DAG.getMachineFunction()));
3665 return Result;
3666 } else if (Subtarget->isROPI() && IsRO) {
3667 // PC-relative.
3668 SDValue G = DAG.getTargetGlobalAddress(GV, DL: dl, VT: PtrVT);
3669 SDValue Result = DAG.getNode(Opcode: ARMISD::WrapperPIC, DL: dl, VT: PtrVT, Operand: G);
3670 return Result;
3671 } else if (Subtarget->isRWPI() && !IsRO) {
3672 // SB-relative.
3673 SDValue RelAddr;
3674 if (Subtarget->useMovt()) {
3675 ++NumMovwMovt;
3676 SDValue G = DAG.getTargetGlobalAddress(GV, DL: dl, VT: PtrVT, offset: 0, TargetFlags: ARMII::MO_SBREL);
3677 RelAddr = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: PtrVT, Operand: G);
3678 } else { // use literal pool for address constant
3679 ARMConstantPoolValue *CPV =
3680 ARMConstantPoolConstant::Create(GV, Modifier: ARMCP::SBREL);
3681 SDValue CPAddr = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3682 CPAddr = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: CPAddr);
3683 RelAddr = DAG.getLoad(
3684 VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: CPAddr,
3685 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3686 }
3687 SDValue SB = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl, Reg: ARM::R9, VT: PtrVT);
3688 SDValue Result = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PtrVT, N1: SB, N2: RelAddr);
3689 return Result;
3690 }
3691
3692 // If we have T2 ops, we can materialize the address directly via movt/movw
3693 // pair. This is always cheaper. If need to generate Execute Only code, and we
3694 // only have Thumb1 available, we can't use a constant pool and are forced to
3695 // use immediate relocations.
3696 if (Subtarget->useMovt() || Subtarget->genExecuteOnly()) {
3697 if (Subtarget->useMovt())
3698 ++NumMovwMovt;
3699 // FIXME: Once remat is capable of dealing with instructions with register
3700 // operands, expand this into two nodes.
3701 return DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: PtrVT,
3702 Operand: DAG.getTargetGlobalAddress(GV, DL: dl, VT: PtrVT));
3703 } else {
3704 SDValue CPAddr = DAG.getTargetConstantPool(C: GV, VT: PtrVT, Align: Align(4));
3705 CPAddr = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: CPAddr);
3706 return DAG.getLoad(
3707 VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: CPAddr,
3708 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3709 }
3710}
3711
3712SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3713 SelectionDAG &DAG) const {
3714 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3715 "ROPI/RWPI not currently supported for Darwin");
3716 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3717 SDLoc dl(Op);
3718 const GlobalValue *GV = cast<GlobalAddressSDNode>(Val&: Op)->getGlobal();
3719
3720 if (Subtarget->useMovt())
3721 ++NumMovwMovt;
3722
3723 // FIXME: Once remat is capable of dealing with instructions with register
3724 // operands, expand this into multiple nodes
3725 unsigned Wrapper =
3726 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3727
3728 SDValue G = DAG.getTargetGlobalAddress(GV, DL: dl, VT: PtrVT, offset: 0, TargetFlags: ARMII::MO_NONLAZY);
3729 SDValue Result = DAG.getNode(Opcode: Wrapper, DL: dl, VT: PtrVT, Operand: G);
3730
3731 if (Subtarget->isGVIndirectSymbol(GV))
3732 Result = DAG.getLoad(VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: Result,
3733 PtrInfo: MachinePointerInfo::getGOT(MF&: DAG.getMachineFunction()));
3734 return Result;
3735}
3736
3737SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3738 SelectionDAG &DAG) const {
3739 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
3740 "non-Windows COFF is not supported");
3741 assert(Subtarget->useMovt() &&
3742 "Windows on ARM expects to use movw/movt");
3743 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3744 "ROPI/RWPI not currently supported for Windows");
3745
3746 const TargetMachine &TM = getTargetMachine();
3747 const GlobalValue *GV = cast<GlobalAddressSDNode>(Val&: Op)->getGlobal();
3748 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3749 if (GV->hasDLLImportStorageClass())
3750 TargetFlags = ARMII::MO_DLLIMPORT;
3751 else if (!TM.shouldAssumeDSOLocal(GV))
3752 TargetFlags = ARMII::MO_COFFSTUB;
3753 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3754 SDValue Result;
3755 SDLoc DL(Op);
3756
3757 ++NumMovwMovt;
3758
3759 // FIXME: Once remat is capable of dealing with instructions with register
3760 // operands, expand this into two nodes.
3761 Result = DAG.getNode(Opcode: ARMISD::Wrapper, DL, VT: PtrVT,
3762 Operand: DAG.getTargetGlobalAddress(GV, DL, VT: PtrVT, /*offset=*/0,
3763 TargetFlags));
3764 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3765 Result = DAG.getLoad(VT: PtrVT, dl: DL, Chain: DAG.getEntryNode(), Ptr: Result,
3766 PtrInfo: MachinePointerInfo::getGOT(MF&: DAG.getMachineFunction()));
3767 return Result;
3768}
3769
3770SDValue
3771ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3772 SDLoc dl(Op);
3773 SDValue Val = DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32);
3774 return DAG.getNode(Opcode: ARMISD::EH_SJLJ_SETJMP, DL: dl,
3775 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), N1: Op.getOperand(i: 0),
3776 N2: Op.getOperand(i: 1), N3: Val);
3777}
3778
3779SDValue
3780ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3781 SDLoc dl(Op);
3782 return DAG.getNode(Opcode: ARMISD::EH_SJLJ_LONGJMP, DL: dl, VT: MVT::Other, N1: Op.getOperand(i: 0),
3783 N2: Op.getOperand(i: 1), N3: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
3784}
3785
3786SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3787 SelectionDAG &DAG) const {
3788 SDLoc dl(Op);
3789 return DAG.getNode(Opcode: ARMISD::EH_SJLJ_SETUP_DISPATCH, DL: dl, VT: MVT::Other,
3790 Operand: Op.getOperand(i: 0));
3791}
3792
3793SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3794 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3795 unsigned IntNo =
3796 Op.getConstantOperandVal(i: Op.getOperand(i: 0).getValueType() == MVT::Other);
3797 switch (IntNo) {
3798 default:
3799 return SDValue(); // Don't custom lower most intrinsics.
3800 case Intrinsic::arm_gnu_eabi_mcount: {
3801 MachineFunction &MF = DAG.getMachineFunction();
3802 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3803 SDLoc dl(Op);
3804 SDValue Chain = Op.getOperand(i: 0);
3805 // call "\01__gnu_mcount_nc"
3806 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3807 const uint32_t *Mask =
3808 ARI->getCallPreservedMask(MF: DAG.getMachineFunction(), CallingConv::C);
3809 assert(Mask && "Missing call preserved mask for calling convention");
3810 // Mark LR an implicit live-in.
3811 Register Reg = MF.addLiveIn(PReg: ARM::LR, RC: getRegClassFor(VT: MVT::i32));
3812 SDValue ReturnAddress =
3813 DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl, Reg, VT: PtrVT);
3814 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3815 SDValue Callee =
3816 DAG.getTargetExternalSymbol(Sym: "\01__gnu_mcount_nc", VT: PtrVT, TargetFlags: 0);
3817 SDValue RegisterMask = DAG.getRegisterMask(RegMask: Mask);
3818 if (Subtarget->isThumb())
3819 return SDValue(
3820 DAG.getMachineNode(
3821 Opcode: ARM::tBL_PUSHLR, dl, ResultTys,
3822 Ops: {ReturnAddress, DAG.getTargetConstant(Val: ARMCC::AL, DL: dl, VT: PtrVT),
3823 DAG.getRegister(Reg: 0, VT: PtrVT), Callee, RegisterMask, Chain}),
3824 0);
3825 return SDValue(
3826 DAG.getMachineNode(Opcode: ARM::BL_PUSHLR, dl, ResultTys,
3827 Ops: {ReturnAddress, Callee, RegisterMask, Chain}),
3828 0);
3829 }
3830 }
3831}
3832
3833SDValue
3834ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3835 const ARMSubtarget *Subtarget) const {
3836 unsigned IntNo = Op.getConstantOperandVal(i: 0);
3837 SDLoc dl(Op);
3838 switch (IntNo) {
3839 default: return SDValue(); // Don't custom lower most intrinsics.
3840 case Intrinsic::thread_pointer: {
3841 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3842 return DAG.getNode(Opcode: ARMISD::THREAD_POINTER, DL: dl, VT: PtrVT);
3843 }
3844 case Intrinsic::arm_cls: {
3845 // Note: arm_cls and arm_cls64 intrinsics are expanded directly here
3846 // in LowerINTRINSIC_WO_CHAIN since there's no native scalar CLS
3847 // instruction.
3848 const SDValue &Operand = Op.getOperand(i: 1);
3849 const EVT VTy = Op.getValueType();
3850 return DAG.getNode(Opcode: ISD::CTLS, DL: dl, VT: VTy, Operand);
3851 }
3852 case Intrinsic::arm_cls64: {
3853 // arm_cls64 returns i32 but takes i64 input.
3854 // Use ISD::CTLS for i64 and truncate the result.
3855 SDValue CTLS64 = DAG.getNode(Opcode: ISD::CTLS, DL: dl, VT: MVT::i64, Operand: Op.getOperand(i: 1));
3856 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::i32, Operand: CTLS64);
3857 }
3858 case Intrinsic::arm_neon_vcls:
3859 case Intrinsic::arm_mve_vcls: {
3860 // Lower vector CLS intrinsics to ISD::CTLS.
3861 // Vector CTLS is Legal when NEON/MVE is available (set elsewhere).
3862 const EVT VTy = Op.getValueType();
3863 return DAG.getNode(Opcode: ISD::CTLS, DL: dl, VT: VTy, Operand: Op.getOperand(i: 1));
3864 }
3865 case Intrinsic::eh_sjlj_lsda: {
3866 MachineFunction &MF = DAG.getMachineFunction();
3867 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3868 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3869 EVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
3870 SDValue CPAddr;
3871 bool IsPositionIndependent = isPositionIndependent();
3872 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3873 ARMConstantPoolValue *CPV =
3874 ARMConstantPoolConstant::Create(C: &MF.getFunction(), ID: ARMPCLabelIndex,
3875 Kind: ARMCP::CPLSDA, PCAdj);
3876 CPAddr = DAG.getTargetConstantPool(C: CPV, VT: PtrVT, Align: Align(4));
3877 CPAddr = DAG.getNode(Opcode: ARMISD::Wrapper, DL: dl, VT: MVT::i32, Operand: CPAddr);
3878 SDValue Result = DAG.getLoad(
3879 VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: CPAddr,
3880 PtrInfo: MachinePointerInfo::getConstantPool(MF&: DAG.getMachineFunction()));
3881
3882 if (IsPositionIndependent) {
3883 SDValue PICLabel = DAG.getConstant(Val: ARMPCLabelIndex, DL: dl, VT: MVT::i32);
3884 Result = DAG.getNode(Opcode: ARMISD::PIC_ADD, DL: dl, VT: PtrVT, N1: Result, N2: PICLabel);
3885 }
3886 return Result;
3887 }
3888 case Intrinsic::arm_neon_vabs:
3889 return DAG.getNode(Opcode: ISD::ABS, DL: SDLoc(Op), VT: Op.getValueType(),
3890 Operand: Op.getOperand(i: 1));
3891 case Intrinsic::arm_neon_vabds:
3892 if (Op.getValueType().isInteger())
3893 return DAG.getNode(Opcode: ISD::ABDS, DL: SDLoc(Op), VT: Op.getValueType(),
3894 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3895 return SDValue();
3896 case Intrinsic::arm_neon_vabdu:
3897 return DAG.getNode(Opcode: ISD::ABDU, DL: SDLoc(Op), VT: Op.getValueType(),
3898 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3899 case Intrinsic::arm_neon_vmulls:
3900 case Intrinsic::arm_neon_vmullu: {
3901 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3902 ? ARMISD::VMULLs : ARMISD::VMULLu;
3903 return DAG.getNode(Opcode: NewOpc, DL: SDLoc(Op), VT: Op.getValueType(),
3904 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3905 }
3906 case Intrinsic::arm_neon_vminnm:
3907 case Intrinsic::arm_neon_vmaxnm: {
3908 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3909 ? ISD::FMINNUM : ISD::FMAXNUM;
3910 return DAG.getNode(Opcode: NewOpc, DL: SDLoc(Op), VT: Op.getValueType(),
3911 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3912 }
3913 case Intrinsic::arm_neon_vminu:
3914 case Intrinsic::arm_neon_vmaxu: {
3915 if (Op.getValueType().isFloatingPoint())
3916 return SDValue();
3917 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3918 ? ISD::UMIN : ISD::UMAX;
3919 return DAG.getNode(Opcode: NewOpc, DL: SDLoc(Op), VT: Op.getValueType(),
3920 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3921 }
3922 case Intrinsic::arm_neon_vmins:
3923 case Intrinsic::arm_neon_vmaxs: {
3924 // v{min,max}s is overloaded between signed integers and floats.
3925 if (!Op.getValueType().isFloatingPoint()) {
3926 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3927 ? ISD::SMIN : ISD::SMAX;
3928 return DAG.getNode(Opcode: NewOpc, DL: SDLoc(Op), VT: Op.getValueType(),
3929 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3930 }
3931 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3932 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3933 return DAG.getNode(Opcode: NewOpc, DL: SDLoc(Op), VT: Op.getValueType(),
3934 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3935 }
3936 case Intrinsic::arm_neon_vtbl1:
3937 return DAG.getNode(Opcode: ARMISD::VTBL1, DL: SDLoc(Op), VT: Op.getValueType(),
3938 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2));
3939 case Intrinsic::arm_neon_vtbl2:
3940 return DAG.getNode(Opcode: ARMISD::VTBL2, DL: SDLoc(Op), VT: Op.getValueType(),
3941 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2), N3: Op.getOperand(i: 3));
3942 case Intrinsic::arm_mve_pred_i2v:
3943 case Intrinsic::arm_mve_pred_v2i:
3944 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: SDLoc(Op), VT: Op.getValueType(),
3945 Operand: Op.getOperand(i: 1));
3946 case Intrinsic::arm_mve_vreinterpretq:
3947 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: SDLoc(Op), VT: Op.getValueType(),
3948 Operand: Op.getOperand(i: 1));
3949 case Intrinsic::arm_mve_lsll:
3950 return DAG.getNode(Opcode: ARMISD::LSLL, DL: SDLoc(Op), VTList: Op->getVTList(),
3951 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2), N3: Op.getOperand(i: 3));
3952 case Intrinsic::arm_mve_asrl:
3953 return DAG.getNode(Opcode: ARMISD::ASRL, DL: SDLoc(Op), VTList: Op->getVTList(),
3954 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2), N3: Op.getOperand(i: 3));
3955 case Intrinsic::arm_mve_vsli:
3956 return DAG.getNode(Opcode: ARMISD::VSLIIMM, DL: SDLoc(Op), VTList: Op->getVTList(),
3957 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2), N3: Op.getOperand(i: 3));
3958 case Intrinsic::arm_mve_vsri:
3959 return DAG.getNode(Opcode: ARMISD::VSRIIMM, DL: SDLoc(Op), VTList: Op->getVTList(),
3960 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2), N3: Op.getOperand(i: 3));
3961 }
3962}
3963
3964static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3965 const ARMSubtarget *Subtarget) {
3966 SDLoc dl(Op);
3967 auto SSID = static_cast<SyncScope::ID>(Op.getConstantOperandVal(i: 2));
3968 if (SSID == SyncScope::SingleThread)
3969 return Op;
3970
3971 if (!Subtarget->hasDataBarrier()) {
3972 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3973 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3974 // here.
3975 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3976 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3977 return DAG.getNode(Opcode: ARMISD::MEMBARRIER_MCR, DL: dl, VT: MVT::Other, N1: Op.getOperand(i: 0),
3978 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
3979 }
3980
3981 AtomicOrdering Ord =
3982 static_cast<AtomicOrdering>(Op.getConstantOperandVal(i: 1));
3983 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3984 if (Subtarget->isMClass()) {
3985 // Only a full system barrier exists in the M-class architectures.
3986 Domain = ARM_MB::SY;
3987 } else if (Subtarget->preferISHSTBarriers() &&
3988 Ord == AtomicOrdering::Release) {
3989 // Swift happens to implement ISHST barriers in a way that's compatible with
3990 // Release semantics but weaker than ISH so we'd be fools not to use
3991 // it. Beware: other processors probably don't!
3992 Domain = ARM_MB::ISHST;
3993 }
3994
3995 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL: dl, VT: MVT::Other, N1: Op.getOperand(i: 0),
3996 N2: DAG.getConstant(Val: Intrinsic::arm_dmb, DL: dl, VT: MVT::i32),
3997 N3: DAG.getConstant(Val: Domain, DL: dl, VT: MVT::i32));
3998}
3999
4000static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
4001 const ARMSubtarget *Subtarget) {
4002 // ARM pre v5TE and Thumb1 does not have preload instructions.
4003 if (!(Subtarget->isThumb2() ||
4004 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4005 // Just preserve the chain.
4006 return Op.getOperand(i: 0);
4007
4008 SDLoc dl(Op);
4009 unsigned isRead = ~Op.getConstantOperandVal(i: 2) & 1;
4010 if (!isRead &&
4011 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4012 // ARMv7 with MP extension has PLDW.
4013 return Op.getOperand(i: 0);
4014
4015 unsigned isData = Op.getConstantOperandVal(i: 4);
4016 if (Subtarget->isThumb()) {
4017 // Invert the bits.
4018 isRead = ~isRead & 1;
4019 isData = ~isData & 1;
4020 }
4021
4022 return DAG.getNode(Opcode: ARMISD::PRELOAD, DL: dl, VT: MVT::Other, N1: Op.getOperand(i: 0),
4023 N2: Op.getOperand(i: 1), N3: DAG.getConstant(Val: isRead, DL: dl, VT: MVT::i32),
4024 N4: DAG.getConstant(Val: isData, DL: dl, VT: MVT::i32));
4025}
4026
4027static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
4028 MachineFunction &MF = DAG.getMachineFunction();
4029 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4030
4031 // vastart just stores the address of the VarArgsFrameIndex slot into the
4032 // memory location argument.
4033 SDLoc dl(Op);
4034 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DL: DAG.getDataLayout());
4035 SDValue FR = DAG.getFrameIndex(FI: FuncInfo->getVarArgsFrameIndex(), VT: PtrVT);
4036 const Value *SV = cast<SrcValueSDNode>(Val: Op.getOperand(i: 2))->getValue();
4037 return DAG.getStore(Chain: Op.getOperand(i: 0), dl, Val: FR, Ptr: Op.getOperand(i: 1),
4038 PtrInfo: MachinePointerInfo(SV));
4039}
4040
4041SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4042 CCValAssign &NextVA,
4043 SDValue &Root,
4044 SelectionDAG &DAG,
4045 const SDLoc &dl) const {
4046 MachineFunction &MF = DAG.getMachineFunction();
4047 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4048
4049 const TargetRegisterClass *RC;
4050 if (AFI->isThumb1OnlyFunction())
4051 RC = &ARM::tGPRRegClass;
4052 else
4053 RC = &ARM::GPRRegClass;
4054
4055 // Transform the arguments stored in physical registers into virtual ones.
4056 Register Reg = MF.addLiveIn(PReg: VA.getLocReg(), RC);
4057 SDValue ArgValue = DAG.getCopyFromReg(Chain: Root, dl, Reg, VT: MVT::i32);
4058
4059 SDValue ArgValue2;
4060 if (NextVA.isMemLoc()) {
4061 MachineFrameInfo &MFI = MF.getFrameInfo();
4062 int FI = MFI.CreateFixedObject(Size: 4, SPOffset: NextVA.getLocMemOffset(), IsImmutable: true);
4063
4064 // Create load node to retrieve arguments from the stack.
4065 SDValue FIN = DAG.getFrameIndex(FI, VT: getPointerTy(DL: DAG.getDataLayout()));
4066 ArgValue2 = DAG.getLoad(
4067 VT: MVT::i32, dl, Chain: Root, Ptr: FIN,
4068 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI));
4069 } else {
4070 Reg = MF.addLiveIn(PReg: NextVA.getLocReg(), RC);
4071 ArgValue2 = DAG.getCopyFromReg(Chain: Root, dl, Reg, VT: MVT::i32);
4072 }
4073 if (!Subtarget->isLittle())
4074 std::swap (a&: ArgValue, b&: ArgValue2);
4075 return DAG.getNode(Opcode: ARMISD::VMOVDRR, DL: dl, VT: MVT::f64, N1: ArgValue, N2: ArgValue2);
4076}
4077
4078// The remaining GPRs hold either the beginning of variable-argument
4079// data, or the beginning of an aggregate passed by value (usually
4080// byval). Either way, we allocate stack slots adjacent to the data
4081// provided by our caller, and store the unallocated registers there.
4082// If this is a variadic function, the va_list pointer will begin with
4083// these values; otherwise, this reassembles a (byval) structure that
4084// was split between registers and memory.
4085// Return: The frame index registers were stored into.
4086int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4087 const SDLoc &dl, SDValue &Chain,
4088 const Value *OrigArg,
4089 unsigned InRegsParamRecordIdx,
4090 int ArgOffset, unsigned ArgSize) const {
4091 // Currently, two use-cases possible:
4092 // Case #1. Non-var-args function, and we meet first byval parameter.
4093 // Setup first unallocated register as first byval register;
4094 // eat all remained registers
4095 // (these two actions are performed by HandleByVal method).
4096 // Then, here, we initialize stack frame with
4097 // "store-reg" instructions.
4098 // Case #2. Var-args function, that doesn't contain byval parameters.
4099 // The same: eat all remained unallocated registers,
4100 // initialize stack frame.
4101
4102 MachineFunction &MF = DAG.getMachineFunction();
4103 MachineFrameInfo &MFI = MF.getFrameInfo();
4104 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4105 unsigned RBegin, REnd;
4106 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4107 CCInfo.getInRegsParamInfo(InRegsParamRecordIndex: InRegsParamRecordIdx, BeginReg&: RBegin, EndReg&: REnd);
4108 } else {
4109 unsigned RBeginIdx = CCInfo.getFirstUnallocated(Regs: GPRArgRegs);
4110 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4111 REnd = ARM::R4;
4112 }
4113
4114 if (REnd != RBegin)
4115 ArgOffset = -4 * (ARM::R4 - RBegin);
4116
4117 auto PtrVT = getPointerTy(DL: DAG.getDataLayout());
4118 int FrameIndex = MFI.CreateFixedObject(Size: ArgSize, SPOffset: ArgOffset, IsImmutable: false);
4119 SDValue FIN = DAG.getFrameIndex(FI: FrameIndex, VT: PtrVT);
4120
4121 SmallVector<SDValue, 4> MemOps;
4122 const TargetRegisterClass *RC =
4123 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4124
4125 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4126 Register VReg = MF.addLiveIn(PReg: Reg, RC);
4127 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg: VReg, VT: MVT::i32);
4128 SDValue Store = DAG.getStore(Chain: Val.getValue(R: 1), dl, Val, Ptr: FIN,
4129 PtrInfo: MachinePointerInfo(OrigArg, 4 * i));
4130 MemOps.push_back(Elt: Store);
4131 FIN = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PtrVT, N1: FIN, N2: DAG.getConstant(Val: 4, DL: dl, VT: PtrVT));
4132 }
4133
4134 if (!MemOps.empty())
4135 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: MemOps);
4136 return FrameIndex;
4137}
4138
4139// Setup stack frame, the va_list pointer will start from.
4140void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4141 const SDLoc &dl, SDValue &Chain,
4142 unsigned ArgOffset,
4143 unsigned TotalArgRegsSaveSize,
4144 bool ForceMutable) const {
4145 MachineFunction &MF = DAG.getMachineFunction();
4146 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4147
4148 // Try to store any remaining integer argument regs
4149 // to their spots on the stack so that they may be loaded by dereferencing
4150 // the result of va_next.
4151 // If there is no regs to be stored, just point address after last
4152 // argument passed via stack.
4153 int FrameIndex = StoreByValRegs(
4154 CCInfo, DAG, dl, Chain, OrigArg: nullptr, InRegsParamRecordIdx: CCInfo.getInRegsParamsCount(),
4155 ArgOffset: CCInfo.getStackSize(), ArgSize: std::max(a: 4U, b: TotalArgRegsSaveSize));
4156 AFI->setVarArgsFrameIndex(FrameIndex);
4157}
4158
4159bool ARMTargetLowering::splitValueIntoRegisterParts(
4160 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4161 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4162 EVT ValueVT = Val.getValueType();
4163 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4164 unsigned ValueBits = ValueVT.getSizeInBits();
4165 unsigned PartBits = PartVT.getSizeInBits();
4166 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::getIntegerVT(BitWidth: ValueBits), Operand: Val);
4167 Val = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: MVT::getIntegerVT(BitWidth: PartBits), Operand: Val);
4168 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: PartVT, Operand: Val);
4169 Parts[0] = Val;
4170 return true;
4171 }
4172 return false;
4173}
4174
4175SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4176 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4177 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
4178 if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4179 unsigned ValueBits = ValueVT.getSizeInBits();
4180 unsigned PartBits = PartVT.getSizeInBits();
4181 SDValue Val = Parts[0];
4182
4183 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::getIntegerVT(BitWidth: PartBits), Operand: Val);
4184 Val = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: MVT::getIntegerVT(BitWidth: ValueBits), Operand: Val);
4185 Val = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: ValueVT, Operand: Val);
4186 return Val;
4187 }
4188 return SDValue();
4189}
4190
4191SDValue ARMTargetLowering::LowerFormalArguments(
4192 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4193 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4194 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4195 MachineFunction &MF = DAG.getMachineFunction();
4196 MachineFrameInfo &MFI = MF.getFrameInfo();
4197
4198 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4199
4200 // Assign locations to all of the incoming arguments.
4201 SmallVector<CCValAssign, 16> ArgLocs;
4202 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4203 *DAG.getContext());
4204 CCInfo.AnalyzeFormalArguments(Ins, Fn: CCAssignFnForCall(CC: CallConv, isVarArg));
4205
4206 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4207 unsigned CurArgIdx = 0;
4208
4209 // Initially ArgRegsSaveSize is zero.
4210 // Then we increase this value each time we meet byval parameter.
4211 // We also increase this value in case of varargs function.
4212 AFI->setArgRegsSaveSize(0);
4213
4214 // Calculate the amount of stack space that we need to allocate to store
4215 // byval and variadic arguments that are passed in registers.
4216 // We need to know this before we allocate the first byval or variadic
4217 // argument, as they will be allocated a stack slot below the CFA (Canonical
4218 // Frame Address, the stack pointer at entry to the function).
4219 unsigned ArgRegBegin = ARM::R4;
4220 for (const CCValAssign &VA : ArgLocs) {
4221 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4222 break;
4223
4224 unsigned Index = VA.getValNo();
4225 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4226 if (!Flags.isByVal())
4227 continue;
4228
4229 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4230 unsigned RBegin, REnd;
4231 CCInfo.getInRegsParamInfo(InRegsParamRecordIndex: CCInfo.getInRegsParamsProcessed(), BeginReg&: RBegin, EndReg&: REnd);
4232 ArgRegBegin = std::min(a: ArgRegBegin, b: RBegin);
4233
4234 CCInfo.nextInRegsParam();
4235 }
4236 CCInfo.rewindByValRegsInfo();
4237
4238 int lastInsIndex = -1;
4239 if (isVarArg && MFI.hasVAStart()) {
4240 unsigned RegIdx = CCInfo.getFirstUnallocated(Regs: GPRArgRegs);
4241 if (RegIdx != std::size(GPRArgRegs))
4242 ArgRegBegin = std::min(a: ArgRegBegin, b: (unsigned)GPRArgRegs[RegIdx]);
4243 }
4244
4245 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4246 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4247 auto PtrVT = getPointerTy(DL: DAG.getDataLayout());
4248
4249 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4250 CCValAssign &VA = ArgLocs[i];
4251 if (Ins[VA.getValNo()].isOrigArg()) {
4252 std::advance(i&: CurOrigArg,
4253 n: Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4254 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4255 }
4256 // Arguments stored in registers.
4257 if (VA.isRegLoc()) {
4258 EVT RegVT = VA.getLocVT();
4259 SDValue ArgValue;
4260
4261 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4262 // f64 and vector types are split up into multiple registers or
4263 // combinations of registers and stack slots.
4264 SDValue ArgValue1 =
4265 GetF64FormalArgument(VA, NextVA&: ArgLocs[++i], Root&: Chain, DAG, dl);
4266 VA = ArgLocs[++i]; // skip ahead to next loc
4267 SDValue ArgValue2;
4268 if (VA.isMemLoc()) {
4269 int FI = MFI.CreateFixedObject(Size: 8, SPOffset: VA.getLocMemOffset(), IsImmutable: true);
4270 SDValue FIN = DAG.getFrameIndex(FI, VT: PtrVT);
4271 ArgValue2 = DAG.getLoad(
4272 VT: MVT::f64, dl, Chain, Ptr: FIN,
4273 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI));
4274 } else {
4275 ArgValue2 = GetF64FormalArgument(VA, NextVA&: ArgLocs[++i], Root&: Chain, DAG, dl);
4276 }
4277 ArgValue = DAG.getNode(Opcode: ISD::UNDEF, DL: dl, VT: MVT::v2f64);
4278 ArgValue = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: MVT::v2f64, N1: ArgValue,
4279 N2: ArgValue1, N3: DAG.getIntPtrConstant(Val: 0, DL: dl));
4280 ArgValue = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: MVT::v2f64, N1: ArgValue,
4281 N2: ArgValue2, N3: DAG.getIntPtrConstant(Val: 1, DL: dl));
4282 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4283 ArgValue = GetF64FormalArgument(VA, NextVA&: ArgLocs[++i], Root&: Chain, DAG, dl);
4284 } else {
4285 const TargetRegisterClass *RC;
4286
4287 if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4288 RC = &ARM::HPRRegClass;
4289 else if (RegVT == MVT::f32)
4290 RC = &ARM::SPRRegClass;
4291 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4292 RegVT == MVT::v4bf16)
4293 RC = &ARM::DPRRegClass;
4294 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4295 RegVT == MVT::v8bf16)
4296 RC = &ARM::QPRRegClass;
4297 else if (RegVT == MVT::i32)
4298 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4299 : &ARM::GPRRegClass;
4300 else
4301 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4302
4303 // Transform the arguments in physical registers into virtual ones.
4304 Register Reg = MF.addLiveIn(PReg: VA.getLocReg(), RC);
4305 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, VT: RegVT);
4306
4307 // If this value is passed in r0 and has the returned attribute (e.g.
4308 // C++ 'structors), record this fact for later use.
4309 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4310 AFI->setPreservesR0();
4311 }
4312 }
4313
4314 // If this is an 8 or 16-bit value, it is really passed promoted
4315 // to 32 bits. Insert an assert[sz]ext to capture this, then
4316 // truncate to the right size.
4317 switch (VA.getLocInfo()) {
4318 default: llvm_unreachable("Unknown loc info!");
4319 case CCValAssign::Full: break;
4320 case CCValAssign::BCvt:
4321 ArgValue = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VA.getValVT(), Operand: ArgValue);
4322 break;
4323 }
4324
4325 // f16 arguments have their size extended to 4 bytes and passed as if they
4326 // had been copied to the LSBs of a 32-bit register.
4327 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4328 if (VA.needsCustom() &&
4329 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4330 ArgValue = MoveToHPR(dl, DAG, LocVT: VA.getLocVT(), ValVT: VA.getValVT(), Val: ArgValue);
4331
4332 // On CMSE Entry Functions, formal integer arguments whose bitwidth is
4333 // less than 32 bits must be sign- or zero-extended in the callee for
4334 // security reasons. Although the ABI mandates an extension done by the
4335 // caller, the latter cannot be trusted to follow the rules of the ABI.
4336 const ISD::InputArg &Arg = Ins[VA.getValNo()];
4337 if (AFI->isCmseNSEntryFunction() && Arg.ArgVT.isScalarInteger() &&
4338 RegVT.isScalarInteger() && Arg.ArgVT.bitsLT(VT: MVT::i32))
4339 ArgValue = handleCMSEValue(Value: ArgValue, Arg, DAG, DL: dl);
4340
4341 InVals.push_back(Elt: ArgValue);
4342 } else { // VA.isRegLoc()
4343 // Only arguments passed on the stack should make it here.
4344 assert(VA.isMemLoc());
4345 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4346
4347 int index = VA.getValNo();
4348
4349 // Some Ins[] entries become multiple ArgLoc[] entries.
4350 // Process them only once.
4351 if (index != lastInsIndex)
4352 {
4353 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4354 // FIXME: For now, all byval parameter objects are marked mutable.
4355 // This can be changed with more analysis.
4356 // In case of tail call optimization mark all arguments mutable.
4357 // Since they could be overwritten by lowering of arguments in case of
4358 // a tail call.
4359 if (Flags.isByVal()) {
4360 assert(Ins[index].isOrigArg() &&
4361 "Byval arguments cannot be implicit");
4362 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4363
4364 int FrameIndex = StoreByValRegs(
4365 CCInfo, DAG, dl, Chain, OrigArg: &*CurOrigArg, InRegsParamRecordIdx: CurByValIndex,
4366 ArgOffset: VA.getLocMemOffset(), ArgSize: Flags.getByValSize());
4367 InVals.push_back(Elt: DAG.getFrameIndex(FI: FrameIndex, VT: PtrVT));
4368 CCInfo.nextInRegsParam();
4369 } else if (VA.needsCustom() && (VA.getValVT() == MVT::f16 ||
4370 VA.getValVT() == MVT::bf16)) {
4371 // f16 and bf16 values are passed in the least-significant half of
4372 // a 4 byte stack slot. This is done as-if the extension was done
4373 // in a 32-bit register, so the actual bytes used for the value
4374 // differ between little and big endian.
4375 assert(VA.getLocVT().getSizeInBits() == 32);
4376 unsigned FIOffset = VA.getLocMemOffset();
4377 int FI = MFI.CreateFixedObject(Size: VA.getLocVT().getSizeInBits() / 8,
4378 SPOffset: FIOffset, IsImmutable: true);
4379
4380 SDValue Addr = DAG.getFrameIndex(FI, VT: PtrVT);
4381 if (DAG.getDataLayout().isBigEndian())
4382 Addr = DAG.getObjectPtrOffset(SL: dl, Ptr: Addr, Offset: TypeSize::getFixed(ExactSize: 2));
4383
4384 InVals.push_back(Elt: DAG.getLoad(VT: VA.getValVT(), dl, Chain, Ptr: Addr,
4385 PtrInfo: MachinePointerInfo::getFixedStack(
4386 MF&: DAG.getMachineFunction(), FI)));
4387
4388 } else {
4389 unsigned FIOffset = VA.getLocMemOffset();
4390 int FI = MFI.CreateFixedObject(Size: VA.getLocVT().getSizeInBits()/8,
4391 SPOffset: FIOffset, IsImmutable: true);
4392
4393 // Create load nodes to retrieve arguments from the stack.
4394 SDValue FIN = DAG.getFrameIndex(FI, VT: PtrVT);
4395 InVals.push_back(Elt: DAG.getLoad(VT: VA.getValVT(), dl, Chain, Ptr: FIN,
4396 PtrInfo: MachinePointerInfo::getFixedStack(
4397 MF&: DAG.getMachineFunction(), FI)));
4398 }
4399 lastInsIndex = index;
4400 }
4401 }
4402 }
4403
4404 // varargs
4405 if (isVarArg && MFI.hasVAStart()) {
4406 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, ArgOffset: CCInfo.getStackSize(),
4407 TotalArgRegsSaveSize);
4408 if (AFI->isCmseNSEntryFunction()) {
4409 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
4410 DAG.getMachineFunction().getFunction(),
4411 "secure entry function must not be variadic", dl.getDebugLoc()));
4412 }
4413 }
4414
4415 unsigned StackArgSize = CCInfo.getStackSize();
4416 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4417 if (canGuaranteeTCO(CC: CallConv, GuaranteeTailCalls: TailCallOpt)) {
4418 // The only way to guarantee a tail call is if the callee restores its
4419 // argument area, but it must also keep the stack aligned when doing so.
4420 MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
4421 assert(StackAlign && "data layout string is missing stack alignment");
4422 StackArgSize = alignTo(Size: StackArgSize, A: *StackAlign);
4423
4424 AFI->setArgumentStackToRestore(StackArgSize);
4425 }
4426 AFI->setArgumentStackSize(StackArgSize);
4427
4428 if (CCInfo.getStackSize() > 0 && AFI->isCmseNSEntryFunction()) {
4429 DAG.getContext()->diagnose(DI: DiagnosticInfoUnsupported(
4430 DAG.getMachineFunction().getFunction(),
4431 "secure entry function requires arguments on stack", dl.getDebugLoc()));
4432 }
4433
4434 return Chain;
4435}
4436
4437/// isFloatingPointZero - Return true if this is +0.0.
4438static bool isFloatingPointZero(SDValue Op) {
4439 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Val&: Op))
4440 return CFP->getValueAPF().isPosZero();
4441 else if (ISD::isEXTLoad(N: Op.getNode()) || ISD::isNON_EXTLoad(N: Op.getNode())) {
4442 // Maybe this has already been legalized into the constant pool?
4443 if (Op.getOperand(i: 1).getOpcode() == ARMISD::Wrapper) {
4444 SDValue WrapperOp = Op.getOperand(i: 1).getOperand(i: 0);
4445 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Val&: WrapperOp))
4446 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(Val: CP->getConstVal()))
4447 return CFP->getValueAPF().isPosZero();
4448 }
4449 } else if (Op->getOpcode() == ISD::BITCAST &&
4450 Op->getValueType(ResNo: 0) == MVT::f64) {
4451 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4452 // created by LowerConstantFP().
4453 SDValue BitcastOp = Op->getOperand(Num: 0);
4454 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4455 isNullConstant(V: BitcastOp->getOperand(Num: 0)))
4456 return true;
4457 }
4458 return false;
4459}
4460
4461/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4462/// the given operands.
4463SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4464 SDValue &ARMcc, SelectionDAG &DAG,
4465 const SDLoc &dl) const {
4466 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Val: RHS.getNode())) {
4467 unsigned C = RHSC->getZExtValue();
4468 if (!isLegalICmpImmediate(Imm: (int32_t)C)) {
4469 // Constant does not fit, try adjusting it by one.
4470 switch (CC) {
4471 default: break;
4472 case ISD::SETLT:
4473 case ISD::SETGE:
4474 if (C != 0x80000000 && isLegalICmpImmediate(Imm: C-1)) {
4475 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4476 RHS = DAG.getConstant(Val: C - 1, DL: dl, VT: MVT::i32);
4477 }
4478 break;
4479 case ISD::SETULT:
4480 case ISD::SETUGE:
4481 if (C != 0 && isLegalICmpImmediate(Imm: C-1)) {
4482 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4483 RHS = DAG.getConstant(Val: C - 1, DL: dl, VT: MVT::i32);
4484 }
4485 break;
4486 case ISD::SETLE:
4487 case ISD::SETGT:
4488 if (C != 0x7fffffff && isLegalICmpImmediate(Imm: C+1)) {
4489 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4490 RHS = DAG.getConstant(Val: C + 1, DL: dl, VT: MVT::i32);
4491 }
4492 break;
4493 case ISD::SETULE:
4494 case ISD::SETUGT:
4495 if (C != 0xffffffff && isLegalICmpImmediate(Imm: C+1)) {
4496 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4497 RHS = DAG.getConstant(Val: C + 1, DL: dl, VT: MVT::i32);
4498 }
4499 break;
4500 }
4501 }
4502 } else if ((ARM_AM::getShiftOpcForNode(Opcode: LHS.getOpcode()) != ARM_AM::no_shift) &&
4503 (ARM_AM::getShiftOpcForNode(Opcode: RHS.getOpcode()) == ARM_AM::no_shift)) {
4504 // In ARM and Thumb-2, the compare instructions can shift their second
4505 // operand.
4506 CC = ISD::getSetCCSwappedOperands(Operation: CC);
4507 std::swap(a&: LHS, b&: RHS);
4508 }
4509
4510 // Thumb1 has very limited immediate modes, so turning an "and" into a
4511 // shift can save multiple instructions.
4512 //
4513 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4514 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4515 // own. If it's the operand to an unsigned comparison with an immediate,
4516 // we can eliminate one of the shifts: we transform
4517 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4518 //
4519 // We avoid transforming cases which aren't profitable due to encoding
4520 // details:
4521 //
4522 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4523 // would not; in that case, we're essentially trading one immediate load for
4524 // another.
4525 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4526 // 3. C2 is zero; we have other code for this special case.
4527 //
4528 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4529 // instruction, since the AND is always one instruction anyway, but we could
4530 // use narrow instructions in some cases.
4531 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4532 LHS->hasOneUse() && isa<ConstantSDNode>(Val: LHS.getOperand(i: 1)) &&
4533 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(Val: RHS) &&
4534 !isSignedIntSetCC(Code: CC)) {
4535 unsigned Mask = LHS.getConstantOperandVal(i: 1);
4536 auto *RHSC = cast<ConstantSDNode>(Val: RHS.getNode());
4537 uint64_t RHSV = RHSC->getZExtValue();
4538 if (isMask_32(Value: Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4539 unsigned ShiftBits = llvm::countl_zero(Val: Mask);
4540 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4541 SDValue ShiftAmt = DAG.getConstant(Val: ShiftBits, DL: dl, VT: MVT::i32);
4542 LHS = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT: MVT::i32, N1: LHS.getOperand(i: 0), N2: ShiftAmt);
4543 RHS = DAG.getConstant(Val: RHSV << ShiftBits, DL: dl, VT: MVT::i32);
4544 }
4545 }
4546 }
4547
4548 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4549 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4550 // way a cmp would.
4551 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4552 // some tweaks to the heuristics for the previous and->shift transform.
4553 // FIXME: Optimize cases where the LHS isn't a shift.
4554 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4555 isa<ConstantSDNode>(Val: RHS) && RHS->getAsZExtVal() == 0x80000000U &&
4556 CC == ISD::SETUGT && isa<ConstantSDNode>(Val: LHS.getOperand(i: 1)) &&
4557 LHS.getConstantOperandVal(i: 1) < 31) {
4558 unsigned ShiftAmt = LHS.getConstantOperandVal(i: 1) + 1;
4559 SDValue Shift =
4560 DAG.getNode(Opcode: ARMISD::LSLS, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT),
4561 N1: LHS.getOperand(i: 0), N2: DAG.getConstant(Val: ShiftAmt, DL: dl, VT: MVT::i32));
4562 ARMcc = DAG.getConstant(Val: ARMCC::HI, DL: dl, VT: MVT::i32);
4563 return Shift.getValue(R: 1);
4564 }
4565
4566 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4567
4568 // If the RHS is a constant zero then the V (overflow) flag will never be
4569 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4570 // simpler for other passes (like the peephole optimiser) to deal with.
4571 if (isNullConstant(V: RHS)) {
4572 switch (CondCode) {
4573 default: break;
4574 case ARMCC::GE:
4575 CondCode = ARMCC::PL;
4576 break;
4577 case ARMCC::LT:
4578 CondCode = ARMCC::MI;
4579 break;
4580 }
4581 }
4582
4583 unsigned CompareType;
4584 switch (CondCode) {
4585 default:
4586 CompareType = ARMISD::CMP;
4587 break;
4588 case ARMCC::EQ:
4589 case ARMCC::NE:
4590 // Uses only Z Flag
4591 CompareType = ARMISD::CMPZ;
4592 break;
4593 }
4594 ARMcc = DAG.getConstant(Val: CondCode, DL: dl, VT: MVT::i32);
4595 return DAG.getNode(Opcode: CompareType, DL: dl, VT: FlagsVT, N1: LHS, N2: RHS);
4596}
4597
4598/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4599SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4600 SelectionDAG &DAG, const SDLoc &dl,
4601 bool Signaling) const {
4602 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4603 SDValue Flags;
4604 if (!isFloatingPointZero(Op: RHS))
4605 Flags = DAG.getNode(Opcode: Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, DL: dl, VT: FlagsVT,
4606 N1: LHS, N2: RHS);
4607 else
4608 Flags = DAG.getNode(Opcode: Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, DL: dl,
4609 VT: FlagsVT, Operand: LHS);
4610 return DAG.getNode(Opcode: ARMISD::FMSTAT, DL: dl, VT: FlagsVT, Operand: Flags);
4611}
4612
4613// This function returns three things: the arithmetic computation itself
4614// (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4615// comparison and the condition code define the case in which the arithmetic
4616// computation *does not* overflow.
4617std::pair<SDValue, SDValue>
4618ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4619 SDValue &ARMcc) const {
4620 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4621
4622 SDValue Value, OverflowCmp;
4623 SDValue LHS = Op.getOperand(i: 0);
4624 SDValue RHS = Op.getOperand(i: 1);
4625 SDLoc dl(Op);
4626
4627 // FIXME: We are currently always generating CMPs because we don't support
4628 // generating CMN through the backend. This is not as good as the natural
4629 // CMP case because it causes a register dependency and cannot be folded
4630 // later.
4631
4632 switch (Op.getOpcode()) {
4633 default:
4634 llvm_unreachable("Unknown overflow instruction!");
4635 case ISD::SADDO:
4636 ARMcc = DAG.getConstant(Val: ARMCC::VC, DL: dl, VT: MVT::i32);
4637 Value = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: Op.getValueType(), N1: LHS, N2: RHS);
4638 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMP, DL: dl, VT: FlagsVT, N1: Value, N2: LHS);
4639 break;
4640 case ISD::UADDO:
4641 ARMcc = DAG.getConstant(Val: ARMCC::HS, DL: dl, VT: MVT::i32);
4642 // We use ADDC here to correspond to its use in LowerALUO.
4643 // We do not use it in the USUBO case as Value may not be used.
4644 Value = DAG.getNode(Opcode: ARMISD::ADDC, DL: dl,
4645 VTList: DAG.getVTList(VT1: Op.getValueType(), VT2: MVT::i32), N1: LHS, N2: RHS)
4646 .getValue(R: 0);
4647 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMP, DL: dl, VT: FlagsVT, N1: Value, N2: LHS);
4648 break;
4649 case ISD::SSUBO:
4650 ARMcc = DAG.getConstant(Val: ARMCC::VC, DL: dl, VT: MVT::i32);
4651 Value = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: Op.getValueType(), N1: LHS, N2: RHS);
4652 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMP, DL: dl, VT: FlagsVT, N1: LHS, N2: RHS);
4653 break;
4654 case ISD::USUBO:
4655 ARMcc = DAG.getConstant(Val: ARMCC::HS, DL: dl, VT: MVT::i32);
4656 Value = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: Op.getValueType(), N1: LHS, N2: RHS);
4657 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMP, DL: dl, VT: FlagsVT, N1: LHS, N2: RHS);
4658 break;
4659 case ISD::UMULO:
4660 // We generate a UMUL_LOHI and then check if the high word is 0.
4661 ARMcc = DAG.getConstant(Val: ARMCC::EQ, DL: dl, VT: MVT::i32);
4662 Value = DAG.getNode(Opcode: ISD::UMUL_LOHI, DL: dl,
4663 VTList: DAG.getVTList(VT1: Op.getValueType(), VT2: Op.getValueType()),
4664 N1: LHS, N2: RHS);
4665 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMPZ, DL: dl, VT: FlagsVT, N1: Value.getValue(R: 1),
4666 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
4667 Value = Value.getValue(R: 0); // We only want the low 32 bits for the result.
4668 break;
4669 case ISD::SMULO:
4670 // We generate a SMUL_LOHI and then check if all the bits of the high word
4671 // are the same as the sign bit of the low word.
4672 ARMcc = DAG.getConstant(Val: ARMCC::EQ, DL: dl, VT: MVT::i32);
4673 Value = DAG.getNode(Opcode: ISD::SMUL_LOHI, DL: dl,
4674 VTList: DAG.getVTList(VT1: Op.getValueType(), VT2: Op.getValueType()),
4675 N1: LHS, N2: RHS);
4676 OverflowCmp = DAG.getNode(Opcode: ARMISD::CMPZ, DL: dl, VT: FlagsVT, N1: Value.getValue(R: 1),
4677 N2: DAG.getNode(Opcode: ISD::SRA, DL: dl, VT: Op.getValueType(),
4678 N1: Value.getValue(R: 0),
4679 N2: DAG.getConstant(Val: 31, DL: dl, VT: MVT::i32)));
4680 Value = Value.getValue(R: 0); // We only want the low 32 bits for the result.
4681 break;
4682 } // switch (...)
4683
4684 return std::make_pair(x&: Value, y&: OverflowCmp);
4685}
4686
4687static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4688 SelectionDAG &DAG) {
4689 SDLoc DL(BoolCarry);
4690 EVT CarryVT = BoolCarry.getValueType();
4691
4692 // This converts the boolean value carry into the carry flag by doing
4693 // ARMISD::SUBC Carry, 1
4694 SDValue Carry = DAG.getNode(Opcode: ARMISD::SUBC, DL,
4695 VTList: DAG.getVTList(VT1: CarryVT, VT2: MVT::i32),
4696 N1: BoolCarry, N2: DAG.getConstant(Val: 1, DL, VT: CarryVT));
4697 return Carry.getValue(R: 1);
4698}
4699
4700static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4701 SelectionDAG &DAG) {
4702 SDLoc DL(Flags);
4703
4704 // Now convert the carry flag into a boolean carry. We do this
4705 // using ARMISD:ADDE 0, 0, Carry
4706 return DAG.getNode(Opcode: ARMISD::ADDE, DL, VTList: DAG.getVTList(VT1: VT, VT2: MVT::i32),
4707 N1: DAG.getConstant(Val: 0, DL, VT: MVT::i32),
4708 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32), N3: Flags);
4709}
4710
4711SDValue ARMTargetLowering::LowerALUO(SDValue Op, SelectionDAG &DAG) const {
4712 // Let legalize expand this if it isn't a legal type yet.
4713 if (!isTypeLegal(VT: Op.getValueType()))
4714 return SDValue();
4715
4716 SDValue LHS = Op.getOperand(i: 0);
4717 SDValue RHS = Op.getOperand(i: 1);
4718 SDLoc dl(Op);
4719
4720 EVT VT = Op.getValueType();
4721 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::i32);
4722 SDValue Value;
4723 SDValue Overflow;
4724 switch (Op.getOpcode()) {
4725 case ISD::UADDO:
4726 Value = DAG.getNode(Opcode: ARMISD::ADDC, DL: dl, VTList: VTs, N1: LHS, N2: RHS);
4727 // Convert the carry flag into a boolean value.
4728 Overflow = ConvertCarryFlagToBooleanCarry(Flags: Value.getValue(R: 1), VT, DAG);
4729 break;
4730 case ISD::USUBO:
4731 Value = DAG.getNode(Opcode: ARMISD::SUBC, DL: dl, VTList: VTs, N1: LHS, N2: RHS);
4732 // Convert the carry flag into a boolean value.
4733 Overflow = ConvertCarryFlagToBooleanCarry(Flags: Value.getValue(R: 1), VT, DAG);
4734 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4735 // value. So compute 1 - C.
4736 Overflow = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
4737 N1: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32), N2: Overflow);
4738 break;
4739 default: {
4740 // Handle other operations with getARMXALUOOp
4741 SDValue OverflowCmp, ARMcc;
4742 std::tie(args&: Value, args&: OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4743 // We use 0 and 1 as false and true values.
4744 // ARMcc represents the "no overflow" condition (e.g., VC for signed ops).
4745 // CMOV operand order is (FalseVal, TrueVal), so we put 1 in FalseVal
4746 // position to get Overflow=1 when the "no overflow" condition is false.
4747 Overflow =
4748 DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT: MVT::i32,
4749 N1: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32), // FalseVal: overflow
4750 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32), // TrueVal: no overflow
4751 N3: ARMcc, N4: OverflowCmp);
4752 break;
4753 }
4754 }
4755
4756 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl, VTList: VTs, N1: Value, N2: Overflow);
4757}
4758
4759static SDValue LowerADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4760 const ARMSubtarget *Subtarget) {
4761 EVT VT = Op.getValueType();
4762 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() || Subtarget->isThumb1Only())
4763 return SDValue();
4764 if (!VT.isSimple())
4765 return SDValue();
4766
4767 unsigned NewOpcode;
4768 switch (VT.getSimpleVT().SimpleTy) {
4769 default:
4770 return SDValue();
4771 case MVT::i8:
4772 switch (Op->getOpcode()) {
4773 case ISD::UADDSAT:
4774 NewOpcode = ARMISD::UQADD8b;
4775 break;
4776 case ISD::SADDSAT:
4777 NewOpcode = ARMISD::QADD8b;
4778 break;
4779 case ISD::USUBSAT:
4780 NewOpcode = ARMISD::UQSUB8b;
4781 break;
4782 case ISD::SSUBSAT:
4783 NewOpcode = ARMISD::QSUB8b;
4784 break;
4785 }
4786 break;
4787 case MVT::i16:
4788 switch (Op->getOpcode()) {
4789 case ISD::UADDSAT:
4790 NewOpcode = ARMISD::UQADD16b;
4791 break;
4792 case ISD::SADDSAT:
4793 NewOpcode = ARMISD::QADD16b;
4794 break;
4795 case ISD::USUBSAT:
4796 NewOpcode = ARMISD::UQSUB16b;
4797 break;
4798 case ISD::SSUBSAT:
4799 NewOpcode = ARMISD::QSUB16b;
4800 break;
4801 }
4802 break;
4803 }
4804
4805 SDLoc dl(Op);
4806 SDValue Add =
4807 DAG.getNode(Opcode: NewOpcode, DL: dl, VT: MVT::i32,
4808 N1: DAG.getSExtOrTrunc(Op: Op->getOperand(Num: 0), DL: dl, VT: MVT::i32),
4809 N2: DAG.getSExtOrTrunc(Op: Op->getOperand(Num: 1), DL: dl, VT: MVT::i32));
4810 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT, Operand: Add);
4811}
4812
4813SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4814 SDValue Cond = Op.getOperand(i: 0);
4815 SDValue SelectTrue = Op.getOperand(i: 1);
4816 SDValue SelectFalse = Op.getOperand(i: 2);
4817 SDLoc dl(Op);
4818 unsigned Opc = Cond.getOpcode();
4819
4820 if (Cond.getResNo() == 1 &&
4821 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4822 Opc == ISD::USUBO)) {
4823 if (!isTypeLegal(VT: Cond->getValueType(ResNo: 0)))
4824 return SDValue();
4825
4826 SDValue Value, OverflowCmp;
4827 SDValue ARMcc;
4828 std::tie(args&: Value, args&: OverflowCmp) = getARMXALUOOp(Op: Cond, DAG, ARMcc);
4829 EVT VT = Op.getValueType();
4830
4831 return getCMOV(dl, VT, FalseVal: SelectTrue, TrueVal: SelectFalse, ARMcc, Flags: OverflowCmp, DAG);
4832 }
4833
4834 // Convert:
4835 //
4836 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4837 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4838 //
4839 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4840 const ConstantSDNode *CMOVTrue =
4841 dyn_cast<ConstantSDNode>(Val: Cond.getOperand(i: 0));
4842 const ConstantSDNode *CMOVFalse =
4843 dyn_cast<ConstantSDNode>(Val: Cond.getOperand(i: 1));
4844
4845 if (CMOVTrue && CMOVFalse) {
4846 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4847 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4848
4849 SDValue True;
4850 SDValue False;
4851 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4852 True = SelectTrue;
4853 False = SelectFalse;
4854 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4855 True = SelectFalse;
4856 False = SelectTrue;
4857 }
4858
4859 if (True.getNode() && False.getNode())
4860 return getCMOV(dl, VT: Op.getValueType(), FalseVal: True, TrueVal: False, ARMcc: Cond.getOperand(i: 2),
4861 Flags: Cond.getOperand(i: 3), DAG);
4862 }
4863 }
4864
4865 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4866 // undefined bits before doing a full-word comparison with zero.
4867 Cond = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: Cond.getValueType(), N1: Cond,
4868 N2: DAG.getConstant(Val: 1, DL: dl, VT: Cond.getValueType()));
4869
4870 return DAG.getSelectCC(DL: dl, LHS: Cond,
4871 RHS: DAG.getConstant(Val: 0, DL: dl, VT: Cond.getValueType()),
4872 True: SelectTrue, False: SelectFalse, Cond: ISD::SETNE);
4873}
4874
4875static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4876 bool &swpCmpOps, bool &swpVselOps) {
4877 // Start by selecting the GE condition code for opcodes that return true for
4878 // 'equality'
4879 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4880 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4881 CondCode = ARMCC::GE;
4882
4883 // and GT for opcodes that return false for 'equality'.
4884 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4885 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4886 CondCode = ARMCC::GT;
4887
4888 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4889 // to swap the compare operands.
4890 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4891 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4892 swpCmpOps = true;
4893
4894 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4895 // If we have an unordered opcode, we need to swap the operands to the VSEL
4896 // instruction (effectively negating the condition).
4897 //
4898 // This also has the effect of swapping which one of 'less' or 'greater'
4899 // returns true, so we also swap the compare operands. It also switches
4900 // whether we return true for 'equality', so we compensate by picking the
4901 // opposite condition code to our original choice.
4902 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4903 CC == ISD::SETUGT) {
4904 swpCmpOps = !swpCmpOps;
4905 swpVselOps = !swpVselOps;
4906 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4907 }
4908
4909 // 'ordered' is 'anything but unordered', so use the VS condition code and
4910 // swap the VSEL operands.
4911 if (CC == ISD::SETO) {
4912 CondCode = ARMCC::VS;
4913 swpVselOps = true;
4914 }
4915
4916 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4917 // code and swap the VSEL operands. Also do this if we don't care about the
4918 // unordered case.
4919 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4920 CondCode = ARMCC::EQ;
4921 swpVselOps = true;
4922 }
4923}
4924
4925SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4926 SDValue TrueVal, SDValue ARMcc,
4927 SDValue Flags, SelectionDAG &DAG) const {
4928 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4929 FalseVal = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl,
4930 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N: FalseVal);
4931 TrueVal = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl,
4932 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N: TrueVal);
4933
4934 SDValue TrueLow = TrueVal.getValue(R: 0);
4935 SDValue TrueHigh = TrueVal.getValue(R: 1);
4936 SDValue FalseLow = FalseVal.getValue(R: 0);
4937 SDValue FalseHigh = FalseVal.getValue(R: 1);
4938
4939 SDValue Low = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT: MVT::i32, N1: FalseLow, N2: TrueLow,
4940 N3: ARMcc, N4: Flags);
4941 SDValue High = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT: MVT::i32, N1: FalseHigh, N2: TrueHigh,
4942 N3: ARMcc, N4: Flags);
4943
4944 return DAG.getNode(Opcode: ARMISD::VMOVDRR, DL: dl, VT: MVT::f64, N1: Low, N2: High);
4945 }
4946 return DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: FalseVal, N2: TrueVal, N3: ARMcc, N4: Flags);
4947}
4948
4949static bool isGTorGE(ISD::CondCode CC) {
4950 return CC == ISD::SETGT || CC == ISD::SETGE;
4951}
4952
4953static bool isLTorLE(ISD::CondCode CC) {
4954 return CC == ISD::SETLT || CC == ISD::SETLE;
4955}
4956
4957// See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4958// All of these conditions (and their <= and >= counterparts) will do:
4959// x < k ? k : x
4960// x > k ? x : k
4961// k < x ? x : k
4962// k > x ? k : x
4963static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4964 const SDValue TrueVal, const SDValue FalseVal,
4965 const ISD::CondCode CC, const SDValue K) {
4966 return (isGTorGE(CC) &&
4967 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4968 (isLTorLE(CC) &&
4969 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4970}
4971
4972// Check if two chained conditionals could be converted into SSAT or USAT.
4973//
4974// SSAT can replace a set of two conditional selectors that bound a number to an
4975// interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4976//
4977// x < -k ? -k : (x > k ? k : x)
4978// x < -k ? -k : (x < k ? x : k)
4979// x > -k ? (x > k ? k : x) : -k
4980// x < k ? (x < -k ? -k : x) : k
4981// etc.
4982//
4983// LLVM canonicalizes these to either a min(max()) or a max(min())
4984// pattern. This function tries to match one of these and will return a SSAT
4985// node if successful.
4986//
4987// USAT works similarly to SSAT but bounds on the interval [0, k] where k + 1
4988// is a power of 2.
4989static SDValue LowerSaturatingConditional(SDValue Op, SelectionDAG &DAG) {
4990 EVT VT = Op.getValueType();
4991 SDValue V1 = Op.getOperand(i: 0);
4992 SDValue K1 = Op.getOperand(i: 1);
4993 SDValue TrueVal1 = Op.getOperand(i: 2);
4994 SDValue FalseVal1 = Op.getOperand(i: 3);
4995 ISD::CondCode CC1 = cast<CondCodeSDNode>(Val: Op.getOperand(i: 4))->get();
4996
4997 const SDValue Op2 = isa<ConstantSDNode>(Val: TrueVal1) ? FalseVal1 : TrueVal1;
4998 if (Op2.getOpcode() != ISD::SELECT_CC)
4999 return SDValue();
5000
5001 SDValue V2 = Op2.getOperand(i: 0);
5002 SDValue K2 = Op2.getOperand(i: 1);
5003 SDValue TrueVal2 = Op2.getOperand(i: 2);
5004 SDValue FalseVal2 = Op2.getOperand(i: 3);
5005 ISD::CondCode CC2 = cast<CondCodeSDNode>(Val: Op2.getOperand(i: 4))->get();
5006
5007 SDValue V1Tmp = V1;
5008 SDValue V2Tmp = V2;
5009
5010 // Check that the registers and the constants match a max(min()) or min(max())
5011 // pattern
5012 if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 ||
5013 K2 != FalseVal2 ||
5014 !((isGTorGE(CC: CC1) && isLTorLE(CC: CC2)) || (isLTorLE(CC: CC1) && isGTorGE(CC: CC2))))
5015 return SDValue();
5016
5017 // Check that the constant in the lower-bound check is
5018 // the opposite of the constant in the upper-bound check
5019 // in 1's complement.
5020 if (!isa<ConstantSDNode>(Val: K1) || !isa<ConstantSDNode>(Val: K2))
5021 return SDValue();
5022
5023 int64_t Val1 = cast<ConstantSDNode>(Val&: K1)->getSExtValue();
5024 int64_t Val2 = cast<ConstantSDNode>(Val&: K2)->getSExtValue();
5025 int64_t PosVal = std::max(a: Val1, b: Val2);
5026 int64_t NegVal = std::min(a: Val1, b: Val2);
5027
5028 if (!((Val1 > Val2 && isLTorLE(CC: CC1)) || (Val1 < Val2 && isLTorLE(CC: CC2))) ||
5029 !isPowerOf2_64(Value: PosVal + 1))
5030 return SDValue();
5031
5032 // Handle the difference between USAT (unsigned) and SSAT (signed)
5033 // saturation
5034 // At this point, PosVal is guaranteed to be positive
5035 uint64_t K = PosVal;
5036 SDLoc dl(Op);
5037 if (Val1 == ~Val2)
5038 return DAG.getNode(Opcode: ARMISD::SSAT, DL: dl, VT, N1: V2Tmp,
5039 N2: DAG.getConstant(Val: llvm::countr_one(Value: K), DL: dl, VT));
5040 if (NegVal == 0)
5041 return DAG.getNode(Opcode: ARMISD::USAT, DL: dl, VT, N1: V2Tmp,
5042 N2: DAG.getConstant(Val: llvm::countr_one(Value: K), DL: dl, VT));
5043
5044 return SDValue();
5045}
5046
5047// Check if a condition of the type x < k ? k : x can be converted into a
5048// bit operation instead of conditional moves.
5049// Currently this is allowed given:
5050// - The conditions and values match up
5051// - k is 0 or -1 (all ones)
5052// This function will not check the last condition, thats up to the caller
5053// It returns true if the transformation can be made, and in such case
5054// returns x in V, and k in SatK.
5055static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
5056 SDValue &SatK)
5057{
5058 SDValue LHS = Op.getOperand(i: 0);
5059 SDValue RHS = Op.getOperand(i: 1);
5060 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 4))->get();
5061 SDValue TrueVal = Op.getOperand(i: 2);
5062 SDValue FalseVal = Op.getOperand(i: 3);
5063
5064 SDValue *K = isa<ConstantSDNode>(Val: LHS) ? &LHS : isa<ConstantSDNode>(Val: RHS)
5065 ? &RHS
5066 : nullptr;
5067
5068 // No constant operation in comparison, early out
5069 if (!K)
5070 return false;
5071
5072 SDValue KTmp = isa<ConstantSDNode>(Val: TrueVal) ? TrueVal : FalseVal;
5073 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5074 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5075
5076 // If the constant on left and right side, or variable on left and right,
5077 // does not match, early out
5078 if (*K != KTmp || V != VTmp)
5079 return false;
5080
5081 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, K: *K)) {
5082 SatK = *K;
5083 return true;
5084 }
5085
5086 return false;
5087}
5088
5089bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5090 if (VT == MVT::f32)
5091 return !Subtarget->hasVFP2Base();
5092 if (VT == MVT::f64)
5093 return !Subtarget->hasFP64();
5094 if (VT == MVT::f16)
5095 return !Subtarget->hasFullFP16();
5096 return false;
5097}
5098
5099static SDValue matchCSET(unsigned &Opcode, bool &InvertCond, SDValue TrueVal,
5100 SDValue FalseVal, const ARMSubtarget *Subtarget) {
5101 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(Val&: FalseVal);
5102 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(Val&: TrueVal);
5103 if (!CFVal || !CTVal || !Subtarget->hasV8_1MMainlineOps())
5104 return SDValue();
5105
5106 unsigned TVal = CTVal->getZExtValue();
5107 unsigned FVal = CFVal->getZExtValue();
5108
5109 Opcode = 0;
5110 InvertCond = false;
5111 if (TVal == ~FVal) {
5112 Opcode = ARMISD::CSINV;
5113 } else if (TVal == ~FVal + 1) {
5114 Opcode = ARMISD::CSNEG;
5115 } else if (TVal + 1 == FVal) {
5116 Opcode = ARMISD::CSINC;
5117 } else if (TVal == FVal + 1) {
5118 Opcode = ARMISD::CSINC;
5119 std::swap(a&: TrueVal, b&: FalseVal);
5120 std::swap(a&: TVal, b&: FVal);
5121 InvertCond = !InvertCond;
5122 } else {
5123 return SDValue();
5124 }
5125
5126 // If one of the constants is cheaper than another, materialise the
5127 // cheaper one and let the csel generate the other.
5128 if (Opcode != ARMISD::CSINC &&
5129 HasLowerConstantMaterializationCost(Val1: FVal, Val2: TVal, Subtarget)) {
5130 std::swap(a&: TrueVal, b&: FalseVal);
5131 std::swap(a&: TVal, b&: FVal);
5132 InvertCond = !InvertCond;
5133 }
5134
5135 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5136 // to get there. CSINC not is invertable like the other two (~(~a) == a,
5137 // -(-a) == a, but (a+1)+1 != a).
5138 if (FVal == 0 && Opcode != ARMISD::CSINC) {
5139 std::swap(a&: TrueVal, b&: FalseVal);
5140 std::swap(a&: TVal, b&: FVal);
5141 InvertCond = !InvertCond;
5142 }
5143
5144 return TrueVal;
5145}
5146
5147SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5148 EVT VT = Op.getValueType();
5149 SDLoc dl(Op);
5150
5151 // Try to convert two saturating conditional selects into a single SSAT
5152 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2())
5153 if (SDValue SatValue = LowerSaturatingConditional(Op, DAG))
5154 return SatValue;
5155
5156 // Try to convert expressions of the form x < k ? k : x (and similar forms)
5157 // into more efficient bit operations, which is possible when k is 0 or -1
5158 // On ARM and Thumb-2 which have flexible operand 2 this will result in
5159 // single instructions. On Thumb the shift and the bit operation will be two
5160 // instructions.
5161 // Only allow this transformation on full-width (32-bit) operations
5162 SDValue LowerSatConstant;
5163 SDValue SatValue;
5164 if (VT == MVT::i32 &&
5165 isLowerSaturatingConditional(Op, V&: SatValue, SatK&: LowerSatConstant)) {
5166 SDValue ShiftV = DAG.getNode(Opcode: ISD::SRA, DL: dl, VT, N1: SatValue,
5167 N2: DAG.getConstant(Val: 31, DL: dl, VT));
5168 if (isNullConstant(V: LowerSatConstant)) {
5169 SDValue NotShiftV = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT, N1: ShiftV,
5170 N2: DAG.getAllOnesConstant(DL: dl, VT));
5171 return DAG.getNode(Opcode: ISD::AND, DL: dl, VT, N1: SatValue, N2: NotShiftV);
5172 } else if (isAllOnesConstant(V: LowerSatConstant))
5173 return DAG.getNode(Opcode: ISD::OR, DL: dl, VT, N1: SatValue, N2: ShiftV);
5174 }
5175
5176 SDValue LHS = Op.getOperand(i: 0);
5177 SDValue RHS = Op.getOperand(i: 1);
5178 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 4))->get();
5179 SDValue TrueVal = Op.getOperand(i: 2);
5180 SDValue FalseVal = Op.getOperand(i: 3);
5181 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(Val&: FalseVal);
5182 ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Val&: RHS);
5183 if (Op.getValueType().isInteger()) {
5184
5185 // Check for SMAX(lhs, 0) and SMIN(lhs, 0) patterns.
5186 // (SELECT_CC setgt, lhs, 0, lhs, 0) -> (BIC lhs, (SRA lhs, typesize-1))
5187 // (SELECT_CC setlt, lhs, 0, lhs, 0) -> (AND lhs, (SRA lhs, typesize-1))
5188 // Both require less instructions than compare and conditional select.
5189 if ((CC == ISD::SETGT || CC == ISD::SETLT) && LHS == TrueVal && RHSC &&
5190 RHSC->isZero() && CFVal && CFVal->isZero() &&
5191 LHS.getValueType() == RHS.getValueType()) {
5192 EVT VT = LHS.getValueType();
5193 SDValue Shift =
5194 DAG.getNode(Opcode: ISD::SRA, DL: dl, VT, N1: LHS,
5195 N2: DAG.getConstant(Val: VT.getSizeInBits() - 1, DL: dl, VT));
5196
5197 if (CC == ISD::SETGT)
5198 Shift = DAG.getNOT(DL: dl, Val: Shift, VT);
5199
5200 return DAG.getNode(Opcode: ISD::AND, DL: dl, VT, N1: LHS, N2: Shift);
5201 }
5202
5203 // (SELECT_CC setlt, x, 0, 1, 0) -> SRL(x, bw-1)
5204 if (CC == ISD::SETLT && isNullConstant(V: RHS) && isOneConstant(V: TrueVal) &&
5205 isNullConstant(V: FalseVal) && LHS.getValueType() == VT)
5206 return DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: LHS,
5207 N2: DAG.getConstant(Val: VT.getSizeInBits() - 1, DL: dl, VT));
5208 }
5209
5210 if (LHS.getValueType() == MVT::i32) {
5211 unsigned Opcode;
5212 bool InvertCond;
5213 if (SDValue Op =
5214 matchCSET(Opcode, InvertCond, TrueVal, FalseVal, Subtarget)) {
5215 if (InvertCond)
5216 CC = ISD::getSetCCInverse(Operation: CC, Type: LHS.getValueType());
5217
5218 SDValue ARMcc;
5219 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5220 EVT VT = Op.getValueType();
5221 return DAG.getNode(Opcode, DL: dl, VT, N1: Op, N2: Op, N3: ARMcc, N4: Cmp);
5222 }
5223 }
5224
5225 if (isUnsupportedFloatingType(VT: LHS.getValueType())) {
5226 softenSetCCOperands(DAG, VT: LHS.getValueType(), NewLHS&: LHS, NewRHS&: RHS, CCCode&: CC, DL: dl, OldLHS: LHS, OldRHS: RHS);
5227
5228 // If softenSetCCOperands only returned one value, we should compare it to
5229 // zero.
5230 if (!RHS.getNode()) {
5231 RHS = DAG.getConstant(Val: 0, DL: dl, VT: LHS.getValueType());
5232 CC = ISD::SETNE;
5233 }
5234 }
5235
5236 if (LHS.getValueType() == MVT::i32) {
5237 // Try to generate VSEL on ARMv8.
5238 // The VSEL instruction can't use all the usual ARM condition
5239 // codes: it only has two bits to select the condition code, so it's
5240 // constrained to use only GE, GT, VS and EQ.
5241 //
5242 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5243 // swap the operands of the previous compare instruction (effectively
5244 // inverting the compare condition, swapping 'less' and 'greater') and
5245 // sometimes need to swap the operands to the VSEL (which inverts the
5246 // condition in the sense of firing whenever the previous condition didn't)
5247 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5248 TrueVal.getValueType() == MVT::f32 ||
5249 TrueVal.getValueType() == MVT::f64)) {
5250 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5251 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5252 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5253 CC = ISD::getSetCCInverse(Operation: CC, Type: LHS.getValueType());
5254 std::swap(a&: TrueVal, b&: FalseVal);
5255 }
5256 }
5257
5258 SDValue ARMcc;
5259 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5260 // Choose GE over PL, which vsel does now support
5261 if (ARMcc->getAsZExtVal() == ARMCC::PL)
5262 ARMcc = DAG.getConstant(Val: ARMCC::GE, DL: dl, VT: MVT::i32);
5263 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Flags: Cmp, DAG);
5264 }
5265
5266 ARMCC::CondCodes CondCode, CondCode2;
5267 FPCCToARMCC(CC, CondCode, CondCode2);
5268
5269 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5270 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5271 // must use VSEL (limited condition codes), due to not having conditional f16
5272 // moves.
5273 if (Subtarget->hasFPARMv8Base() &&
5274 !(isFloatingPointZero(Op: RHS) && TrueVal.getValueType() != MVT::f16) &&
5275 (TrueVal.getValueType() == MVT::f16 ||
5276 TrueVal.getValueType() == MVT::f32 ||
5277 TrueVal.getValueType() == MVT::f64)) {
5278 bool swpCmpOps = false;
5279 bool swpVselOps = false;
5280 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5281
5282 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5283 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5284 if (swpCmpOps)
5285 std::swap(a&: LHS, b&: RHS);
5286 if (swpVselOps)
5287 std::swap(a&: TrueVal, b&: FalseVal);
5288 }
5289 }
5290
5291 SDValue ARMcc = DAG.getConstant(Val: CondCode, DL: dl, VT: MVT::i32);
5292 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5293 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Flags: Cmp, DAG);
5294 if (CondCode2 != ARMCC::AL) {
5295 SDValue ARMcc2 = DAG.getConstant(Val: CondCode2, DL: dl, VT: MVT::i32);
5296 Result = getCMOV(dl, VT, FalseVal: Result, TrueVal, ARMcc: ARMcc2, Flags: Cmp, DAG);
5297 }
5298 return Result;
5299}
5300
5301/// canChangeToInt - Given the fp compare operand, return true if it is suitable
5302/// to morph to an integer compare sequence.
5303static bool canChangeToInt(SDValue Op, bool &SeenZero,
5304 const ARMSubtarget *Subtarget) {
5305 SDNode *N = Op.getNode();
5306 if (!N->hasOneUse())
5307 // Otherwise it requires moving the value from fp to integer registers.
5308 return false;
5309 if (!N->getNumValues())
5310 return false;
5311 EVT VT = Op.getValueType();
5312 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5313 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5314 // vmrs are very slow, e.g. cortex-a8.
5315 return false;
5316
5317 if (isFloatingPointZero(Op)) {
5318 SeenZero = true;
5319 return true;
5320 }
5321 return ISD::isNormalLoad(N);
5322}
5323
5324static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5325 if (isFloatingPointZero(Op))
5326 return DAG.getConstant(Val: 0, DL: SDLoc(Op), VT: MVT::i32);
5327
5328 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val&: Op))
5329 return DAG.getLoad(VT: MVT::i32, dl: SDLoc(Op), Chain: Ld->getChain(), Ptr: Ld->getBasePtr(),
5330 PtrInfo: Ld->getPointerInfo(), Alignment: Ld->getAlign(),
5331 MMOFlags: Ld->getMemOperand()->getFlags());
5332
5333 llvm_unreachable("Unknown VFP cmp argument!");
5334}
5335
5336static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5337 SDValue &RetVal1, SDValue &RetVal2) {
5338 SDLoc dl(Op);
5339
5340 if (isFloatingPointZero(Op)) {
5341 RetVal1 = DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32);
5342 RetVal2 = DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32);
5343 return;
5344 }
5345
5346 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val&: Op)) {
5347 SDValue Ptr = Ld->getBasePtr();
5348 RetVal1 =
5349 DAG.getLoad(VT: MVT::i32, dl, Chain: Ld->getChain(), Ptr, PtrInfo: Ld->getPointerInfo(),
5350 Alignment: Ld->getAlign(), MMOFlags: Ld->getMemOperand()->getFlags());
5351
5352 EVT PtrType = Ptr.getValueType();
5353 SDValue NewPtr = DAG.getNode(Opcode: ISD::ADD, DL: dl,
5354 VT: PtrType, N1: Ptr, N2: DAG.getConstant(Val: 4, DL: dl, VT: PtrType));
5355 RetVal2 = DAG.getLoad(VT: MVT::i32, dl, Chain: Ld->getChain(), Ptr: NewPtr,
5356 PtrInfo: Ld->getPointerInfo().getWithOffset(O: 4),
5357 Alignment: commonAlignment(A: Ld->getAlign(), Offset: 4),
5358 MMOFlags: Ld->getMemOperand()->getFlags());
5359 return;
5360 }
5361
5362 llvm_unreachable("Unknown VFP cmp argument!");
5363}
5364
5365/// OptimizeVFPBrcond - With nnan and without daz, it's legal to optimize some
5366/// f32 and even f64 comparisons to integer ones.
5367SDValue
5368ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5369 SDValue Chain = Op.getOperand(i: 0);
5370 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 1))->get();
5371 SDValue LHS = Op.getOperand(i: 2);
5372 SDValue RHS = Op.getOperand(i: 3);
5373 SDValue Dest = Op.getOperand(i: 4);
5374 SDLoc dl(Op);
5375
5376 bool LHSSeenZero = false;
5377 bool LHSOk = canChangeToInt(Op: LHS, SeenZero&: LHSSeenZero, Subtarget);
5378 bool RHSSeenZero = false;
5379 bool RHSOk = canChangeToInt(Op: RHS, SeenZero&: RHSSeenZero, Subtarget);
5380 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5381 // If unsafe fp math optimization is enabled and there are no other uses of
5382 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5383 // to an integer comparison.
5384 if (CC == ISD::SETOEQ)
5385 CC = ISD::SETEQ;
5386 else if (CC == ISD::SETUNE)
5387 CC = ISD::SETNE;
5388
5389 SDValue Mask = DAG.getConstant(Val: 0x7fffffff, DL: dl, VT: MVT::i32);
5390 SDValue ARMcc;
5391 if (LHS.getValueType() == MVT::f32) {
5392 LHS = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32,
5393 N1: bitcastf32Toi32(Op: LHS, DAG), N2: Mask);
5394 RHS = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32,
5395 N1: bitcastf32Toi32(Op: RHS, DAG), N2: Mask);
5396 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5397 return DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, N1: Chain, N2: Dest, N3: ARMcc,
5398 N4: Cmp);
5399 }
5400
5401 SDValue LHS1, LHS2;
5402 SDValue RHS1, RHS2;
5403 expandf64Toi32(Op: LHS, DAG, RetVal1&: LHS1, RetVal2&: LHS2);
5404 expandf64Toi32(Op: RHS, DAG, RetVal1&: RHS1, RetVal2&: RHS2);
5405 LHS2 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: LHS2, N2: Mask);
5406 RHS2 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: RHS2, N2: Mask);
5407 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5408 ARMcc = DAG.getConstant(Val: CondCode, DL: dl, VT: MVT::i32);
5409 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5410 return DAG.getNode(Opcode: ARMISD::BCC_i64, DL: dl, VT: MVT::Other, Ops);
5411 }
5412
5413 return SDValue();
5414}
5415
5416// Generate CMP + CMOV for integer abs.
5417SDValue ARMTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
5418 SDLoc DL(Op);
5419
5420 SDValue Neg = DAG.getNegative(Val: Op.getOperand(i: 0), DL, VT: MVT::i32);
5421
5422 // Generate CMP & CMOV.
5423 SDValue Cmp = DAG.getNode(Opcode: ARMISD::CMP, DL, VT: FlagsVT, N1: Op.getOperand(i: 0),
5424 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
5425 return DAG.getNode(Opcode: ARMISD::CMOV, DL, VT: MVT::i32, N1: Op.getOperand(i: 0), N2: Neg,
5426 N3: DAG.getConstant(Val: ARMCC::MI, DL, VT: MVT::i32), N4: Cmp);
5427}
5428
5429static SDValue getInvertedARMCondCode(SDValue ARMcc, SelectionDAG &DAG) {
5430 ARMCC::CondCodes CondCode =
5431 (ARMCC::CondCodes)cast<ConstantSDNode>(Val&: ARMcc)->getZExtValue();
5432 CondCode = ARMCC::getOppositeCondition(CC: CondCode);
5433 return DAG.getConstant(Val: CondCode, DL: SDLoc(ARMcc), VT: MVT::i32);
5434}
5435
5436SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5437 SDValue Chain = Op.getOperand(i: 0);
5438 SDValue Cond = Op.getOperand(i: 1);
5439 SDValue Dest = Op.getOperand(i: 2);
5440 SDLoc dl(Op);
5441
5442 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5443 // instruction.
5444 unsigned Opc = Cond.getOpcode();
5445 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5446 !Subtarget->isThumb1Only();
5447 if (Cond.getResNo() == 1 &&
5448 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5449 Opc == ISD::USUBO || OptimizeMul)) {
5450 // Only lower legal XALUO ops.
5451 if (!isTypeLegal(VT: Cond->getValueType(ResNo: 0)))
5452 return SDValue();
5453
5454 // The actual operation with overflow check.
5455 SDValue Value, OverflowCmp;
5456 SDValue ARMcc;
5457 std::tie(args&: Value, args&: OverflowCmp) = getARMXALUOOp(Op: Cond, DAG, ARMcc);
5458
5459 // Reverse the condition code.
5460 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5461
5462 return DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, N1: Chain, N2: Dest, N3: ARMcc,
5463 N4: OverflowCmp);
5464 }
5465
5466 return SDValue();
5467}
5468
5469SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5470 SDValue Chain = Op.getOperand(i: 0);
5471 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 1))->get();
5472 SDValue LHS = Op.getOperand(i: 2);
5473 SDValue RHS = Op.getOperand(i: 3);
5474 SDValue Dest = Op.getOperand(i: 4);
5475 SDLoc dl(Op);
5476
5477 if (isUnsupportedFloatingType(VT: LHS.getValueType())) {
5478 softenSetCCOperands(DAG, VT: LHS.getValueType(), NewLHS&: LHS, NewRHS&: RHS, CCCode&: CC, DL: dl, OldLHS: LHS, OldRHS: RHS);
5479
5480 // If softenSetCCOperands only returned one value, we should compare it to
5481 // zero.
5482 if (!RHS.getNode()) {
5483 RHS = DAG.getConstant(Val: 0, DL: dl, VT: LHS.getValueType());
5484 CC = ISD::SETNE;
5485 }
5486 }
5487
5488 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5489 // instruction.
5490 unsigned Opc = LHS.getOpcode();
5491 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5492 !Subtarget->isThumb1Only();
5493 if (LHS.getResNo() == 1 && (isOneConstant(V: RHS) || isNullConstant(V: RHS)) &&
5494 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5495 Opc == ISD::USUBO || OptimizeMul) &&
5496 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5497 // Only lower legal XALUO ops.
5498 if (!isTypeLegal(VT: LHS->getValueType(ResNo: 0)))
5499 return SDValue();
5500
5501 // The actual operation with overflow check.
5502 SDValue Value, OverflowCmp;
5503 SDValue ARMcc;
5504 std::tie(args&: Value, args&: OverflowCmp) = getARMXALUOOp(Op: LHS.getValue(R: 0), DAG, ARMcc);
5505
5506 if ((CC == ISD::SETNE) != isOneConstant(V: RHS)) {
5507 // Reverse the condition code.
5508 ARMcc = getInvertedARMCondCode(ARMcc, DAG);
5509 }
5510
5511 return DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, N1: Chain, N2: Dest, N3: ARMcc,
5512 N4: OverflowCmp);
5513 }
5514
5515 if (LHS.getValueType() == MVT::i32) {
5516 SDValue ARMcc;
5517 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5518 return DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, N1: Chain, N2: Dest, N3: ARMcc, N4: Cmp);
5519 }
5520
5521 SDNodeFlags Flags = Op->getFlags();
5522 if (Flags.hasNoNaNs() &&
5523 DAG.getDenormalMode(VT: MVT::f32) == DenormalMode::getIEEE() &&
5524 DAG.getDenormalMode(VT: MVT::f64) == DenormalMode::getIEEE() &&
5525 (CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETNE ||
5526 CC == ISD::SETUNE)) {
5527 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5528 return Result;
5529 }
5530
5531 ARMCC::CondCodes CondCode, CondCode2;
5532 FPCCToARMCC(CC, CondCode, CondCode2);
5533
5534 SDValue ARMcc = DAG.getConstant(Val: CondCode, DL: dl, VT: MVT::i32);
5535 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5536 SDValue Ops[] = {Chain, Dest, ARMcc, Cmp};
5537 SDValue Res = DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, Ops);
5538 if (CondCode2 != ARMCC::AL) {
5539 ARMcc = DAG.getConstant(Val: CondCode2, DL: dl, VT: MVT::i32);
5540 SDValue Ops[] = {Res, Dest, ARMcc, Cmp};
5541 Res = DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, Ops);
5542 }
5543 return Res;
5544}
5545
5546SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5547 SDValue Chain = Op.getOperand(i: 0);
5548 SDValue Table = Op.getOperand(i: 1);
5549 SDValue Index = Op.getOperand(i: 2);
5550 SDLoc dl(Op);
5551
5552 EVT PTy = getPointerTy(DL: DAG.getDataLayout());
5553 JumpTableSDNode *JT = cast<JumpTableSDNode>(Val&: Table);
5554 SDValue JTI = DAG.getTargetJumpTable(JTI: JT->getIndex(), VT: PTy);
5555 Table = DAG.getNode(Opcode: ARMISD::WrapperJT, DL: dl, VT: MVT::i32, Operand: JTI);
5556 Index = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: PTy, N1: Index, N2: DAG.getConstant(Val: 4, DL: dl, VT: PTy));
5557 SDValue Addr = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PTy, N1: Table, N2: Index);
5558 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5559 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5560 // which does another jump to the destination. This also makes it easier
5561 // to translate it to TBB / TBH later (Thumb2 only).
5562 // FIXME: This might not work if the function is extremely large.
5563 return DAG.getNode(Opcode: ARMISD::BR2_JT, DL: dl, VT: MVT::Other, N1: Chain,
5564 N2: Addr, N3: Op.getOperand(i: 2), N4: JTI);
5565 }
5566 if (isPositionIndependent() || Subtarget->isROPI()) {
5567 Addr =
5568 DAG.getLoad(VT: (EVT)MVT::i32, dl, Chain, Ptr: Addr,
5569 PtrInfo: MachinePointerInfo::getJumpTable(MF&: DAG.getMachineFunction()));
5570 Chain = Addr.getValue(R: 1);
5571 Addr = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PTy, N1: Table, N2: Addr);
5572 return DAG.getNode(Opcode: ARMISD::BR_JT, DL: dl, VT: MVT::Other, N1: Chain, N2: Addr, N3: JTI);
5573 } else {
5574 Addr =
5575 DAG.getLoad(VT: PTy, dl, Chain, Ptr: Addr,
5576 PtrInfo: MachinePointerInfo::getJumpTable(MF&: DAG.getMachineFunction()));
5577 Chain = Addr.getValue(R: 1);
5578 return DAG.getNode(Opcode: ARMISD::BR_JT, DL: dl, VT: MVT::Other, N1: Chain, N2: Addr, N3: JTI);
5579 }
5580}
5581
5582static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5583 EVT VT = Op.getValueType();
5584 SDLoc dl(Op);
5585
5586 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5587 if (Op.getOperand(i: 0).getValueType().getVectorElementType() == MVT::f32)
5588 return Op;
5589 return DAG.UnrollVectorOp(N: Op.getNode());
5590 }
5591
5592 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5593
5594 EVT NewTy;
5595 const EVT OpTy = Op.getOperand(i: 0).getValueType();
5596 if (OpTy == MVT::v4f32)
5597 NewTy = MVT::v4i32;
5598 else if (OpTy == MVT::v4f16 && HasFullFP16)
5599 NewTy = MVT::v4i16;
5600 else if (OpTy == MVT::v8f16 && HasFullFP16)
5601 NewTy = MVT::v8i16;
5602 else
5603 llvm_unreachable("Invalid type for custom lowering!");
5604
5605 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5606 return DAG.UnrollVectorOp(N: Op.getNode());
5607
5608 Op = DAG.getNode(Opcode: Op.getOpcode(), DL: dl, VT: NewTy, Operand: Op.getOperand(i: 0));
5609 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT, Operand: Op);
5610}
5611
5612SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5613 EVT VT = Op.getValueType();
5614 if (VT.isVector())
5615 return LowerVectorFP_TO_INT(Op, DAG);
5616
5617 bool IsStrict = Op->isStrictFPOpcode();
5618 SDValue SrcVal = Op.getOperand(i: IsStrict ? 1 : 0);
5619
5620 if (isUnsupportedFloatingType(VT: SrcVal.getValueType())) {
5621 RTLIB::Libcall LC;
5622 if (Op.getOpcode() == ISD::FP_TO_SINT ||
5623 Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5624 LC = RTLIB::getFPTOSINT(OpVT: SrcVal.getValueType(),
5625 RetVT: Op.getValueType());
5626 else
5627 LC = RTLIB::getFPTOUINT(OpVT: SrcVal.getValueType(),
5628 RetVT: Op.getValueType());
5629 SDLoc Loc(Op);
5630 MakeLibCallOptions CallOptions;
5631 SDValue Chain = IsStrict ? Op.getOperand(i: 0) : SDValue();
5632 SDValue Result;
5633 std::tie(args&: Result, args&: Chain) = makeLibCall(DAG, LC, RetVT: Op.getValueType(), Ops: SrcVal,
5634 CallOptions, dl: Loc, Chain);
5635 return IsStrict ? DAG.getMergeValues(Ops: {Result, Chain}, dl: Loc) : Result;
5636 }
5637
5638 // FIXME: Remove this when we have strict fp instruction selection patterns
5639 if (IsStrict) {
5640 SDLoc Loc(Op);
5641 SDValue Result =
5642 DAG.getNode(Opcode: Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5643 : ISD::FP_TO_UINT,
5644 DL: Loc, VT: Op.getValueType(), Operand: SrcVal);
5645 return DAG.getMergeValues(Ops: {Result, Op.getOperand(i: 0)}, dl: Loc);
5646 }
5647
5648 return Op;
5649}
5650
5651static SDValue LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
5652 const ARMSubtarget *Subtarget) {
5653 EVT VT = Op.getValueType();
5654 EVT ToVT = cast<VTSDNode>(Val: Op.getOperand(i: 1))->getVT();
5655 EVT FromVT = Op.getOperand(i: 0).getValueType();
5656
5657 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f32)
5658 return Op;
5659 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f64 &&
5660 Subtarget->hasFP64())
5661 return Op;
5662 if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f16 &&
5663 Subtarget->hasFullFP16())
5664 return Op;
5665 if (VT == MVT::v4i32 && ToVT == MVT::i32 && FromVT == MVT::v4f32 &&
5666 Subtarget->hasMVEFloatOps())
5667 return Op;
5668 if (VT == MVT::v8i16 && ToVT == MVT::i16 && FromVT == MVT::v8f16 &&
5669 Subtarget->hasMVEFloatOps())
5670 return Op;
5671
5672 if (FromVT != MVT::v4f32 && FromVT != MVT::v8f16)
5673 return SDValue();
5674
5675 SDLoc DL(Op);
5676 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
5677 unsigned BW = ToVT.getScalarSizeInBits() - IsSigned;
5678 SDValue CVT = DAG.getNode(Opcode: Op.getOpcode(), DL, VT, N1: Op.getOperand(i: 0),
5679 N2: DAG.getValueType(VT.getScalarType()));
5680 SDValue Max = DAG.getNode(Opcode: IsSigned ? ISD::SMIN : ISD::UMIN, DL, VT, N1: CVT,
5681 N2: DAG.getConstant(Val: (1 << BW) - 1, DL, VT));
5682 if (IsSigned)
5683 Max = DAG.getNode(Opcode: ISD::SMAX, DL, VT, N1: Max,
5684 N2: DAG.getSignedConstant(Val: -(1 << BW), DL, VT));
5685 return Max;
5686}
5687
5688static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5689 EVT VT = Op.getValueType();
5690 SDLoc dl(Op);
5691
5692 if (Op.getOperand(i: 0).getValueType().getVectorElementType() == MVT::i32) {
5693 if (VT.getVectorElementType() == MVT::f32)
5694 return Op;
5695 return DAG.UnrollVectorOp(N: Op.getNode());
5696 }
5697
5698 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5699 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5700 "Invalid type for custom lowering!");
5701
5702 const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5703
5704 EVT DestVecType;
5705 if (VT == MVT::v4f32)
5706 DestVecType = MVT::v4i32;
5707 else if (VT == MVT::v4f16 && HasFullFP16)
5708 DestVecType = MVT::v4i16;
5709 else if (VT == MVT::v8f16 && HasFullFP16)
5710 DestVecType = MVT::v8i16;
5711 else
5712 return DAG.UnrollVectorOp(N: Op.getNode());
5713
5714 unsigned CastOpc;
5715 unsigned Opc;
5716 switch (Op.getOpcode()) {
5717 default: llvm_unreachable("Invalid opcode!");
5718 case ISD::SINT_TO_FP:
5719 CastOpc = ISD::SIGN_EXTEND;
5720 Opc = ISD::SINT_TO_FP;
5721 break;
5722 case ISD::UINT_TO_FP:
5723 CastOpc = ISD::ZERO_EXTEND;
5724 Opc = ISD::UINT_TO_FP;
5725 break;
5726 }
5727
5728 Op = DAG.getNode(Opcode: CastOpc, DL: dl, VT: DestVecType, Operand: Op.getOperand(i: 0));
5729 return DAG.getNode(Opcode: Opc, DL: dl, VT, Operand: Op);
5730}
5731
5732SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5733 EVT VT = Op.getValueType();
5734 if (VT.isVector())
5735 return LowerVectorINT_TO_FP(Op, DAG);
5736 if (isUnsupportedFloatingType(VT)) {
5737 RTLIB::Libcall LC;
5738 if (Op.getOpcode() == ISD::SINT_TO_FP)
5739 LC = RTLIB::getSINTTOFP(OpVT: Op.getOperand(i: 0).getValueType(),
5740 RetVT: Op.getValueType());
5741 else
5742 LC = RTLIB::getUINTTOFP(OpVT: Op.getOperand(i: 0).getValueType(),
5743 RetVT: Op.getValueType());
5744 MakeLibCallOptions CallOptions;
5745 return makeLibCall(DAG, LC, RetVT: Op.getValueType(), Ops: Op.getOperand(i: 0),
5746 CallOptions, dl: SDLoc(Op)).first;
5747 }
5748
5749 return Op;
5750}
5751
5752SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5753 // Implement fcopysign with a fabs and a conditional fneg.
5754 SDValue Tmp0 = Op.getOperand(i: 0);
5755 SDValue Tmp1 = Op.getOperand(i: 1);
5756 SDLoc dl(Op);
5757 EVT VT = Op.getValueType();
5758 EVT SrcVT = Tmp1.getValueType();
5759 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5760 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5761 bool UseNEON = !InGPR && Subtarget->hasNEON();
5762
5763 if (UseNEON) {
5764 // Use VBSL to copy the sign bit.
5765 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode: 0x6, Val: 0x80);
5766 SDValue Mask = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: MVT::v2i32,
5767 Operand: DAG.getTargetConstant(Val: EncodedVal, DL: dl, VT: MVT::i32));
5768 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5769 if (VT == MVT::f64)
5770 Mask = DAG.getNode(Opcode: ARMISD::VSHLIMM, DL: dl, VT: OpVT,
5771 N1: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: OpVT, Operand: Mask),
5772 N2: DAG.getConstant(Val: 32, DL: dl, VT: MVT::i32));
5773 else /*if (VT == MVT::f32)*/
5774 Tmp0 = DAG.getNode(Opcode: ISD::SCALAR_TO_VECTOR, DL: dl, VT: MVT::v2f32, Operand: Tmp0);
5775 if (SrcVT == MVT::f32) {
5776 Tmp1 = DAG.getNode(Opcode: ISD::SCALAR_TO_VECTOR, DL: dl, VT: MVT::v2f32, Operand: Tmp1);
5777 if (VT == MVT::f64)
5778 Tmp1 = DAG.getNode(Opcode: ARMISD::VSHLIMM, DL: dl, VT: OpVT,
5779 N1: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: OpVT, Operand: Tmp1),
5780 N2: DAG.getConstant(Val: 32, DL: dl, VT: MVT::i32));
5781 } else if (VT == MVT::f32)
5782 Tmp1 = DAG.getNode(Opcode: ARMISD::VSHRuIMM, DL: dl, VT: MVT::v1i64,
5783 N1: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v1i64, Operand: Tmp1),
5784 N2: DAG.getConstant(Val: 32, DL: dl, VT: MVT::i32));
5785 Tmp0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: OpVT, Operand: Tmp0);
5786 Tmp1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: OpVT, Operand: Tmp1);
5787
5788 SDValue AllOnes = DAG.getTargetConstant(Val: ARM_AM::createVMOVModImm(OpCmode: 0xe, Val: 0xff),
5789 DL: dl, VT: MVT::i32);
5790 AllOnes = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: MVT::v8i8, Operand: AllOnes);
5791 SDValue MaskNot = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT: OpVT, N1: Mask,
5792 N2: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: OpVT, Operand: AllOnes));
5793
5794 SDValue Res = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: OpVT,
5795 N1: DAG.getNode(Opcode: ISD::AND, DL: dl, VT: OpVT, N1: Tmp1, N2: Mask),
5796 N2: DAG.getNode(Opcode: ISD::AND, DL: dl, VT: OpVT, N1: Tmp0, N2: MaskNot));
5797 if (VT == MVT::f32) {
5798 Res = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v2f32, Operand: Res);
5799 Res = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f32, N1: Res,
5800 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
5801 } else {
5802 Res = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f64, Operand: Res);
5803 }
5804
5805 return Res;
5806 }
5807
5808 // Bitcast operand 1 to i32.
5809 if (SrcVT == MVT::f64)
5810 Tmp1 = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
5811 N: Tmp1).getValue(R: 1);
5812 Tmp1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Tmp1);
5813
5814 // Or in the signbit with integer operations.
5815 SDValue Mask1 = DAG.getConstant(Val: 0x80000000, DL: dl, VT: MVT::i32);
5816 SDValue Mask2 = DAG.getConstant(Val: 0x7fffffff, DL: dl, VT: MVT::i32);
5817 Tmp1 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Tmp1, N2: Mask1);
5818 if (VT == MVT::f32) {
5819 Tmp0 = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32,
5820 N1: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Tmp0), N2: Mask2);
5821 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f32,
5822 Operand: DAG.getNode(Opcode: ISD::OR, DL: dl, VT: MVT::i32, N1: Tmp0, N2: Tmp1));
5823 }
5824
5825 // f64: Or the high part with signbit and then combine two parts.
5826 Tmp0 = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
5827 N: Tmp0);
5828 SDValue Lo = Tmp0.getValue(R: 0);
5829 SDValue Hi = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: Tmp0.getValue(R: 1), N2: Mask2);
5830 Hi = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: MVT::i32, N1: Hi, N2: Tmp1);
5831 return DAG.getNode(Opcode: ARMISD::VMOVDRR, DL: dl, VT: MVT::f64, N1: Lo, N2: Hi);
5832}
5833
5834SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5835 MachineFunction &MF = DAG.getMachineFunction();
5836 MachineFrameInfo &MFI = MF.getFrameInfo();
5837 MFI.setReturnAddressIsTaken(true);
5838
5839 EVT VT = Op.getValueType();
5840 SDLoc dl(Op);
5841 unsigned Depth = Op.getConstantOperandVal(i: 0);
5842 if (Depth) {
5843 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5844 SDValue Offset = DAG.getConstant(Val: 4, DL: dl, VT: MVT::i32);
5845 return DAG.getLoad(VT, dl, Chain: DAG.getEntryNode(),
5846 Ptr: DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: FrameAddr, N2: Offset),
5847 PtrInfo: MachinePointerInfo());
5848 }
5849
5850 // Return LR, which contains the return address. Mark it an implicit live-in.
5851 Register Reg = MF.addLiveIn(PReg: ARM::LR, RC: getRegClassFor(VT: MVT::i32));
5852 return DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl, Reg, VT);
5853}
5854
5855SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5856 const ARMBaseRegisterInfo &ARI =
5857 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5858 MachineFunction &MF = DAG.getMachineFunction();
5859 MachineFrameInfo &MFI = MF.getFrameInfo();
5860 MFI.setFrameAddressIsTaken(true);
5861
5862 EVT VT = Op.getValueType();
5863 SDLoc dl(Op); // FIXME probably not meaningful
5864 unsigned Depth = Op.getConstantOperandVal(i: 0);
5865 Register FrameReg = ARI.getFrameRegister(MF);
5866 SDValue FrameAddr = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl, Reg: FrameReg, VT);
5867 while (Depth--)
5868 FrameAddr = DAG.getLoad(VT, dl, Chain: DAG.getEntryNode(), Ptr: FrameAddr,
5869 PtrInfo: MachinePointerInfo());
5870 return FrameAddr;
5871}
5872
5873// FIXME? Maybe this could be a TableGen attribute on some registers and
5874// this table could be generated automatically from RegInfo.
5875Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
5876 const MachineFunction &MF) const {
5877 return StringSwitch<Register>(RegName)
5878 .Case(S: "sp", Value: ARM::SP)
5879 .Default(Value: Register());
5880}
5881
5882// Result is 64 bit value so split into two 32 bit values and return as a
5883// pair of values.
5884static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5885 SelectionDAG &DAG) {
5886 SDLoc DL(N);
5887
5888 // This function is only supposed to be called for i64 type destination.
5889 assert(N->getValueType(0) == MVT::i64
5890 && "ExpandREAD_REGISTER called for non-i64 type result.");
5891
5892 SDValue Read = DAG.getNode(Opcode: ISD::READ_REGISTER, DL,
5893 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32, VT3: MVT::Other),
5894 N1: N->getOperand(Num: 0),
5895 N2: N->getOperand(Num: 1));
5896
5897 Results.push_back(Elt: DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VT: MVT::i64, N1: Read.getValue(R: 0),
5898 N2: Read.getValue(R: 1)));
5899 Results.push_back(Elt: Read.getValue(R: 2)); // Chain
5900}
5901
5902/// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5903/// When \p DstVT, the destination type of \p BC, is on the vector
5904/// register bank and the source of bitcast, \p Op, operates on the same bank,
5905/// it might be possible to combine them, such that everything stays on the
5906/// vector register bank.
5907/// \p return The node that would replace \p BT, if the combine
5908/// is possible.
5909static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5910 SelectionDAG &DAG) {
5911 SDValue Op = BC->getOperand(Num: 0);
5912 EVT DstVT = BC->getValueType(ResNo: 0);
5913
5914 // The only vector instruction that can produce a scalar (remember,
5915 // since the bitcast was about to be turned into VMOVDRR, the source
5916 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5917 // Moreover, we can do this combine only if there is one use.
5918 // Finally, if the destination type is not a vector, there is not
5919 // much point on forcing everything on the vector bank.
5920 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5921 !Op.hasOneUse())
5922 return SDValue();
5923
5924 // If the index is not constant, we will introduce an additional
5925 // multiply that will stick.
5926 // Give up in that case.
5927 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 1));
5928 if (!Index)
5929 return SDValue();
5930 unsigned DstNumElt = DstVT.getVectorNumElements();
5931
5932 // Compute the new index.
5933 const APInt &APIntIndex = Index->getAPIntValue();
5934 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5935 NewIndex *= APIntIndex;
5936 // Check if the new constant index fits into i32.
5937 if (NewIndex.getBitWidth() > 32)
5938 return SDValue();
5939
5940 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5941 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5942 SDLoc dl(Op);
5943 SDValue ExtractSrc = Op.getOperand(i: 0);
5944 EVT VecVT = EVT::getVectorVT(
5945 Context&: *DAG.getContext(), VT: DstVT.getScalarType(),
5946 NumElements: ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5947 SDValue BitCast = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VecVT, Operand: ExtractSrc);
5948 return DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: DstVT, N1: BitCast,
5949 N2: DAG.getConstant(Val: NewIndex.getZExtValue(), DL: dl, VT: MVT::i32));
5950}
5951
5952/// ExpandBITCAST - If the target supports VFP, this function is called to
5953/// expand a bit convert where either the source or destination type is i64 to
5954/// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5955/// operand type is illegal (e.g., v2f32 for a target that doesn't support
5956/// vectors), since the legalizer won't know what to do with that.
5957SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5958 const ARMSubtarget *Subtarget) const {
5959 SDLoc dl(N);
5960 SDValue Op = N->getOperand(Num: 0);
5961
5962 // This function is only supposed to be called for i16 and i64 types, either
5963 // as the source or destination of the bit convert.
5964 EVT SrcVT = Op.getValueType();
5965 EVT DstVT = N->getValueType(ResNo: 0);
5966
5967 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
5968 (DstVT == MVT::f16 || DstVT == MVT::bf16))
5969 return MoveToHPR(dl: SDLoc(N), DAG, LocVT: MVT::i32, ValVT: DstVT.getSimpleVT(),
5970 Val: DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: SDLoc(N), VT: MVT::i32, Operand: Op));
5971
5972 if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
5973 (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) {
5974 if (Subtarget->hasFullFP16() && !Subtarget->hasBF16())
5975 Op = DAG.getBitcast(VT: MVT::f16, V: Op);
5976 return DAG.getNode(
5977 Opcode: ISD::TRUNCATE, DL: SDLoc(N), VT: DstVT,
5978 Operand: MoveFromHPR(dl: SDLoc(N), DAG, LocVT: MVT::i32, ValVT: SrcVT.getSimpleVT(), Val: Op));
5979 }
5980
5981 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5982 return SDValue();
5983
5984 // Turn i64->f64 into VMOVDRR.
5985 if (SrcVT == MVT::i64 && isTypeLegal(VT: DstVT)) {
5986 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5987 // if we can combine the bitcast with its source.
5988 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(BC: N, DAG))
5989 return Val;
5990 SDValue Lo, Hi;
5991 std::tie(args&: Lo, args&: Hi) = DAG.SplitScalar(N: Op, DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
5992 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: DstVT,
5993 Operand: DAG.getNode(Opcode: ARMISD::VMOVDRR, DL: dl, VT: MVT::f64, N1: Lo, N2: Hi));
5994 }
5995
5996 // Turn f64->i64 into VMOVRRD.
5997 if (DstVT == MVT::i64 && isTypeLegal(VT: SrcVT)) {
5998 SDValue Cvt;
5999 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6000 SrcVT.getVectorNumElements() > 1)
6001 Cvt = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl,
6002 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
6003 N: DAG.getNode(Opcode: ARMISD::VREV64, DL: dl, VT: SrcVT, Operand: Op));
6004 else
6005 Cvt = DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl,
6006 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N: Op);
6007 // Merge the pieces into a single i64 value.
6008 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Cvt, N2: Cvt.getValue(R: 1));
6009 }
6010
6011 return SDValue();
6012}
6013
6014/// getZeroVector - Returns a vector of specified type with all zero elements.
6015/// Zero vectors are used to represent vector negation and in those cases
6016/// will be implemented with the NEON VNEG instruction. However, VNEG does
6017/// not support i64 elements, so sometimes the zero vectors will need to be
6018/// explicitly constructed. Regardless, use a canonical VMOV to create the
6019/// zero vector.
6020static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6021 assert(VT.isVector() && "Expected a vector type");
6022 // The canonical modified immediate encoding of a zero vector is....0!
6023 SDValue EncodedVal = DAG.getTargetConstant(Val: 0, DL: dl, VT: MVT::i32);
6024 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6025 SDValue Vmov = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: VmovVT, Operand: EncodedVal);
6026 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Vmov);
6027}
6028
6029/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6030/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6031SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6032 SelectionDAG &DAG) const {
6033 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6034 EVT VT = Op.getValueType();
6035 unsigned VTBits = VT.getSizeInBits();
6036 SDLoc dl(Op);
6037 SDValue ShOpLo = Op.getOperand(i: 0);
6038 SDValue ShOpHi = Op.getOperand(i: 1);
6039 SDValue ShAmt = Op.getOperand(i: 2);
6040 SDValue ARMcc;
6041 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6042
6043 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6044
6045 SDValue RevShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
6046 N1: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32), N2: ShAmt);
6047 SDValue Tmp1 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: ShOpLo, N2: ShAmt);
6048 SDValue ExtraShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: ShAmt,
6049 N2: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32));
6050 SDValue Tmp2 = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpHi, N2: RevShAmt);
6051 SDValue LoSmallShift = DAG.getNode(Opcode: ISD::OR, DL: dl, VT, N1: Tmp1, N2: Tmp2);
6052 SDValue LoBigShift = DAG.getNode(Opcode: Opc, DL: dl, VT, N1: ShOpHi, N2: ExtraShAmt);
6053 SDValue CmpLo = getARMCmp(LHS: ExtraShAmt, RHS: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32),
6054 CC: ISD::SETGE, ARMcc, DAG, dl);
6055 SDValue Lo =
6056 DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: LoSmallShift, N2: LoBigShift, N3: ARMcc, N4: CmpLo);
6057
6058 SDValue HiSmallShift = DAG.getNode(Opcode: Opc, DL: dl, VT, N1: ShOpHi, N2: ShAmt);
6059 SDValue HiBigShift = Opc == ISD::SRA
6060 ? DAG.getNode(Opcode: Opc, DL: dl, VT, N1: ShOpHi,
6061 N2: DAG.getConstant(Val: VTBits - 1, DL: dl, VT))
6062 : DAG.getConstant(Val: 0, DL: dl, VT);
6063 SDValue CmpHi = getARMCmp(LHS: ExtraShAmt, RHS: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32),
6064 CC: ISD::SETGE, ARMcc, DAG, dl);
6065 SDValue Hi =
6066 DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: HiSmallShift, N2: HiBigShift, N3: ARMcc, N4: CmpHi);
6067
6068 SDValue Ops[2] = { Lo, Hi };
6069 return DAG.getMergeValues(Ops, dl);
6070}
6071
6072/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6073/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6074SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6075 SelectionDAG &DAG) const {
6076 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6077 EVT VT = Op.getValueType();
6078 unsigned VTBits = VT.getSizeInBits();
6079 SDLoc dl(Op);
6080 SDValue ShOpLo = Op.getOperand(i: 0);
6081 SDValue ShOpHi = Op.getOperand(i: 1);
6082 SDValue ShAmt = Op.getOperand(i: 2);
6083 SDValue ARMcc;
6084
6085 assert(Op.getOpcode() == ISD::SHL_PARTS);
6086 SDValue RevShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
6087 N1: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32), N2: ShAmt);
6088 SDValue Tmp1 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: ShOpLo, N2: RevShAmt);
6089 SDValue Tmp2 = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpHi, N2: ShAmt);
6090 SDValue HiSmallShift = DAG.getNode(Opcode: ISD::OR, DL: dl, VT, N1: Tmp1, N2: Tmp2);
6091
6092 SDValue ExtraShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: ShAmt,
6093 N2: DAG.getConstant(Val: VTBits, DL: dl, VT: MVT::i32));
6094 SDValue HiBigShift = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpLo, N2: ExtraShAmt);
6095 SDValue CmpHi = getARMCmp(LHS: ExtraShAmt, RHS: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32),
6096 CC: ISD::SETGE, ARMcc, DAG, dl);
6097 SDValue Hi =
6098 DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: HiSmallShift, N2: HiBigShift, N3: ARMcc, N4: CmpHi);
6099
6100 SDValue CmpLo = getARMCmp(LHS: ExtraShAmt, RHS: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32),
6101 CC: ISD::SETGE, ARMcc, DAG, dl);
6102 SDValue LoSmallShift = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: ShOpLo, N2: ShAmt);
6103 SDValue Lo = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: LoSmallShift,
6104 N2: DAG.getConstant(Val: 0, DL: dl, VT), N3: ARMcc, N4: CmpLo);
6105
6106 SDValue Ops[2] = { Lo, Hi };
6107 return DAG.getMergeValues(Ops, dl);
6108}
6109
6110SDValue ARMTargetLowering::LowerGET_ROUNDING(SDValue Op,
6111 SelectionDAG &DAG) const {
6112 // The rounding mode is in bits 23:22 of the FPSCR.
6113 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6114 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6115 // so that the shift + and get folded into a bitfield extract.
6116 SDLoc dl(Op);
6117 SDValue Chain = Op.getOperand(i: 0);
6118 SDValue Ops[] = {Chain,
6119 DAG.getConstant(Val: Intrinsic::arm_get_fpscr, DL: dl, VT: MVT::i32)};
6120
6121 SDValue FPSCR =
6122 DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL: dl, ResultTys: {MVT::i32, MVT::Other}, Ops);
6123 Chain = FPSCR.getValue(R: 1);
6124 SDValue FltRounds = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: FPSCR,
6125 N2: DAG.getConstant(Val: 1U << 22, DL: dl, VT: MVT::i32));
6126 SDValue RMODE = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32, N1: FltRounds,
6127 N2: DAG.getConstant(Val: 22, DL: dl, VT: MVT::i32));
6128 SDValue And = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i32, N1: RMODE,
6129 N2: DAG.getConstant(Val: 3, DL: dl, VT: MVT::i32));
6130 return DAG.getMergeValues(Ops: {And, Chain}, dl);
6131}
6132
6133SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op,
6134 SelectionDAG &DAG) const {
6135 SDLoc DL(Op);
6136 SDValue Chain = Op->getOperand(Num: 0);
6137 SDValue RMValue = Op->getOperand(Num: 1);
6138
6139 // The rounding mode is in bits 23:22 of the FPSCR.
6140 // The llvm.set.rounding argument value to ARM rounding mode value mapping
6141 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
6142 // ((arg - 1) & 3) << 22).
6143 //
6144 // It is expected that the argument of llvm.set.rounding is within the
6145 // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is
6146 // responsibility of the code generated llvm.set.rounding to ensure this
6147 // condition.
6148
6149 // Calculate new value of FPSCR[23:22].
6150 RMValue = DAG.getNode(Opcode: ISD::SUB, DL, VT: MVT::i32, N1: RMValue,
6151 N2: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
6152 RMValue = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: RMValue,
6153 N2: DAG.getConstant(Val: 0x3, DL, VT: MVT::i32));
6154 RMValue = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: RMValue,
6155 N2: DAG.getConstant(Val: ARM::RoundingBitsPos, DL, VT: MVT::i32));
6156
6157 // Get current value of FPSCR.
6158 SDValue Ops[] = {Chain,
6159 DAG.getConstant(Val: Intrinsic::arm_get_fpscr, DL, VT: MVT::i32)};
6160 SDValue FPSCR =
6161 DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL, ResultTys: {MVT::i32, MVT::Other}, Ops);
6162 Chain = FPSCR.getValue(R: 1);
6163 FPSCR = FPSCR.getValue(R: 0);
6164
6165 // Put new rounding mode into FPSCR[23:22].
6166 const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos);
6167 FPSCR = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: FPSCR,
6168 N2: DAG.getConstant(Val: RMMask, DL, VT: MVT::i32));
6169 FPSCR = DAG.getNode(Opcode: ISD::OR, DL, VT: MVT::i32, N1: FPSCR, N2: RMValue);
6170 SDValue Ops2[] = {
6171 Chain, DAG.getConstant(Val: Intrinsic::arm_set_fpscr, DL, VT: MVT::i32), FPSCR};
6172 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL, VT: MVT::Other, Ops: Ops2);
6173}
6174
6175SDValue ARMTargetLowering::LowerSET_FPMODE(SDValue Op,
6176 SelectionDAG &DAG) const {
6177 SDLoc DL(Op);
6178 SDValue Chain = Op->getOperand(Num: 0);
6179 SDValue Mode = Op->getOperand(Num: 1);
6180
6181 // Generate nodes to build:
6182 // FPSCR = (FPSCR & FPStatusBits) | (Mode & ~FPStatusBits)
6183 SDValue Ops[] = {Chain,
6184 DAG.getConstant(Val: Intrinsic::arm_get_fpscr, DL, VT: MVT::i32)};
6185 SDValue FPSCR =
6186 DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL, ResultTys: {MVT::i32, MVT::Other}, Ops);
6187 Chain = FPSCR.getValue(R: 1);
6188 FPSCR = FPSCR.getValue(R: 0);
6189
6190 SDValue FPSCRMasked =
6191 DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: FPSCR,
6192 N2: DAG.getConstant(Val: ARM::FPStatusBits, DL, VT: MVT::i32));
6193 SDValue InputMasked =
6194 DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: Mode,
6195 N2: DAG.getConstant(Val: ~ARM::FPStatusBits, DL, VT: MVT::i32));
6196 FPSCR = DAG.getNode(Opcode: ISD::OR, DL, VT: MVT::i32, N1: FPSCRMasked, N2: InputMasked);
6197
6198 SDValue Ops2[] = {
6199 Chain, DAG.getConstant(Val: Intrinsic::arm_set_fpscr, DL, VT: MVT::i32), FPSCR};
6200 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL, VT: MVT::Other, Ops: Ops2);
6201}
6202
6203SDValue ARMTargetLowering::LowerRESET_FPMODE(SDValue Op,
6204 SelectionDAG &DAG) const {
6205 SDLoc DL(Op);
6206 SDValue Chain = Op->getOperand(Num: 0);
6207
6208 // To get the default FP mode all control bits are cleared:
6209 // FPSCR = FPSCR & (FPStatusBits | FPReservedBits)
6210 SDValue Ops[] = {Chain,
6211 DAG.getConstant(Val: Intrinsic::arm_get_fpscr, DL, VT: MVT::i32)};
6212 SDValue FPSCR =
6213 DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL, ResultTys: {MVT::i32, MVT::Other}, Ops);
6214 Chain = FPSCR.getValue(R: 1);
6215 FPSCR = FPSCR.getValue(R: 0);
6216
6217 SDValue FPSCRMasked = DAG.getNode(
6218 Opcode: ISD::AND, DL, VT: MVT::i32, N1: FPSCR,
6219 N2: DAG.getConstant(Val: ARM::FPStatusBits | ARM::FPReservedBits, DL, VT: MVT::i32));
6220 SDValue Ops2[] = {Chain,
6221 DAG.getConstant(Val: Intrinsic::arm_set_fpscr, DL, VT: MVT::i32),
6222 FPSCRMasked};
6223 return DAG.getNode(Opcode: ISD::INTRINSIC_VOID, DL, VT: MVT::Other, Ops: Ops2);
6224}
6225
6226static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
6227 const ARMSubtarget *ST) {
6228 SDLoc dl(N);
6229 EVT VT = N->getValueType(ResNo: 0);
6230 if (VT.isVector() && ST->hasNEON()) {
6231
6232 // Compute the least significant set bit: LSB = X & -X
6233 SDValue X = N->getOperand(Num: 0);
6234 SDValue NX = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: getZeroVector(VT, DAG, dl), N2: X);
6235 SDValue LSB = DAG.getNode(Opcode: ISD::AND, DL: dl, VT, N1: X, N2: NX);
6236
6237 EVT ElemTy = VT.getVectorElementType();
6238
6239 if (ElemTy == MVT::i8) {
6240 // Compute with: cttz(x) = ctpop(lsb - 1)
6241 SDValue One = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT,
6242 Operand: DAG.getTargetConstant(Val: 1, DL: dl, VT: ElemTy));
6243 SDValue Bits = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: LSB, N2: One);
6244 return DAG.getNode(Opcode: ISD::CTPOP, DL: dl, VT, Operand: Bits);
6245 }
6246
6247 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6248 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6249 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6250 unsigned NumBits = ElemTy.getSizeInBits();
6251 SDValue WidthMinus1 =
6252 DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT,
6253 Operand: DAG.getTargetConstant(Val: NumBits - 1, DL: dl, VT: ElemTy));
6254 SDValue CTLZ = DAG.getNode(Opcode: ISD::CTLZ, DL: dl, VT, Operand: LSB);
6255 return DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: WidthMinus1, N2: CTLZ);
6256 }
6257
6258 // Compute with: cttz(x) = ctpop(lsb - 1)
6259
6260 // Compute LSB - 1.
6261 SDValue Bits;
6262 if (ElemTy == MVT::i64) {
6263 // Load constant 0xffff'ffff'ffff'ffff to register.
6264 SDValue FF = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT,
6265 Operand: DAG.getTargetConstant(Val: 0x1eff, DL: dl, VT: MVT::i32));
6266 Bits = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: LSB, N2: FF);
6267 } else {
6268 SDValue One = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT,
6269 Operand: DAG.getTargetConstant(Val: 1, DL: dl, VT: ElemTy));
6270 Bits = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: LSB, N2: One);
6271 }
6272 return DAG.getNode(Opcode: ISD::CTPOP, DL: dl, VT, Operand: Bits);
6273 }
6274
6275 if (!ST->hasV6T2Ops())
6276 return SDValue();
6277
6278 SDValue rbit = DAG.getNode(Opcode: ISD::BITREVERSE, DL: dl, VT, Operand: N->getOperand(Num: 0));
6279 return DAG.getNode(Opcode: ISD::CTLZ, DL: dl, VT, Operand: rbit);
6280}
6281
6282static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6283 const ARMSubtarget *ST) {
6284 EVT VT = N->getValueType(ResNo: 0);
6285 SDLoc DL(N);
6286
6287 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6288 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6289 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6290 "Unexpected type for custom ctpop lowering");
6291
6292 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6293 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6294 SDValue Res = DAG.getBitcast(VT: VT8Bit, V: N->getOperand(Num: 0));
6295 Res = DAG.getNode(Opcode: ISD::CTPOP, DL, VT: VT8Bit, Operand: Res);
6296
6297 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6298 unsigned EltSize = 8;
6299 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6300 while (EltSize != VT.getScalarSizeInBits()) {
6301 SmallVector<SDValue, 8> Ops;
6302 Ops.push_back(Elt: DAG.getConstant(Val: Intrinsic::arm_neon_vpaddlu, DL,
6303 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
6304 Ops.push_back(Elt: Res);
6305
6306 EltSize *= 2;
6307 NumElts /= 2;
6308 MVT WidenVT = MVT::getVectorVT(VT: MVT::getIntegerVT(BitWidth: EltSize), NumElements: NumElts);
6309 Res = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT: WidenVT, Ops);
6310 }
6311
6312 return Res;
6313}
6314
6315/// Getvshiftimm - Check if this is a valid build_vector for the immediate
6316/// operand of a vector shift operation, where all the elements of the
6317/// build_vector must have the same constant integer value.
6318static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6319 // Ignore bit_converts.
6320 while (Op.getOpcode() == ISD::BITCAST)
6321 Op = Op.getOperand(i: 0);
6322 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Val: Op.getNode());
6323 APInt SplatBits, SplatUndef;
6324 unsigned SplatBitSize;
6325 bool HasAnyUndefs;
6326 if (!BVN ||
6327 !BVN->isConstantSplat(SplatValue&: SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6328 MinSplatBits: ElementBits) ||
6329 SplatBitSize > ElementBits)
6330 return false;
6331 Cnt = SplatBits.getSExtValue();
6332 return true;
6333}
6334
6335/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6336/// operand of a vector shift left operation. That value must be in the range:
6337/// 0 <= Value < ElementBits for a left shift; or
6338/// 0 <= Value <= ElementBits for a long left shift.
6339static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6340 assert(VT.isVector() && "vector shift count is not a vector type");
6341 int64_t ElementBits = VT.getScalarSizeInBits();
6342 if (!getVShiftImm(Op, ElementBits, Cnt))
6343 return false;
6344 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6345}
6346
6347/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6348/// operand of a vector shift right operation. For a shift opcode, the value
6349/// is positive, but for an intrinsic the value count must be negative. The
6350/// absolute value must be in the range:
6351/// 1 <= |Value| <= ElementBits for a right shift; or
6352/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6353static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6354 int64_t &Cnt) {
6355 assert(VT.isVector() && "vector shift count is not a vector type");
6356 int64_t ElementBits = VT.getScalarSizeInBits();
6357 if (!getVShiftImm(Op, ElementBits, Cnt))
6358 return false;
6359 if (!isIntrinsic)
6360 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6361 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6362 Cnt = -Cnt;
6363 return true;
6364 }
6365 return false;
6366}
6367
6368static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6369 const ARMSubtarget *ST) {
6370 EVT VT = N->getValueType(ResNo: 0);
6371 SDLoc dl(N);
6372 int64_t Cnt;
6373
6374 if (!VT.isVector())
6375 return SDValue();
6376
6377 // We essentially have two forms here. Shift by an immediate and shift by a
6378 // vector register (there are also shift by a gpr, but that is just handled
6379 // with a tablegen pattern). We cannot easily match shift by an immediate in
6380 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6381 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6382 // signed or unsigned, and a negative shift indicates a shift right).
6383 if (N->getOpcode() == ISD::SHL) {
6384 if (isVShiftLImm(Op: N->getOperand(Num: 1), VT, isLong: false, Cnt))
6385 return DAG.getNode(Opcode: ARMISD::VSHLIMM, DL: dl, VT, N1: N->getOperand(Num: 0),
6386 N2: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
6387 return DAG.getNode(Opcode: ARMISD::VSHLu, DL: dl, VT, N1: N->getOperand(Num: 0),
6388 N2: N->getOperand(Num: 1));
6389 }
6390
6391 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6392 "unexpected vector shift opcode");
6393
6394 if (isVShiftRImm(Op: N->getOperand(Num: 1), VT, isNarrow: false, isIntrinsic: false, Cnt)) {
6395 unsigned VShiftOpc =
6396 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6397 return DAG.getNode(Opcode: VShiftOpc, DL: dl, VT, N1: N->getOperand(Num: 0),
6398 N2: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
6399 }
6400
6401 // Other right shifts we don't have operations for (we use a shift left by a
6402 // negative number).
6403 EVT ShiftVT = N->getOperand(Num: 1).getValueType();
6404 SDValue NegatedCount = DAG.getNode(
6405 Opcode: ISD::SUB, DL: dl, VT: ShiftVT, N1: getZeroVector(VT: ShiftVT, DAG, dl), N2: N->getOperand(Num: 1));
6406 unsigned VShiftOpc =
6407 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6408 return DAG.getNode(Opcode: VShiftOpc, DL: dl, VT, N1: N->getOperand(Num: 0), N2: NegatedCount);
6409}
6410
6411static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6412 const ARMSubtarget *ST) {
6413 EVT VT = N->getValueType(ResNo: 0);
6414 SDLoc dl(N);
6415
6416 // We can get here for a node like i32 = ISD::SHL i32, i64
6417 if (VT != MVT::i64)
6418 return SDValue();
6419
6420 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6421 N->getOpcode() == ISD::SHL) &&
6422 "Unknown shift to lower!");
6423
6424 unsigned ShOpc = N->getOpcode();
6425 if (ST->hasMVEIntegerOps()) {
6426 SDValue ShAmt = N->getOperand(Num: 1);
6427 unsigned ShPartsOpc = ARMISD::LSLL;
6428 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(Val&: ShAmt);
6429
6430 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6431 // then do the default optimisation
6432 if ((!Con && ShAmt->getValueType(ResNo: 0).getSizeInBits() > 64) ||
6433 (Con && (Con->getAPIntValue() == 0 || Con->getAPIntValue().uge(RHS: 32))))
6434 return SDValue();
6435
6436 // Extract the lower 32 bits of the shift amount if it's not an i32
6437 if (ShAmt->getValueType(ResNo: 0) != MVT::i32)
6438 ShAmt = DAG.getZExtOrTrunc(Op: ShAmt, DL: dl, VT: MVT::i32);
6439
6440 if (ShOpc == ISD::SRL) {
6441 if (!Con)
6442 // There is no t2LSRLr instruction so negate and perform an lsll if the
6443 // shift amount is in a register, emulating a right shift.
6444 ShAmt = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
6445 N1: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32), N2: ShAmt);
6446 else
6447 // Else generate an lsrl on the immediate shift amount
6448 ShPartsOpc = ARMISD::LSRL;
6449 } else if (ShOpc == ISD::SRA)
6450 ShPartsOpc = ARMISD::ASRL;
6451
6452 // Split Lower/Upper 32 bits of the destination/source
6453 SDValue Lo, Hi;
6454 std::tie(args&: Lo, args&: Hi) =
6455 DAG.SplitScalar(N: N->getOperand(Num: 0), DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
6456 // Generate the shift operation as computed above
6457 Lo = DAG.getNode(Opcode: ShPartsOpc, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N1: Lo, N2: Hi,
6458 N3: ShAmt);
6459 // The upper 32 bits come from the second return value of lsll
6460 Hi = SDValue(Lo.getNode(), 1);
6461 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lo, N2: Hi);
6462 }
6463
6464 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6465 if (!isOneConstant(V: N->getOperand(Num: 1)) || N->getOpcode() == ISD::SHL)
6466 return SDValue();
6467
6468 // If we are in thumb mode, we don't have RRX.
6469 if (ST->isThumb1Only())
6470 return SDValue();
6471
6472 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6473 SDValue Lo, Hi;
6474 std::tie(args&: Lo, args&: Hi) = DAG.SplitScalar(N: N->getOperand(Num: 0), DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
6475
6476 // First, build a LSRS1/ASRS1 op, which shifts the top part by one and
6477 // captures the shifted out bit into a carry flag.
6478 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::LSRS1 : ARMISD::ASRS1;
6479 Hi = DAG.getNode(Opcode: Opc, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT), N: Hi);
6480
6481 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6482 Lo = DAG.getNode(Opcode: ARMISD::RRX, DL: dl, VT: MVT::i32, N1: Lo, N2: Hi.getValue(R: 1));
6483
6484 // Merge the pieces into a single i64 value.
6485 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lo, N2: Hi);
6486}
6487
6488static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6489 const ARMSubtarget *ST) {
6490 bool Invert = false;
6491 bool Swap = false;
6492 unsigned Opc = ARMCC::AL;
6493
6494 SDValue Op0 = Op.getOperand(i: 0);
6495 SDValue Op1 = Op.getOperand(i: 1);
6496 SDValue CC = Op.getOperand(i: 2);
6497 EVT VT = Op.getValueType();
6498 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(Val&: CC)->get();
6499 SDLoc dl(Op);
6500
6501 EVT CmpVT;
6502 if (ST->hasNEON())
6503 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6504 else {
6505 assert(ST->hasMVEIntegerOps() &&
6506 "No hardware support for integer vector comparison!");
6507
6508 if (Op.getValueType().getVectorElementType() != MVT::i1)
6509 return SDValue();
6510
6511 // Make sure we expand floating point setcc to scalar if we do not have
6512 // mve.fp, so that we can handle them from there.
6513 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6514 return SDValue();
6515
6516 CmpVT = VT;
6517 }
6518
6519 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6520 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6521 // Special-case integer 64-bit equality comparisons. They aren't legal,
6522 // but they can be lowered with a few vector instructions.
6523 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6524 EVT SplitVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::i32, NumElements: CmpElements);
6525 SDValue CastOp0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: SplitVT, Operand: Op0);
6526 SDValue CastOp1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: SplitVT, Operand: Op1);
6527 SDValue Cmp = DAG.getNode(Opcode: ISD::SETCC, DL: dl, VT: SplitVT, N1: CastOp0, N2: CastOp1,
6528 N3: DAG.getCondCode(Cond: ISD::SETEQ));
6529 SDValue Reversed = DAG.getNode(Opcode: ARMISD::VREV64, DL: dl, VT: SplitVT, Operand: Cmp);
6530 SDValue Merged = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: SplitVT, N1: Cmp, N2: Reversed);
6531 Merged = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: CmpVT, Operand: Merged);
6532 if (SetCCOpcode == ISD::SETNE)
6533 Merged = DAG.getNOT(DL: dl, Val: Merged, VT: CmpVT);
6534 Merged = DAG.getSExtOrTrunc(Op: Merged, DL: dl, VT);
6535 return Merged;
6536 }
6537
6538 if (CmpVT.getVectorElementType() == MVT::i64)
6539 // 64-bit comparisons are not legal in general.
6540 return SDValue();
6541
6542 if (Op1.getValueType().isFloatingPoint()) {
6543 switch (SetCCOpcode) {
6544 default: llvm_unreachable("Illegal FP comparison");
6545 case ISD::SETUNE:
6546 case ISD::SETNE:
6547 if (ST->hasMVEFloatOps()) {
6548 Opc = ARMCC::NE; break;
6549 } else {
6550 Invert = true; [[fallthrough]];
6551 }
6552 case ISD::SETOEQ:
6553 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6554 case ISD::SETOLT:
6555 case ISD::SETLT: Swap = true; [[fallthrough]];
6556 case ISD::SETOGT:
6557 case ISD::SETGT: Opc = ARMCC::GT; break;
6558 case ISD::SETOLE:
6559 case ISD::SETLE: Swap = true; [[fallthrough]];
6560 case ISD::SETOGE:
6561 case ISD::SETGE: Opc = ARMCC::GE; break;
6562 case ISD::SETUGE: Swap = true; [[fallthrough]];
6563 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6564 case ISD::SETUGT: Swap = true; [[fallthrough]];
6565 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6566 case ISD::SETUEQ: Invert = true; [[fallthrough]];
6567 case ISD::SETONE: {
6568 // Expand this to (OLT | OGT).
6569 SDValue TmpOp0 = DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT: CmpVT, N1: Op1, N2: Op0,
6570 N3: DAG.getConstant(Val: ARMCC::GT, DL: dl, VT: MVT::i32));
6571 SDValue TmpOp1 = DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT: CmpVT, N1: Op0, N2: Op1,
6572 N3: DAG.getConstant(Val: ARMCC::GT, DL: dl, VT: MVT::i32));
6573 SDValue Result = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: CmpVT, N1: TmpOp0, N2: TmpOp1);
6574 if (Invert)
6575 Result = DAG.getNOT(DL: dl, Val: Result, VT);
6576 return Result;
6577 }
6578 case ISD::SETUO: Invert = true; [[fallthrough]];
6579 case ISD::SETO: {
6580 // Expand this to (OLT | OGE).
6581 SDValue TmpOp0 = DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT: CmpVT, N1: Op1, N2: Op0,
6582 N3: DAG.getConstant(Val: ARMCC::GT, DL: dl, VT: MVT::i32));
6583 SDValue TmpOp1 = DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT: CmpVT, N1: Op0, N2: Op1,
6584 N3: DAG.getConstant(Val: ARMCC::GE, DL: dl, VT: MVT::i32));
6585 SDValue Result = DAG.getNode(Opcode: ISD::OR, DL: dl, VT: CmpVT, N1: TmpOp0, N2: TmpOp1);
6586 if (Invert)
6587 Result = DAG.getNOT(DL: dl, Val: Result, VT);
6588 return Result;
6589 }
6590 }
6591 } else {
6592 // Integer comparisons.
6593 switch (SetCCOpcode) {
6594 default: llvm_unreachable("Illegal integer comparison");
6595 case ISD::SETNE:
6596 if (ST->hasMVEIntegerOps()) {
6597 Opc = ARMCC::NE; break;
6598 } else {
6599 Invert = true; [[fallthrough]];
6600 }
6601 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6602 case ISD::SETLT: Swap = true; [[fallthrough]];
6603 case ISD::SETGT: Opc = ARMCC::GT; break;
6604 case ISD::SETLE: Swap = true; [[fallthrough]];
6605 case ISD::SETGE: Opc = ARMCC::GE; break;
6606 case ISD::SETULT: Swap = true; [[fallthrough]];
6607 case ISD::SETUGT: Opc = ARMCC::HI; break;
6608 case ISD::SETULE: Swap = true; [[fallthrough]];
6609 case ISD::SETUGE: Opc = ARMCC::HS; break;
6610 }
6611
6612 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6613 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6614 SDValue AndOp;
6615 if (ISD::isBuildVectorAllZeros(N: Op1.getNode()))
6616 AndOp = Op0;
6617 else if (ISD::isBuildVectorAllZeros(N: Op0.getNode()))
6618 AndOp = Op1;
6619
6620 // Ignore bitconvert.
6621 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6622 AndOp = AndOp.getOperand(i: 0);
6623
6624 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6625 Op0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: CmpVT, Operand: AndOp.getOperand(i: 0));
6626 Op1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: CmpVT, Operand: AndOp.getOperand(i: 1));
6627 SDValue Result = DAG.getNode(Opcode: ARMISD::VTST, DL: dl, VT: CmpVT, N1: Op0, N2: Op1);
6628 if (!Invert)
6629 Result = DAG.getNOT(DL: dl, Val: Result, VT);
6630 return Result;
6631 }
6632 }
6633 }
6634
6635 if (Swap)
6636 std::swap(a&: Op0, b&: Op1);
6637
6638 // If one of the operands is a constant vector zero, attempt to fold the
6639 // comparison to a specialized compare-against-zero form.
6640 if (ISD::isBuildVectorAllZeros(N: Op0.getNode()) &&
6641 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::EQ ||
6642 Opc == ARMCC::NE)) {
6643 if (Opc == ARMCC::GE)
6644 Opc = ARMCC::LE;
6645 else if (Opc == ARMCC::GT)
6646 Opc = ARMCC::LT;
6647 std::swap(a&: Op0, b&: Op1);
6648 }
6649
6650 SDValue Result;
6651 if (ISD::isBuildVectorAllZeros(N: Op1.getNode()) &&
6652 (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::LE ||
6653 Opc == ARMCC::LT || Opc == ARMCC::NE || Opc == ARMCC::EQ))
6654 Result = DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT: CmpVT, N1: Op0,
6655 N2: DAG.getConstant(Val: Opc, DL: dl, VT: MVT::i32));
6656 else
6657 Result = DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT: CmpVT, N1: Op0, N2: Op1,
6658 N3: DAG.getConstant(Val: Opc, DL: dl, VT: MVT::i32));
6659
6660 Result = DAG.getSExtOrTrunc(Op: Result, DL: dl, VT);
6661
6662 if (Invert)
6663 Result = DAG.getNOT(DL: dl, Val: Result, VT);
6664
6665 return Result;
6666}
6667
6668static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6669 SDValue LHS = Op.getOperand(i: 0);
6670 SDValue RHS = Op.getOperand(i: 1);
6671 SDValue Carry = Op.getOperand(i: 2);
6672 SDValue Cond = Op.getOperand(i: 3);
6673 SDLoc DL(Op);
6674
6675 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6676
6677 // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
6678 // have to invert the carry first.
6679 Carry = DAG.getNode(Opcode: ISD::SUB, DL, VT: MVT::i32,
6680 N1: DAG.getConstant(Val: 1, DL, VT: MVT::i32), N2: Carry);
6681 // This converts the boolean value carry into the carry flag.
6682 Carry = ConvertBooleanCarryToCarryFlag(BoolCarry: Carry, DAG);
6683
6684 SDVTList VTs = DAG.getVTList(VT1: LHS.getValueType(), VT2: MVT::i32);
6685 SDValue Cmp = DAG.getNode(Opcode: ARMISD::SUBE, DL, VTList: VTs, N1: LHS, N2: RHS, N3: Carry);
6686
6687 SDValue FVal = DAG.getConstant(Val: 0, DL, VT: MVT::i32);
6688 SDValue TVal = DAG.getConstant(Val: 1, DL, VT: MVT::i32);
6689 SDValue ARMcc = DAG.getConstant(
6690 Val: IntCCToARMCC(CC: cast<CondCodeSDNode>(Val&: Cond)->get()), DL, VT: MVT::i32);
6691 return DAG.getNode(Opcode: ARMISD::CMOV, DL, VT: Op.getValueType(), N1: FVal, N2: TVal, N3: ARMcc,
6692 N4: Cmp.getValue(R: 1));
6693}
6694
6695/// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6696/// valid vector constant for a NEON or MVE instruction with a "modified
6697/// immediate" operand (e.g., VMOV). If so, return the encoded value.
6698static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6699 unsigned SplatBitSize, SelectionDAG &DAG,
6700 const SDLoc &dl, EVT &VT, EVT VectorVT,
6701 VMOVModImmType type) {
6702 unsigned OpCmode, Imm;
6703 bool is128Bits = VectorVT.is128BitVector();
6704
6705 // SplatBitSize is set to the smallest size that splats the vector, so a
6706 // zero vector will always have SplatBitSize == 8. However, NEON modified
6707 // immediate instructions others than VMOV do not support the 8-bit encoding
6708 // of a zero vector, and the default encoding of zero is supposed to be the
6709 // 32-bit version.
6710 if (SplatBits == 0)
6711 SplatBitSize = 32;
6712
6713 switch (SplatBitSize) {
6714 case 8:
6715 if (type != VMOVModImm)
6716 return SDValue();
6717 // Any 1-byte value is OK. Op=0, Cmode=1110.
6718 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6719 OpCmode = 0xe;
6720 Imm = SplatBits;
6721 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6722 break;
6723
6724 case 16:
6725 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6726 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6727 if ((SplatBits & ~0xff) == 0) {
6728 // Value = 0x00nn: Op=x, Cmode=100x.
6729 OpCmode = 0x8;
6730 Imm = SplatBits;
6731 break;
6732 }
6733 if ((SplatBits & ~0xff00) == 0) {
6734 // Value = 0xnn00: Op=x, Cmode=101x.
6735 OpCmode = 0xa;
6736 Imm = SplatBits >> 8;
6737 break;
6738 }
6739 return SDValue();
6740
6741 case 32:
6742 // NEON's 32-bit VMOV supports splat values where:
6743 // * only one byte is nonzero, or
6744 // * the least significant byte is 0xff and the second byte is nonzero, or
6745 // * the least significant 2 bytes are 0xff and the third is nonzero.
6746 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6747 if ((SplatBits & ~0xff) == 0) {
6748 // Value = 0x000000nn: Op=x, Cmode=000x.
6749 OpCmode = 0;
6750 Imm = SplatBits;
6751 break;
6752 }
6753 if ((SplatBits & ~0xff00) == 0) {
6754 // Value = 0x0000nn00: Op=x, Cmode=001x.
6755 OpCmode = 0x2;
6756 Imm = SplatBits >> 8;
6757 break;
6758 }
6759 if ((SplatBits & ~0xff0000) == 0) {
6760 // Value = 0x00nn0000: Op=x, Cmode=010x.
6761 OpCmode = 0x4;
6762 Imm = SplatBits >> 16;
6763 break;
6764 }
6765 if ((SplatBits & ~0xff000000) == 0) {
6766 // Value = 0xnn000000: Op=x, Cmode=011x.
6767 OpCmode = 0x6;
6768 Imm = SplatBits >> 24;
6769 break;
6770 }
6771
6772 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6773 if (type == OtherModImm) return SDValue();
6774
6775 if ((SplatBits & ~0xffff) == 0 &&
6776 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6777 // Value = 0x0000nnff: Op=x, Cmode=1100.
6778 OpCmode = 0xc;
6779 Imm = SplatBits >> 8;
6780 break;
6781 }
6782
6783 // cmode == 0b1101 is not supported for MVE VMVN
6784 if (type == MVEVMVNModImm)
6785 return SDValue();
6786
6787 if ((SplatBits & ~0xffffff) == 0 &&
6788 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6789 // Value = 0x00nnffff: Op=x, Cmode=1101.
6790 OpCmode = 0xd;
6791 Imm = SplatBits >> 16;
6792 break;
6793 }
6794
6795 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6796 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6797 // VMOV.I32. A (very) minor optimization would be to replicate the value
6798 // and fall through here to test for a valid 64-bit splat. But, then the
6799 // caller would also need to check and handle the change in size.
6800 return SDValue();
6801
6802 case 64: {
6803 if (type != VMOVModImm)
6804 return SDValue();
6805 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6806 uint64_t BitMask = 0xff;
6807 unsigned ImmMask = 1;
6808 Imm = 0;
6809 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6810 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6811 Imm |= ImmMask;
6812 } else if ((SplatBits & BitMask) != 0) {
6813 return SDValue();
6814 }
6815 BitMask <<= 8;
6816 ImmMask <<= 1;
6817 }
6818
6819 // Op=1, Cmode=1110.
6820 OpCmode = 0x1e;
6821 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6822 break;
6823 }
6824
6825 default:
6826 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6827 }
6828
6829 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Val: Imm);
6830 return DAG.getTargetConstant(Val: EncodedVal, DL: dl, VT: MVT::i32);
6831}
6832
6833SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6834 const ARMSubtarget *ST) const {
6835 EVT VT = Op.getValueType();
6836 bool IsDouble = (VT == MVT::f64);
6837 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Val&: Op);
6838 const APFloat &FPVal = CFP->getValueAPF();
6839
6840 // Prevent floating-point constants from using literal loads
6841 // when execute-only is enabled.
6842 if (ST->genExecuteOnly()) {
6843 // We shouldn't trigger this for v6m execute-only
6844 assert((!ST->isThumb1Only() || ST->hasV8MBaselineOps()) &&
6845 "Unexpected architecture");
6846
6847 // If we can represent the constant as an immediate, don't lower it
6848 if (isFPImmLegal(Imm: FPVal, VT))
6849 return Op;
6850 // Otherwise, construct as integer, and move to float register
6851 APInt INTVal = FPVal.bitcastToAPInt();
6852 SDLoc DL(CFP);
6853 switch (VT.getSimpleVT().SimpleTy) {
6854 default:
6855 llvm_unreachable("Unknown floating point type!");
6856 break;
6857 case MVT::f64: {
6858 SDValue Lo = DAG.getConstant(Val: INTVal.trunc(width: 32), DL, VT: MVT::i32);
6859 SDValue Hi = DAG.getConstant(Val: INTVal.lshr(shiftAmt: 32).trunc(width: 32), DL, VT: MVT::i32);
6860 return DAG.getNode(Opcode: ARMISD::VMOVDRR, DL, VT: MVT::f64, N1: Lo, N2: Hi);
6861 }
6862 case MVT::f32:
6863 return DAG.getNode(Opcode: ARMISD::VMOVSR, DL, VT,
6864 Operand: DAG.getConstant(Val: INTVal, DL, VT: MVT::i32));
6865 }
6866 }
6867
6868 if (!ST->hasVFP3Base())
6869 return SDValue();
6870
6871 // Use the default (constant pool) lowering for double constants when we have
6872 // an SP-only FPU
6873 if (IsDouble && !Subtarget->hasFP64())
6874 return SDValue();
6875
6876 // Try splatting with a VMOV.f32...
6877 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPImm: FPVal) : ARM_AM::getFP32Imm(FPImm: FPVal);
6878
6879 if (ImmVal != -1) {
6880 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6881 // We have code in place to select a valid ConstantFP already, no need to
6882 // do any mangling.
6883 return Op;
6884 }
6885
6886 // It's a float and we are trying to use NEON operations where
6887 // possible. Lower it to a splat followed by an extract.
6888 SDLoc DL(Op);
6889 SDValue NewVal = DAG.getTargetConstant(Val: ImmVal, DL, VT: MVT::i32);
6890 SDValue VecConstant = DAG.getNode(Opcode: ARMISD::VMOVFPIMM, DL, VT: MVT::v2f32,
6891 Operand: NewVal);
6892 return DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: VecConstant,
6893 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
6894 }
6895
6896 // The rest of our options are NEON only, make sure that's allowed before
6897 // proceeding..
6898 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6899 return SDValue();
6900
6901 EVT VMovVT;
6902 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6903
6904 // It wouldn't really be worth bothering for doubles except for one very
6905 // important value, which does happen to match: 0.0. So make sure we don't do
6906 // anything stupid.
6907 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6908 return SDValue();
6909
6910 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6911 SDValue NewVal = isVMOVModifiedImm(SplatBits: iVal & 0xffffffffU, SplatUndef: 0, SplatBitSize: 32, DAG, dl: SDLoc(Op),
6912 VT&: VMovVT, VectorVT: VT, type: VMOVModImm);
6913 if (NewVal != SDValue()) {
6914 SDLoc DL(Op);
6915 SDValue VecConstant = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL, VT: VMovVT,
6916 Operand: NewVal);
6917 if (IsDouble)
6918 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::f64, Operand: VecConstant);
6919
6920 // It's a float: cast and extract a vector element.
6921 SDValue VecFConstant = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::v2f32,
6922 Operand: VecConstant);
6923 return DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: VecFConstant,
6924 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
6925 }
6926
6927 // Finally, try a VMVN.i32
6928 NewVal = isVMOVModifiedImm(SplatBits: ~iVal & 0xffffffffU, SplatUndef: 0, SplatBitSize: 32, DAG, dl: SDLoc(Op), VT&: VMovVT,
6929 VectorVT: VT, type: VMVNModImm);
6930 if (NewVal != SDValue()) {
6931 SDLoc DL(Op);
6932 SDValue VecConstant = DAG.getNode(Opcode: ARMISD::VMVNIMM, DL, VT: VMovVT, Operand: NewVal);
6933
6934 if (IsDouble)
6935 return DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::f64, Operand: VecConstant);
6936
6937 // It's a float: cast and extract a vector element.
6938 SDValue VecFConstant = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: MVT::v2f32,
6939 Operand: VecConstant);
6940 return DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::f32, N1: VecFConstant,
6941 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
6942 }
6943
6944 return SDValue();
6945}
6946
6947// check if an VEXT instruction can handle the shuffle mask when the
6948// vector sources of the shuffle are the same.
6949static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6950 unsigned NumElts = VT.getVectorNumElements();
6951
6952 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6953 if (M[0] < 0)
6954 return false;
6955
6956 Imm = M[0];
6957
6958 // If this is a VEXT shuffle, the immediate value is the index of the first
6959 // element. The other shuffle indices must be the successive elements after
6960 // the first one.
6961 unsigned ExpectedElt = Imm;
6962 for (unsigned i = 1; i < NumElts; ++i) {
6963 // Increment the expected index. If it wraps around, just follow it
6964 // back to index zero and keep going.
6965 ++ExpectedElt;
6966 if (ExpectedElt == NumElts)
6967 ExpectedElt = 0;
6968
6969 if (M[i] < 0) continue; // ignore UNDEF indices
6970 if (ExpectedElt != static_cast<unsigned>(M[i]))
6971 return false;
6972 }
6973
6974 return true;
6975}
6976
6977static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6978 bool &ReverseVEXT, unsigned &Imm) {
6979 unsigned NumElts = VT.getVectorNumElements();
6980 ReverseVEXT = false;
6981
6982 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6983 if (M[0] < 0)
6984 return false;
6985
6986 Imm = M[0];
6987
6988 // If this is a VEXT shuffle, the immediate value is the index of the first
6989 // element. The other shuffle indices must be the successive elements after
6990 // the first one.
6991 unsigned ExpectedElt = Imm;
6992 for (unsigned i = 1; i < NumElts; ++i) {
6993 // Increment the expected index. If it wraps around, it may still be
6994 // a VEXT but the source vectors must be swapped.
6995 ExpectedElt += 1;
6996 if (ExpectedElt == NumElts * 2) {
6997 ExpectedElt = 0;
6998 ReverseVEXT = true;
6999 }
7000
7001 if (M[i] < 0) continue; // ignore UNDEF indices
7002 if (ExpectedElt != static_cast<unsigned>(M[i]))
7003 return false;
7004 }
7005
7006 // Adjust the index value if the source operands will be swapped.
7007 if (ReverseVEXT)
7008 Imm -= NumElts;
7009
7010 return true;
7011}
7012
7013static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
7014 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
7015 // range, then 0 is placed into the resulting vector. So pretty much any mask
7016 // of 8 elements can work here.
7017 return VT == MVT::v8i8 && M.size() == 8;
7018}
7019
7020static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
7021 unsigned Index) {
7022 if (Mask.size() == Elements * 2)
7023 return Index / Elements;
7024 return Mask[Index] == 0 ? 0 : 1;
7025}
7026
7027// Checks whether the shuffle mask represents a vector transpose (VTRN) by
7028// checking that pairs of elements in the shuffle mask represent the same index
7029// in each vector, incrementing the expected index by 2 at each step.
7030// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
7031// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
7032// v2={e,f,g,h}
7033// WhichResult gives the offset for each element in the mask based on which
7034// of the two results it belongs to.
7035//
7036// The transpose can be represented either as:
7037// result1 = shufflevector v1, v2, result1_shuffle_mask
7038// result2 = shufflevector v1, v2, result2_shuffle_mask
7039// where v1/v2 and the shuffle masks have the same number of elements
7040// (here WhichResult (see below) indicates which result is being checked)
7041//
7042// or as:
7043// results = shufflevector v1, v2, shuffle_mask
7044// where both results are returned in one vector and the shuffle mask has twice
7045// as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7046// want to check the low half and high half of the shuffle mask as if it were
7047// the other case
7048static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7049 unsigned EltSz = VT.getScalarSizeInBits();
7050 if (EltSz == 64)
7051 return false;
7052
7053 unsigned NumElts = VT.getVectorNumElements();
7054 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7055 return false;
7056
7057 // If the mask is twice as long as the input vector then we need to check the
7058 // upper and lower parts of the mask with a matching value for WhichResult
7059 // FIXME: A mask with only even values will be rejected in case the first
7060 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7061 // M[0] is used to determine WhichResult
7062 for (unsigned i = 0; i < M.size(); i += NumElts) {
7063 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7064 for (unsigned j = 0; j < NumElts; j += 2) {
7065 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7066 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7067 return false;
7068 }
7069 }
7070
7071 if (M.size() == NumElts*2)
7072 WhichResult = 0;
7073
7074 return true;
7075}
7076
7077/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7078/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7079/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7080static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7081 unsigned EltSz = VT.getScalarSizeInBits();
7082 if (EltSz == 64)
7083 return false;
7084
7085 unsigned NumElts = VT.getVectorNumElements();
7086 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7087 return false;
7088
7089 for (unsigned i = 0; i < M.size(); i += NumElts) {
7090 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7091 for (unsigned j = 0; j < NumElts; j += 2) {
7092 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7093 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7094 return false;
7095 }
7096 }
7097
7098 if (M.size() == NumElts*2)
7099 WhichResult = 0;
7100
7101 return true;
7102}
7103
7104// Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7105// that the mask elements are either all even and in steps of size 2 or all odd
7106// and in steps of size 2.
7107// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7108// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7109// v2={e,f,g,h}
7110// Requires similar checks to that of isVTRNMask with
7111// respect the how results are returned.
7112static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7113 unsigned EltSz = VT.getScalarSizeInBits();
7114 if (EltSz == 64)
7115 return false;
7116
7117 unsigned NumElts = VT.getVectorNumElements();
7118 if (M.size() != NumElts && M.size() != NumElts*2)
7119 return false;
7120
7121 for (unsigned i = 0; i < M.size(); i += NumElts) {
7122 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7123 for (unsigned j = 0; j < NumElts; ++j) {
7124 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7125 return false;
7126 }
7127 }
7128
7129 if (M.size() == NumElts*2)
7130 WhichResult = 0;
7131
7132 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7133 if (VT.is64BitVector() && EltSz == 32)
7134 return false;
7135
7136 return true;
7137}
7138
7139/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7140/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7141/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7142static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7143 unsigned EltSz = VT.getScalarSizeInBits();
7144 if (EltSz == 64)
7145 return false;
7146
7147 unsigned NumElts = VT.getVectorNumElements();
7148 if (M.size() != NumElts && M.size() != NumElts*2)
7149 return false;
7150
7151 unsigned Half = NumElts / 2;
7152 for (unsigned i = 0; i < M.size(); i += NumElts) {
7153 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7154 for (unsigned j = 0; j < NumElts; j += Half) {
7155 unsigned Idx = WhichResult;
7156 for (unsigned k = 0; k < Half; ++k) {
7157 int MIdx = M[i + j + k];
7158 if (MIdx >= 0 && (unsigned) MIdx != Idx)
7159 return false;
7160 Idx += 2;
7161 }
7162 }
7163 }
7164
7165 if (M.size() == NumElts*2)
7166 WhichResult = 0;
7167
7168 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7169 if (VT.is64BitVector() && EltSz == 32)
7170 return false;
7171
7172 return true;
7173}
7174
7175// Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7176// that pairs of elements of the shufflemask represent the same index in each
7177// vector incrementing sequentially through the vectors.
7178// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7179// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7180// v2={e,f,g,h}
7181// Requires similar checks to that of isVTRNMask with respect the how results
7182// are returned.
7183static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7184 unsigned EltSz = VT.getScalarSizeInBits();
7185 if (EltSz == 64)
7186 return false;
7187
7188 unsigned NumElts = VT.getVectorNumElements();
7189 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7190 return false;
7191
7192 for (unsigned i = 0; i < M.size(); i += NumElts) {
7193 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7194 unsigned Idx = WhichResult * NumElts / 2;
7195 for (unsigned j = 0; j < NumElts; j += 2) {
7196 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7197 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7198 return false;
7199 Idx += 1;
7200 }
7201 }
7202
7203 if (M.size() == NumElts*2)
7204 WhichResult = 0;
7205
7206 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7207 if (VT.is64BitVector() && EltSz == 32)
7208 return false;
7209
7210 return true;
7211}
7212
7213/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7214/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7215/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7216static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7217 unsigned EltSz = VT.getScalarSizeInBits();
7218 if (EltSz == 64)
7219 return false;
7220
7221 unsigned NumElts = VT.getVectorNumElements();
7222 if ((M.size() != NumElts && M.size() != NumElts * 2) || NumElts % 2 != 0)
7223 return false;
7224
7225 for (unsigned i = 0; i < M.size(); i += NumElts) {
7226 WhichResult = SelectPairHalf(Elements: NumElts, Mask: M, Index: i);
7227 unsigned Idx = WhichResult * NumElts / 2;
7228 for (unsigned j = 0; j < NumElts; j += 2) {
7229 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7230 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7231 return false;
7232 Idx += 1;
7233 }
7234 }
7235
7236 if (M.size() == NumElts*2)
7237 WhichResult = 0;
7238
7239 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7240 if (VT.is64BitVector() && EltSz == 32)
7241 return false;
7242
7243 return true;
7244}
7245
7246/// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7247/// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7248static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7249 unsigned &WhichResult,
7250 bool &isV_UNDEF) {
7251 isV_UNDEF = false;
7252 if (isVTRNMask(M: ShuffleMask, VT, WhichResult))
7253 return ARMISD::VTRN;
7254 if (isVUZPMask(M: ShuffleMask, VT, WhichResult))
7255 return ARMISD::VUZP;
7256 if (isVZIPMask(M: ShuffleMask, VT, WhichResult))
7257 return ARMISD::VZIP;
7258
7259 isV_UNDEF = true;
7260 if (isVTRN_v_undef_Mask(M: ShuffleMask, VT, WhichResult))
7261 return ARMISD::VTRN;
7262 if (isVUZP_v_undef_Mask(M: ShuffleMask, VT, WhichResult))
7263 return ARMISD::VUZP;
7264 if (isVZIP_v_undef_Mask(M: ShuffleMask, VT, WhichResult))
7265 return ARMISD::VZIP;
7266
7267 return 0;
7268}
7269
7270/// \return true if this is a reverse operation on an vector.
7271static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7272 unsigned NumElts = VT.getVectorNumElements();
7273 // Make sure the mask has the right size.
7274 if (NumElts != M.size())
7275 return false;
7276
7277 // Look for <15, ..., 3, -1, 1, 0>.
7278 for (unsigned i = 0; i != NumElts; ++i)
7279 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7280 return false;
7281
7282 return true;
7283}
7284
7285static bool isTruncMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7286 unsigned NumElts = VT.getVectorNumElements();
7287 // Make sure the mask has the right size.
7288 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7289 return false;
7290
7291 // Half-width truncation patterns (e.g. v4i32 -> v8i16):
7292 // !Top && SingleSource: <0, 2, 4, 6, 0, 2, 4, 6>
7293 // !Top && !SingleSource: <0, 2, 4, 6, 8, 10, 12, 14>
7294 // Top && SingleSource: <1, 3, 5, 7, 1, 3, 5, 7>
7295 // Top && !SingleSource: <1, 3, 5, 7, 9, 11, 13, 15>
7296 int Ofs = Top ? 1 : 0;
7297 int Upper = SingleSource ? 0 : NumElts;
7298 for (int i = 0, e = NumElts / 2; i != e; ++i) {
7299 if (M[i] >= 0 && M[i] != (i * 2) + Ofs)
7300 return false;
7301 if (M[i + e] >= 0 && M[i + e] != (i * 2) + Ofs + Upper)
7302 return false;
7303 }
7304 return true;
7305}
7306
7307static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7308 unsigned NumElts = VT.getVectorNumElements();
7309 // Make sure the mask has the right size.
7310 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7311 return false;
7312
7313 // If Top
7314 // Look for <0, N, 2, N+2, 4, N+4, ..>.
7315 // This inserts Input2 into Input1
7316 // else if not Top
7317 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
7318 // This inserts Input1 into Input2
7319 unsigned Offset = Top ? 0 : 1;
7320 unsigned N = SingleSource ? 0 : NumElts;
7321 for (unsigned i = 0; i < NumElts; i += 2) {
7322 if (M[i] >= 0 && M[i] != (int)i)
7323 return false;
7324 if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset))
7325 return false;
7326 }
7327
7328 return true;
7329}
7330
7331static bool isVMOVNTruncMask(ArrayRef<int> M, EVT ToVT, bool rev) {
7332 unsigned NumElts = ToVT.getVectorNumElements();
7333 if (NumElts != M.size())
7334 return false;
7335
7336 // Test if the Trunc can be convertible to a VMOVN with this shuffle. We are
7337 // looking for patterns of:
7338 // !rev: 0 N/2 1 N/2+1 2 N/2+2 ...
7339 // rev: N/2 0 N/2+1 1 N/2+2 2 ...
7340
7341 unsigned Off0 = rev ? NumElts / 2 : 0;
7342 unsigned Off1 = rev ? 0 : NumElts / 2;
7343 for (unsigned i = 0; i < NumElts; i += 2) {
7344 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
7345 return false;
7346 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
7347 return false;
7348 }
7349
7350 return true;
7351}
7352
7353// Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7354// from a pair of inputs. For example:
7355// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7356// FP_ROUND(EXTRACT_ELT(Y, 0),
7357// FP_ROUND(EXTRACT_ELT(X, 1),
7358// FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7359static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG,
7360 const ARMSubtarget *ST) {
7361 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7362 if (!ST->hasMVEFloatOps())
7363 return SDValue();
7364
7365 SDLoc dl(BV);
7366 EVT VT = BV.getValueType();
7367 if (VT != MVT::v8f16)
7368 return SDValue();
7369
7370 // We are looking for a buildvector of fptrunc elements, where all the
7371 // elements are interleavingly extracted from two sources. Check the first two
7372 // items are valid enough and extract some info from them (they are checked
7373 // properly in the loop below).
7374 if (BV.getOperand(i: 0).getOpcode() != ISD::FP_ROUND ||
7375 BV.getOperand(i: 0).getOperand(i: 0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7376 BV.getOperand(i: 0).getOperand(i: 0).getConstantOperandVal(i: 1) != 0)
7377 return SDValue();
7378 if (BV.getOperand(i: 1).getOpcode() != ISD::FP_ROUND ||
7379 BV.getOperand(i: 1).getOperand(i: 0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7380 BV.getOperand(i: 1).getOperand(i: 0).getConstantOperandVal(i: 1) != 0)
7381 return SDValue();
7382 SDValue Op0 = BV.getOperand(i: 0).getOperand(i: 0).getOperand(i: 0);
7383 SDValue Op1 = BV.getOperand(i: 1).getOperand(i: 0).getOperand(i: 0);
7384 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7385 return SDValue();
7386
7387 // Check all the values in the BuildVector line up with our expectations.
7388 for (unsigned i = 1; i < 4; i++) {
7389 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7390 return Trunc.getOpcode() == ISD::FP_ROUND &&
7391 Trunc.getOperand(i: 0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7392 Trunc.getOperand(i: 0).getOperand(i: 0) == Op &&
7393 Trunc.getOperand(i: 0).getConstantOperandVal(i: 1) == Idx;
7394 };
7395 if (!Check(BV.getOperand(i: i * 2 + 0), Op0, i))
7396 return SDValue();
7397 if (!Check(BV.getOperand(i: i * 2 + 1), Op1, i))
7398 return SDValue();
7399 }
7400
7401 SDValue N1 = DAG.getNode(Opcode: ARMISD::VCVTN, DL: dl, VT, N1: DAG.getUNDEF(VT), N2: Op0,
7402 N3: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
7403 return DAG.getNode(Opcode: ARMISD::VCVTN, DL: dl, VT, N1, N2: Op1,
7404 N3: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
7405}
7406
7407// Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7408// from a single input on alternating lanes. For example:
7409// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7410// FP_ROUND(EXTRACT_ELT(X, 2),
7411// FP_ROUND(EXTRACT_ELT(X, 4), ...)
7412static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG,
7413 const ARMSubtarget *ST) {
7414 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7415 if (!ST->hasMVEFloatOps())
7416 return SDValue();
7417
7418 SDLoc dl(BV);
7419 EVT VT = BV.getValueType();
7420 if (VT != MVT::v4f32)
7421 return SDValue();
7422
7423 // We are looking for a buildvector of fptext elements, where all the
7424 // elements are alternating lanes from a single source. For example <0,2,4,6>
7425 // or <1,3,5,7>. Check the first two items are valid enough and extract some
7426 // info from them (they are checked properly in the loop below).
7427 if (BV.getOperand(i: 0).getOpcode() != ISD::FP_EXTEND ||
7428 BV.getOperand(i: 0).getOperand(i: 0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7429 return SDValue();
7430 SDValue Op0 = BV.getOperand(i: 0).getOperand(i: 0).getOperand(i: 0);
7431 int Offset = BV.getOperand(i: 0).getOperand(i: 0).getConstantOperandVal(i: 1);
7432 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7433 return SDValue();
7434
7435 // Check all the values in the BuildVector line up with our expectations.
7436 for (unsigned i = 1; i < 4; i++) {
7437 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7438 return Trunc.getOpcode() == ISD::FP_EXTEND &&
7439 Trunc.getOperand(i: 0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7440 Trunc.getOperand(i: 0).getOperand(i: 0) == Op &&
7441 Trunc.getOperand(i: 0).getConstantOperandVal(i: 1) == Idx;
7442 };
7443 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7444 return SDValue();
7445 }
7446
7447 return DAG.getNode(Opcode: ARMISD::VCVTL, DL: dl, VT, N1: Op0,
7448 N2: DAG.getConstant(Val: Offset, DL: dl, VT: MVT::i32));
7449}
7450
7451// If N is an integer constant that can be moved into a register in one
7452// instruction, return an SDValue of such a constant (will become a MOV
7453// instruction). Otherwise return null.
7454static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7455 const ARMSubtarget *ST, const SDLoc &dl) {
7456 uint64_t Val;
7457 if (!isa<ConstantSDNode>(Val: N))
7458 return SDValue();
7459 Val = N->getAsZExtVal();
7460
7461 if (ST->isThumb1Only()) {
7462 if (Val <= 255 || ~Val <= 255)
7463 return DAG.getConstant(Val, DL: dl, VT: MVT::i32);
7464 } else {
7465 if (ARM_AM::getSOImmVal(Arg: Val) != -1 || ARM_AM::getSOImmVal(Arg: ~Val) != -1)
7466 return DAG.getConstant(Val, DL: dl, VT: MVT::i32);
7467 }
7468 return SDValue();
7469}
7470
7471static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7472 const ARMSubtarget *ST) {
7473 SDLoc dl(Op);
7474 EVT VT = Op.getValueType();
7475
7476 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7477
7478 unsigned NumElts = VT.getVectorNumElements();
7479 unsigned BoolMask;
7480 unsigned BitsPerBool;
7481 if (NumElts == 2) {
7482 BitsPerBool = 8;
7483 BoolMask = 0xff;
7484 } else if (NumElts == 4) {
7485 BitsPerBool = 4;
7486 BoolMask = 0xf;
7487 } else if (NumElts == 8) {
7488 BitsPerBool = 2;
7489 BoolMask = 0x3;
7490 } else if (NumElts == 16) {
7491 BitsPerBool = 1;
7492 BoolMask = 0x1;
7493 } else
7494 return SDValue();
7495
7496 // If this is a single value copied into all lanes (a splat), we can just sign
7497 // extend that single value
7498 SDValue FirstOp = Op.getOperand(i: 0);
7499 if (!isa<ConstantSDNode>(Val: FirstOp) &&
7500 llvm::all_of(Range: llvm::drop_begin(RangeOrContainer: Op->ops()), P: [&FirstOp](const SDUse &U) {
7501 return U.get().isUndef() || U.get() == FirstOp;
7502 })) {
7503 SDValue Ext = DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL: dl, VT: MVT::i32, N1: FirstOp,
7504 N2: DAG.getValueType(MVT::i1));
7505 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: Op.getValueType(), Operand: Ext);
7506 }
7507
7508 // First create base with bits set where known
7509 unsigned Bits32 = 0;
7510 for (unsigned i = 0; i < NumElts; ++i) {
7511 SDValue V = Op.getOperand(i);
7512 if (!isa<ConstantSDNode>(Val: V) && !V.isUndef())
7513 continue;
7514 bool BitSet = V.isUndef() ? false : V->getAsZExtVal();
7515 if (BitSet)
7516 Bits32 |= BoolMask << (i * BitsPerBool);
7517 }
7518
7519 // Add in unknown nodes
7520 SDValue Base = DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT,
7521 Operand: DAG.getConstant(Val: Bits32, DL: dl, VT: MVT::i32));
7522 for (unsigned i = 0; i < NumElts; ++i) {
7523 SDValue V = Op.getOperand(i);
7524 if (isa<ConstantSDNode>(Val: V) || V.isUndef())
7525 continue;
7526 Base = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT, N1: Base, N2: V,
7527 N3: DAG.getConstant(Val: i, DL: dl, VT: MVT::i32));
7528 }
7529
7530 return Base;
7531}
7532
7533static SDValue LowerBUILD_VECTORToVIDUP(SDValue Op, SelectionDAG &DAG,
7534 const ARMSubtarget *ST) {
7535 if (!ST->hasMVEIntegerOps())
7536 return SDValue();
7537
7538 // We are looking for a buildvector where each element is Op[0] + i*N
7539 EVT VT = Op.getValueType();
7540 SDValue Op0 = Op.getOperand(i: 0);
7541 unsigned NumElts = VT.getVectorNumElements();
7542
7543 // Get the increment value from operand 1
7544 SDValue Op1 = Op.getOperand(i: 1);
7545 if (Op1.getOpcode() != ISD::ADD || Op1.getOperand(i: 0) != Op0 ||
7546 !isa<ConstantSDNode>(Val: Op1.getOperand(i: 1)))
7547 return SDValue();
7548 unsigned N = Op1.getConstantOperandVal(i: 1);
7549 if (N != 1 && N != 2 && N != 4 && N != 8)
7550 return SDValue();
7551
7552 // Check that each other operand matches
7553 for (unsigned I = 2; I < NumElts; I++) {
7554 SDValue OpI = Op.getOperand(i: I);
7555 if (OpI.getOpcode() != ISD::ADD || OpI.getOperand(i: 0) != Op0 ||
7556 !isa<ConstantSDNode>(Val: OpI.getOperand(i: 1)) ||
7557 OpI.getConstantOperandVal(i: 1) != I * N)
7558 return SDValue();
7559 }
7560
7561 SDLoc DL(Op);
7562 return DAG.getNode(Opcode: ARMISD::VIDUP, DL, VTList: DAG.getVTList(VT1: VT, VT2: MVT::i32), N1: Op0,
7563 N2: DAG.getConstant(Val: N, DL, VT: MVT::i32));
7564}
7565
7566// Returns true if the operation N can be treated as qr instruction variant at
7567// operand Op.
7568static bool IsQRMVEInstruction(const SDNode *N, const SDNode *Op) {
7569 switch (N->getOpcode()) {
7570 case ISD::ADD:
7571 case ISD::MUL:
7572 case ISD::SADDSAT:
7573 case ISD::UADDSAT:
7574 case ISD::AVGFLOORS:
7575 case ISD::AVGFLOORU:
7576 return true;
7577 case ISD::SUB:
7578 case ISD::SSUBSAT:
7579 case ISD::USUBSAT:
7580 return N->getOperand(Num: 1).getNode() == Op;
7581 case ISD::INTRINSIC_WO_CHAIN:
7582 switch (N->getConstantOperandVal(Num: 0)) {
7583 case Intrinsic::arm_mve_add_predicated:
7584 case Intrinsic::arm_mve_mul_predicated:
7585 case Intrinsic::arm_mve_qadd_predicated:
7586 case Intrinsic::arm_mve_vhadd:
7587 case Intrinsic::arm_mve_hadd_predicated:
7588 case Intrinsic::arm_mve_vqdmulh:
7589 case Intrinsic::arm_mve_qdmulh_predicated:
7590 case Intrinsic::arm_mve_vqrdmulh:
7591 case Intrinsic::arm_mve_qrdmulh_predicated:
7592 case Intrinsic::arm_mve_vqdmull:
7593 case Intrinsic::arm_mve_vqdmull_predicated:
7594 return true;
7595 case Intrinsic::arm_mve_sub_predicated:
7596 case Intrinsic::arm_mve_qsub_predicated:
7597 case Intrinsic::arm_mve_vhsub:
7598 case Intrinsic::arm_mve_hsub_predicated:
7599 return N->getOperand(Num: 2).getNode() == Op;
7600 default:
7601 return false;
7602 }
7603 default:
7604 return false;
7605 }
7606}
7607
7608// If this is a case we can't handle, return null and let the default
7609// expansion code take care of it.
7610SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7611 const ARMSubtarget *ST) const {
7612 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Val: Op.getNode());
7613 SDLoc dl(Op);
7614 EVT VT = Op.getValueType();
7615
7616 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7617 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7618
7619 if (SDValue R = LowerBUILD_VECTORToVIDUP(Op, DAG, ST))
7620 return R;
7621
7622 APInt SplatBits, SplatUndef;
7623 unsigned SplatBitSize;
7624 bool HasAnyUndefs;
7625 if (BVN->isConstantSplat(SplatValue&: SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7626 if (SplatUndef.isAllOnes())
7627 return DAG.getUNDEF(VT);
7628
7629 // If all the users of this constant splat are qr instruction variants,
7630 // generate a vdup of the constant.
7631 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == SplatBitSize &&
7632 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32) &&
7633 all_of(Range: BVN->users(),
7634 P: [BVN](const SDNode *U) { return IsQRMVEInstruction(N: U, Op: BVN); })) {
7635 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7636 : SplatBitSize == 16 ? MVT::v8i16
7637 : MVT::v16i8;
7638 SDValue Const = DAG.getConstant(Val: SplatBits.getZExtValue(), DL: dl, VT: MVT::i32);
7639 SDValue VDup = DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT: DupVT, Operand: Const);
7640 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: VDup);
7641 }
7642
7643 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7644 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7645 // Check if an immediate VMOV works.
7646 EVT VmovVT;
7647 SDValue Val =
7648 isVMOVModifiedImm(SplatBits: SplatBits.getZExtValue(), SplatUndef: SplatUndef.getZExtValue(),
7649 SplatBitSize, DAG, dl, VT&: VmovVT, VectorVT: VT, type: VMOVModImm);
7650
7651 if (Val.getNode()) {
7652 SDValue Vmov = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: VmovVT, Operand: Val);
7653 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Vmov);
7654 }
7655
7656 // Try an immediate VMVN.
7657 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7658 Val = isVMOVModifiedImm(
7659 SplatBits: NegatedImm, SplatUndef: SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VT&: VmovVT,
7660 VectorVT: VT, type: ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7661 if (Val.getNode()) {
7662 SDValue Vmov = DAG.getNode(Opcode: ARMISD::VMVNIMM, DL: dl, VT: VmovVT, Operand: Val);
7663 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Vmov);
7664 }
7665
7666 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7667 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7668 int ImmVal = ARM_AM::getFP32Imm(Imm: SplatBits);
7669 if (ImmVal != -1) {
7670 SDValue Val = DAG.getTargetConstant(Val: ImmVal, DL: dl, VT: MVT::i32);
7671 return DAG.getNode(Opcode: ARMISD::VMOVFPIMM, DL: dl, VT, Operand: Val);
7672 }
7673 }
7674
7675 // If we are under MVE, generate a VDUP(constant), bitcast to the original
7676 // type.
7677 if (ST->hasMVEIntegerOps() &&
7678 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32)) {
7679 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7680 : SplatBitSize == 16 ? MVT::v8i16
7681 : MVT::v16i8;
7682 SDValue Const = DAG.getConstant(Val: SplatBits.getZExtValue(), DL: dl, VT: MVT::i32);
7683 SDValue VDup = DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT: DupVT, Operand: Const);
7684 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: VDup);
7685 }
7686 }
7687 }
7688
7689 // Scan through the operands to see if only one value is used.
7690 //
7691 // As an optimisation, even if more than one value is used it may be more
7692 // profitable to splat with one value then change some lanes.
7693 //
7694 // Heuristically we decide to do this if the vector has a "dominant" value,
7695 // defined as splatted to more than half of the lanes.
7696 unsigned NumElts = VT.getVectorNumElements();
7697 bool isOnlyLowElement = true;
7698 bool usesOnlyOneValue = true;
7699 bool hasDominantValue = false;
7700 bool isConstant = true;
7701
7702 // Map of the number of times a particular SDValue appears in the
7703 // element list.
7704 DenseMap<SDValue, unsigned> ValueCounts;
7705 SDValue Value;
7706 for (unsigned i = 0; i < NumElts; ++i) {
7707 SDValue V = Op.getOperand(i);
7708 if (V.isUndef())
7709 continue;
7710 if (i > 0)
7711 isOnlyLowElement = false;
7712 if (!isa<ConstantFPSDNode>(Val: V) && !isa<ConstantSDNode>(Val: V))
7713 isConstant = false;
7714
7715 unsigned &Count = ValueCounts[V];
7716
7717 // Is this value dominant? (takes up more than half of the lanes)
7718 if (++Count > (NumElts / 2)) {
7719 hasDominantValue = true;
7720 Value = V;
7721 }
7722 }
7723 if (ValueCounts.size() != 1)
7724 usesOnlyOneValue = false;
7725 if (!Value.getNode() && !ValueCounts.empty())
7726 Value = ValueCounts.begin()->first;
7727
7728 if (ValueCounts.empty())
7729 return DAG.getUNDEF(VT);
7730
7731 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7732 // Keep going if we are hitting this case.
7733 if (isOnlyLowElement && !ISD::isNormalLoad(N: Value.getNode()))
7734 return DAG.getNode(Opcode: ISD::SCALAR_TO_VECTOR, DL: dl, VT, Operand: Value);
7735
7736 unsigned EltSize = VT.getScalarSizeInBits();
7737
7738 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7739 // i32 and try again.
7740 if (hasDominantValue && EltSize <= 32) {
7741 if (!isConstant) {
7742 SDValue N;
7743
7744 // If we are VDUPing a value that comes directly from a vector, that will
7745 // cause an unnecessary move to and from a GPR, where instead we could
7746 // just use VDUPLANE. We can only do this if the lane being extracted
7747 // is at a constant index, as the VDUP from lane instructions only have
7748 // constant-index forms.
7749 ConstantSDNode *constIndex;
7750 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7751 (constIndex = dyn_cast<ConstantSDNode>(Val: Value->getOperand(Num: 1)))) {
7752 // We need to create a new undef vector to use for the VDUPLANE if the
7753 // size of the vector from which we get the value is different than the
7754 // size of the vector that we need to create. We will insert the element
7755 // such that the register coalescer will remove unnecessary copies.
7756 if (VT != Value->getOperand(Num: 0).getValueType()) {
7757 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7758 VT.getVectorNumElements();
7759 N = DAG.getNode(Opcode: ARMISD::VDUPLANE, DL: dl, VT,
7760 N1: DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT, N1: DAG.getUNDEF(VT),
7761 N2: Value, N3: DAG.getConstant(Val: index, DL: dl, VT: MVT::i32)),
7762 N2: DAG.getConstant(Val: index, DL: dl, VT: MVT::i32));
7763 } else
7764 N = DAG.getNode(Opcode: ARMISD::VDUPLANE, DL: dl, VT,
7765 N1: Value->getOperand(Num: 0), N2: Value->getOperand(Num: 1));
7766 } else
7767 N = DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT, Operand: Value);
7768
7769 if (!usesOnlyOneValue) {
7770 // The dominant value was splatted as 'N', but we now have to insert
7771 // all differing elements.
7772 for (unsigned I = 0; I < NumElts; ++I) {
7773 if (Op.getOperand(i: I) == Value)
7774 continue;
7775 SmallVector<SDValue, 3> Ops;
7776 Ops.push_back(Elt: N);
7777 Ops.push_back(Elt: Op.getOperand(i: I));
7778 Ops.push_back(Elt: DAG.getConstant(Val: I, DL: dl, VT: MVT::i32));
7779 N = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT, Ops);
7780 }
7781 }
7782 return N;
7783 }
7784 if (VT.getVectorElementType().isFloatingPoint()) {
7785 SmallVector<SDValue, 8> Ops;
7786 MVT FVT = VT.getVectorElementType().getSimpleVT();
7787 assert(FVT == MVT::f32 || FVT == MVT::f16);
7788 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7789 for (unsigned i = 0; i < NumElts; ++i)
7790 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: IVT,
7791 Operand: Op.getOperand(i)));
7792 EVT VecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: IVT, NumElements: NumElts);
7793 SDValue Val = DAG.getBuildVector(VT: VecVT, DL: dl, Ops);
7794 Val = LowerBUILD_VECTOR(Op: Val, DAG, ST);
7795 if (Val.getNode())
7796 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Val);
7797 }
7798 if (usesOnlyOneValue) {
7799 SDValue Val = IsSingleInstrConstant(N: Value, DAG, ST, dl);
7800 if (isConstant && Val.getNode())
7801 return DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT, Operand: Val);
7802 }
7803 }
7804
7805 // If all elements are constants and the case above didn't get hit, fall back
7806 // to the default expansion, which will generate a load from the constant
7807 // pool.
7808 if (isConstant)
7809 return SDValue();
7810
7811 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7812 // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7813 // length <= 2.
7814 if (NumElts >= 4)
7815 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7816 return shuffle;
7817
7818 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7819 // VCVT's
7820 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(BV: Op, DAG, ST: Subtarget))
7821 return VCVT;
7822 if (SDValue VCVT = LowerBuildVectorOfFPExt(BV: Op, DAG, ST: Subtarget))
7823 return VCVT;
7824
7825 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7826 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7827 // into two 64-bit vectors; we might discover a better way to lower it.
7828 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7829 EVT ExtVT = VT.getVectorElementType();
7830 EVT HVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: ExtVT, NumElements: NumElts / 2);
7831 SDValue Lower = DAG.getBuildVector(VT: HVT, DL: dl, Ops: ArrayRef(&Ops[0], NumElts / 2));
7832 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7833 Lower = LowerBUILD_VECTOR(Op: Lower, DAG, ST);
7834 SDValue Upper =
7835 DAG.getBuildVector(VT: HVT, DL: dl, Ops: ArrayRef(&Ops[NumElts / 2], NumElts / 2));
7836 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7837 Upper = LowerBUILD_VECTOR(Op: Upper, DAG, ST);
7838 if (Lower && Upper)
7839 return DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: dl, VT, N1: Lower, N2: Upper);
7840 }
7841
7842 // Vectors with 32- or 64-bit elements can be built by directly assigning
7843 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7844 // will be legalized.
7845 if (EltSize >= 32) {
7846 // Do the expansion with floating-point types, since that is what the VFP
7847 // registers are defined to use, and since i64 is not legal.
7848 EVT EltVT = EVT::getFloatingPointVT(BitWidth: EltSize);
7849 EVT VecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: EltVT, NumElements: NumElts);
7850 SmallVector<SDValue, 8> Ops;
7851 for (unsigned i = 0; i < NumElts; ++i)
7852 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: EltVT, Operand: Op.getOperand(i)));
7853 SDValue Val = DAG.getNode(Opcode: ARMISD::BUILD_VECTOR, DL: dl, VT: VecVT, Ops);
7854 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Val);
7855 }
7856
7857 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7858 // know the default expansion would otherwise fall back on something even
7859 // worse. For a vector with one or two non-undef values, that's
7860 // scalar_to_vector for the elements followed by a shuffle (provided the
7861 // shuffle is valid for the target) and materialization element by element
7862 // on the stack followed by a load for everything else.
7863 if (!isConstant && !usesOnlyOneValue) {
7864 SDValue Vec = DAG.getUNDEF(VT);
7865 for (unsigned i = 0 ; i < NumElts; ++i) {
7866 SDValue V = Op.getOperand(i);
7867 if (V.isUndef())
7868 continue;
7869 SDValue LaneIdx = DAG.getConstant(Val: i, DL: dl, VT: MVT::i32);
7870 Vec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT, N1: Vec, N2: V, N3: LaneIdx);
7871 }
7872 return Vec;
7873 }
7874
7875 return SDValue();
7876}
7877
7878// Gather data to see if the operation can be modelled as a
7879// shuffle in combination with VEXTs.
7880SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7881 SelectionDAG &DAG) const {
7882 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7883 SDLoc dl(Op);
7884 EVT VT = Op.getValueType();
7885 unsigned NumElts = VT.getVectorNumElements();
7886
7887 struct ShuffleSourceInfo {
7888 SDValue Vec;
7889 unsigned MinElt = std::numeric_limits<unsigned>::max();
7890 unsigned MaxElt = 0;
7891
7892 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7893 // be compatible with the shuffle we intend to construct. As a result
7894 // ShuffleVec will be some sliding window into the original Vec.
7895 SDValue ShuffleVec;
7896
7897 // Code should guarantee that element i in Vec starts at element "WindowBase
7898 // + i * WindowScale in ShuffleVec".
7899 int WindowBase = 0;
7900 int WindowScale = 1;
7901
7902 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7903
7904 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7905 };
7906
7907 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7908 // node.
7909 SmallVector<ShuffleSourceInfo, 2> Sources;
7910 for (unsigned i = 0; i < NumElts; ++i) {
7911 SDValue V = Op.getOperand(i);
7912 if (V.isUndef())
7913 continue;
7914 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7915 // A shuffle can only come from building a vector from various
7916 // elements of other vectors.
7917 return SDValue();
7918 } else if (!isa<ConstantSDNode>(Val: V.getOperand(i: 1))) {
7919 // Furthermore, shuffles require a constant mask, whereas extractelts
7920 // accept variable indices.
7921 return SDValue();
7922 }
7923
7924 // Add this element source to the list if it's not already there.
7925 SDValue SourceVec = V.getOperand(i: 0);
7926 auto Source = llvm::find(Range&: Sources, Val: SourceVec);
7927 if (Source == Sources.end())
7928 Source = Sources.insert(I: Sources.end(), Elt: ShuffleSourceInfo(SourceVec));
7929
7930 // Update the minimum and maximum lane number seen.
7931 unsigned EltNo = V.getConstantOperandVal(i: 1);
7932 Source->MinElt = std::min(a: Source->MinElt, b: EltNo);
7933 Source->MaxElt = std::max(a: Source->MaxElt, b: EltNo);
7934 }
7935
7936 // Currently only do something sane when at most two source vectors
7937 // are involved.
7938 if (Sources.size() > 2)
7939 return SDValue();
7940
7941 // Find out the smallest element size among result and two sources, and use
7942 // it as element size to build the shuffle_vector.
7943 EVT SmallestEltTy = VT.getVectorElementType();
7944 for (auto &Source : Sources) {
7945 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7946 if (SrcEltTy.bitsLT(VT: SmallestEltTy))
7947 SmallestEltTy = SrcEltTy;
7948 }
7949 unsigned ResMultiplier =
7950 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7951 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7952 EVT ShuffleVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: SmallestEltTy, NumElements: NumElts);
7953
7954 // If the source vector is too wide or too narrow, we may nevertheless be able
7955 // to construct a compatible shuffle either by concatenating it with UNDEF or
7956 // extracting a suitable range of elements.
7957 for (auto &Src : Sources) {
7958 EVT SrcVT = Src.ShuffleVec.getValueType();
7959
7960 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
7961 uint64_t VTSize = VT.getFixedSizeInBits();
7962 if (SrcVTSize == VTSize)
7963 continue;
7964
7965 // This stage of the search produces a source with the same element type as
7966 // the original, but with a total width matching the BUILD_VECTOR output.
7967 EVT EltVT = SrcVT.getVectorElementType();
7968 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
7969 EVT DestVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: EltVT, NumElements: NumSrcElts);
7970
7971 if (SrcVTSize < VTSize) {
7972 if (2 * SrcVTSize != VTSize)
7973 return SDValue();
7974 // We can pad out the smaller vector for free, so if it's part of a
7975 // shuffle...
7976 Src.ShuffleVec =
7977 DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: dl, VT: DestVT, N1: Src.ShuffleVec,
7978 N2: DAG.getUNDEF(VT: Src.ShuffleVec.getValueType()));
7979 continue;
7980 }
7981
7982 if (SrcVTSize != 2 * VTSize)
7983 return SDValue();
7984
7985 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7986 // Span too large for a VEXT to cope
7987 return SDValue();
7988 }
7989
7990 if (Src.MinElt >= NumSrcElts) {
7991 // The extraction can just take the second half
7992 Src.ShuffleVec =
7993 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: DestVT, N1: Src.ShuffleVec,
7994 N2: DAG.getConstant(Val: NumSrcElts, DL: dl, VT: MVT::i32));
7995 Src.WindowBase = -NumSrcElts;
7996 } else if (Src.MaxElt < NumSrcElts) {
7997 // The extraction can just take the first half
7998 Src.ShuffleVec =
7999 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: DestVT, N1: Src.ShuffleVec,
8000 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
8001 } else {
8002 // An actual VEXT is needed
8003 SDValue VEXTSrc1 =
8004 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: DestVT, N1: Src.ShuffleVec,
8005 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
8006 SDValue VEXTSrc2 =
8007 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: DestVT, N1: Src.ShuffleVec,
8008 N2: DAG.getConstant(Val: NumSrcElts, DL: dl, VT: MVT::i32));
8009
8010 Src.ShuffleVec = DAG.getNode(Opcode: ARMISD::VEXT, DL: dl, VT: DestVT, N1: VEXTSrc1,
8011 N2: VEXTSrc2,
8012 N3: DAG.getConstant(Val: Src.MinElt, DL: dl, VT: MVT::i32));
8013 Src.WindowBase = -Src.MinElt;
8014 }
8015 }
8016
8017 // Another possible incompatibility occurs from the vector element types. We
8018 // can fix this by bitcasting the source vectors to the same type we intend
8019 // for the shuffle.
8020 for (auto &Src : Sources) {
8021 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8022 if (SrcEltTy == SmallestEltTy)
8023 continue;
8024 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
8025 Src.ShuffleVec = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: ShuffleVT, Operand: Src.ShuffleVec);
8026 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
8027 Src.WindowBase *= Src.WindowScale;
8028 }
8029
8030 // Final check before we try to actually produce a shuffle.
8031 LLVM_DEBUG({
8032 for (auto Src : Sources)
8033 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
8034 });
8035
8036 // The stars all align, our next step is to produce the mask for the shuffle.
8037 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8038 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8039 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8040 SDValue Entry = Op.getOperand(i);
8041 if (Entry.isUndef())
8042 continue;
8043
8044 auto Src = llvm::find(Range&: Sources, Val: Entry.getOperand(i: 0));
8045 int EltNo = cast<ConstantSDNode>(Val: Entry.getOperand(i: 1))->getSExtValue();
8046
8047 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8048 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8049 // segment.
8050 EVT OrigEltTy = Entry.getOperand(i: 0).getValueType().getVectorElementType();
8051 int BitsDefined = std::min(a: OrigEltTy.getScalarSizeInBits(),
8052 b: VT.getScalarSizeInBits());
8053 int LanesDefined = BitsDefined / BitsPerShuffleLane;
8054
8055 // This source is expected to fill ResMultiplier lanes of the final shuffle,
8056 // starting at the appropriate offset.
8057 int *LaneMask = &Mask[i * ResMultiplier];
8058
8059 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8060 ExtractBase += NumElts * (Src - Sources.begin());
8061 for (int j = 0; j < LanesDefined; ++j)
8062 LaneMask[j] = ExtractBase + j;
8063 }
8064
8065
8066 // We can't handle more than two sources. This should have already
8067 // been checked before this point.
8068 assert(Sources.size() <= 2 && "Too many sources!");
8069
8070 SDValue ShuffleOps[] = { DAG.getUNDEF(VT: ShuffleVT), DAG.getUNDEF(VT: ShuffleVT) };
8071 for (unsigned i = 0; i < Sources.size(); ++i)
8072 ShuffleOps[i] = Sources[i].ShuffleVec;
8073
8074 SDValue Shuffle = buildLegalVectorShuffle(VT: ShuffleVT, DL: dl, N0: ShuffleOps[0],
8075 N1: ShuffleOps[1], Mask, DAG);
8076 if (!Shuffle)
8077 return SDValue();
8078 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Shuffle);
8079}
8080
8081enum ShuffleOpCodes {
8082 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8083 OP_VREV,
8084 OP_VDUP0,
8085 OP_VDUP1,
8086 OP_VDUP2,
8087 OP_VDUP3,
8088 OP_VEXT1,
8089 OP_VEXT2,
8090 OP_VEXT3,
8091 OP_VUZPL, // VUZP, left result
8092 OP_VUZPR, // VUZP, right result
8093 OP_VZIPL, // VZIP, left result
8094 OP_VZIPR, // VZIP, right result
8095 OP_VTRNL, // VTRN, left result
8096 OP_VTRNR // VTRN, right result
8097};
8098
8099static bool isLegalMVEShuffleOp(unsigned PFEntry) {
8100 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8101 switch (OpNum) {
8102 case OP_COPY:
8103 case OP_VREV:
8104 case OP_VDUP0:
8105 case OP_VDUP1:
8106 case OP_VDUP2:
8107 case OP_VDUP3:
8108 return true;
8109 }
8110 return false;
8111}
8112
8113/// isShuffleMaskLegal - Targets can use this to indicate that they only
8114/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8115/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8116/// are assumed to be legal.
8117bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8118 if (VT.getVectorNumElements() == 4 &&
8119 (VT.is128BitVector() || VT.is64BitVector())) {
8120 unsigned PFIndexes[4];
8121 for (unsigned i = 0; i != 4; ++i) {
8122 if (M[i] < 0)
8123 PFIndexes[i] = 8;
8124 else
8125 PFIndexes[i] = M[i];
8126 }
8127
8128 // Compute the index in the perfect shuffle table.
8129 unsigned PFTableIndex =
8130 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8131 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8132 unsigned Cost = (PFEntry >> 30);
8133
8134 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
8135 return true;
8136 }
8137
8138 bool ReverseVEXT, isV_UNDEF;
8139 unsigned Imm, WhichResult;
8140
8141 unsigned EltSize = VT.getScalarSizeInBits();
8142 if (EltSize >= 32 ||
8143 ShuffleVectorSDNode::isSplatMask(Mask: M) ||
8144 ShuffleVectorInst::isIdentityMask(Mask: M, NumSrcElts: M.size()) ||
8145 isVREVMask(M, VT, BlockSize: 64) ||
8146 isVREVMask(M, VT, BlockSize: 32) ||
8147 isVREVMask(M, VT, BlockSize: 16))
8148 return true;
8149 else if (Subtarget->hasNEON() &&
8150 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
8151 isVTBLMask(M, VT) ||
8152 isNEONTwoResultShuffleMask(ShuffleMask: M, VT, WhichResult, isV_UNDEF)))
8153 return true;
8154 else if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8155 isReverseMask(M, VT))
8156 return true;
8157 else if (Subtarget->hasMVEIntegerOps() &&
8158 (isVMOVNMask(M, VT, Top: true, SingleSource: false) ||
8159 isVMOVNMask(M, VT, Top: false, SingleSource: false) || isVMOVNMask(M, VT, Top: true, SingleSource: true)))
8160 return true;
8161 else if (Subtarget->hasMVEIntegerOps() &&
8162 (isTruncMask(M, VT, Top: false, SingleSource: false) ||
8163 isTruncMask(M, VT, Top: false, SingleSource: true) ||
8164 isTruncMask(M, VT, Top: true, SingleSource: false) || isTruncMask(M, VT, Top: true, SingleSource: true)))
8165 return true;
8166 else
8167 return false;
8168}
8169
8170/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8171/// the specified operations to build the shuffle.
8172static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8173 SDValue RHS, SelectionDAG &DAG,
8174 const SDLoc &dl) {
8175 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8176 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8177 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8178
8179 if (OpNum == OP_COPY) {
8180 if (LHSID == (1*9+2)*9+3) return LHS;
8181 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8182 return RHS;
8183 }
8184
8185 SDValue OpLHS, OpRHS;
8186 OpLHS = GeneratePerfectShuffle(PFEntry: PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8187 OpRHS = GeneratePerfectShuffle(PFEntry: PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8188 EVT VT = OpLHS.getValueType();
8189
8190 switch (OpNum) {
8191 default: llvm_unreachable("Unknown shuffle opcode!");
8192 case OP_VREV:
8193 // VREV divides the vector in half and swaps within the half.
8194 if (VT.getScalarSizeInBits() == 32)
8195 return DAG.getNode(Opcode: ARMISD::VREV64, DL: dl, VT, Operand: OpLHS);
8196 // vrev <4 x i16> -> VREV32
8197 if (VT.getScalarSizeInBits() == 16)
8198 return DAG.getNode(Opcode: ARMISD::VREV32, DL: dl, VT, Operand: OpLHS);
8199 // vrev <4 x i8> -> VREV16
8200 assert(VT.getScalarSizeInBits() == 8);
8201 return DAG.getNode(Opcode: ARMISD::VREV16, DL: dl, VT, Operand: OpLHS);
8202 case OP_VDUP0:
8203 case OP_VDUP1:
8204 case OP_VDUP2:
8205 case OP_VDUP3:
8206 return DAG.getNode(Opcode: ARMISD::VDUPLANE, DL: dl, VT,
8207 N1: OpLHS, N2: DAG.getConstant(Val: OpNum-OP_VDUP0, DL: dl, VT: MVT::i32));
8208 case OP_VEXT1:
8209 case OP_VEXT2:
8210 case OP_VEXT3:
8211 return DAG.getNode(Opcode: ARMISD::VEXT, DL: dl, VT,
8212 N1: OpLHS, N2: OpRHS,
8213 N3: DAG.getConstant(Val: OpNum - OP_VEXT1 + 1, DL: dl, VT: MVT::i32));
8214 case OP_VUZPL:
8215 case OP_VUZPR:
8216 return DAG.getNode(Opcode: ARMISD::VUZP, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT),
8217 N1: OpLHS, N2: OpRHS).getValue(R: OpNum-OP_VUZPL);
8218 case OP_VZIPL:
8219 case OP_VZIPR:
8220 return DAG.getNode(Opcode: ARMISD::VZIP, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT),
8221 N1: OpLHS, N2: OpRHS).getValue(R: OpNum-OP_VZIPL);
8222 case OP_VTRNL:
8223 case OP_VTRNR:
8224 return DAG.getNode(Opcode: ARMISD::VTRN, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT),
8225 N1: OpLHS, N2: OpRHS).getValue(R: OpNum-OP_VTRNL);
8226 }
8227}
8228
8229static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
8230 ArrayRef<int> ShuffleMask,
8231 SelectionDAG &DAG) {
8232 // Check to see if we can use the VTBL instruction.
8233 SDValue V1 = Op.getOperand(i: 0);
8234 SDValue V2 = Op.getOperand(i: 1);
8235 SDLoc DL(Op);
8236
8237 SmallVector<SDValue, 8> VTBLMask;
8238 for (int I : ShuffleMask)
8239 VTBLMask.push_back(Elt: DAG.getSignedConstant(Val: I, DL, VT: MVT::i32));
8240
8241 if (V2.getNode()->isUndef())
8242 return DAG.getNode(Opcode: ARMISD::VTBL1, DL, VT: MVT::v8i8, N1: V1,
8243 N2: DAG.getBuildVector(VT: MVT::v8i8, DL, Ops: VTBLMask));
8244
8245 return DAG.getNode(Opcode: ARMISD::VTBL2, DL, VT: MVT::v8i8, N1: V1, N2: V2,
8246 N3: DAG.getBuildVector(VT: MVT::v8i8, DL, Ops: VTBLMask));
8247}
8248
8249static SDValue LowerReverse_VECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
8250 SDLoc DL(Op);
8251 EVT VT = Op.getValueType();
8252
8253 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8254 "Expect an v8i16/v16i8 type");
8255 SDValue OpLHS = DAG.getNode(Opcode: ARMISD::VREV64, DL, VT, Operand: Op.getOperand(i: 0));
8256 // For a v16i8 type: After the VREV, we have got <7, ..., 0, 15, ..., 8>. Now,
8257 // extract the first 8 bytes into the top double word and the last 8 bytes
8258 // into the bottom double word, through a new vector shuffle that will be
8259 // turned into a VEXT on Neon, or a couple of VMOVDs on MVE.
8260 std::vector<int> NewMask;
8261 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8262 NewMask.push_back(x: VT.getVectorNumElements() / 2 + i);
8263 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8264 NewMask.push_back(x: i);
8265 return DAG.getVectorShuffle(VT, dl: DL, N1: OpLHS, N2: OpLHS, Mask: NewMask);
8266}
8267
8268static EVT getVectorTyFromPredicateVector(EVT VT) {
8269 switch (VT.getSimpleVT().SimpleTy) {
8270 case MVT::v2i1:
8271 return MVT::v2f64;
8272 case MVT::v4i1:
8273 return MVT::v4i32;
8274 case MVT::v8i1:
8275 return MVT::v8i16;
8276 case MVT::v16i1:
8277 return MVT::v16i8;
8278 default:
8279 llvm_unreachable("Unexpected vector predicate type");
8280 }
8281}
8282
8283static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
8284 SelectionDAG &DAG) {
8285 // Converting from boolean predicates to integers involves creating a vector
8286 // of all ones or all zeroes and selecting the lanes based upon the real
8287 // predicate.
8288 SDValue AllOnes =
8289 DAG.getTargetConstant(Val: ARM_AM::createVMOVModImm(OpCmode: 0xe, Val: 0xff), DL: dl, VT: MVT::i32);
8290 AllOnes = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: MVT::v16i8, Operand: AllOnes);
8291
8292 SDValue AllZeroes =
8293 DAG.getTargetConstant(Val: ARM_AM::createVMOVModImm(OpCmode: 0xe, Val: 0x0), DL: dl, VT: MVT::i32);
8294 AllZeroes = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT: MVT::v16i8, Operand: AllZeroes);
8295
8296 // Get full vector type from predicate type
8297 EVT NewVT = getVectorTyFromPredicateVector(VT);
8298
8299 SDValue RecastV1;
8300 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8301 // this to a v16i1. This cannot be done with an ordinary bitcast because the
8302 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8303 // since we know in hardware the sizes are really the same.
8304 if (VT != MVT::v16i1)
8305 RecastV1 = DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::v16i1, Operand: Pred);
8306 else
8307 RecastV1 = Pred;
8308
8309 // Select either all ones or zeroes depending upon the real predicate bits.
8310 SDValue PredAsVector =
8311 DAG.getNode(Opcode: ISD::VSELECT, DL: dl, VT: MVT::v16i8, N1: RecastV1, N2: AllOnes, N3: AllZeroes);
8312
8313 // Recast our new predicate-as-integer v16i8 vector into something
8314 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8315 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: NewVT, Operand: PredAsVector);
8316}
8317
8318static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
8319 const ARMSubtarget *ST) {
8320 EVT VT = Op.getValueType();
8321 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Val: Op.getNode());
8322 ArrayRef<int> ShuffleMask = SVN->getMask();
8323
8324 assert(ST->hasMVEIntegerOps() &&
8325 "No support for vector shuffle of boolean predicates");
8326
8327 SDValue V1 = Op.getOperand(i: 0);
8328 SDValue V2 = Op.getOperand(i: 1);
8329 SDLoc dl(Op);
8330 if (isReverseMask(M: ShuffleMask, VT)) {
8331 SDValue cast = DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::i32, Operand: V1);
8332 SDValue rbit = DAG.getNode(Opcode: ISD::BITREVERSE, DL: dl, VT: MVT::i32, Operand: cast);
8333 SDValue srl = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32, N1: rbit,
8334 N2: DAG.getConstant(Val: 16, DL: dl, VT: MVT::i32));
8335 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT, Operand: srl);
8336 }
8337
8338 // Until we can come up with optimised cases for every single vector
8339 // shuffle in existence we have chosen the least painful strategy. This is
8340 // to essentially promote the boolean predicate to a 8-bit integer, where
8341 // each predicate represents a byte. Then we fall back on a normal integer
8342 // vector shuffle and convert the result back into a predicate vector. In
8343 // many cases the generated code might be even better than scalar code
8344 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8345 // fields in a register into 8 other arbitrary 2-bit fields!
8346 SDValue PredAsVector1 = PromoteMVEPredVector(dl, Pred: V1, VT, DAG);
8347 EVT NewVT = PredAsVector1.getValueType();
8348 SDValue PredAsVector2 = V2.isUndef() ? DAG.getUNDEF(VT: NewVT)
8349 : PromoteMVEPredVector(dl, Pred: V2, VT, DAG);
8350 assert(PredAsVector2.getValueType() == NewVT &&
8351 "Expected identical vector type in expanded i1 shuffle!");
8352
8353 // Do the shuffle!
8354 SDValue Shuffled = DAG.getVectorShuffle(VT: NewVT, dl, N1: PredAsVector1,
8355 N2: PredAsVector2, Mask: ShuffleMask);
8356
8357 // Now return the result of comparing the shuffled vector with zero,
8358 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. For a v2i1
8359 // we convert to a v4i1 compare to fill in the two halves of the i64 as i32s.
8360 if (VT == MVT::v2i1) {
8361 SDValue BC = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: Shuffled);
8362 SDValue Cmp = DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT: MVT::v4i1, N1: BC,
8363 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8364 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::v2i1, Operand: Cmp);
8365 }
8366 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: Shuffled,
8367 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8368}
8369
8370static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
8371 ArrayRef<int> ShuffleMask,
8372 SelectionDAG &DAG) {
8373 // Attempt to lower the vector shuffle using as many whole register movs as
8374 // possible. This is useful for types smaller than 32bits, which would
8375 // often otherwise become a series for grp movs.
8376 SDLoc dl(Op);
8377 EVT VT = Op.getValueType();
8378 if (VT.getScalarSizeInBits() >= 32)
8379 return SDValue();
8380
8381 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8382 "Unexpected vector type");
8383 int NumElts = VT.getVectorNumElements();
8384 int QuarterSize = NumElts / 4;
8385 // The four final parts of the vector, as i32's
8386 SDValue Parts[4];
8387
8388 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8389 // <u,u,u,u>), returning the vmov lane index
8390 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8391 // Detect which mov lane this would be from the first non-undef element.
8392 int MovIdx = -1;
8393 for (int i = 0; i < Length; i++) {
8394 if (ShuffleMask[Start + i] >= 0) {
8395 if (ShuffleMask[Start + i] % Length != i)
8396 return -1;
8397 MovIdx = ShuffleMask[Start + i] / Length;
8398 break;
8399 }
8400 }
8401 // If all items are undef, leave this for other combines
8402 if (MovIdx == -1)
8403 return -1;
8404 // Check the remaining values are the correct part of the same mov
8405 for (int i = 1; i < Length; i++) {
8406 if (ShuffleMask[Start + i] >= 0 &&
8407 (ShuffleMask[Start + i] / Length != MovIdx ||
8408 ShuffleMask[Start + i] % Length != i))
8409 return -1;
8410 }
8411 return MovIdx;
8412 };
8413
8414 for (int Part = 0; Part < 4; ++Part) {
8415 // Does this part look like a mov
8416 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8417 if (Elt != -1) {
8418 SDValue Input = Op->getOperand(Num: 0);
8419 if (Elt >= 4) {
8420 Input = Op->getOperand(Num: 1);
8421 Elt -= 4;
8422 }
8423 SDValue BitCast = DAG.getBitcast(VT: MVT::v4f32, V: Input);
8424 Parts[Part] = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f32, N1: BitCast,
8425 N2: DAG.getConstant(Val: Elt, DL: dl, VT: MVT::i32));
8426 }
8427 }
8428
8429 // Nothing interesting found, just return
8430 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8431 return SDValue();
8432
8433 // The other parts need to be built with the old shuffle vector, cast to a
8434 // v4i32 and extract_vector_elts
8435 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8436 SmallVector<int, 16> NewShuffleMask;
8437 for (int Part = 0; Part < 4; ++Part)
8438 for (int i = 0; i < QuarterSize; i++)
8439 NewShuffleMask.push_back(
8440 Elt: Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8441 SDValue NewShuffle = DAG.getVectorShuffle(
8442 VT, dl, N1: Op->getOperand(Num: 0), N2: Op->getOperand(Num: 1), Mask: NewShuffleMask);
8443 SDValue BitCast = DAG.getBitcast(VT: MVT::v4f32, V: NewShuffle);
8444
8445 for (int Part = 0; Part < 4; ++Part)
8446 if (!Parts[Part])
8447 Parts[Part] = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f32,
8448 N1: BitCast, N2: DAG.getConstant(Val: Part, DL: dl, VT: MVT::i32));
8449 }
8450 // Build a vector out of the various parts and bitcast it back to the original
8451 // type.
8452 SDValue NewVec = DAG.getNode(Opcode: ARMISD::BUILD_VECTOR, DL: dl, VT: MVT::v4f32, Ops: Parts);
8453 return DAG.getBitcast(VT, V: NewVec);
8454}
8455
8456static SDValue LowerVECTOR_SHUFFLEUsingOneOff(SDValue Op,
8457 ArrayRef<int> ShuffleMask,
8458 SelectionDAG &DAG) {
8459 SDValue V1 = Op.getOperand(i: 0);
8460 SDValue V2 = Op.getOperand(i: 1);
8461 EVT VT = Op.getValueType();
8462 unsigned NumElts = VT.getVectorNumElements();
8463
8464 // An One-Off Identity mask is one that is mostly an identity mask from as
8465 // single source but contains a single element out-of-place, either from a
8466 // different vector or from another position in the same vector. As opposed to
8467 // lowering this via a ARMISD::BUILD_VECTOR we can generate an extract/insert
8468 // pair directly.
8469 auto isOneOffIdentityMask = [](ArrayRef<int> Mask, EVT VT, int BaseOffset,
8470 int &OffElement) {
8471 OffElement = -1;
8472 int NonUndef = 0;
8473 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
8474 if (Mask[i] == -1)
8475 continue;
8476 NonUndef++;
8477 if (Mask[i] != i + BaseOffset) {
8478 if (OffElement == -1)
8479 OffElement = i;
8480 else
8481 return false;
8482 }
8483 }
8484 return NonUndef > 2 && OffElement != -1;
8485 };
8486 int OffElement;
8487 SDValue VInput;
8488 if (isOneOffIdentityMask(ShuffleMask, VT, 0, OffElement))
8489 VInput = V1;
8490 else if (isOneOffIdentityMask(ShuffleMask, VT, NumElts, OffElement))
8491 VInput = V2;
8492 else
8493 return SDValue();
8494
8495 SDLoc dl(Op);
8496 EVT SVT = VT.getScalarType() == MVT::i8 || VT.getScalarType() == MVT::i16
8497 ? MVT::i32
8498 : VT.getScalarType();
8499 SDValue Elt = DAG.getNode(
8500 Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: SVT,
8501 N1: ShuffleMask[OffElement] < (int)NumElts ? V1 : V2,
8502 N2: DAG.getVectorIdxConstant(Val: ShuffleMask[OffElement] % NumElts, DL: dl));
8503 return DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT, N1: VInput, N2: Elt,
8504 N3: DAG.getVectorIdxConstant(Val: OffElement % NumElts, DL: dl));
8505}
8506
8507static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
8508 const ARMSubtarget *ST) {
8509 SDValue V1 = Op.getOperand(i: 0);
8510 SDValue V2 = Op.getOperand(i: 1);
8511 SDLoc dl(Op);
8512 EVT VT = Op.getValueType();
8513 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Val: Op.getNode());
8514 unsigned EltSize = VT.getScalarSizeInBits();
8515
8516 if (ST->hasMVEIntegerOps() && EltSize == 1)
8517 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8518
8519 // Convert shuffles that are directly supported on NEON to target-specific
8520 // DAG nodes, instead of keeping them as shuffles and matching them again
8521 // during code selection. This is more efficient and avoids the possibility
8522 // of inconsistencies between legalization and selection.
8523 // FIXME: floating-point vectors should be canonicalized to integer vectors
8524 // of the same time so that they get CSEd properly.
8525 ArrayRef<int> ShuffleMask = SVN->getMask();
8526
8527 if (EltSize <= 32) {
8528 if (SVN->isSplat()) {
8529 int Lane = SVN->getSplatIndex();
8530 // If this is undef splat, generate it via "just" vdup, if possible.
8531 if (Lane == -1) Lane = 0;
8532
8533 // Test if V1 is a SCALAR_TO_VECTOR.
8534 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8535 return DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT, Operand: V1.getOperand(i: 0));
8536 }
8537 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8538 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8539 // reaches it).
8540 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8541 !isa<ConstantSDNode>(Val: V1.getOperand(i: 0))) {
8542 bool IsScalarToVector = true;
8543 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8544 if (!V1.getOperand(i).isUndef()) {
8545 IsScalarToVector = false;
8546 break;
8547 }
8548 if (IsScalarToVector)
8549 return DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT, Operand: V1.getOperand(i: 0));
8550 }
8551 return DAG.getNode(Opcode: ARMISD::VDUPLANE, DL: dl, VT, N1: V1,
8552 N2: DAG.getConstant(Val: Lane, DL: dl, VT: MVT::i32));
8553 }
8554
8555 bool ReverseVEXT = false;
8556 unsigned Imm = 0;
8557 if (ST->hasNEON() && isVEXTMask(M: ShuffleMask, VT, ReverseVEXT, Imm)) {
8558 if (ReverseVEXT)
8559 std::swap(a&: V1, b&: V2);
8560 return DAG.getNode(Opcode: ARMISD::VEXT, DL: dl, VT, N1: V1, N2: V2,
8561 N3: DAG.getConstant(Val: Imm, DL: dl, VT: MVT::i32));
8562 }
8563
8564 if (isVREVMask(M: ShuffleMask, VT, BlockSize: 64))
8565 return DAG.getNode(Opcode: ARMISD::VREV64, DL: dl, VT, Operand: V1);
8566 if (isVREVMask(M: ShuffleMask, VT, BlockSize: 32))
8567 return DAG.getNode(Opcode: ARMISD::VREV32, DL: dl, VT, Operand: V1);
8568 if (isVREVMask(M: ShuffleMask, VT, BlockSize: 16))
8569 return DAG.getNode(Opcode: ARMISD::VREV16, DL: dl, VT, Operand: V1);
8570
8571 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(M: ShuffleMask, VT, Imm)) {
8572 return DAG.getNode(Opcode: ARMISD::VEXT, DL: dl, VT, N1: V1, N2: V1,
8573 N3: DAG.getConstant(Val: Imm, DL: dl, VT: MVT::i32));
8574 }
8575
8576 // Check for Neon shuffles that modify both input vectors in place.
8577 // If both results are used, i.e., if there are two shuffles with the same
8578 // source operands and with masks corresponding to both results of one of
8579 // these operations, DAG memoization will ensure that a single node is
8580 // used for both shuffles.
8581 unsigned WhichResult = 0;
8582 bool isV_UNDEF = false;
8583 if (ST->hasNEON()) {
8584 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8585 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8586 if (isV_UNDEF)
8587 V2 = V1;
8588 return DAG.getNode(Opcode: ShuffleOpc, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT), N1: V1, N2: V2)
8589 .getValue(R: WhichResult);
8590 }
8591 }
8592 if (ST->hasMVEIntegerOps()) {
8593 if (isVMOVNMask(M: ShuffleMask, VT, Top: false, SingleSource: false))
8594 return DAG.getNode(Opcode: ARMISD::VMOVN, DL: dl, VT, N1: V2, N2: V1,
8595 N3: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
8596 if (isVMOVNMask(M: ShuffleMask, VT, Top: true, SingleSource: false))
8597 return DAG.getNode(Opcode: ARMISD::VMOVN, DL: dl, VT, N1: V1, N2: V2,
8598 N3: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
8599 if (isVMOVNMask(M: ShuffleMask, VT, Top: true, SingleSource: true))
8600 return DAG.getNode(Opcode: ARMISD::VMOVN, DL: dl, VT, N1: V1, N2: V1,
8601 N3: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
8602 }
8603
8604 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8605 // shuffles that produce a result larger than their operands with:
8606 // shuffle(concat(v1, undef), concat(v2, undef))
8607 // ->
8608 // shuffle(concat(v1, v2), undef)
8609 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8610 //
8611 // This is useful in the general case, but there are special cases where
8612 // native shuffles produce larger results: the two-result ops.
8613 //
8614 // Look through the concat when lowering them:
8615 // shuffle(concat(v1, v2), undef)
8616 // ->
8617 // concat(VZIP(v1, v2):0, :1)
8618 //
8619 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8620 SDValue SubV1 = V1->getOperand(Num: 0);
8621 SDValue SubV2 = V1->getOperand(Num: 1);
8622 EVT SubVT = SubV1.getValueType();
8623
8624 // We expect these to have been canonicalized to -1.
8625 assert(llvm::all_of(ShuffleMask, [&](int i) {
8626 return i < (int)VT.getVectorNumElements();
8627 }) && "Unexpected shuffle index into UNDEF operand!");
8628
8629 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8630 ShuffleMask, VT: SubVT, WhichResult, isV_UNDEF)) {
8631 if (isV_UNDEF)
8632 SubV2 = SubV1;
8633 assert((WhichResult == 0) &&
8634 "In-place shuffle of concat can only have one result!");
8635 SDValue Res = DAG.getNode(Opcode: ShuffleOpc, DL: dl, VTList: DAG.getVTList(VT1: SubVT, VT2: SubVT),
8636 N1: SubV1, N2: SubV2);
8637 return DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: dl, VT, N1: Res.getValue(R: 0),
8638 N2: Res.getValue(R: 1));
8639 }
8640 }
8641 }
8642
8643 if (ST->hasMVEIntegerOps() && EltSize <= 32) {
8644 if (SDValue V = LowerVECTOR_SHUFFLEUsingOneOff(Op, ShuffleMask, DAG))
8645 return V;
8646
8647 for (bool Top : {false, true}) {
8648 for (bool SingleSource : {false, true}) {
8649 if (isTruncMask(M: ShuffleMask, VT, Top, SingleSource)) {
8650 MVT FromSVT = MVT::getIntegerVT(BitWidth: EltSize * 2);
8651 MVT FromVT = MVT::getVectorVT(VT: FromSVT, NumElements: ShuffleMask.size() / 2);
8652 SDValue Lo = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: FromVT, Operand: V1);
8653 SDValue Hi = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: FromVT,
8654 Operand: SingleSource ? V1 : V2);
8655 if (Top) {
8656 SDValue Amt = DAG.getConstant(Val: EltSize, DL: dl, VT: FromVT);
8657 Lo = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: FromVT, N1: Lo, N2: Amt);
8658 Hi = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: FromVT, N1: Hi, N2: Amt);
8659 }
8660 return DAG.getNode(Opcode: ARMISD::MVETRUNC, DL: dl, VT, N1: Lo, N2: Hi);
8661 }
8662 }
8663 }
8664 }
8665
8666 // If the shuffle is not directly supported and it has 4 elements, use
8667 // the PerfectShuffle-generated table to synthesize it from other shuffles.
8668 unsigned NumElts = VT.getVectorNumElements();
8669 if (NumElts == 4) {
8670 unsigned PFIndexes[4];
8671 for (unsigned i = 0; i != 4; ++i) {
8672 if (ShuffleMask[i] < 0)
8673 PFIndexes[i] = 8;
8674 else
8675 PFIndexes[i] = ShuffleMask[i];
8676 }
8677
8678 // Compute the index in the perfect shuffle table.
8679 unsigned PFTableIndex =
8680 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8681 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8682 unsigned Cost = (PFEntry >> 30);
8683
8684 if (Cost <= 4) {
8685 if (ST->hasNEON())
8686 return GeneratePerfectShuffle(PFEntry, LHS: V1, RHS: V2, DAG, dl);
8687 else if (isLegalMVEShuffleOp(PFEntry)) {
8688 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8689 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8690 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8691 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8692 if (isLegalMVEShuffleOp(PFEntry: PFEntryLHS) && isLegalMVEShuffleOp(PFEntry: PFEntryRHS))
8693 return GeneratePerfectShuffle(PFEntry, LHS: V1, RHS: V2, DAG, dl);
8694 }
8695 }
8696 }
8697
8698 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8699 if (EltSize >= 32) {
8700 // Do the expansion with floating-point types, since that is what the VFP
8701 // registers are defined to use, and since i64 is not legal.
8702 EVT EltVT = EVT::getFloatingPointVT(BitWidth: EltSize);
8703 EVT VecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: EltVT, NumElements: NumElts);
8704 V1 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VecVT, Operand: V1);
8705 V2 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VecVT, Operand: V2);
8706 SmallVector<SDValue, 8> Ops;
8707 for (unsigned i = 0; i < NumElts; ++i) {
8708 if (ShuffleMask[i] < 0)
8709 Ops.push_back(Elt: DAG.getUNDEF(VT: EltVT));
8710 else
8711 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT,
8712 N1: ShuffleMask[i] < (int)NumElts ? V1 : V2,
8713 N2: DAG.getConstant(Val: ShuffleMask[i] & (NumElts-1),
8714 DL: dl, VT: MVT::i32)));
8715 }
8716 SDValue Val = DAG.getNode(Opcode: ARMISD::BUILD_VECTOR, DL: dl, VT: VecVT, Ops);
8717 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Val);
8718 }
8719
8720 if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8721 isReverseMask(M: ShuffleMask, VT))
8722 return LowerReverse_VECTOR_SHUFFLE(Op, DAG);
8723
8724 if (ST->hasNEON() && VT == MVT::v8i8)
8725 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8726 return NewOp;
8727
8728 if (ST->hasMVEIntegerOps())
8729 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8730 return NewOp;
8731
8732 return SDValue();
8733}
8734
8735static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8736 const ARMSubtarget *ST) {
8737 EVT VecVT = Op.getOperand(i: 0).getValueType();
8738 SDLoc dl(Op);
8739
8740 assert(ST->hasMVEIntegerOps() &&
8741 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8742
8743 SDValue Conv =
8744 DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::i32, Operand: Op->getOperand(Num: 0));
8745 unsigned Lane = Op.getConstantOperandVal(i: 2);
8746 unsigned LaneWidth =
8747 getVectorTyFromPredicateVector(VT: VecVT).getScalarSizeInBits() / 8;
8748 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8749 SDValue Ext = DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL: dl, VT: MVT::i32,
8750 N1: Op.getOperand(i: 1), N2: DAG.getValueType(MVT::i1));
8751 SDValue BFI = DAG.getNode(Opcode: ARMISD::BFI, DL: dl, VT: MVT::i32, N1: Conv, N2: Ext,
8752 N3: DAG.getConstant(Val: ~Mask, DL: dl, VT: MVT::i32));
8753 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: Op.getValueType(), Operand: BFI);
8754}
8755
8756SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8757 SelectionDAG &DAG) const {
8758 // INSERT_VECTOR_ELT is legal only for immediate indexes.
8759 SDValue Lane = Op.getOperand(i: 2);
8760 if (!isa<ConstantSDNode>(Val: Lane))
8761 return SDValue();
8762
8763 SDValue Elt = Op.getOperand(i: 1);
8764 EVT EltVT = Elt.getValueType();
8765
8766 if (Subtarget->hasMVEIntegerOps() &&
8767 Op.getValueType().getScalarSizeInBits() == 1)
8768 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, ST: Subtarget);
8769
8770 if (getTypeAction(Context&: *DAG.getContext(), VT: EltVT) ==
8771 TargetLowering::TypeSoftPromoteHalf) {
8772 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8773 // but the type system will try to do that if we don't intervene.
8774 // Reinterpret any such vector-element insertion as one with the
8775 // corresponding integer types.
8776
8777 SDLoc dl(Op);
8778
8779 EVT IEltVT = MVT::getIntegerVT(BitWidth: EltVT.getScalarSizeInBits());
8780 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8781 TargetLowering::TypeSoftPromoteHalf);
8782
8783 SDValue VecIn = Op.getOperand(i: 0);
8784 EVT VecVT = VecIn.getValueType();
8785 EVT IVecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: IEltVT,
8786 NumElements: VecVT.getVectorNumElements());
8787
8788 SDValue IElt = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: IEltVT, Operand: Elt);
8789 SDValue IVecIn = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: IVecVT, Operand: VecIn);
8790 SDValue IVecOut = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: IVecVT,
8791 N1: IVecIn, N2: IElt, N3: Lane);
8792 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VecVT, Operand: IVecOut);
8793 }
8794
8795 return Op;
8796}
8797
8798static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8799 const ARMSubtarget *ST) {
8800 EVT VecVT = Op.getOperand(i: 0).getValueType();
8801 SDLoc dl(Op);
8802
8803 assert(ST->hasMVEIntegerOps() &&
8804 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8805
8806 SDValue Conv =
8807 DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::i32, Operand: Op->getOperand(Num: 0));
8808 unsigned Lane = Op.getConstantOperandVal(i: 1);
8809 unsigned LaneWidth =
8810 getVectorTyFromPredicateVector(VT: VecVT).getScalarSizeInBits() / 8;
8811 SDValue Shift = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32, N1: Conv,
8812 N2: DAG.getConstant(Val: Lane * LaneWidth, DL: dl, VT: MVT::i32));
8813 return Shift;
8814}
8815
8816static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8817 const ARMSubtarget *ST) {
8818 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8819 SDValue Lane = Op.getOperand(i: 1);
8820 if (!isa<ConstantSDNode>(Val: Lane))
8821 return SDValue();
8822
8823 SDValue Vec = Op.getOperand(i: 0);
8824 EVT VT = Vec.getValueType();
8825
8826 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8827 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8828
8829 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8830 SDLoc dl(Op);
8831 return DAG.getNode(Opcode: ARMISD::VGETLANEu, DL: dl, VT: MVT::i32, N1: Vec, N2: Lane);
8832 }
8833
8834 return Op;
8835}
8836
8837static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8838 const ARMSubtarget *ST) {
8839 SDLoc dl(Op);
8840 assert(Op.getValueType().getScalarSizeInBits() == 1 &&
8841 "Unexpected custom CONCAT_VECTORS lowering");
8842 assert(isPowerOf2_32(Op.getNumOperands()) &&
8843 "Unexpected custom CONCAT_VECTORS lowering");
8844 assert(ST->hasMVEIntegerOps() &&
8845 "CONCAT_VECTORS lowering only supported for MVE");
8846
8847 auto ConcatPair = [&](SDValue V1, SDValue V2) {
8848 EVT Op1VT = V1.getValueType();
8849 EVT Op2VT = V2.getValueType();
8850 assert(Op1VT == Op2VT && "Operand types don't match!");
8851 assert((Op1VT == MVT::v2i1 || Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) &&
8852 "Unexpected i1 concat operations!");
8853 EVT VT = Op1VT.getDoubleNumVectorElementsVT(Context&: *DAG.getContext());
8854
8855 SDValue NewV1 = PromoteMVEPredVector(dl, Pred: V1, VT: Op1VT, DAG);
8856 SDValue NewV2 = PromoteMVEPredVector(dl, Pred: V2, VT: Op2VT, DAG);
8857
8858 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8859 // promoted to v8i16, etc.
8860 MVT ElType =
8861 getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8862 unsigned NumElts = 2 * Op1VT.getVectorNumElements();
8863
8864 EVT ConcatVT = MVT::getVectorVT(VT: ElType, NumElements: NumElts);
8865 if (Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) {
8866 // Use MVETRUNC to truncate the combined NewV1::NewV2 into the smaller
8867 // ConcatVT.
8868 SDValue ConVec =
8869 DAG.getNode(Opcode: ARMISD::MVETRUNC, DL: dl, VT: ConcatVT, N1: NewV1, N2: NewV2);
8870 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: ConVec,
8871 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8872 }
8873
8874 // Extract the vector elements from Op1 and Op2 one by one and truncate them
8875 // to be the right size for the destination. For example, if Op1 is v4i1
8876 // then the promoted vector is v4i32. The result of concatenation gives a
8877 // v8i1, which when promoted is v8i16. That means each i32 element from Op1
8878 // needs truncating to i16 and inserting in the result.
8879 auto ExtractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8880 EVT NewVT = NewV.getValueType();
8881 EVT ConcatVT = ConVec.getValueType();
8882 unsigned ExtScale = 1;
8883 if (NewVT == MVT::v2f64) {
8884 NewV = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: NewV);
8885 ExtScale = 2;
8886 }
8887 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8888 SDValue Elt = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::i32, N1: NewV,
8889 N2: DAG.getIntPtrConstant(Val: i * ExtScale, DL: dl));
8890 ConVec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: ConcatVT, N1: ConVec, N2: Elt,
8891 N3: DAG.getConstant(Val: j, DL: dl, VT: MVT::i32));
8892 }
8893 return ConVec;
8894 };
8895 unsigned j = 0;
8896 SDValue ConVec = DAG.getNode(Opcode: ISD::UNDEF, DL: dl, VT: ConcatVT);
8897 ConVec = ExtractInto(NewV1, ConVec, j);
8898 ConVec = ExtractInto(NewV2, ConVec, j);
8899
8900 // Now return the result of comparing the subvector with zero, which will
8901 // generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8902 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: ConVec,
8903 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8904 };
8905
8906 // Concat each pair of subvectors and pack into the lower half of the array.
8907 SmallVector<SDValue> ConcatOps(Op->ops());
8908 while (ConcatOps.size() > 1) {
8909 for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
8910 SDValue V1 = ConcatOps[I];
8911 SDValue V2 = ConcatOps[I + 1];
8912 ConcatOps[I / 2] = ConcatPair(V1, V2);
8913 }
8914 ConcatOps.resize(N: ConcatOps.size() / 2);
8915 }
8916 return ConcatOps[0];
8917}
8918
8919static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8920 const ARMSubtarget *ST) {
8921 EVT VT = Op->getValueType(ResNo: 0);
8922 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8923 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8924
8925 // The only time a CONCAT_VECTORS operation can have legal types is when
8926 // two 64-bit vectors are concatenated to a 128-bit vector.
8927 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8928 "unexpected CONCAT_VECTORS");
8929 SDLoc dl(Op);
8930 SDValue Val = DAG.getUNDEF(VT: MVT::v2f64);
8931 SDValue Op0 = Op.getOperand(i: 0);
8932 SDValue Op1 = Op.getOperand(i: 1);
8933 if (!Op0.isUndef())
8934 Val = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: MVT::v2f64, N1: Val,
8935 N2: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f64, Operand: Op0),
8936 N3: DAG.getIntPtrConstant(Val: 0, DL: dl));
8937 if (!Op1.isUndef())
8938 Val = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: MVT::v2f64, N1: Val,
8939 N2: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f64, Operand: Op1),
8940 N3: DAG.getIntPtrConstant(Val: 1, DL: dl));
8941 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: Op.getValueType(), Operand: Val);
8942}
8943
8944static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8945 const ARMSubtarget *ST) {
8946 SDValue V1 = Op.getOperand(i: 0);
8947 SDValue V2 = Op.getOperand(i: 1);
8948 SDLoc dl(Op);
8949 EVT VT = Op.getValueType();
8950 EVT Op1VT = V1.getValueType();
8951 unsigned NumElts = VT.getVectorNumElements();
8952 unsigned Index = V2->getAsZExtVal();
8953
8954 assert(VT.getScalarSizeInBits() == 1 &&
8955 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8956 assert(ST->hasMVEIntegerOps() &&
8957 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8958
8959 SDValue NewV1 = PromoteMVEPredVector(dl, Pred: V1, VT: Op1VT, DAG);
8960
8961 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8962 // promoted to v8i16, etc.
8963
8964 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8965
8966 if (NumElts == 2) {
8967 EVT SubVT = MVT::v4i32;
8968 SDValue SubVec = DAG.getNode(Opcode: ISD::UNDEF, DL: dl, VT: SubVT);
8969 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j += 2) {
8970 SDValue Elt = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::i32, N1: NewV1,
8971 N2: DAG.getIntPtrConstant(Val: i, DL: dl));
8972 SubVec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: SubVT, N1: SubVec, N2: Elt,
8973 N3: DAG.getConstant(Val: j, DL: dl, VT: MVT::i32));
8974 SubVec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: SubVT, N1: SubVec, N2: Elt,
8975 N3: DAG.getConstant(Val: j + 1, DL: dl, VT: MVT::i32));
8976 }
8977 SDValue Cmp = DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT: MVT::v4i1, N1: SubVec,
8978 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8979 return DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::v2i1, Operand: Cmp);
8980 }
8981
8982 EVT SubVT = MVT::getVectorVT(VT: ElType, NumElements: NumElts);
8983 SDValue SubVec = DAG.getNode(Opcode: ISD::UNDEF, DL: dl, VT: SubVT);
8984 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8985 SDValue Elt = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::i32, N1: NewV1,
8986 N2: DAG.getIntPtrConstant(Val: i, DL: dl));
8987 SubVec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: SubVT, N1: SubVec, N2: Elt,
8988 N3: DAG.getConstant(Val: j, DL: dl, VT: MVT::i32));
8989 }
8990
8991 // Now return the result of comparing the subvector with zero,
8992 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8993 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: SubVec,
8994 N2: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32));
8995}
8996
8997// Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0).
8998static SDValue LowerTruncatei1(SDNode *N, SelectionDAG &DAG,
8999 const ARMSubtarget *ST) {
9000 assert(ST->hasMVEIntegerOps() && "Expected MVE!");
9001 EVT VT = N->getValueType(ResNo: 0);
9002 assert((VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) &&
9003 "Expected a vector i1 type!");
9004 SDValue Op = N->getOperand(Num: 0);
9005 EVT FromVT = Op.getValueType();
9006 SDLoc DL(N);
9007
9008 SDValue And =
9009 DAG.getNode(Opcode: ISD::AND, DL, VT: FromVT, N1: Op, N2: DAG.getConstant(Val: 1, DL, VT: FromVT));
9010 return DAG.getNode(Opcode: ISD::SETCC, DL, VT, N1: And, N2: DAG.getConstant(Val: 0, DL, VT: FromVT),
9011 N3: DAG.getCondCode(Cond: ISD::SETNE));
9012}
9013
9014static SDValue LowerTruncate(SDNode *N, SelectionDAG &DAG,
9015 const ARMSubtarget *Subtarget) {
9016 if (!Subtarget->hasMVEIntegerOps())
9017 return SDValue();
9018
9019 EVT ToVT = N->getValueType(ResNo: 0);
9020 if (ToVT.getScalarType() == MVT::i1)
9021 return LowerTruncatei1(N, DAG, ST: Subtarget);
9022
9023 // MVE does not have a single instruction to perform the truncation of a v4i32
9024 // into the lower half of a v8i16, in the same way that a NEON vmovn would.
9025 // Most of the instructions in MVE follow the 'Beats' system, where moving
9026 // values from different lanes is usually something that the instructions
9027 // avoid.
9028 //
9029 // Instead it has top/bottom instructions such as VMOVLT/B and VMOVNT/B,
9030 // which take a the top/bottom half of a larger lane and extend it (or do the
9031 // opposite, truncating into the top/bottom lane from a larger lane). Note
9032 // that because of the way we widen lanes, a v4i16 is really a v4i32 using the
9033 // bottom 16bits from each vector lane. This works really well with T/B
9034 // instructions, but that doesn't extend to v8i32->v8i16 where the lanes need
9035 // to move order.
9036 //
9037 // But truncates and sext/zext are always going to be fairly common from llvm.
9038 // We have several options for how to deal with them:
9039 // - Wherever possible combine them into an instruction that makes them
9040 // "free". This includes loads/stores, which can perform the trunc as part
9041 // of the memory operation. Or certain shuffles that can be turned into
9042 // VMOVN/VMOVL.
9043 // - Lane Interleaving to transform blocks surrounded by ext/trunc. So
9044 // trunc(mul(sext(a), sext(b))) may become
9045 // VMOVNT(VMUL(VMOVLB(a), VMOVLB(b)), VMUL(VMOVLT(a), VMOVLT(b))). (Which in
9046 // this case can use VMULL). This is performed in the
9047 // MVELaneInterleavingPass.
9048 // - Otherwise we have an option. By default we would expand the
9049 // zext/sext/trunc into a series of lane extract/inserts going via GPR
9050 // registers. One for each vector lane in the vector. This can obviously be
9051 // very expensive.
9052 // - The other option is to use the fact that loads/store can extend/truncate
9053 // to turn a trunc into two truncating stack stores and a stack reload. This
9054 // becomes 3 back-to-back memory operations, but at least that is less than
9055 // all the insert/extracts.
9056 //
9057 // In order to do the last, we convert certain trunc's into MVETRUNC, which
9058 // are either optimized where they can be, or eventually lowered into stack
9059 // stores/loads. This prevents us from splitting a v8i16 trunc into two stores
9060 // two early, where other instructions would be better, and stops us from
9061 // having to reconstruct multiple buildvector shuffles into loads/stores.
9062 if (ToVT != MVT::v8i16 && ToVT != MVT::v16i8)
9063 return SDValue();
9064 EVT FromVT = N->getOperand(Num: 0).getValueType();
9065 if (FromVT != MVT::v8i32 && FromVT != MVT::v16i16)
9066 return SDValue();
9067
9068 SDValue Lo, Hi;
9069 std::tie(args&: Lo, args&: Hi) = DAG.SplitVectorOperand(N, OpNo: 0);
9070 SDLoc DL(N);
9071 return DAG.getNode(Opcode: ARMISD::MVETRUNC, DL, VT: ToVT, N1: Lo, N2: Hi);
9072}
9073
9074static SDValue LowerVectorExtend(SDNode *N, SelectionDAG &DAG,
9075 const ARMSubtarget *Subtarget) {
9076 if (!Subtarget->hasMVEIntegerOps())
9077 return SDValue();
9078
9079 // See LowerTruncate above for an explanation of MVEEXT/MVETRUNC.
9080
9081 EVT ToVT = N->getValueType(ResNo: 0);
9082 if (ToVT != MVT::v16i32 && ToVT != MVT::v8i32 && ToVT != MVT::v16i16)
9083 return SDValue();
9084 SDValue Op = N->getOperand(Num: 0);
9085 EVT FromVT = Op.getValueType();
9086 if (FromVT != MVT::v8i16 && FromVT != MVT::v16i8)
9087 return SDValue();
9088
9089 SDLoc DL(N);
9090 EVT ExtVT = ToVT.getHalfNumVectorElementsVT(Context&: *DAG.getContext());
9091 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8)
9092 ExtVT = MVT::v8i16;
9093
9094 unsigned Opcode =
9095 N->getOpcode() == ISD::SIGN_EXTEND ? ARMISD::MVESEXT : ARMISD::MVEZEXT;
9096 SDValue Ext = DAG.getNode(Opcode, DL, VTList: DAG.getVTList(VT1: ExtVT, VT2: ExtVT), N: Op);
9097 SDValue Ext1 = Ext.getValue(R: 1);
9098
9099 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8) {
9100 Ext = DAG.getNode(Opcode: N->getOpcode(), DL, VT: MVT::v8i32, Operand: Ext);
9101 Ext1 = DAG.getNode(Opcode: N->getOpcode(), DL, VT: MVT::v8i32, Operand: Ext1);
9102 }
9103
9104 return DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: ToVT, N1: Ext, N2: Ext1);
9105}
9106
9107/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
9108/// element has been zero/sign-extended, depending on the isSigned parameter,
9109/// from an integer type half its size.
9110static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
9111 bool isSigned) {
9112 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
9113 EVT VT = N->getValueType(ResNo: 0);
9114 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
9115 SDNode *BVN = N->getOperand(Num: 0).getNode();
9116 if (BVN->getValueType(ResNo: 0) != MVT::v4i32 ||
9117 BVN->getOpcode() != ISD::BUILD_VECTOR)
9118 return false;
9119 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9120 unsigned HiElt = 1 - LoElt;
9121 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(Val: BVN->getOperand(Num: LoElt));
9122 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(Val: BVN->getOperand(Num: HiElt));
9123 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(Val: BVN->getOperand(Num: LoElt+2));
9124 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(Val: BVN->getOperand(Num: HiElt+2));
9125 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
9126 return false;
9127 if (isSigned) {
9128 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
9129 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
9130 return true;
9131 } else {
9132 if (Hi0->isZero() && Hi1->isZero())
9133 return true;
9134 }
9135 return false;
9136 }
9137
9138 if (N->getOpcode() != ISD::BUILD_VECTOR)
9139 return false;
9140
9141 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9142 SDNode *Elt = N->getOperand(Num: i).getNode();
9143 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val: Elt)) {
9144 unsigned EltSize = VT.getScalarSizeInBits();
9145 unsigned HalfSize = EltSize / 2;
9146 if (isSigned) {
9147 if (!isIntN(N: HalfSize, x: C->getSExtValue()))
9148 return false;
9149 } else {
9150 if (!isUIntN(N: HalfSize, x: C->getZExtValue()))
9151 return false;
9152 }
9153 continue;
9154 }
9155 return false;
9156 }
9157
9158 return true;
9159}
9160
9161/// isSignExtended - Check if a node is a vector value that is sign-extended
9162/// or a constant BUILD_VECTOR with sign-extended elements.
9163static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
9164 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
9165 return true;
9166 if (isExtendedBUILD_VECTOR(N, DAG, isSigned: true))
9167 return true;
9168 return false;
9169}
9170
9171/// isZeroExtended - Check if a node is a vector value that is zero-extended (or
9172/// any-extended) or a constant BUILD_VECTOR with zero-extended elements.
9173static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
9174 if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND ||
9175 ISD::isZEXTLoad(N))
9176 return true;
9177 if (isExtendedBUILD_VECTOR(N, DAG, isSigned: false))
9178 return true;
9179 return false;
9180}
9181
9182static EVT getExtensionTo64Bits(const EVT &OrigVT) {
9183 if (OrigVT.getSizeInBits() >= 64)
9184 return OrigVT;
9185
9186 assert(OrigVT.isSimple() && "Expecting a simple value type");
9187
9188 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
9189 switch (OrigSimpleTy) {
9190 default: llvm_unreachable("Unexpected Vector Type");
9191 case MVT::v2i8:
9192 case MVT::v2i16:
9193 return MVT::v2i32;
9194 case MVT::v4i8:
9195 return MVT::v4i16;
9196 }
9197}
9198
9199/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
9200/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
9201/// We insert the required extension here to get the vector to fill a D register.
9202static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
9203 const EVT &OrigTy,
9204 const EVT &ExtTy,
9205 unsigned ExtOpcode) {
9206 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
9207 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
9208 // 64-bits we need to insert a new extension so that it will be 64-bits.
9209 assert(ExtTy.is128BitVector() && "Unexpected extension size");
9210 if (OrigTy.getSizeInBits() >= 64)
9211 return N;
9212
9213 // Must extend size to at least 64 bits to be used as an operand for VMULL.
9214 EVT NewVT = getExtensionTo64Bits(OrigVT: OrigTy);
9215
9216 return DAG.getNode(Opcode: ExtOpcode, DL: SDLoc(N), VT: NewVT, Operand: N);
9217}
9218
9219/// SkipLoadExtensionForVMULL - return a load of the original vector size that
9220/// does not do any sign/zero extension. If the original vector is less
9221/// than 64 bits, an appropriate extension will be added after the load to
9222/// reach a total size of 64 bits. We have to add the extension separately
9223/// because ARM does not have a sign/zero extending load for vectors.
9224static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
9225 EVT ExtendedTy = getExtensionTo64Bits(OrigVT: LD->getMemoryVT());
9226
9227 // The load already has the right type.
9228 if (ExtendedTy == LD->getMemoryVT())
9229 return DAG.getLoad(VT: LD->getMemoryVT(), dl: SDLoc(LD), Chain: LD->getChain(),
9230 Ptr: LD->getBasePtr(), PtrInfo: LD->getPointerInfo(), Alignment: LD->getAlign(),
9231 MMOFlags: LD->getMemOperand()->getFlags());
9232
9233 // We need to create a zextload/sextload. We cannot just create a load
9234 // followed by a zext/zext node because LowerMUL is also run during normal
9235 // operation legalization where we can't create illegal types.
9236 return DAG.getExtLoad(ExtType: LD->getExtensionType(), dl: SDLoc(LD), VT: ExtendedTy,
9237 Chain: LD->getChain(), Ptr: LD->getBasePtr(), PtrInfo: LD->getPointerInfo(),
9238 MemVT: LD->getMemoryVT(), Alignment: LD->getAlign(),
9239 MMOFlags: LD->getMemOperand()->getFlags());
9240}
9241
9242/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
9243/// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return
9244/// the unextended value. The unextended vector should be 64 bits so that it can
9245/// be used as an operand to a VMULL instruction. If the original vector size
9246/// before extension is less than 64 bits we add a an extension to resize
9247/// the vector to 64 bits.
9248static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
9249 if (N->getOpcode() == ISD::SIGN_EXTEND ||
9250 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
9251 return AddRequiredExtensionForVMULL(N: N->getOperand(Num: 0), DAG,
9252 OrigTy: N->getOperand(Num: 0)->getValueType(ResNo: 0),
9253 ExtTy: N->getValueType(ResNo: 0),
9254 ExtOpcode: N->getOpcode());
9255
9256 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: N)) {
9257 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
9258 "Expected extending load");
9259
9260 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
9261 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 1), To: newLoad.getValue(R: 1));
9262 unsigned Opcode = ISD::isSEXTLoad(N: LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9263 SDValue extLoad =
9264 DAG.getNode(Opcode, DL: SDLoc(newLoad), VT: LD->getValueType(ResNo: 0), Operand: newLoad);
9265 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 0), To: extLoad);
9266
9267 return newLoad;
9268 }
9269
9270 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
9271 // have been legalized as a BITCAST from v4i32.
9272 if (N->getOpcode() == ISD::BITCAST) {
9273 SDNode *BVN = N->getOperand(Num: 0).getNode();
9274 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
9275 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
9276 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9277 return DAG.getBuildVector(
9278 VT: MVT::v2i32, DL: SDLoc(N),
9279 Ops: {BVN->getOperand(Num: LowElt), BVN->getOperand(Num: LowElt + 2)});
9280 }
9281 // Construct a new BUILD_VECTOR with elements truncated to half the size.
9282 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
9283 EVT VT = N->getValueType(ResNo: 0);
9284 unsigned EltSize = VT.getScalarSizeInBits() / 2;
9285 unsigned NumElts = VT.getVectorNumElements();
9286 MVT TruncVT = MVT::getIntegerVT(BitWidth: EltSize);
9287 SmallVector<SDValue, 8> Ops;
9288 SDLoc dl(N);
9289 for (unsigned i = 0; i != NumElts; ++i) {
9290 const APInt &CInt = N->getConstantOperandAPInt(Num: i);
9291 // Element types smaller than 32 bits are not legal, so use i32 elements.
9292 // The values are implicitly truncated so sext vs. zext doesn't matter.
9293 Ops.push_back(Elt: DAG.getConstant(Val: CInt.zextOrTrunc(width: 32), DL: dl, VT: MVT::i32));
9294 }
9295 return DAG.getBuildVector(VT: MVT::getVectorVT(VT: TruncVT, NumElements: NumElts), DL: dl, Ops);
9296}
9297
9298static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
9299 unsigned Opcode = N->getOpcode();
9300 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9301 SDNode *N0 = N->getOperand(Num: 0).getNode();
9302 SDNode *N1 = N->getOperand(Num: 1).getNode();
9303 return N0->hasOneUse() && N1->hasOneUse() &&
9304 isSignExtended(N: N0, DAG) && isSignExtended(N: N1, DAG);
9305 }
9306 return false;
9307}
9308
9309static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
9310 unsigned Opcode = N->getOpcode();
9311 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9312 SDNode *N0 = N->getOperand(Num: 0).getNode();
9313 SDNode *N1 = N->getOperand(Num: 1).getNode();
9314 return N0->hasOneUse() && N1->hasOneUse() &&
9315 isZeroExtended(N: N0, DAG) && isZeroExtended(N: N1, DAG);
9316 }
9317 return false;
9318}
9319
9320static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
9321 // Multiplications are only custom-lowered for 128-bit vectors so that
9322 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
9323 EVT VT = Op.getValueType();
9324 assert(VT.is128BitVector() && VT.isInteger() &&
9325 "unexpected type for custom-lowering ISD::MUL");
9326 SDNode *N0 = Op.getOperand(i: 0).getNode();
9327 SDNode *N1 = Op.getOperand(i: 1).getNode();
9328 unsigned NewOpc = 0;
9329 bool isMLA = false;
9330 bool isN0SExt = isSignExtended(N: N0, DAG);
9331 bool isN1SExt = isSignExtended(N: N1, DAG);
9332 if (isN0SExt && isN1SExt)
9333 NewOpc = ARMISD::VMULLs;
9334 else {
9335 bool isN0ZExt = isZeroExtended(N: N0, DAG);
9336 bool isN1ZExt = isZeroExtended(N: N1, DAG);
9337 if (isN0ZExt && isN1ZExt)
9338 NewOpc = ARMISD::VMULLu;
9339 else if (isN1SExt || isN1ZExt) {
9340 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
9341 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
9342 if (isN1SExt && isAddSubSExt(N: N0, DAG)) {
9343 NewOpc = ARMISD::VMULLs;
9344 isMLA = true;
9345 } else if (isN1ZExt && isAddSubZExt(N: N0, DAG)) {
9346 NewOpc = ARMISD::VMULLu;
9347 isMLA = true;
9348 } else if (isN0ZExt && isAddSubZExt(N: N1, DAG)) {
9349 std::swap(a&: N0, b&: N1);
9350 NewOpc = ARMISD::VMULLu;
9351 isMLA = true;
9352 }
9353 }
9354
9355 if (!NewOpc) {
9356 if (VT == MVT::v2i64)
9357 // Fall through to expand this. It is not legal.
9358 return SDValue();
9359 else
9360 // Other vector multiplications are legal.
9361 return Op;
9362 }
9363 }
9364
9365 // Legalize to a VMULL instruction.
9366 SDLoc DL(Op);
9367 SDValue Op0;
9368 SDValue Op1 = SkipExtensionForVMULL(N: N1, DAG);
9369 if (!isMLA) {
9370 Op0 = SkipExtensionForVMULL(N: N0, DAG);
9371 assert(Op0.getValueType().is64BitVector() &&
9372 Op1.getValueType().is64BitVector() &&
9373 "unexpected types for extended operands to VMULL");
9374 return DAG.getNode(Opcode: NewOpc, DL, VT, N1: Op0, N2: Op1);
9375 }
9376
9377 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
9378 // isel lowering to take advantage of no-stall back to back vmul + vmla.
9379 // vmull q0, d4, d6
9380 // vmlal q0, d5, d6
9381 // is faster than
9382 // vaddl q0, d4, d5
9383 // vmovl q1, d6
9384 // vmul q0, q0, q1
9385 SDValue N00 = SkipExtensionForVMULL(N: N0->getOperand(Num: 0).getNode(), DAG);
9386 SDValue N01 = SkipExtensionForVMULL(N: N0->getOperand(Num: 1).getNode(), DAG);
9387 EVT Op1VT = Op1.getValueType();
9388 return DAG.getNode(Opcode: N0->getOpcode(), DL, VT,
9389 N1: DAG.getNode(Opcode: NewOpc, DL, VT,
9390 N1: DAG.getNode(Opcode: ISD::BITCAST, DL, VT: Op1VT, Operand: N00), N2: Op1),
9391 N2: DAG.getNode(Opcode: NewOpc, DL, VT,
9392 N1: DAG.getNode(Opcode: ISD::BITCAST, DL, VT: Op1VT, Operand: N01), N2: Op1));
9393}
9394
9395static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
9396 SelectionDAG &DAG) {
9397 // TODO: Should this propagate fast-math-flags?
9398
9399 // Convert to float
9400 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
9401 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
9402 X = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v4i32, Operand: X);
9403 Y = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v4i32, Operand: Y);
9404 X = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: X);
9405 Y = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: Y);
9406 // Get reciprocal estimate.
9407 // float4 recip = vrecpeq_f32(yf);
9408 Y = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9409 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecpe, DL: dl, VT: MVT::i32),
9410 N2: Y);
9411 // Because char has a smaller range than uchar, we can actually get away
9412 // without any newton steps. This requires that we use a weird bias
9413 // of 0xb000, however (again, this has been exhaustively tested).
9414 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
9415 X = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1: X, N2: Y);
9416 X = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4i32, Operand: X);
9417 Y = DAG.getConstant(Val: 0xb000, DL: dl, VT: MVT::v4i32);
9418 X = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::v4i32, N1: X, N2: Y);
9419 X = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4f32, Operand: X);
9420 // Convert back to short.
9421 X = DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: dl, VT: MVT::v4i32, Operand: X);
9422 X = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::v4i16, Operand: X);
9423 return X;
9424}
9425
9426static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
9427 SelectionDAG &DAG) {
9428 // TODO: Should this propagate fast-math-flags?
9429
9430 SDValue N2;
9431 // Convert to float.
9432 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
9433 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
9434 N0 = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v4i32, Operand: N0);
9435 N1 = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v4i32, Operand: N1);
9436 N0 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: N0);
9437 N1 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: N1);
9438
9439 // Use reciprocal estimate and one refinement step.
9440 // float4 recip = vrecpeq_f32(yf);
9441 // recip *= vrecpsq_f32(yf, recip);
9442 N2 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9443 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecpe, DL: dl, VT: MVT::i32),
9444 N2: N1);
9445 N1 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9446 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecps, DL: dl, VT: MVT::i32),
9447 N2: N1, N3: N2);
9448 N2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1, N2);
9449 // Because short has a smaller range than ushort, we can actually get away
9450 // with only a single newton step. This requires that we use a weird bias
9451 // of 89, however (again, this has been exhaustively tested).
9452 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9453 N0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1: N0, N2);
9454 N0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4i32, Operand: N0);
9455 N1 = DAG.getConstant(Val: 0x89, DL: dl, VT: MVT::v4i32);
9456 N0 = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::v4i32, N1: N0, N2: N1);
9457 N0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4f32, Operand: N0);
9458 // Convert back to integer and return.
9459 // return vmovn_s32(vcvt_s32_f32(result));
9460 N0 = DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: dl, VT: MVT::v4i32, Operand: N0);
9461 N0 = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::v4i16, Operand: N0);
9462 return N0;
9463}
9464
9465static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
9466 const ARMSubtarget *ST) {
9467 EVT VT = Op.getValueType();
9468 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9469 "unexpected type for custom-lowering ISD::SDIV");
9470
9471 SDLoc dl(Op);
9472 SDValue N0 = Op.getOperand(i: 0);
9473 SDValue N1 = Op.getOperand(i: 1);
9474 SDValue N2, N3;
9475
9476 if (VT == MVT::v8i8) {
9477 N0 = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v8i16, Operand: N0);
9478 N1 = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: MVT::v8i16, Operand: N1);
9479
9480 N2 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1: N0,
9481 N2: DAG.getIntPtrConstant(Val: 4, DL: dl));
9482 N3 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1,
9483 N2: DAG.getIntPtrConstant(Val: 4, DL: dl));
9484 N0 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1: N0,
9485 N2: DAG.getIntPtrConstant(Val: 0, DL: dl));
9486 N1 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1,
9487 N2: DAG.getIntPtrConstant(Val: 0, DL: dl));
9488
9489 N0 = LowerSDIV_v4i8(X: N0, Y: N1, dl, DAG); // v4i16
9490 N2 = LowerSDIV_v4i8(X: N2, Y: N3, dl, DAG); // v4i16
9491
9492 N0 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: dl, VT: MVT::v8i16, N1: N0, N2);
9493 N0 = LowerCONCAT_VECTORS(Op: N0, DAG, ST);
9494
9495 N0 = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::v8i8, Operand: N0);
9496 return N0;
9497 }
9498 return LowerSDIV_v4i16(N0, N1, dl, DAG);
9499}
9500
9501static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
9502 const ARMSubtarget *ST) {
9503 // TODO: Should this propagate fast-math-flags?
9504 EVT VT = Op.getValueType();
9505 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9506 "unexpected type for custom-lowering ISD::UDIV");
9507
9508 SDLoc dl(Op);
9509 SDValue N0 = Op.getOperand(i: 0);
9510 SDValue N1 = Op.getOperand(i: 1);
9511 SDValue N2, N3;
9512
9513 if (VT == MVT::v8i8) {
9514 N0 = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: MVT::v8i16, Operand: N0);
9515 N1 = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: MVT::v8i16, Operand: N1);
9516
9517 N2 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1: N0,
9518 N2: DAG.getIntPtrConstant(Val: 4, DL: dl));
9519 N3 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1,
9520 N2: DAG.getIntPtrConstant(Val: 4, DL: dl));
9521 N0 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1: N0,
9522 N2: DAG.getIntPtrConstant(Val: 0, DL: dl));
9523 N1 = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MVT::v4i16, N1,
9524 N2: DAG.getIntPtrConstant(Val: 0, DL: dl));
9525
9526 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9527 N2 = LowerSDIV_v4i16(N0: N2, N1: N3, dl, DAG); // v4i16
9528
9529 N0 = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: dl, VT: MVT::v8i16, N1: N0, N2);
9530 N0 = LowerCONCAT_VECTORS(Op: N0, DAG, ST);
9531
9532 N0 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v8i8,
9533 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vqmovnsu, DL: dl,
9534 VT: MVT::i32),
9535 N2: N0);
9536 return N0;
9537 }
9538
9539 // v4i16 sdiv ... Convert to float.
9540 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9541 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9542 N0 = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: MVT::v4i32, Operand: N0);
9543 N1 = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: MVT::v4i32, Operand: N1);
9544 N0 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: N0);
9545 SDValue BN1 = DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: dl, VT: MVT::v4f32, Operand: N1);
9546
9547 // Use reciprocal estimate and two refinement steps.
9548 // float4 recip = vrecpeq_f32(yf);
9549 // recip *= vrecpsq_f32(yf, recip);
9550 // recip *= vrecpsq_f32(yf, recip);
9551 N2 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9552 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecpe, DL: dl, VT: MVT::i32),
9553 N2: BN1);
9554 N1 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9555 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecps, DL: dl, VT: MVT::i32),
9556 N2: BN1, N3: N2);
9557 N2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1, N2);
9558 N1 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: MVT::v4f32,
9559 N1: DAG.getConstant(Val: Intrinsic::arm_neon_vrecps, DL: dl, VT: MVT::i32),
9560 N2: BN1, N3: N2);
9561 N2 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1, N2);
9562 // Simply multiplying by the reciprocal estimate can leave us a few ulps
9563 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9564 // and that it will never cause us to return an answer too large).
9565 // float4 result = as_float4(as_int4(xf*recip) + 2);
9566 N0 = DAG.getNode(Opcode: ISD::FMUL, DL: dl, VT: MVT::v4f32, N1: N0, N2);
9567 N0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4i32, Operand: N0);
9568 N1 = DAG.getConstant(Val: 2, DL: dl, VT: MVT::v4i32);
9569 N0 = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::v4i32, N1: N0, N2: N1);
9570 N0 = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::v4f32, Operand: N0);
9571 // Convert back to integer and return.
9572 // return vmovn_u32(vcvt_s32_f32(result));
9573 N0 = DAG.getNode(Opcode: ISD::FP_TO_SINT, DL: dl, VT: MVT::v4i32, Operand: N0);
9574 N0 = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::v4i16, Operand: N0);
9575 return N0;
9576}
9577
9578static SDValue LowerUADDSUBO_CARRY(SDValue Op, SelectionDAG &DAG) {
9579 SDNode *N = Op.getNode();
9580 EVT VT = N->getValueType(ResNo: 0);
9581 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::i32);
9582
9583 SDValue Carry = Op.getOperand(i: 2);
9584
9585 SDLoc DL(Op);
9586
9587 SDValue Result;
9588 if (Op.getOpcode() == ISD::UADDO_CARRY) {
9589 // This converts the boolean value carry into the carry flag.
9590 Carry = ConvertBooleanCarryToCarryFlag(BoolCarry: Carry, DAG);
9591
9592 // Do the addition proper using the carry flag we wanted.
9593 Result = DAG.getNode(Opcode: ARMISD::ADDE, DL, VTList: VTs, N1: Op.getOperand(i: 0),
9594 N2: Op.getOperand(i: 1), N3: Carry);
9595
9596 // Now convert the carry flag into a boolean value.
9597 Carry = ConvertCarryFlagToBooleanCarry(Flags: Result.getValue(R: 1), VT, DAG);
9598 } else {
9599 // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
9600 // have to invert the carry first.
9601 Carry = DAG.getNode(Opcode: ISD::SUB, DL, VT: MVT::i32,
9602 N1: DAG.getConstant(Val: 1, DL, VT: MVT::i32), N2: Carry);
9603 // This converts the boolean value carry into the carry flag.
9604 Carry = ConvertBooleanCarryToCarryFlag(BoolCarry: Carry, DAG);
9605
9606 // Do the subtraction proper using the carry flag we wanted.
9607 Result = DAG.getNode(Opcode: ARMISD::SUBE, DL, VTList: VTs, N1: Op.getOperand(i: 0),
9608 N2: Op.getOperand(i: 1), N3: Carry);
9609
9610 // Now convert the carry flag into a boolean value.
9611 Carry = ConvertCarryFlagToBooleanCarry(Flags: Result.getValue(R: 1), VT, DAG);
9612 // But the carry returned by ARMISD::SUBE is not a borrow as expected
9613 // by ISD::USUBO_CARRY, so compute 1 - C.
9614 Carry = DAG.getNode(Opcode: ISD::SUB, DL, VT: MVT::i32,
9615 N1: DAG.getConstant(Val: 1, DL, VT: MVT::i32), N2: Carry);
9616 }
9617
9618 // Return both values.
9619 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL, VTList: N->getVTList(), N1: Result, N2: Carry);
9620}
9621
9622SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9623 bool Signed,
9624 SDValue &Chain) const {
9625 EVT VT = Op.getValueType();
9626 assert((VT == MVT::i32 || VT == MVT::i64) &&
9627 "unexpected type for custom lowering DIV");
9628 SDLoc dl(Op);
9629
9630 const auto &DL = DAG.getDataLayout();
9631 RTLIB::Libcall LC;
9632 if (Signed)
9633 LC = VT == MVT::i32 ? RTLIB::SDIVREM_I32 : RTLIB::SDIVREM_I64;
9634 else
9635 LC = VT == MVT::i32 ? RTLIB::UDIVREM_I32 : RTLIB::UDIVREM_I64;
9636
9637 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(Call: LC);
9638 SDValue ES = DAG.getExternalSymbol(LCImpl, VT: getPointerTy(DL));
9639
9640 ARMTargetLowering::ArgListTy Args;
9641
9642 for (auto AI : {1, 0}) {
9643 SDValue Operand = Op.getOperand(i: AI);
9644 Args.emplace_back(args&: Operand,
9645 args: Operand.getValueType().getTypeForEVT(Context&: *DAG.getContext()));
9646 }
9647
9648 CallLoweringInfo CLI(DAG);
9649 CLI.setDebugLoc(dl).setChain(Chain).setCallee(
9650 CC: DAG.getLibcalls().getLibcallImplCallingConv(Call: LCImpl),
9651 ResultType: VT.getTypeForEVT(Context&: *DAG.getContext()), Target: ES, ArgsList: std::move(Args));
9652
9653 return LowerCallTo(CLI).first;
9654}
9655
9656// This is a code size optimisation: return the original SDIV node to
9657// DAGCombiner when we don't want to expand SDIV into a sequence of
9658// instructions, and an empty node otherwise which will cause the
9659// SDIV to be expanded in DAGCombine.
9660SDValue
9661ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9662 SelectionDAG &DAG,
9663 SmallVectorImpl<SDNode *> &Created) const {
9664 // TODO: Support SREM
9665 if (N->getOpcode() != ISD::SDIV)
9666 return SDValue();
9667
9668 const auto &ST = DAG.getSubtarget<ARMSubtarget>();
9669 const bool MinSize = ST.hasMinSize();
9670 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9671 : ST.hasDivideInARMMode();
9672
9673 // Don't touch vector types; rewriting this may lead to scalarizing
9674 // the int divs.
9675 if (N->getOperand(Num: 0).getValueType().isVector())
9676 return SDValue();
9677
9678 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9679 // hwdiv support for this to be really profitable.
9680 if (!(MinSize && HasDivide))
9681 return SDValue();
9682
9683 // ARM mode is a bit simpler than Thumb: we can handle large power
9684 // of 2 immediates with 1 mov instruction; no further checks required,
9685 // just return the sdiv node.
9686 if (!ST.isThumb())
9687 return SDValue(N, 0);
9688
9689 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9690 // and thus lose the code size benefits of a MOVS that requires only 2.
9691 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9692 // but as it's doing exactly this, it's not worth the trouble to get TTI.
9693 if (Divisor.sgt(RHS: 128))
9694 return SDValue();
9695
9696 return SDValue(N, 0);
9697}
9698
9699SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9700 bool Signed) const {
9701 assert(Op.getValueType() == MVT::i32 &&
9702 "unexpected type for custom lowering DIV");
9703 SDLoc dl(Op);
9704
9705 SDValue DBZCHK = DAG.getNode(Opcode: ARMISD::WIN__DBZCHK, DL: dl, VT: MVT::Other,
9706 N1: DAG.getEntryNode(), N2: Op.getOperand(i: 1));
9707
9708 return LowerWindowsDIVLibCall(Op, DAG, Signed, Chain&: DBZCHK);
9709}
9710
9711static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9712 SDLoc DL(N);
9713 SDValue Op = N->getOperand(Num: 1);
9714 if (N->getValueType(ResNo: 0) == MVT::i32)
9715 return DAG.getNode(Opcode: ARMISD::WIN__DBZCHK, DL, VT: MVT::Other, N1: InChain, N2: Op);
9716 SDValue Lo, Hi;
9717 std::tie(args&: Lo, args&: Hi) = DAG.SplitScalar(N: Op, DL, LoVT: MVT::i32, HiVT: MVT::i32);
9718 return DAG.getNode(Opcode: ARMISD::WIN__DBZCHK, DL, VT: MVT::Other, N1: InChain,
9719 N2: DAG.getNode(Opcode: ISD::OR, DL, VT: MVT::i32, N1: Lo, N2: Hi));
9720}
9721
9722void ARMTargetLowering::ExpandDIV_Windows(
9723 SDValue Op, SelectionDAG &DAG, bool Signed,
9724 SmallVectorImpl<SDValue> &Results) const {
9725 const auto &DL = DAG.getDataLayout();
9726
9727 assert(Op.getValueType() == MVT::i64 &&
9728 "unexpected type for custom lowering DIV");
9729 SDLoc dl(Op);
9730
9731 SDValue DBZCHK = WinDBZCheckDenominator(DAG, N: Op.getNode(), InChain: DAG.getEntryNode());
9732
9733 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, Chain&: DBZCHK);
9734
9735 SDValue Lower = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::i32, Operand: Result);
9736 SDValue Upper = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i64, N1: Result,
9737 N2: DAG.getConstant(Val: 32, DL: dl, VT: getPointerTy(DL)));
9738 Upper = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MVT::i32, Operand: Upper);
9739
9740 Results.push_back(Elt: DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lower, N2: Upper));
9741}
9742
9743std::pair<SDValue, SDValue>
9744ARMTargetLowering::LowerAEABIUnalignedLoad(SDValue Op,
9745 SelectionDAG &DAG) const {
9746 // If we have an unaligned load from a i32 or i64 that would normally be
9747 // split into separate ldrb's, we can use the __aeabi_uread4/__aeabi_uread8
9748 // functions instead.
9749 LoadSDNode *LD = cast<LoadSDNode>(Val: Op.getNode());
9750 EVT MemVT = LD->getMemoryVT();
9751 if (MemVT != MVT::i32 && MemVT != MVT::i64)
9752 return std::make_pair(x: SDValue(), y: SDValue());
9753
9754 const auto &MF = DAG.getMachineFunction();
9755 unsigned AS = LD->getAddressSpace();
9756 Align Alignment = LD->getAlign();
9757 const DataLayout &DL = DAG.getDataLayout();
9758 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9759
9760 if (MF.getFunction().hasMinSize() && !AllowsUnaligned &&
9761 Alignment <= llvm::Align(2)) {
9762
9763 RTLIB::Libcall LC =
9764 (MemVT == MVT::i32) ? RTLIB::AEABI_UREAD4 : RTLIB::AEABI_UREAD8;
9765
9766 MakeLibCallOptions Opts;
9767 SDLoc dl(Op);
9768
9769 auto Pair = makeLibCall(DAG, LC, RetVT: MemVT.getSimpleVT(), Ops: LD->getBasePtr(),
9770 CallOptions: Opts, dl, Chain: LD->getChain());
9771
9772 // If necessary, extend the node to 64bit
9773 if (LD->getExtensionType() != ISD::NON_EXTLOAD) {
9774 unsigned ExtType = LD->getExtensionType() == ISD::SEXTLOAD
9775 ? ISD::SIGN_EXTEND
9776 : ISD::ZERO_EXTEND;
9777 SDValue EN = DAG.getNode(Opcode: ExtType, DL: dl, VT: LD->getValueType(ResNo: 0), Operand: Pair.first);
9778 Pair.first = EN;
9779 }
9780 return Pair;
9781 }
9782
9783 // Default expand to individual loads
9784 if (!allowsMemoryAccess(Context&: *DAG.getContext(), DL, VT: MemVT, AddrSpace: AS, Alignment))
9785 return expandUnalignedLoad(LD, DAG);
9786 return std::make_pair(x: SDValue(), y: SDValue());
9787}
9788
9789SDValue ARMTargetLowering::LowerAEABIUnalignedStore(SDValue Op,
9790 SelectionDAG &DAG) const {
9791 // If we have an unaligned store to a i32 or i64 that would normally be
9792 // split into separate ldrb's, we can use the __aeabi_uwrite4/__aeabi_uwrite8
9793 // functions instead.
9794 StoreSDNode *ST = cast<StoreSDNode>(Val: Op.getNode());
9795 EVT MemVT = ST->getMemoryVT();
9796 if (MemVT != MVT::i32 && MemVT != MVT::i64)
9797 return SDValue();
9798
9799 const auto &MF = DAG.getMachineFunction();
9800 unsigned AS = ST->getAddressSpace();
9801 Align Alignment = ST->getAlign();
9802 const DataLayout &DL = DAG.getDataLayout();
9803 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9804
9805 if (MF.getFunction().hasMinSize() && !AllowsUnaligned &&
9806 Alignment <= llvm::Align(2)) {
9807
9808 SDLoc dl(Op);
9809
9810 // If necessary, trunc the value to 32bit
9811 SDValue StoreVal = ST->getOperand(Num: 1);
9812 if (ST->isTruncatingStore())
9813 StoreVal = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: MemVT, Operand: ST->getOperand(Num: 1));
9814
9815 RTLIB::Libcall LC =
9816 (MemVT == MVT::i32) ? RTLIB::AEABI_UWRITE4 : RTLIB::AEABI_UWRITE8;
9817
9818 MakeLibCallOptions Opts;
9819 auto CallResult =
9820 makeLibCall(DAG, LC, RetVT: MVT::isVoid, Ops: {StoreVal, ST->getBasePtr()}, CallOptions: Opts,
9821 dl, Chain: ST->getChain());
9822
9823 return CallResult.second;
9824 }
9825
9826 // Default expand to individual stores
9827 if (!allowsMemoryAccess(Context&: *DAG.getContext(), DL, VT: MemVT, AddrSpace: AS, Alignment))
9828 return expandUnalignedStore(ST, DAG);
9829 return SDValue();
9830}
9831
9832static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9833 LoadSDNode *LD = cast<LoadSDNode>(Val: Op.getNode());
9834 EVT MemVT = LD->getMemoryVT();
9835 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9836 MemVT == MVT::v16i1) &&
9837 "Expected a predicate type!");
9838 assert(MemVT == Op.getValueType());
9839 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9840 "Expected a non-extending load");
9841 assert(LD->isUnindexed() && "Expected a unindexed load");
9842
9843 // The basic MVE VLDR on a v2i1/v4i1/v8i1 actually loads the entire 16bit
9844 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9845 // need to make sure that 8/4/2 bits are actually loaded into the correct
9846 // place, which means loading the value and then shuffling the values into
9847 // the bottom bits of the predicate.
9848 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9849 // for BE).
9850 // Speaking of BE, apparently the rest of llvm will assume a reverse order to
9851 // a natural VMSR(load), so needs to be reversed.
9852
9853 SDLoc dl(Op);
9854 SDValue Load = DAG.getExtLoad(
9855 ExtType: ISD::EXTLOAD, dl, VT: MVT::i32, Chain: LD->getChain(), Ptr: LD->getBasePtr(),
9856 MemVT: EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: MemVT.getSizeInBits()),
9857 MMO: LD->getMemOperand());
9858 SDValue Val = Load;
9859 if (DAG.getDataLayout().isBigEndian())
9860 Val = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32,
9861 N1: DAG.getNode(Opcode: ISD::BITREVERSE, DL: dl, VT: MVT::i32, Operand: Load),
9862 N2: DAG.getConstant(Val: 32 - MemVT.getSizeInBits(), DL: dl, VT: MVT::i32));
9863 SDValue Pred = DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::v16i1, Operand: Val);
9864 if (MemVT != MVT::v16i1)
9865 Pred = DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL: dl, VT: MemVT, N1: Pred,
9866 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
9867 return DAG.getMergeValues(Ops: {Pred, Load.getValue(R: 1)}, dl);
9868}
9869
9870void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9871 SelectionDAG &DAG) const {
9872 LoadSDNode *LD = cast<LoadSDNode>(Val: N);
9873 EVT MemVT = LD->getMemoryVT();
9874
9875 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9876 !Subtarget->isThumb1Only() && LD->isVolatile() &&
9877 LD->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
9878 assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9879 SDLoc dl(N);
9880 SDValue Result = DAG.getMemIntrinsicNode(
9881 Opcode: ARMISD::LDRD, dl, VTList: DAG.getVTList(VTs: {MVT::i32, MVT::i32, MVT::Other}),
9882 Ops: {LD->getChain(), LD->getBasePtr()}, MemVT, MMO: LD->getMemOperand());
9883 SDValue Lo = Result.getValue(R: DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9884 SDValue Hi = Result.getValue(R: DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9885 SDValue Pair = DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lo, N2: Hi);
9886 Results.append(IL: {Pair, Result.getValue(R: 2)});
9887 } else if (MemVT == MVT::i32 || MemVT == MVT::i64) {
9888 auto Pair = LowerAEABIUnalignedLoad(Op: SDValue(N, 0), DAG);
9889 if (Pair.first) {
9890 Results.push_back(Elt: Pair.first);
9891 Results.push_back(Elt: Pair.second);
9892 }
9893 }
9894}
9895
9896static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9897 StoreSDNode *ST = cast<StoreSDNode>(Val: Op.getNode());
9898 EVT MemVT = ST->getMemoryVT();
9899 assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9900 MemVT == MVT::v16i1) &&
9901 "Expected a predicate type!");
9902 assert(MemVT == ST->getValue().getValueType());
9903 assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9904 assert(ST->isUnindexed() && "Expected a unindexed store");
9905
9906 // Only store the v2i1 or v4i1 or v8i1 worth of bits, via a buildvector with
9907 // top bits unset and a scalar store.
9908 SDLoc dl(Op);
9909 SDValue Build = ST->getValue();
9910 if (MemVT != MVT::v16i1) {
9911 SmallVector<SDValue, 16> Ops;
9912 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) {
9913 unsigned Elt = DAG.getDataLayout().isBigEndian()
9914 ? MemVT.getVectorNumElements() - I - 1
9915 : I;
9916 Ops.push_back(Elt: DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::i32, N1: Build,
9917 N2: DAG.getConstant(Val: Elt, DL: dl, VT: MVT::i32)));
9918 }
9919 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9920 Ops.push_back(Elt: DAG.getUNDEF(VT: MVT::i32));
9921 Build = DAG.getNode(Opcode: ISD::BUILD_VECTOR, DL: dl, VT: MVT::v16i1, Ops);
9922 }
9923 SDValue GRP = DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT: MVT::i32, Operand: Build);
9924 if (MemVT == MVT::v16i1 && DAG.getDataLayout().isBigEndian())
9925 GRP = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32,
9926 N1: DAG.getNode(Opcode: ISD::BITREVERSE, DL: dl, VT: MVT::i32, Operand: GRP),
9927 N2: DAG.getConstant(Val: 16, DL: dl, VT: MVT::i32));
9928 return DAG.getTruncStore(
9929 Chain: ST->getChain(), dl, Val: GRP, Ptr: ST->getBasePtr(),
9930 SVT: EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: MemVT.getSizeInBits()),
9931 MMO: ST->getMemOperand());
9932}
9933
9934SDValue ARMTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG,
9935 const ARMSubtarget *Subtarget) const {
9936 StoreSDNode *ST = cast<StoreSDNode>(Val: Op.getNode());
9937 EVT MemVT = ST->getMemoryVT();
9938
9939 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9940 !Subtarget->isThumb1Only() && ST->isVolatile() &&
9941 ST->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
9942 assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9943 SDNode *N = Op.getNode();
9944 SDLoc dl(N);
9945
9946 SDValue Lo = DAG.getNode(
9947 Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32, N1: ST->getValue(),
9948 N2: DAG.getTargetConstant(Val: DAG.getDataLayout().isLittleEndian() ? 0 : 1, DL: dl,
9949 VT: MVT::i32));
9950 SDValue Hi = DAG.getNode(
9951 Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32, N1: ST->getValue(),
9952 N2: DAG.getTargetConstant(Val: DAG.getDataLayout().isLittleEndian() ? 1 : 0, DL: dl,
9953 VT: MVT::i32));
9954
9955 return DAG.getMemIntrinsicNode(Opcode: ARMISD::STRD, dl, VTList: DAG.getVTList(VT: MVT::Other),
9956 Ops: {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9957 MemVT, MMO: ST->getMemOperand());
9958 } else if (Subtarget->hasMVEIntegerOps() &&
9959 ((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9960 MemVT == MVT::v16i1))) {
9961 return LowerPredicateStore(Op, DAG);
9962 } else if (MemVT == MVT::i32 || MemVT == MVT::i64) {
9963 return LowerAEABIUnalignedStore(Op, DAG);
9964 }
9965 return SDValue();
9966}
9967
9968static bool isZeroVector(SDValue N) {
9969 return (ISD::isBuildVectorAllZeros(N: N.getNode()) ||
9970 (N->getOpcode() == ARMISD::VMOVIMM &&
9971 isNullConstant(V: N->getOperand(Num: 0))));
9972}
9973
9974static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9975 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Val: Op.getNode());
9976 MVT VT = Op.getSimpleValueType();
9977 SDValue Mask = N->getMask();
9978 SDValue PassThru = N->getPassThru();
9979 SDLoc dl(Op);
9980
9981 if (isZeroVector(N: PassThru))
9982 return Op;
9983
9984 // MVE Masked loads use zero as the passthru value. Here we convert undef to
9985 // zero too, and other values are lowered to a select.
9986 SDValue ZeroVec = DAG.getNode(Opcode: ARMISD::VMOVIMM, DL: dl, VT,
9987 Operand: DAG.getTargetConstant(Val: 0, DL: dl, VT: MVT::i32));
9988 SDValue NewLoad = DAG.getMaskedLoad(
9989 VT, dl, Chain: N->getChain(), Base: N->getBasePtr(), Offset: N->getOffset(), Mask, Src0: ZeroVec,
9990 MemVT: N->getMemoryVT(), MMO: N->getMemOperand(), AM: N->getAddressingMode(),
9991 N->getExtensionType(), IsExpanding: N->isExpandingLoad());
9992 SDValue Combo = NewLoad;
9993 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9994 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9995 isZeroVector(N: PassThru->getOperand(Num: 0));
9996 if (!PassThru.isUndef() && !PassThruIsCastZero)
9997 Combo = DAG.getNode(Opcode: ISD::VSELECT, DL: dl, VT, N1: Mask, N2: NewLoad, N3: PassThru);
9998 return DAG.getMergeValues(Ops: {Combo, NewLoad.getValue(R: 1)}, dl);
9999}
10000
10001static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG,
10002 const ARMSubtarget *ST) {
10003 if (!ST->hasMVEIntegerOps())
10004 return SDValue();
10005
10006 SDLoc dl(Op);
10007 unsigned BaseOpcode = 0;
10008 switch (Op->getOpcode()) {
10009 default: llvm_unreachable("Expected VECREDUCE opcode");
10010 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
10011 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
10012 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break;
10013 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break;
10014 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break;
10015 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break;
10016 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
10017 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
10018 }
10019
10020 SDValue Op0 = Op->getOperand(Num: 0);
10021 EVT VT = Op0.getValueType();
10022 EVT EltVT = VT.getVectorElementType();
10023 unsigned NumElts = VT.getVectorNumElements();
10024 unsigned NumActiveLanes = NumElts;
10025
10026 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10027 NumActiveLanes == 2) &&
10028 "Only expected a power 2 vector size");
10029
10030 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
10031 // allows us to easily extract vector elements from the lanes.
10032 while (NumActiveLanes > 4) {
10033 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
10034 SDValue Rev = DAG.getNode(Opcode: RevOpcode, DL: dl, VT, Operand: Op0);
10035 Op0 = DAG.getNode(Opcode: BaseOpcode, DL: dl, VT, N1: Op0, N2: Rev);
10036 NumActiveLanes /= 2;
10037 }
10038
10039 SDValue Res;
10040 if (NumActiveLanes == 4) {
10041 // The remaining 4 elements are summed sequentially
10042 SDValue Ext0 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10043 N2: DAG.getConstant(Val: 0 * NumElts / 4, DL: dl, VT: MVT::i32));
10044 SDValue Ext1 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10045 N2: DAG.getConstant(Val: 1 * NumElts / 4, DL: dl, VT: MVT::i32));
10046 SDValue Ext2 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10047 N2: DAG.getConstant(Val: 2 * NumElts / 4, DL: dl, VT: MVT::i32));
10048 SDValue Ext3 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10049 N2: DAG.getConstant(Val: 3 * NumElts / 4, DL: dl, VT: MVT::i32));
10050 SDValue Res0 = DAG.getNode(Opcode: BaseOpcode, DL: dl, VT: EltVT, N1: Ext0, N2: Ext1, Flags: Op->getFlags());
10051 SDValue Res1 = DAG.getNode(Opcode: BaseOpcode, DL: dl, VT: EltVT, N1: Ext2, N2: Ext3, Flags: Op->getFlags());
10052 Res = DAG.getNode(Opcode: BaseOpcode, DL: dl, VT: EltVT, N1: Res0, N2: Res1, Flags: Op->getFlags());
10053 } else {
10054 SDValue Ext0 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10055 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
10056 SDValue Ext1 = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10057 N2: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
10058 Res = DAG.getNode(Opcode: BaseOpcode, DL: dl, VT: EltVT, N1: Ext0, N2: Ext1, Flags: Op->getFlags());
10059 }
10060
10061 // Result type may be wider than element type.
10062 if (EltVT != Op->getValueType(ResNo: 0))
10063 Res = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL: dl, VT: Op->getValueType(ResNo: 0), Operand: Res);
10064 return Res;
10065}
10066
10067static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG,
10068 const ARMSubtarget *ST) {
10069 if (!ST->hasMVEFloatOps())
10070 return SDValue();
10071 return LowerVecReduce(Op, DAG, ST);
10072}
10073
10074static SDValue LowerVecReduceMinMax(SDValue Op, SelectionDAG &DAG,
10075 const ARMSubtarget *ST) {
10076 if (!ST->hasNEON())
10077 return SDValue();
10078
10079 SDLoc dl(Op);
10080 SDValue Op0 = Op->getOperand(Num: 0);
10081 EVT VT = Op0.getValueType();
10082 EVT EltVT = VT.getVectorElementType();
10083
10084 unsigned PairwiseIntrinsic = 0;
10085 switch (Op->getOpcode()) {
10086 default:
10087 llvm_unreachable("Expected VECREDUCE opcode");
10088 case ISD::VECREDUCE_UMIN:
10089 PairwiseIntrinsic = Intrinsic::arm_neon_vpminu;
10090 break;
10091 case ISD::VECREDUCE_UMAX:
10092 PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxu;
10093 break;
10094 case ISD::VECREDUCE_SMIN:
10095 PairwiseIntrinsic = Intrinsic::arm_neon_vpmins;
10096 break;
10097 case ISD::VECREDUCE_SMAX:
10098 PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxs;
10099 break;
10100 }
10101 SDValue PairwiseOp = DAG.getConstant(Val: PairwiseIntrinsic, DL: dl, VT: MVT::i32);
10102
10103 unsigned NumElts = VT.getVectorNumElements();
10104 unsigned NumActiveLanes = NumElts;
10105
10106 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10107 NumActiveLanes == 2) &&
10108 "Only expected a power 2 vector size");
10109
10110 // Split 128-bit vectors, since vpmin/max takes 2 64-bit vectors.
10111 if (VT.is128BitVector()) {
10112 SDValue Lo, Hi;
10113 std::tie(args&: Lo, args&: Hi) = DAG.SplitVector(N: Op0, DL: dl);
10114 VT = Lo.getValueType();
10115 Op0 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT, Ops: {PairwiseOp, Lo, Hi});
10116 NumActiveLanes /= 2;
10117 }
10118
10119 // Use pairwise reductions until one lane remains
10120 while (NumActiveLanes > 1) {
10121 Op0 = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT, Ops: {PairwiseOp, Op0, Op0});
10122 NumActiveLanes /= 2;
10123 }
10124
10125 SDValue Res = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: EltVT, N1: Op0,
10126 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
10127
10128 // Result type may be wider than element type.
10129 if (EltVT != Op.getValueType()) {
10130 unsigned Extend = 0;
10131 switch (Op->getOpcode()) {
10132 default:
10133 llvm_unreachable("Expected VECREDUCE opcode");
10134 case ISD::VECREDUCE_UMIN:
10135 case ISD::VECREDUCE_UMAX:
10136 Extend = ISD::ZERO_EXTEND;
10137 break;
10138 case ISD::VECREDUCE_SMIN:
10139 case ISD::VECREDUCE_SMAX:
10140 Extend = ISD::SIGN_EXTEND;
10141 break;
10142 }
10143 Res = DAG.getNode(Opcode: Extend, DL: dl, VT: Op.getValueType(), Operand: Res);
10144 }
10145 return Res;
10146}
10147
10148static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
10149 if (isStrongerThanMonotonic(AO: cast<AtomicSDNode>(Val&: Op)->getSuccessOrdering()))
10150 // Acquire/Release load/store is not legal for targets without a dmb or
10151 // equivalent available.
10152 return SDValue();
10153
10154 // Monotonic load/store is legal for all targets.
10155 return Op;
10156}
10157
10158static void ReplaceREADCYCLECOUNTER(SDNode *N,
10159 SmallVectorImpl<SDValue> &Results,
10160 SelectionDAG &DAG,
10161 const ARMSubtarget *Subtarget) {
10162 SDLoc DL(N);
10163 // Under Power Management extensions, the cycle-count is:
10164 // mrc p15, #0, <Rt>, c9, c13, #0
10165 SDValue Ops[] = { N->getOperand(Num: 0), // Chain
10166 DAG.getTargetConstant(Val: Intrinsic::arm_mrc, DL, VT: MVT::i32),
10167 DAG.getTargetConstant(Val: 15, DL, VT: MVT::i32),
10168 DAG.getTargetConstant(Val: 0, DL, VT: MVT::i32),
10169 DAG.getTargetConstant(Val: 9, DL, VT: MVT::i32),
10170 DAG.getTargetConstant(Val: 13, DL, VT: MVT::i32),
10171 DAG.getTargetConstant(Val: 0, DL, VT: MVT::i32)
10172 };
10173
10174 SDValue Cycles32 = DAG.getNode(Opcode: ISD::INTRINSIC_W_CHAIN, DL,
10175 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), Ops);
10176 Results.push_back(Elt: DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VT: MVT::i64, N1: Cycles32,
10177 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32)));
10178 Results.push_back(Elt: Cycles32.getValue(R: 1));
10179}
10180
10181static SDValue createGPRPairNode2xi32(SelectionDAG &DAG, SDValue V0,
10182 SDValue V1) {
10183 SDLoc dl(V0.getNode());
10184 SDValue RegClass =
10185 DAG.getTargetConstant(Val: ARM::GPRPairRegClassID, DL: dl, VT: MVT::i32);
10186 SDValue SubReg0 = DAG.getTargetConstant(Val: ARM::gsub_0, DL: dl, VT: MVT::i32);
10187 SDValue SubReg1 = DAG.getTargetConstant(Val: ARM::gsub_1, DL: dl, VT: MVT::i32);
10188 const SDValue Ops[] = {RegClass, V0, SubReg0, V1, SubReg1};
10189 return SDValue(
10190 DAG.getMachineNode(Opcode: TargetOpcode::REG_SEQUENCE, dl, VT: MVT::Untyped, Ops), 0);
10191}
10192
10193static SDValue createGPRPairNodei64(SelectionDAG &DAG, SDValue V) {
10194 SDLoc dl(V.getNode());
10195 auto [VLo, VHi] = DAG.SplitScalar(N: V, DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
10196 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10197 if (isBigEndian)
10198 std::swap(a&: VLo, b&: VHi);
10199 return createGPRPairNode2xi32(DAG, V0: VLo, V1: VHi);
10200}
10201
10202static void ReplaceCMP_SWAP_64Results(SDNode *N,
10203 SmallVectorImpl<SDValue> &Results,
10204 SelectionDAG &DAG) {
10205 assert(N->getValueType(0) == MVT::i64 &&
10206 "AtomicCmpSwap on types less than 64 should be legal");
10207 SDValue Ops[] = {
10208 createGPRPairNode2xi32(DAG, V0: N->getOperand(Num: 1),
10209 V1: DAG.getUNDEF(VT: MVT::i32)), // pointer, temp
10210 createGPRPairNodei64(DAG, V: N->getOperand(Num: 2)), // expected
10211 createGPRPairNodei64(DAG, V: N->getOperand(Num: 3)), // new
10212 N->getOperand(Num: 0), // chain in
10213 };
10214 SDNode *CmpSwap = DAG.getMachineNode(
10215 Opcode: ARM::CMP_SWAP_64, dl: SDLoc(N),
10216 VTs: DAG.getVTList(VT1: MVT::Untyped, VT2: MVT::Untyped, VT3: MVT::Other), Ops);
10217
10218 MachineMemOperand *MemOp = cast<MemSDNode>(Val: N)->getMemOperand();
10219 DAG.setNodeMemRefs(N: cast<MachineSDNode>(Val: CmpSwap), NewMemRefs: {MemOp});
10220
10221 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10222
10223 SDValue Lo =
10224 DAG.getTargetExtractSubreg(SRIdx: isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
10225 DL: SDLoc(N), VT: MVT::i32, Operand: SDValue(CmpSwap, 0));
10226 SDValue Hi =
10227 DAG.getTargetExtractSubreg(SRIdx: isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
10228 DL: SDLoc(N), VT: MVT::i32, Operand: SDValue(CmpSwap, 0));
10229 Results.push_back(Elt: DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: SDLoc(N), VT: MVT::i64, N1: Lo, N2: Hi));
10230 Results.push_back(Elt: SDValue(CmpSwap, 2));
10231}
10232
10233SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
10234 SDLoc dl(Op);
10235 EVT VT = Op.getValueType();
10236 SDValue Chain = Op.getOperand(i: 0);
10237 SDValue LHS = Op.getOperand(i: 1);
10238 SDValue RHS = Op.getOperand(i: 2);
10239 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 3))->get();
10240 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
10241
10242 // If we don't have instructions of this float type then soften to a libcall
10243 // and use SETCC instead.
10244 if (isUnsupportedFloatingType(VT: LHS.getValueType())) {
10245 softenSetCCOperands(DAG, VT: LHS.getValueType(), NewLHS&: LHS, NewRHS&: RHS, CCCode&: CC, DL: dl, OldLHS: LHS, OldRHS: RHS,
10246 Chain, IsSignaling);
10247 if (!RHS.getNode()) {
10248 RHS = DAG.getConstant(Val: 0, DL: dl, VT: LHS.getValueType());
10249 CC = ISD::SETNE;
10250 }
10251 SDValue Result = DAG.getNode(Opcode: ISD::SETCC, DL: dl, VT, N1: LHS, N2: RHS,
10252 N3: DAG.getCondCode(Cond: CC));
10253 return DAG.getMergeValues(Ops: {Result, Chain}, dl);
10254 }
10255
10256 ARMCC::CondCodes CondCode, CondCode2;
10257 FPCCToARMCC(CC, CondCode, CondCode2);
10258
10259 SDValue True = DAG.getConstant(Val: 1, DL: dl, VT);
10260 SDValue False = DAG.getConstant(Val: 0, DL: dl, VT);
10261 SDValue ARMcc = DAG.getConstant(Val: CondCode, DL: dl, VT: MVT::i32);
10262 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, Signaling: IsSignaling);
10263 SDValue Result = getCMOV(dl, VT, FalseVal: False, TrueVal: True, ARMcc, Flags: Cmp, DAG);
10264 if (CondCode2 != ARMCC::AL) {
10265 ARMcc = DAG.getConstant(Val: CondCode2, DL: dl, VT: MVT::i32);
10266 Result = getCMOV(dl, VT, FalseVal: Result, TrueVal: True, ARMcc, Flags: Cmp, DAG);
10267 }
10268 return DAG.getMergeValues(Ops: {Result, Chain}, dl);
10269}
10270
10271SDValue ARMTargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const {
10272 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10273
10274 EVT VT = getPointerTy(DL: DAG.getDataLayout());
10275 int FI = MFI.CreateFixedObject(Size: 4, SPOffset: 0, IsImmutable: false);
10276 return DAG.getFrameIndex(FI, VT);
10277}
10278
10279SDValue ARMTargetLowering::LowerFP_TO_BF16(SDValue Op,
10280 SelectionDAG &DAG) const {
10281 SDLoc DL(Op);
10282 MakeLibCallOptions CallOptions;
10283 MVT SVT = Op.getOperand(i: 0).getSimpleValueType();
10284 RTLIB::Libcall LC = RTLIB::getFPROUND(OpVT: SVT, RetVT: MVT::bf16);
10285 SDValue Res =
10286 makeLibCall(DAG, LC, RetVT: MVT::f32, Ops: Op.getOperand(i: 0), CallOptions, dl: DL).first;
10287 return DAG.getBitcast(VT: MVT::i32, V: Res);
10288}
10289
10290SDValue ARMTargetLowering::LowerCMP(SDValue Op, SelectionDAG &DAG) const {
10291 SDLoc dl(Op);
10292 SDValue LHS = Op.getOperand(i: 0);
10293 SDValue RHS = Op.getOperand(i: 1);
10294
10295 // Determine if this is signed or unsigned comparison
10296 bool IsSigned = (Op.getOpcode() == ISD::SCMP);
10297
10298 // Special case for Thumb1 UCMP only
10299 if (!IsSigned && Subtarget->isThumb1Only()) {
10300 // For Thumb unsigned comparison, use this sequence:
10301 // subs r2, r0, r1 ; r2 = LHS - RHS, sets flags
10302 // sbc r2, r2 ; r2 = r2 - r2 - !carry
10303 // cmp r1, r0 ; compare RHS with LHS
10304 // sbc r1, r1 ; r1 = r1 - r1 - !carry
10305 // subs r0, r2, r1 ; r0 = r2 - r1 (final result)
10306
10307 // First subtraction: LHS - RHS
10308 SDValue Sub1WithFlags = DAG.getNode(
10309 Opcode: ARMISD::SUBC, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT), N1: LHS, N2: RHS);
10310 SDValue Sub1Result = Sub1WithFlags.getValue(R: 0);
10311 SDValue Flags1 = Sub1WithFlags.getValue(R: 1);
10312
10313 // SUBE: Sub1Result - Sub1Result - !carry
10314 // This gives 0 if LHS >= RHS (unsigned), -1 if LHS < RHS (unsigned)
10315 SDValue Sbc1 =
10316 DAG.getNode(Opcode: ARMISD::SUBE, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT),
10317 N1: Sub1Result, N2: Sub1Result, N3: Flags1);
10318 SDValue Sbc1Result = Sbc1.getValue(R: 0);
10319
10320 // Second comparison: RHS vs LHS (reverse comparison)
10321 SDValue CmpFlags = DAG.getNode(Opcode: ARMISD::CMP, DL: dl, VT: FlagsVT, N1: RHS, N2: LHS);
10322
10323 // SUBE: RHS - RHS - !carry
10324 // This gives 0 if RHS <= LHS (unsigned), -1 if RHS > LHS (unsigned)
10325 SDValue Sbc2 = DAG.getNode(
10326 Opcode: ARMISD::SUBE, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT), N1: RHS, N2: RHS, N3: CmpFlags);
10327 SDValue Sbc2Result = Sbc2.getValue(R: 0);
10328
10329 // Final subtraction: Sbc1Result - Sbc2Result (no flags needed)
10330 SDValue Result =
10331 DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32, N1: Sbc1Result, N2: Sbc2Result);
10332 if (Op.getValueType() != MVT::i32)
10333 Result = DAG.getSExtOrTrunc(Op: Result, DL: dl, VT: Op.getValueType());
10334
10335 return Result;
10336 }
10337
10338 // For the ARM assembly pattern:
10339 // subs r0, r0, r1 ; subtract RHS from LHS and set flags
10340 // movgt r0, #1 ; if LHS > RHS, set result to 1 (GT for signed, HI for
10341 // unsigned) mvnlt r0, #0 ; if LHS < RHS, set result to -1 (LT for
10342 // signed, LO for unsigned)
10343 // ; if LHS == RHS, result remains 0 from the subs
10344
10345 // Optimization: if RHS is a subtraction against 0, use ADDC instead of SUBC
10346 unsigned Opcode = ARMISD::SUBC;
10347
10348 // Check if RHS is a subtraction against 0: (0 - X)
10349 if (RHS.getOpcode() == ISD::SUB) {
10350 SDValue SubLHS = RHS.getOperand(i: 0);
10351 SDValue SubRHS = RHS.getOperand(i: 1);
10352
10353 // Check if it's 0 - X
10354 if (isNullConstant(V: SubLHS)) {
10355 bool CanUseAdd = false;
10356 if (IsSigned) {
10357 // For SCMP: only if X is known to never be INT_MIN (to avoid overflow)
10358 if (RHS->getFlags().hasNoSignedWrap() || !DAG.computeKnownBits(Op: SubRHS)
10359 .getSignedMinValue()
10360 .isMinSignedValue()) {
10361 CanUseAdd = true;
10362 }
10363 } else {
10364 // For UCMP: only if X is known to never be zero
10365 if (DAG.isKnownNeverZero(Op: SubRHS)) {
10366 CanUseAdd = true;
10367 }
10368 }
10369
10370 if (CanUseAdd) {
10371 Opcode = ARMISD::ADDC;
10372 RHS = SubRHS; // Replace RHS with X, so we do LHS + X instead of
10373 // LHS - (0 - X)
10374 }
10375 }
10376 }
10377
10378 // Generate the operation with flags
10379 SDValue OpWithFlags =
10380 DAG.getNode(Opcode, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: FlagsVT), N1: LHS, N2: RHS);
10381
10382 SDValue OpResult = OpWithFlags.getValue(R: 0);
10383 SDValue Flags = OpWithFlags.getValue(R: 1);
10384
10385 // Constants for conditional moves
10386 SDValue One = DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32);
10387 SDValue MinusOne = DAG.getAllOnesConstant(DL: dl, VT: MVT::i32);
10388
10389 // Select condition codes based on signed vs unsigned
10390 ARMCC::CondCodes GTCond = IsSigned ? ARMCC::GT : ARMCC::HI;
10391 ARMCC::CondCodes LTCond = IsSigned ? ARMCC::LT : ARMCC::LO;
10392
10393 // First conditional move: if greater than, set to 1
10394 SDValue GTCondValue = DAG.getConstant(Val: GTCond, DL: dl, VT: MVT::i32);
10395 SDValue Result1 = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT: MVT::i32, N1: OpResult, N2: One,
10396 N3: GTCondValue, N4: Flags);
10397
10398 // Second conditional move: if less than, set to -1
10399 SDValue LTCondValue = DAG.getConstant(Val: LTCond, DL: dl, VT: MVT::i32);
10400 SDValue Result2 = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT: MVT::i32, N1: Result1, N2: MinusOne,
10401 N3: LTCondValue, N4: Flags);
10402
10403 if (Op.getValueType() != MVT::i32)
10404 Result2 = DAG.getSExtOrTrunc(Op: Result2, DL: dl, VT: Op.getValueType());
10405
10406 return Result2;
10407}
10408
10409SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10410 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
10411 switch (Op.getOpcode()) {
10412 default: llvm_unreachable("Don't know how to custom lower this!");
10413 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
10414 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10415 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10416 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10417 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10418 case ISD::SELECT: return LowerSELECT(Op, DAG);
10419 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
10420 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10421 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
10422 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
10423 case ISD::VASTART: return LowerVASTART(Op, DAG);
10424 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
10425 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
10426 case ISD::SINT_TO_FP:
10427 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
10428 case ISD::STRICT_FP_TO_SINT:
10429 case ISD::STRICT_FP_TO_UINT:
10430 case ISD::FP_TO_SINT:
10431 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
10432 case ISD::FP_TO_SINT_SAT:
10433 case ISD::FP_TO_UINT_SAT: return LowerFP_TO_INT_SAT(Op, DAG, Subtarget);
10434 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10435 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10436 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10437 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
10438 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
10439 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
10440 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
10441 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
10442 Subtarget);
10443 case ISD::BITCAST: return ExpandBITCAST(N: Op.getNode(), DAG, Subtarget);
10444 case ISD::SHL:
10445 case ISD::SRL:
10446 case ISD::SRA: return LowerShift(N: Op.getNode(), DAG, ST: Subtarget);
10447 case ISD::SREM: return LowerREM(N: Op.getNode(), DAG);
10448 case ISD::UREM: return LowerREM(N: Op.getNode(), DAG);
10449 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
10450 case ISD::SRL_PARTS:
10451 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
10452 case ISD::CTTZ:
10453 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(N: Op.getNode(), DAG, ST: Subtarget);
10454 case ISD::CTPOP: return LowerCTPOP(N: Op.getNode(), DAG, ST: Subtarget);
10455 case ISD::SETCC: return LowerVSETCC(Op, DAG, ST: Subtarget);
10456 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
10457 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, ST: Subtarget);
10458 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, ST: Subtarget);
10459 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, ST: Subtarget);
10460 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, ST: Subtarget);
10461 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10462 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, ST: Subtarget);
10463 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, ST: Subtarget);
10464 case ISD::TRUNCATE: return LowerTruncate(N: Op.getNode(), DAG, Subtarget);
10465 case ISD::SIGN_EXTEND:
10466 case ISD::ZERO_EXTEND: return LowerVectorExtend(N: Op.getNode(), DAG, Subtarget);
10467 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG);
10468 case ISD::SET_ROUNDING: return LowerSET_ROUNDING(Op, DAG);
10469 case ISD::SET_FPMODE:
10470 return LowerSET_FPMODE(Op, DAG);
10471 case ISD::RESET_FPMODE:
10472 return LowerRESET_FPMODE(Op, DAG);
10473 case ISD::MUL: return LowerMUL(Op, DAG);
10474 case ISD::SDIV:
10475 if (getTargetMachine().getTargetTriple().isOSWindows() &&
10476 !Op.getValueType().isVector())
10477 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
10478 return LowerSDIV(Op, DAG, ST: Subtarget);
10479 case ISD::UDIV:
10480 if (getTargetMachine().getTargetTriple().isOSWindows() &&
10481 !Op.getValueType().isVector())
10482 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
10483 return LowerUDIV(Op, DAG, ST: Subtarget);
10484 case ISD::UADDO_CARRY:
10485 case ISD::USUBO_CARRY:
10486 return LowerUADDSUBO_CARRY(Op, DAG);
10487 case ISD::UADDO:
10488 case ISD::USUBO:
10489 case ISD::UMULO:
10490 case ISD::SADDO:
10491 case ISD::SSUBO:
10492 case ISD::SMULO:
10493 return LowerALUO(Op, DAG);
10494 case ISD::SADDSAT:
10495 case ISD::SSUBSAT:
10496 case ISD::UADDSAT:
10497 case ISD::USUBSAT:
10498 return LowerADDSUBSAT(Op, DAG, Subtarget);
10499 case ISD::LOAD: {
10500 auto *LD = cast<LoadSDNode>(Val&: Op);
10501 EVT MemVT = LD->getMemoryVT();
10502 if (Subtarget->hasMVEIntegerOps() &&
10503 (MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10504 MemVT == MVT::v16i1))
10505 return LowerPredicateLoad(Op, DAG);
10506
10507 auto Pair = LowerAEABIUnalignedLoad(Op, DAG);
10508 if (Pair.first)
10509 return DAG.getMergeValues(Ops: {Pair.first, Pair.second}, dl: SDLoc(Pair.first));
10510 return SDValue();
10511 }
10512 case ISD::STORE:
10513 return LowerSTORE(Op, DAG, Subtarget);
10514 case ISD::MLOAD:
10515 return LowerMLOAD(Op, DAG);
10516 case ISD::VECREDUCE_MUL:
10517 case ISD::VECREDUCE_AND:
10518 case ISD::VECREDUCE_OR:
10519 case ISD::VECREDUCE_XOR:
10520 return LowerVecReduce(Op, DAG, ST: Subtarget);
10521 case ISD::VECREDUCE_FADD:
10522 case ISD::VECREDUCE_FMUL:
10523 case ISD::VECREDUCE_FMIN:
10524 case ISD::VECREDUCE_FMAX:
10525 return LowerVecReduceF(Op, DAG, ST: Subtarget);
10526 case ISD::VECREDUCE_UMIN:
10527 case ISD::VECREDUCE_UMAX:
10528 case ISD::VECREDUCE_SMIN:
10529 case ISD::VECREDUCE_SMAX:
10530 return LowerVecReduceMinMax(Op, DAG, ST: Subtarget);
10531 case ISD::ATOMIC_LOAD:
10532 case ISD::ATOMIC_STORE:
10533 return LowerAtomicLoadStore(Op, DAG);
10534 case ISD::SDIVREM:
10535 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
10536 case ISD::DYNAMIC_STACKALLOC:
10537 if (getTargetMachine().getTargetTriple().isOSWindows())
10538 return LowerDYNAMIC_STACKALLOC(Op, DAG);
10539 llvm_unreachable("Don't know how to custom lower this!");
10540 case ISD::STRICT_FP_ROUND:
10541 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
10542 case ISD::STRICT_FP_EXTEND:
10543 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
10544 case ISD::STRICT_FSETCC:
10545 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
10546 case ISD::SPONENTRY:
10547 return LowerSPONENTRY(Op, DAG);
10548 case ISD::FP_TO_BF16:
10549 return LowerFP_TO_BF16(Op, DAG);
10550 case ARMISD::WIN__DBZCHK: return SDValue();
10551 case ISD::UCMP:
10552 case ISD::SCMP:
10553 return LowerCMP(Op, DAG);
10554 case ISD::ABS:
10555 return LowerABS(Op, DAG);
10556 case ISD::STRICT_LROUND:
10557 case ISD::STRICT_LLROUND:
10558 case ISD::STRICT_LRINT:
10559 case ISD::STRICT_LLRINT: {
10560 assert((Op.getOperand(1).getValueType() == MVT::f16 ||
10561 Op.getOperand(1).getValueType() == MVT::bf16) &&
10562 "Expected custom lowering of rounding operations only for f16");
10563 SDLoc DL(Op);
10564 SDValue Ext = DAG.getNode(Opcode: ISD::STRICT_FP_EXTEND, DL, ResultTys: {MVT::f32, MVT::Other},
10565 Ops: {Op.getOperand(i: 0), Op.getOperand(i: 1)});
10566 return DAG.getNode(Opcode: Op.getOpcode(), DL, ResultTys: {Op.getValueType(), MVT::Other},
10567 Ops: {Ext.getValue(R: 1), Ext.getValue(R: 0)});
10568 }
10569 }
10570}
10571
10572static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
10573 SelectionDAG &DAG) {
10574 unsigned IntNo = N->getConstantOperandVal(Num: 0);
10575 unsigned Opc = 0;
10576 if (IntNo == Intrinsic::arm_smlald)
10577 Opc = ARMISD::SMLALD;
10578 else if (IntNo == Intrinsic::arm_smlaldx)
10579 Opc = ARMISD::SMLALDX;
10580 else if (IntNo == Intrinsic::arm_smlsld)
10581 Opc = ARMISD::SMLSLD;
10582 else if (IntNo == Intrinsic::arm_smlsldx)
10583 Opc = ARMISD::SMLSLDX;
10584 else
10585 return;
10586
10587 SDLoc dl(N);
10588 SDValue Lo, Hi;
10589 std::tie(args&: Lo, args&: Hi) = DAG.SplitScalar(N: N->getOperand(Num: 3), DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
10590
10591 SDValue LongMul = DAG.getNode(Opcode: Opc, DL: dl,
10592 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
10593 N1: N->getOperand(Num: 1), N2: N->getOperand(Num: 2),
10594 N3: Lo, N4: Hi);
10595 Results.push_back(Elt: DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64,
10596 N1: LongMul.getValue(R: 0), N2: LongMul.getValue(R: 1)));
10597}
10598
10599/// ReplaceNodeResults - Replace the results of node with an illegal result
10600/// type with new values built out of custom code.
10601void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
10602 SmallVectorImpl<SDValue> &Results,
10603 SelectionDAG &DAG) const {
10604 SDValue Res;
10605 switch (N->getOpcode()) {
10606 default:
10607 llvm_unreachable("Don't know how to custom expand this!");
10608 case ISD::READ_REGISTER:
10609 ExpandREAD_REGISTER(N, Results, DAG);
10610 break;
10611 case ISD::BITCAST:
10612 Res = ExpandBITCAST(N, DAG, Subtarget);
10613 break;
10614 case ISD::SRL:
10615 case ISD::SRA:
10616 case ISD::SHL:
10617 Res = Expand64BitShift(N, DAG, ST: Subtarget);
10618 break;
10619 case ISD::SREM:
10620 case ISD::UREM:
10621 Res = LowerREM(N, DAG);
10622 break;
10623 case ISD::SDIVREM:
10624 case ISD::UDIVREM:
10625 Res = LowerDivRem(Op: SDValue(N, 0), DAG);
10626 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
10627 Results.push_back(Elt: Res.getValue(R: 0));
10628 Results.push_back(Elt: Res.getValue(R: 1));
10629 return;
10630 case ISD::SADDSAT:
10631 case ISD::SSUBSAT:
10632 case ISD::UADDSAT:
10633 case ISD::USUBSAT:
10634 Res = LowerADDSUBSAT(Op: SDValue(N, 0), DAG, Subtarget);
10635 break;
10636 case ISD::READCYCLECOUNTER:
10637 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
10638 return;
10639 case ISD::UDIV:
10640 case ISD::SDIV:
10641 assert(getTargetMachine().getTargetTriple().isOSWindows() &&
10642 "can only expand DIV on Windows");
10643 return ExpandDIV_Windows(Op: SDValue(N, 0), DAG, Signed: N->getOpcode() == ISD::SDIV,
10644 Results);
10645 case ISD::ATOMIC_CMP_SWAP:
10646 ReplaceCMP_SWAP_64Results(N, Results, DAG);
10647 return;
10648 case ISD::INTRINSIC_WO_CHAIN:
10649 return ReplaceLongIntrinsic(N, Results, DAG);
10650 case ISD::LOAD:
10651 LowerLOAD(N, Results, DAG);
10652 break;
10653 case ISD::STORE:
10654 Res = LowerAEABIUnalignedStore(Op: SDValue(N, 0), DAG);
10655 break;
10656 case ISD::TRUNCATE:
10657 Res = LowerTruncate(N, DAG, Subtarget);
10658 break;
10659 case ISD::SIGN_EXTEND:
10660 case ISD::ZERO_EXTEND:
10661 Res = LowerVectorExtend(N, DAG, Subtarget);
10662 break;
10663 case ISD::FP_TO_SINT_SAT:
10664 case ISD::FP_TO_UINT_SAT:
10665 Res = LowerFP_TO_INT_SAT(Op: SDValue(N, 0), DAG, Subtarget);
10666 break;
10667 }
10668 if (Res.getNode())
10669 Results.push_back(Elt: Res);
10670}
10671
10672//===----------------------------------------------------------------------===//
10673// ARM Scheduler Hooks
10674//===----------------------------------------------------------------------===//
10675
10676/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
10677/// registers the function context.
10678void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
10679 MachineBasicBlock *MBB,
10680 MachineBasicBlock *DispatchBB,
10681 int FI) const {
10682 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
10683 "ROPI/RWPI not currently supported with SjLj");
10684 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10685 DebugLoc dl = MI.getDebugLoc();
10686 MachineFunction *MF = MBB->getParent();
10687 MachineRegisterInfo *MRI = &MF->getRegInfo();
10688 MachineConstantPool *MCP = MF->getConstantPool();
10689 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
10690 const Function &F = MF->getFunction();
10691
10692 bool isThumb = Subtarget->isThumb();
10693 bool isThumb2 = Subtarget->isThumb2();
10694
10695 unsigned PCLabelId = AFI->createPICLabelUId();
10696 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
10697 ARMConstantPoolValue *CPV =
10698 ARMConstantPoolMBB::Create(C&: F.getContext(), mbb: DispatchBB, ID: PCLabelId, PCAdj);
10699 unsigned CPI = MCP->getConstantPoolIndex(V: CPV, Alignment: Align(4));
10700
10701 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
10702 : &ARM::GPRRegClass;
10703
10704 // Grab constant pool and fixed stack memory operands.
10705 MachineMemOperand *CPMMO =
10706 MF->getMachineMemOperand(PtrInfo: MachinePointerInfo::getConstantPool(MF&: *MF),
10707 F: MachineMemOperand::MOLoad, Size: 4, BaseAlignment: Align(4));
10708
10709 MachineMemOperand *FIMMOSt =
10710 MF->getMachineMemOperand(PtrInfo: MachinePointerInfo::getFixedStack(MF&: *MF, FI),
10711 F: MachineMemOperand::MOStore, Size: 4, BaseAlignment: Align(4));
10712
10713 // Load the address of the dispatch MBB into the jump buffer.
10714 if (isThumb2) {
10715 // Incoming value: jbuf
10716 // ldr.n r5, LCPI1_1
10717 // orr r5, r5, #1
10718 // add r5, pc
10719 // str r5, [$jbuf, #+4] ; &jbuf[1]
10720 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
10721 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::t2LDRpci), DestReg: NewVReg1)
10722 .addConstantPoolIndex(Idx: CPI)
10723 .addMemOperand(MMO: CPMMO)
10724 .add(MOs: predOps(Pred: ARMCC::AL));
10725 // Set the low bit because of thumb mode.
10726 Register NewVReg2 = MRI->createVirtualRegister(RegClass: TRC);
10727 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::t2ORRri), DestReg: NewVReg2)
10728 .addReg(RegNo: NewVReg1, Flags: RegState::Kill)
10729 .addImm(Val: 0x01)
10730 .add(MOs: predOps(Pred: ARMCC::AL))
10731 .add(MO: condCodeOp());
10732 Register NewVReg3 = MRI->createVirtualRegister(RegClass: TRC);
10733 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tPICADD), DestReg: NewVReg3)
10734 .addReg(RegNo: NewVReg2, Flags: RegState::Kill)
10735 .addImm(Val: PCLabelId);
10736 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::t2STRi12))
10737 .addReg(RegNo: NewVReg3, Flags: RegState::Kill)
10738 .addFrameIndex(Idx: FI)
10739 .addImm(Val: 36) // &jbuf[1] :: pc
10740 .addMemOperand(MMO: FIMMOSt)
10741 .add(MOs: predOps(Pred: ARMCC::AL));
10742 } else if (isThumb) {
10743 // Incoming value: jbuf
10744 // ldr.n r1, LCPI1_4
10745 // add r1, pc
10746 // mov r2, #1
10747 // orrs r1, r2
10748 // add r2, $jbuf, #+4 ; &jbuf[1]
10749 // str r1, [r2]
10750 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
10751 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDRpci), DestReg: NewVReg1)
10752 .addConstantPoolIndex(Idx: CPI)
10753 .addMemOperand(MMO: CPMMO)
10754 .add(MOs: predOps(Pred: ARMCC::AL));
10755 Register NewVReg2 = MRI->createVirtualRegister(RegClass: TRC);
10756 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tPICADD), DestReg: NewVReg2)
10757 .addReg(RegNo: NewVReg1, Flags: RegState::Kill)
10758 .addImm(Val: PCLabelId);
10759 // Set the low bit because of thumb mode.
10760 Register NewVReg3 = MRI->createVirtualRegister(RegClass: TRC);
10761 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tMOVi8), DestReg: NewVReg3)
10762 .addReg(RegNo: ARM::CPSR, Flags: RegState::Define)
10763 .addImm(Val: 1)
10764 .add(MOs: predOps(Pred: ARMCC::AL));
10765 Register NewVReg4 = MRI->createVirtualRegister(RegClass: TRC);
10766 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tORR), DestReg: NewVReg4)
10767 .addReg(RegNo: ARM::CPSR, Flags: RegState::Define)
10768 .addReg(RegNo: NewVReg2, Flags: RegState::Kill)
10769 .addReg(RegNo: NewVReg3, Flags: RegState::Kill)
10770 .add(MOs: predOps(Pred: ARMCC::AL));
10771 Register NewVReg5 = MRI->createVirtualRegister(RegClass: TRC);
10772 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tADDframe), DestReg: NewVReg5)
10773 .addFrameIndex(Idx: FI)
10774 .addImm(Val: 36); // &jbuf[1] :: pc
10775 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tSTRi))
10776 .addReg(RegNo: NewVReg4, Flags: RegState::Kill)
10777 .addReg(RegNo: NewVReg5, Flags: RegState::Kill)
10778 .addImm(Val: 0)
10779 .addMemOperand(MMO: FIMMOSt)
10780 .add(MOs: predOps(Pred: ARMCC::AL));
10781 } else {
10782 // Incoming value: jbuf
10783 // ldr r1, LCPI1_1
10784 // add r1, pc, r1
10785 // str r1, [$jbuf, #+4] ; &jbuf[1]
10786 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
10787 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::LDRi12), DestReg: NewVReg1)
10788 .addConstantPoolIndex(Idx: CPI)
10789 .addImm(Val: 0)
10790 .addMemOperand(MMO: CPMMO)
10791 .add(MOs: predOps(Pred: ARMCC::AL));
10792 Register NewVReg2 = MRI->createVirtualRegister(RegClass: TRC);
10793 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::PICADD), DestReg: NewVReg2)
10794 .addReg(RegNo: NewVReg1, Flags: RegState::Kill)
10795 .addImm(Val: PCLabelId)
10796 .add(MOs: predOps(Pred: ARMCC::AL));
10797 BuildMI(BB&: *MBB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::STRi12))
10798 .addReg(RegNo: NewVReg2, Flags: RegState::Kill)
10799 .addFrameIndex(Idx: FI)
10800 .addImm(Val: 36) // &jbuf[1] :: pc
10801 .addMemOperand(MMO: FIMMOSt)
10802 .add(MOs: predOps(Pred: ARMCC::AL));
10803 }
10804}
10805
10806void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10807 MachineBasicBlock *MBB) const {
10808 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10809 DebugLoc dl = MI.getDebugLoc();
10810 MachineFunction *MF = MBB->getParent();
10811 MachineRegisterInfo *MRI = &MF->getRegInfo();
10812 MachineFrameInfo &MFI = MF->getFrameInfo();
10813 int FI = MFI.getFunctionContextIndex();
10814
10815 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10816 : &ARM::GPRnopcRegClass;
10817
10818 // Get a mapping of the call site numbers to all of the landing pads they're
10819 // associated with.
10820 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10821 unsigned MaxCSNum = 0;
10822 for (MachineBasicBlock &BB : *MF) {
10823 if (!BB.isEHPad())
10824 continue;
10825
10826 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10827 // pad.
10828 for (MachineInstr &II : BB) {
10829 if (!II.isEHLabel())
10830 continue;
10831
10832 MCSymbol *Sym = II.getOperand(i: 0).getMCSymbol();
10833 if (!MF->hasCallSiteLandingPad(Sym)) continue;
10834
10835 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10836 for (unsigned Idx : CallSiteIdxs) {
10837 CallSiteNumToLPad[Idx].push_back(Elt: &BB);
10838 MaxCSNum = std::max(a: MaxCSNum, b: Idx);
10839 }
10840 break;
10841 }
10842 }
10843
10844 // Get an ordered list of the machine basic blocks for the jump table.
10845 std::vector<MachineBasicBlock*> LPadList;
10846 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10847 LPadList.reserve(n: CallSiteNumToLPad.size());
10848 for (unsigned I = 1; I <= MaxCSNum; ++I) {
10849 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10850 for (MachineBasicBlock *MBB : MBBList) {
10851 LPadList.push_back(x: MBB);
10852 InvokeBBs.insert_range(R: MBB->predecessors());
10853 }
10854 }
10855
10856 assert(!LPadList.empty() &&
10857 "No landing pad destinations for the dispatch jump table!");
10858
10859 // Create the jump table and associated information.
10860 MachineJumpTableInfo *JTI =
10861 MF->getOrCreateJumpTableInfo(JTEntryKind: MachineJumpTableInfo::EK_Inline);
10862 unsigned MJTI = JTI->createJumpTableIndex(DestBBs: LPadList);
10863
10864 // Create the MBBs for the dispatch code.
10865
10866 // Shove the dispatch's address into the return slot in the function context.
10867 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10868 DispatchBB->setIsEHPad();
10869
10870 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10871
10872 BuildMI(BB: TrapBB, MIMD: dl, MCID: TII->get(Opcode: Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
10873 DispatchBB->addSuccessor(Succ: TrapBB);
10874
10875 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10876 DispatchBB->addSuccessor(Succ: DispContBB);
10877
10878 // Insert and MBBs.
10879 MF->insert(MBBI: MF->end(), MBB: DispatchBB);
10880 MF->insert(MBBI: MF->end(), MBB: DispContBB);
10881 MF->insert(MBBI: MF->end(), MBB: TrapBB);
10882
10883 // Insert code into the entry block that creates and registers the function
10884 // context.
10885 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10886
10887 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10888 PtrInfo: MachinePointerInfo::getFixedStack(MF&: *MF, FI),
10889 F: MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, Size: 4, BaseAlignment: Align(4));
10890
10891 MachineInstrBuilder MIB;
10892 MIB = BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::Int_eh_sjlj_dispatchsetup));
10893
10894 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10895 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10896
10897 // Add a register mask with no preserved registers. This results in all
10898 // registers being marked as clobbered. This can't work if the dispatch block
10899 // is in a Thumb1 function and is linked with ARM code which uses the FP
10900 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10901 MIB.addRegMask(Mask: RI.getSjLjDispatchPreservedMask(MF: *MF));
10902
10903 bool IsPositionIndependent = isPositionIndependent();
10904 unsigned NumLPads = LPadList.size();
10905 if (Subtarget->isThumb2()) {
10906 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
10907 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2LDRi12), DestReg: NewVReg1)
10908 .addFrameIndex(Idx: FI)
10909 .addImm(Val: 4)
10910 .addMemOperand(MMO: FIMMOLd)
10911 .add(MOs: predOps(Pred: ARMCC::AL));
10912
10913 if (NumLPads < 256) {
10914 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2CMPri))
10915 .addReg(RegNo: NewVReg1)
10916 .addImm(Val: LPadList.size())
10917 .add(MOs: predOps(Pred: ARMCC::AL));
10918 } else {
10919 Register VReg1 = MRI->createVirtualRegister(RegClass: TRC);
10920 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2MOVi16), DestReg: VReg1)
10921 .addImm(Val: NumLPads & 0xFFFF)
10922 .add(MOs: predOps(Pred: ARMCC::AL));
10923
10924 unsigned VReg2 = VReg1;
10925 if ((NumLPads & 0xFFFF0000) != 0) {
10926 VReg2 = MRI->createVirtualRegister(RegClass: TRC);
10927 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2MOVTi16), DestReg: VReg2)
10928 .addReg(RegNo: VReg1)
10929 .addImm(Val: NumLPads >> 16)
10930 .add(MOs: predOps(Pred: ARMCC::AL));
10931 }
10932
10933 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2CMPrr))
10934 .addReg(RegNo: NewVReg1)
10935 .addReg(RegNo: VReg2)
10936 .add(MOs: predOps(Pred: ARMCC::AL));
10937 }
10938
10939 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2Bcc))
10940 .addMBB(MBB: TrapBB)
10941 .addImm(Val: ARMCC::HI)
10942 .addReg(RegNo: ARM::CPSR);
10943
10944 Register NewVReg3 = MRI->createVirtualRegister(RegClass: TRC);
10945 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2LEApcrelJT), DestReg: NewVReg3)
10946 .addJumpTableIndex(Idx: MJTI)
10947 .add(MOs: predOps(Pred: ARMCC::AL));
10948
10949 Register NewVReg4 = MRI->createVirtualRegister(RegClass: TRC);
10950 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2ADDrs), DestReg: NewVReg4)
10951 .addReg(RegNo: NewVReg3, Flags: RegState::Kill)
10952 .addReg(RegNo: NewVReg1)
10953 .addImm(Val: ARM_AM::getSORegOpc(ShOp: ARM_AM::lsl, Imm: 2))
10954 .add(MOs: predOps(Pred: ARMCC::AL))
10955 .add(MO: condCodeOp());
10956
10957 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2BR_JT))
10958 .addReg(RegNo: NewVReg4, Flags: RegState::Kill)
10959 .addReg(RegNo: NewVReg1)
10960 .addJumpTableIndex(Idx: MJTI);
10961 } else if (Subtarget->isThumb()) {
10962 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
10963 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDRspi), DestReg: NewVReg1)
10964 .addFrameIndex(Idx: FI)
10965 .addImm(Val: 1)
10966 .addMemOperand(MMO: FIMMOLd)
10967 .add(MOs: predOps(Pred: ARMCC::AL));
10968
10969 if (NumLPads < 256) {
10970 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tCMPi8))
10971 .addReg(RegNo: NewVReg1)
10972 .addImm(Val: NumLPads)
10973 .add(MOs: predOps(Pred: ARMCC::AL));
10974 } else {
10975 MachineConstantPool *ConstantPool = MF->getConstantPool();
10976 Type *Int32Ty = Type::getInt32Ty(C&: MF->getFunction().getContext());
10977 const Constant *C = ConstantInt::get(Ty: Int32Ty, V: NumLPads);
10978
10979 // MachineConstantPool wants an explicit alignment.
10980 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Ty: Int32Ty);
10981 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10982
10983 Register VReg1 = MRI->createVirtualRegister(RegClass: TRC);
10984 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDRpci))
10985 .addReg(RegNo: VReg1, Flags: RegState::Define)
10986 .addConstantPoolIndex(Idx)
10987 .add(MOs: predOps(Pred: ARMCC::AL));
10988 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tCMPr))
10989 .addReg(RegNo: NewVReg1)
10990 .addReg(RegNo: VReg1)
10991 .add(MOs: predOps(Pred: ARMCC::AL));
10992 }
10993
10994 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tBcc))
10995 .addMBB(MBB: TrapBB)
10996 .addImm(Val: ARMCC::HI)
10997 .addReg(RegNo: ARM::CPSR);
10998
10999 Register NewVReg2 = MRI->createVirtualRegister(RegClass: TRC);
11000 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tLSLri), DestReg: NewVReg2)
11001 .addReg(RegNo: ARM::CPSR, Flags: RegState::Define)
11002 .addReg(RegNo: NewVReg1)
11003 .addImm(Val: 2)
11004 .add(MOs: predOps(Pred: ARMCC::AL));
11005
11006 Register NewVReg3 = MRI->createVirtualRegister(RegClass: TRC);
11007 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tLEApcrelJT), DestReg: NewVReg3)
11008 .addJumpTableIndex(Idx: MJTI)
11009 .add(MOs: predOps(Pred: ARMCC::AL));
11010
11011 Register NewVReg4 = MRI->createVirtualRegister(RegClass: TRC);
11012 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tADDrr), DestReg: NewVReg4)
11013 .addReg(RegNo: ARM::CPSR, Flags: RegState::Define)
11014 .addReg(RegNo: NewVReg2, Flags: RegState::Kill)
11015 .addReg(RegNo: NewVReg3)
11016 .add(MOs: predOps(Pred: ARMCC::AL));
11017
11018 MachineMemOperand *JTMMOLd =
11019 MF->getMachineMemOperand(PtrInfo: MachinePointerInfo::getJumpTable(MF&: *MF),
11020 F: MachineMemOperand::MOLoad, Size: 4, BaseAlignment: Align(4));
11021
11022 Register NewVReg5 = MRI->createVirtualRegister(RegClass: TRC);
11023 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDRi), DestReg: NewVReg5)
11024 .addReg(RegNo: NewVReg4, Flags: RegState::Kill)
11025 .addImm(Val: 0)
11026 .addMemOperand(MMO: JTMMOLd)
11027 .add(MOs: predOps(Pred: ARMCC::AL));
11028
11029 unsigned NewVReg6 = NewVReg5;
11030 if (IsPositionIndependent) {
11031 NewVReg6 = MRI->createVirtualRegister(RegClass: TRC);
11032 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tADDrr), DestReg: NewVReg6)
11033 .addReg(RegNo: ARM::CPSR, Flags: RegState::Define)
11034 .addReg(RegNo: NewVReg5, Flags: RegState::Kill)
11035 .addReg(RegNo: NewVReg3)
11036 .add(MOs: predOps(Pred: ARMCC::AL));
11037 }
11038
11039 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::tBR_JTr))
11040 .addReg(RegNo: NewVReg6, Flags: RegState::Kill)
11041 .addJumpTableIndex(Idx: MJTI);
11042 } else {
11043 Register NewVReg1 = MRI->createVirtualRegister(RegClass: TRC);
11044 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::LDRi12), DestReg: NewVReg1)
11045 .addFrameIndex(Idx: FI)
11046 .addImm(Val: 4)
11047 .addMemOperand(MMO: FIMMOLd)
11048 .add(MOs: predOps(Pred: ARMCC::AL));
11049
11050 if (NumLPads < 256) {
11051 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::CMPri))
11052 .addReg(RegNo: NewVReg1)
11053 .addImm(Val: NumLPads)
11054 .add(MOs: predOps(Pred: ARMCC::AL));
11055 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(x: NumLPads)) {
11056 Register VReg1 = MRI->createVirtualRegister(RegClass: TRC);
11057 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::MOVi16), DestReg: VReg1)
11058 .addImm(Val: NumLPads & 0xFFFF)
11059 .add(MOs: predOps(Pred: ARMCC::AL));
11060
11061 unsigned VReg2 = VReg1;
11062 if ((NumLPads & 0xFFFF0000) != 0) {
11063 VReg2 = MRI->createVirtualRegister(RegClass: TRC);
11064 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::MOVTi16), DestReg: VReg2)
11065 .addReg(RegNo: VReg1)
11066 .addImm(Val: NumLPads >> 16)
11067 .add(MOs: predOps(Pred: ARMCC::AL));
11068 }
11069
11070 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::CMPrr))
11071 .addReg(RegNo: NewVReg1)
11072 .addReg(RegNo: VReg2)
11073 .add(MOs: predOps(Pred: ARMCC::AL));
11074 } else {
11075 MachineConstantPool *ConstantPool = MF->getConstantPool();
11076 Type *Int32Ty = Type::getInt32Ty(C&: MF->getFunction().getContext());
11077 const Constant *C = ConstantInt::get(Ty: Int32Ty, V: NumLPads);
11078
11079 // MachineConstantPool wants an explicit alignment.
11080 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Ty: Int32Ty);
11081 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11082
11083 Register VReg1 = MRI->createVirtualRegister(RegClass: TRC);
11084 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::LDRcp))
11085 .addReg(RegNo: VReg1, Flags: RegState::Define)
11086 .addConstantPoolIndex(Idx)
11087 .addImm(Val: 0)
11088 .add(MOs: predOps(Pred: ARMCC::AL));
11089 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::CMPrr))
11090 .addReg(RegNo: NewVReg1)
11091 .addReg(RegNo: VReg1, Flags: RegState::Kill)
11092 .add(MOs: predOps(Pred: ARMCC::AL));
11093 }
11094
11095 BuildMI(BB: DispatchBB, MIMD: dl, MCID: TII->get(Opcode: ARM::Bcc))
11096 .addMBB(MBB: TrapBB)
11097 .addImm(Val: ARMCC::HI)
11098 .addReg(RegNo: ARM::CPSR);
11099
11100 Register NewVReg3 = MRI->createVirtualRegister(RegClass: TRC);
11101 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::MOVsi), DestReg: NewVReg3)
11102 .addReg(RegNo: NewVReg1)
11103 .addImm(Val: ARM_AM::getSORegOpc(ShOp: ARM_AM::lsl, Imm: 2))
11104 .add(MOs: predOps(Pred: ARMCC::AL))
11105 .add(MO: condCodeOp());
11106 Register NewVReg4 = MRI->createVirtualRegister(RegClass: TRC);
11107 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::LEApcrelJT), DestReg: NewVReg4)
11108 .addJumpTableIndex(Idx: MJTI)
11109 .add(MOs: predOps(Pred: ARMCC::AL));
11110
11111 MachineMemOperand *JTMMOLd =
11112 MF->getMachineMemOperand(PtrInfo: MachinePointerInfo::getJumpTable(MF&: *MF),
11113 F: MachineMemOperand::MOLoad, Size: 4, BaseAlignment: Align(4));
11114 Register NewVReg5 = MRI->createVirtualRegister(RegClass: TRC);
11115 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::LDRrs), DestReg: NewVReg5)
11116 .addReg(RegNo: NewVReg3, Flags: RegState::Kill)
11117 .addReg(RegNo: NewVReg4)
11118 .addImm(Val: 0)
11119 .addMemOperand(MMO: JTMMOLd)
11120 .add(MOs: predOps(Pred: ARMCC::AL));
11121
11122 if (IsPositionIndependent) {
11123 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::BR_JTadd))
11124 .addReg(RegNo: NewVReg5, Flags: RegState::Kill)
11125 .addReg(RegNo: NewVReg4)
11126 .addJumpTableIndex(Idx: MJTI);
11127 } else {
11128 BuildMI(BB: DispContBB, MIMD: dl, MCID: TII->get(Opcode: ARM::BR_JTr))
11129 .addReg(RegNo: NewVReg5, Flags: RegState::Kill)
11130 .addJumpTableIndex(Idx: MJTI);
11131 }
11132 }
11133
11134 // Add the jump table entries as successors to the MBB.
11135 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
11136 for (MachineBasicBlock *CurMBB : LPadList) {
11137 if (SeenMBBs.insert(Ptr: CurMBB).second)
11138 DispContBB->addSuccessor(Succ: CurMBB);
11139 }
11140
11141 // N.B. the order the invoke BBs are processed in doesn't matter here.
11142 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
11143 SmallVector<MachineBasicBlock*, 64> MBBLPads;
11144 for (MachineBasicBlock *BB : InvokeBBs) {
11145
11146 // Remove the landing pad successor from the invoke block and replace it
11147 // with the new dispatch block.
11148 SmallVector<MachineBasicBlock*, 4> Successors(BB->successors());
11149 while (!Successors.empty()) {
11150 MachineBasicBlock *SMBB = Successors.pop_back_val();
11151 if (SMBB->isEHPad()) {
11152 BB->removeSuccessor(Succ: SMBB);
11153 MBBLPads.push_back(Elt: SMBB);
11154 }
11155 }
11156
11157 BB->addSuccessor(Succ: DispatchBB, Prob: BranchProbability::getZero());
11158 BB->normalizeSuccProbs();
11159
11160 // Find the invoke call and mark all of the callee-saved registers as
11161 // 'implicit defined' so that they're spilled. This prevents code from
11162 // moving instructions to before the EH block, where they will never be
11163 // executed.
11164 for (MachineBasicBlock::reverse_iterator
11165 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
11166 if (!II->isCall()) continue;
11167
11168 DenseSet<unsigned> DefRegs;
11169 for (MachineInstr::mop_iterator
11170 OI = II->operands_begin(), OE = II->operands_end();
11171 OI != OE; ++OI) {
11172 if (!OI->isReg()) continue;
11173 DefRegs.insert(V: OI->getReg());
11174 }
11175
11176 MachineInstrBuilder MIB(*MF, &*II);
11177
11178 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
11179 unsigned Reg = SavedRegs[i];
11180 if (Subtarget->isThumb2() &&
11181 !ARM::tGPRRegClass.contains(Reg) &&
11182 !ARM::hGPRRegClass.contains(Reg))
11183 continue;
11184 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
11185 continue;
11186 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
11187 continue;
11188 if (!DefRegs.contains(V: Reg))
11189 MIB.addReg(RegNo: Reg, Flags: RegState::ImplicitDefine | RegState::Dead);
11190 }
11191
11192 break;
11193 }
11194 }
11195
11196 // Mark all former landing pads as non-landing pads. The dispatch is the only
11197 // landing pad now.
11198 for (MachineBasicBlock *MBBLPad : MBBLPads)
11199 MBBLPad->setIsEHPad(false);
11200
11201 // The instruction is gone now.
11202 MI.eraseFromParent();
11203}
11204
11205static
11206MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
11207 for (MachineBasicBlock *S : MBB->successors())
11208 if (S != Succ)
11209 return S;
11210 llvm_unreachable("Expecting a BB with two successors!");
11211}
11212
11213/// Return the load opcode for a given load size. If load size >= 8,
11214/// neon opcode will be returned.
11215static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
11216 if (LdSize >= 8)
11217 return LdSize == 16 ? ARM::VLD1q32wb_fixed
11218 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
11219 if (IsThumb1)
11220 return LdSize == 4 ? ARM::tLDRi
11221 : LdSize == 2 ? ARM::tLDRHi
11222 : LdSize == 1 ? ARM::tLDRBi : 0;
11223 if (IsThumb2)
11224 return LdSize == 4 ? ARM::t2LDR_POST
11225 : LdSize == 2 ? ARM::t2LDRH_POST
11226 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
11227 return LdSize == 4 ? ARM::LDR_POST_IMM
11228 : LdSize == 2 ? ARM::LDRH_POST
11229 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
11230}
11231
11232/// Return the store opcode for a given store size. If store size >= 8,
11233/// neon opcode will be returned.
11234static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
11235 if (StSize >= 8)
11236 return StSize == 16 ? ARM::VST1q32wb_fixed
11237 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
11238 if (IsThumb1)
11239 return StSize == 4 ? ARM::tSTRi
11240 : StSize == 2 ? ARM::tSTRHi
11241 : StSize == 1 ? ARM::tSTRBi : 0;
11242 if (IsThumb2)
11243 return StSize == 4 ? ARM::t2STR_POST
11244 : StSize == 2 ? ARM::t2STRH_POST
11245 : StSize == 1 ? ARM::t2STRB_POST : 0;
11246 return StSize == 4 ? ARM::STR_POST_IMM
11247 : StSize == 2 ? ARM::STRH_POST
11248 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
11249}
11250
11251/// Emit a post-increment load operation with given size. The instructions
11252/// will be added to BB at Pos.
11253static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11254 const TargetInstrInfo *TII, const DebugLoc &dl,
11255 unsigned LdSize, unsigned Data, unsigned AddrIn,
11256 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11257 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
11258 assert(LdOpc != 0 && "Should have a load opcode");
11259 if (LdSize >= 8) {
11260 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: LdOpc), DestReg: Data)
11261 .addReg(RegNo: AddrOut, Flags: RegState::Define)
11262 .addReg(RegNo: AddrIn)
11263 .addImm(Val: 0)
11264 .add(MOs: predOps(Pred: ARMCC::AL));
11265 } else if (IsThumb1) {
11266 // load + update AddrIn
11267 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: LdOpc), DestReg: Data)
11268 .addReg(RegNo: AddrIn)
11269 .addImm(Val: 0)
11270 .add(MOs: predOps(Pred: ARMCC::AL));
11271 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: ARM::tADDi8), DestReg: AddrOut)
11272 .add(MO: t1CondCodeOp())
11273 .addReg(RegNo: AddrIn)
11274 .addImm(Val: LdSize)
11275 .add(MOs: predOps(Pred: ARMCC::AL));
11276 } else if (IsThumb2) {
11277 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: LdOpc), DestReg: Data)
11278 .addReg(RegNo: AddrOut, Flags: RegState::Define)
11279 .addReg(RegNo: AddrIn)
11280 .addImm(Val: LdSize)
11281 .add(MOs: predOps(Pred: ARMCC::AL));
11282 } else { // arm
11283 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: LdOpc), DestReg: Data)
11284 .addReg(RegNo: AddrOut, Flags: RegState::Define)
11285 .addReg(RegNo: AddrIn)
11286 .addReg(RegNo: 0)
11287 .addImm(Val: LdSize)
11288 .add(MOs: predOps(Pred: ARMCC::AL));
11289 }
11290}
11291
11292/// Emit a post-increment store operation with given size. The instructions
11293/// will be added to BB at Pos.
11294static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11295 const TargetInstrInfo *TII, const DebugLoc &dl,
11296 unsigned StSize, unsigned Data, unsigned AddrIn,
11297 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11298 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
11299 assert(StOpc != 0 && "Should have a store opcode");
11300 if (StSize >= 8) {
11301 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: StOpc), DestReg: AddrOut)
11302 .addReg(RegNo: AddrIn)
11303 .addImm(Val: 0)
11304 .addReg(RegNo: Data)
11305 .add(MOs: predOps(Pred: ARMCC::AL));
11306 } else if (IsThumb1) {
11307 // store + update AddrIn
11308 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: StOpc))
11309 .addReg(RegNo: Data)
11310 .addReg(RegNo: AddrIn)
11311 .addImm(Val: 0)
11312 .add(MOs: predOps(Pred: ARMCC::AL));
11313 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: ARM::tADDi8), DestReg: AddrOut)
11314 .add(MO: t1CondCodeOp())
11315 .addReg(RegNo: AddrIn)
11316 .addImm(Val: StSize)
11317 .add(MOs: predOps(Pred: ARMCC::AL));
11318 } else if (IsThumb2) {
11319 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: StOpc), DestReg: AddrOut)
11320 .addReg(RegNo: Data)
11321 .addReg(RegNo: AddrIn)
11322 .addImm(Val: StSize)
11323 .add(MOs: predOps(Pred: ARMCC::AL));
11324 } else { // arm
11325 BuildMI(BB&: *BB, I: Pos, MIMD: dl, MCID: TII->get(Opcode: StOpc), DestReg: AddrOut)
11326 .addReg(RegNo: Data)
11327 .addReg(RegNo: AddrIn)
11328 .addReg(RegNo: 0)
11329 .addImm(Val: StSize)
11330 .add(MOs: predOps(Pred: ARMCC::AL));
11331 }
11332}
11333
11334MachineBasicBlock *
11335ARMTargetLowering::EmitStructByval(MachineInstr &MI,
11336 MachineBasicBlock *BB) const {
11337 // This pseudo instruction has 3 operands: dst, src, size
11338 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
11339 // Otherwise, we will generate unrolled scalar copies.
11340 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11341 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11342 MachineFunction::iterator It = ++BB->getIterator();
11343
11344 Register dest = MI.getOperand(i: 0).getReg();
11345 Register src = MI.getOperand(i: 1).getReg();
11346 unsigned SizeVal = MI.getOperand(i: 2).getImm();
11347 unsigned Alignment = MI.getOperand(i: 3).getImm();
11348 DebugLoc dl = MI.getDebugLoc();
11349
11350 MachineFunction *MF = BB->getParent();
11351 MachineRegisterInfo &MRI = MF->getRegInfo();
11352 unsigned UnitSize = 0;
11353 const TargetRegisterClass *TRC = nullptr;
11354 const TargetRegisterClass *VecTRC = nullptr;
11355
11356 bool IsThumb1 = Subtarget->isThumb1Only();
11357 bool IsThumb2 = Subtarget->isThumb2();
11358 bool IsThumb = Subtarget->isThumb();
11359
11360 if (Alignment & 1) {
11361 UnitSize = 1;
11362 } else if (Alignment & 2) {
11363 UnitSize = 2;
11364 } else {
11365 // Check whether we can use NEON instructions.
11366 if (!MF->getFunction().hasFnAttribute(Kind: Attribute::NoImplicitFloat) &&
11367 Subtarget->hasNEON()) {
11368 if ((Alignment % 16 == 0) && SizeVal >= 16)
11369 UnitSize = 16;
11370 else if ((Alignment % 8 == 0) && SizeVal >= 8)
11371 UnitSize = 8;
11372 }
11373 // Can't use NEON instructions.
11374 if (UnitSize == 0)
11375 UnitSize = 4;
11376 }
11377
11378 // Select the correct opcode and register class for unit size load/store
11379 bool IsNeon = UnitSize >= 8;
11380 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
11381 if (IsNeon)
11382 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
11383 : UnitSize == 8 ? &ARM::DPRRegClass
11384 : nullptr;
11385
11386 unsigned BytesLeft = SizeVal % UnitSize;
11387 unsigned LoopSize = SizeVal - BytesLeft;
11388
11389 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
11390 // Use LDR and STR to copy.
11391 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
11392 // [destOut] = STR_POST(scratch, destIn, UnitSize)
11393 unsigned srcIn = src;
11394 unsigned destIn = dest;
11395 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
11396 Register srcOut = MRI.createVirtualRegister(RegClass: TRC);
11397 Register destOut = MRI.createVirtualRegister(RegClass: TRC);
11398 Register scratch = MRI.createVirtualRegister(RegClass: IsNeon ? VecTRC : TRC);
11399 emitPostLd(BB, Pos: MI, TII, dl, LdSize: UnitSize, Data: scratch, AddrIn: srcIn, AddrOut: srcOut,
11400 IsThumb1, IsThumb2);
11401 emitPostSt(BB, Pos: MI, TII, dl, StSize: UnitSize, Data: scratch, AddrIn: destIn, AddrOut: destOut,
11402 IsThumb1, IsThumb2);
11403 srcIn = srcOut;
11404 destIn = destOut;
11405 }
11406
11407 // Handle the leftover bytes with LDRB and STRB.
11408 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
11409 // [destOut] = STRB_POST(scratch, destIn, 1)
11410 for (unsigned i = 0; i < BytesLeft; i++) {
11411 Register srcOut = MRI.createVirtualRegister(RegClass: TRC);
11412 Register destOut = MRI.createVirtualRegister(RegClass: TRC);
11413 Register scratch = MRI.createVirtualRegister(RegClass: TRC);
11414 emitPostLd(BB, Pos: MI, TII, dl, LdSize: 1, Data: scratch, AddrIn: srcIn, AddrOut: srcOut,
11415 IsThumb1, IsThumb2);
11416 emitPostSt(BB, Pos: MI, TII, dl, StSize: 1, Data: scratch, AddrIn: destIn, AddrOut: destOut,
11417 IsThumb1, IsThumb2);
11418 srcIn = srcOut;
11419 destIn = destOut;
11420 }
11421 MI.eraseFromParent(); // The instruction is gone now.
11422 return BB;
11423 }
11424
11425 // Expand the pseudo op to a loop.
11426 // thisMBB:
11427 // ...
11428 // movw varEnd, # --> with thumb2
11429 // movt varEnd, #
11430 // ldrcp varEnd, idx --> without thumb2
11431 // fallthrough --> loopMBB
11432 // loopMBB:
11433 // PHI varPhi, varEnd, varLoop
11434 // PHI srcPhi, src, srcLoop
11435 // PHI destPhi, dst, destLoop
11436 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11437 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
11438 // subs varLoop, varPhi, #UnitSize
11439 // bne loopMBB
11440 // fallthrough --> exitMBB
11441 // exitMBB:
11442 // epilogue to handle left-over bytes
11443 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11444 // [destOut] = STRB_POST(scratch, destLoop, 1)
11445 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(BB: LLVM_BB);
11446 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(BB: LLVM_BB);
11447 MF->insert(MBBI: It, MBB: loopMBB);
11448 MF->insert(MBBI: It, MBB: exitMBB);
11449
11450 // Set the call frame size on entry to the new basic blocks.
11451 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
11452 loopMBB->setCallFrameSize(CallFrameSize);
11453 exitMBB->setCallFrameSize(CallFrameSize);
11454
11455 // Transfer the remainder of BB and its successor edges to exitMBB.
11456 exitMBB->splice(Where: exitMBB->begin(), Other: BB,
11457 From: std::next(x: MachineBasicBlock::iterator(MI)), To: BB->end());
11458 exitMBB->transferSuccessorsAndUpdatePHIs(FromMBB: BB);
11459
11460 // Load an immediate to varEnd.
11461 Register varEnd = MRI.createVirtualRegister(RegClass: TRC);
11462 if (Subtarget->useMovt()) {
11463 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: IsThumb ? ARM::t2MOVi32imm : ARM::MOVi32imm),
11464 DestReg: varEnd)
11465 .addImm(Val: LoopSize);
11466 } else if (Subtarget->genExecuteOnly()) {
11467 assert(IsThumb && "Non-thumb expected to have used movt");
11468 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::tMOVi32imm), DestReg: varEnd).addImm(Val: LoopSize);
11469 } else {
11470 MachineConstantPool *ConstantPool = MF->getConstantPool();
11471 Type *Int32Ty = Type::getInt32Ty(C&: MF->getFunction().getContext());
11472 const Constant *C = ConstantInt::get(Ty: Int32Ty, V: LoopSize);
11473
11474 // MachineConstantPool wants an explicit alignment.
11475 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Ty: Int32Ty);
11476 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11477 MachineMemOperand *CPMMO =
11478 MF->getMachineMemOperand(PtrInfo: MachinePointerInfo::getConstantPool(MF&: *MF),
11479 F: MachineMemOperand::MOLoad, Size: 4, BaseAlignment: Align(4));
11480
11481 if (IsThumb)
11482 BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDRpci))
11483 .addReg(RegNo: varEnd, Flags: RegState::Define)
11484 .addConstantPoolIndex(Idx)
11485 .add(MOs: predOps(Pred: ARMCC::AL))
11486 .addMemOperand(MMO: CPMMO);
11487 else
11488 BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::LDRcp))
11489 .addReg(RegNo: varEnd, Flags: RegState::Define)
11490 .addConstantPoolIndex(Idx)
11491 .addImm(Val: 0)
11492 .add(MOs: predOps(Pred: ARMCC::AL))
11493 .addMemOperand(MMO: CPMMO);
11494 }
11495 BB->addSuccessor(Succ: loopMBB);
11496
11497 // Generate the loop body:
11498 // varPhi = PHI(varLoop, varEnd)
11499 // srcPhi = PHI(srcLoop, src)
11500 // destPhi = PHI(destLoop, dst)
11501 MachineBasicBlock *entryBB = BB;
11502 BB = loopMBB;
11503 Register varLoop = MRI.createVirtualRegister(RegClass: TRC);
11504 Register varPhi = MRI.createVirtualRegister(RegClass: TRC);
11505 Register srcLoop = MRI.createVirtualRegister(RegClass: TRC);
11506 Register srcPhi = MRI.createVirtualRegister(RegClass: TRC);
11507 Register destLoop = MRI.createVirtualRegister(RegClass: TRC);
11508 Register destPhi = MRI.createVirtualRegister(RegClass: TRC);
11509
11510 BuildMI(BB&: *BB, I: BB->begin(), MIMD: dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: varPhi)
11511 .addReg(RegNo: varLoop).addMBB(MBB: loopMBB)
11512 .addReg(RegNo: varEnd).addMBB(MBB: entryBB);
11513 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: srcPhi)
11514 .addReg(RegNo: srcLoop).addMBB(MBB: loopMBB)
11515 .addReg(RegNo: src).addMBB(MBB: entryBB);
11516 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: destPhi)
11517 .addReg(RegNo: destLoop).addMBB(MBB: loopMBB)
11518 .addReg(RegNo: dest).addMBB(MBB: entryBB);
11519
11520 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11521 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
11522 Register scratch = MRI.createVirtualRegister(RegClass: IsNeon ? VecTRC : TRC);
11523 emitPostLd(BB, Pos: BB->end(), TII, dl, LdSize: UnitSize, Data: scratch, AddrIn: srcPhi, AddrOut: srcLoop,
11524 IsThumb1, IsThumb2);
11525 emitPostSt(BB, Pos: BB->end(), TII, dl, StSize: UnitSize, Data: scratch, AddrIn: destPhi, AddrOut: destLoop,
11526 IsThumb1, IsThumb2);
11527
11528 // Decrement loop variable by UnitSize.
11529 if (IsThumb1) {
11530 BuildMI(BB&: *BB, I: BB->end(), MIMD: dl, MCID: TII->get(Opcode: ARM::tSUBi8), DestReg: varLoop)
11531 .add(MO: t1CondCodeOp())
11532 .addReg(RegNo: varPhi)
11533 .addImm(Val: UnitSize)
11534 .add(MOs: predOps(Pred: ARMCC::AL));
11535 } else {
11536 MachineInstrBuilder MIB =
11537 BuildMI(BB&: *BB, I: BB->end(), MIMD: dl,
11538 MCID: TII->get(Opcode: IsThumb2 ? ARM::t2SUBri : ARM::SUBri), DestReg: varLoop);
11539 MIB.addReg(RegNo: varPhi)
11540 .addImm(Val: UnitSize)
11541 .add(MOs: predOps(Pred: ARMCC::AL))
11542 .add(MO: condCodeOp());
11543 MIB->getOperand(i: 5).setReg(ARM::CPSR);
11544 MIB->getOperand(i: 5).setIsDef(true);
11545 }
11546 BuildMI(BB&: *BB, I: BB->end(), MIMD: dl,
11547 MCID: TII->get(Opcode: IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
11548 .addMBB(MBB: loopMBB).addImm(Val: ARMCC::NE).addReg(RegNo: ARM::CPSR);
11549
11550 // loopMBB can loop back to loopMBB or fall through to exitMBB.
11551 BB->addSuccessor(Succ: loopMBB);
11552 BB->addSuccessor(Succ: exitMBB);
11553
11554 // Add epilogue to handle BytesLeft.
11555 BB = exitMBB;
11556 auto StartOfExit = exitMBB->begin();
11557
11558 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11559 // [destOut] = STRB_POST(scratch, destLoop, 1)
11560 unsigned srcIn = srcLoop;
11561 unsigned destIn = destLoop;
11562 for (unsigned i = 0; i < BytesLeft; i++) {
11563 Register srcOut = MRI.createVirtualRegister(RegClass: TRC);
11564 Register destOut = MRI.createVirtualRegister(RegClass: TRC);
11565 Register scratch = MRI.createVirtualRegister(RegClass: TRC);
11566 emitPostLd(BB, Pos: StartOfExit, TII, dl, LdSize: 1, Data: scratch, AddrIn: srcIn, AddrOut: srcOut,
11567 IsThumb1, IsThumb2);
11568 emitPostSt(BB, Pos: StartOfExit, TII, dl, StSize: 1, Data: scratch, AddrIn: destIn, AddrOut: destOut,
11569 IsThumb1, IsThumb2);
11570 srcIn = srcOut;
11571 destIn = destOut;
11572 }
11573
11574 MI.eraseFromParent(); // The instruction is gone now.
11575 return BB;
11576}
11577
11578MachineBasicBlock *
11579ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
11580 MachineBasicBlock *MBB) const {
11581 const TargetMachine &TM = getTargetMachine();
11582 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
11583 DebugLoc DL = MI.getDebugLoc();
11584
11585 assert(TM.getTargetTriple().isOSWindows() &&
11586 "__chkstk is only supported on Windows");
11587 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
11588
11589 // __chkstk takes the number of words to allocate on the stack in R4, and
11590 // returns the stack adjustment in number of bytes in R4. This will not
11591 // clober any other registers (other than the obvious lr).
11592 //
11593 // Although, technically, IP should be considered a register which may be
11594 // clobbered, the call itself will not touch it. Windows on ARM is a pure
11595 // thumb-2 environment, so there is no interworking required. As a result, we
11596 // do not expect a veneer to be emitted by the linker, clobbering IP.
11597 //
11598 // Each module receives its own copy of __chkstk, so no import thunk is
11599 // required, again, ensuring that IP is not clobbered.
11600 //
11601 // Finally, although some linkers may theoretically provide a trampoline for
11602 // out of range calls (which is quite common due to a 32M range limitation of
11603 // branches for Thumb), we can generate the long-call version via
11604 // -mcmodel=large, alleviating the need for the trampoline which may clobber
11605 // IP.
11606
11607 RTLIB::LibcallImpl ChkStkLibcall = getLibcallImpl(Call: RTLIB::STACK_PROBE);
11608 if (ChkStkLibcall == RTLIB::Unsupported)
11609 reportFatalUsageError(reason: "no available implementation of __chkstk");
11610
11611 const char *ChkStk = getLibcallImplName(Call: ChkStkLibcall).data();
11612 switch (TM.getCodeModel()) {
11613 case CodeModel::Tiny:
11614 llvm_unreachable("Tiny code model not available on ARM.");
11615 case CodeModel::Small:
11616 case CodeModel::Medium:
11617 case CodeModel::Kernel:
11618 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::tBL))
11619 .add(MOs: predOps(Pred: ARMCC::AL))
11620 .addExternalSymbol(FnName: ChkStk)
11621 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit | RegState::Kill)
11622 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit | RegState::Define)
11623 .addReg(RegNo: ARM::R12,
11624 Flags: RegState::Implicit | RegState::Define | RegState::Dead)
11625 .addReg(RegNo: ARM::CPSR,
11626 Flags: RegState::Implicit | RegState::Define | RegState::Dead);
11627 break;
11628 case CodeModel::Large: {
11629 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11630 Register Reg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11631
11632 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::t2MOVi32imm), DestReg: Reg)
11633 .addExternalSymbol(FnName: ChkStk);
11634 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII.get(Opcode: gettBLXrOpcode(MF: *MBB->getParent())))
11635 .add(MOs: predOps(Pred: ARMCC::AL))
11636 .addReg(RegNo: Reg, Flags: RegState::Kill)
11637 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit | RegState::Kill)
11638 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit | RegState::Define)
11639 .addReg(RegNo: ARM::R12,
11640 Flags: RegState::Implicit | RegState::Define | RegState::Dead)
11641 .addReg(RegNo: ARM::CPSR,
11642 Flags: RegState::Implicit | RegState::Define | RegState::Dead);
11643 break;
11644 }
11645 }
11646
11647 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::t2SUBrr), DestReg: ARM::SP)
11648 .addReg(RegNo: ARM::SP, Flags: RegState::Kill)
11649 .addReg(RegNo: ARM::R4, Flags: RegState::Kill)
11650 .setMIFlags(MachineInstr::FrameSetup)
11651 .add(MOs: predOps(Pred: ARMCC::AL))
11652 .add(MO: condCodeOp());
11653
11654 MI.eraseFromParent();
11655 return MBB;
11656}
11657
11658MachineBasicBlock *
11659ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
11660 MachineBasicBlock *MBB) const {
11661 DebugLoc DL = MI.getDebugLoc();
11662 MachineFunction *MF = MBB->getParent();
11663 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11664
11665 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
11666 MF->insert(MBBI: ++MBB->getIterator(), MBB: ContBB);
11667 ContBB->splice(Where: ContBB->begin(), Other: MBB,
11668 From: std::next(x: MachineBasicBlock::iterator(MI)), To: MBB->end());
11669 ContBB->transferSuccessorsAndUpdatePHIs(FromMBB: MBB);
11670 MBB->addSuccessor(Succ: ContBB);
11671
11672 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
11673 BuildMI(BB: TrapBB, MIMD: DL, MCID: TII->get(Opcode: ARM::t__brkdiv0));
11674 MF->push_back(MBB: TrapBB);
11675 MBB->addSuccessor(Succ: TrapBB);
11676
11677 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII->get(Opcode: ARM::tCMPi8))
11678 .addReg(RegNo: MI.getOperand(i: 0).getReg())
11679 .addImm(Val: 0)
11680 .add(MOs: predOps(Pred: ARMCC::AL));
11681 BuildMI(BB&: *MBB, I&: MI, MIMD: DL, MCID: TII->get(Opcode: ARM::t2Bcc))
11682 .addMBB(MBB: TrapBB)
11683 .addImm(Val: ARMCC::EQ)
11684 .addReg(RegNo: ARM::CPSR);
11685
11686 MI.eraseFromParent();
11687 return ContBB;
11688}
11689
11690// The CPSR operand of SelectItr might be missing a kill marker
11691// because there were multiple uses of CPSR, and ISel didn't know
11692// which to mark. Figure out whether SelectItr should have had a
11693// kill marker, and set it if it should. Returns the correct kill
11694// marker value.
11695static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
11696 MachineBasicBlock* BB,
11697 const TargetRegisterInfo* TRI) {
11698 // Scan forward through BB for a use/def of CPSR.
11699 MachineBasicBlock::iterator miI(std::next(x: SelectItr));
11700 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
11701 const MachineInstr& mi = *miI;
11702 if (mi.readsRegister(Reg: ARM::CPSR, /*TRI=*/nullptr))
11703 return false;
11704 if (mi.definesRegister(Reg: ARM::CPSR, /*TRI=*/nullptr))
11705 break; // Should have kill-flag - update below.
11706 }
11707
11708 // If we hit the end of the block, check whether CPSR is live into a
11709 // successor.
11710 if (miI == BB->end()) {
11711 for (MachineBasicBlock *Succ : BB->successors())
11712 if (Succ->isLiveIn(Reg: ARM::CPSR))
11713 return false;
11714 }
11715
11716 // We found a def, or hit the end of the basic block and CPSR wasn't live
11717 // out. SelectMI should have a kill flag on CPSR.
11718 SelectItr->addRegisterKilled(IncomingReg: ARM::CPSR, RegInfo: TRI);
11719 return true;
11720}
11721
11722/// Adds logic in loop entry MBB to calculate loop iteration count and adds
11723/// t2WhileLoopSetup and t2WhileLoopStart to generate WLS loop
11724static Register genTPEntry(MachineBasicBlock *TpEntry,
11725 MachineBasicBlock *TpLoopBody,
11726 MachineBasicBlock *TpExit, Register OpSizeReg,
11727 const TargetInstrInfo *TII, DebugLoc Dl,
11728 MachineRegisterInfo &MRI) {
11729 // Calculates loop iteration count = ceil(n/16) = (n + 15) >> 4.
11730 Register AddDestReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11731 BuildMI(BB: TpEntry, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2ADDri), DestReg: AddDestReg)
11732 .addUse(RegNo: OpSizeReg)
11733 .addImm(Val: 15)
11734 .add(MOs: predOps(Pred: ARMCC::AL))
11735 .addReg(RegNo: 0);
11736
11737 Register LsrDestReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11738 BuildMI(BB: TpEntry, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2LSRri), DestReg: LsrDestReg)
11739 .addUse(RegNo: AddDestReg, Flags: RegState::Kill)
11740 .addImm(Val: 4)
11741 .add(MOs: predOps(Pred: ARMCC::AL))
11742 .addReg(RegNo: 0);
11743
11744 Register TotalIterationsReg = MRI.createVirtualRegister(RegClass: &ARM::GPRlrRegClass);
11745 BuildMI(BB: TpEntry, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2WhileLoopSetup), DestReg: TotalIterationsReg)
11746 .addUse(RegNo: LsrDestReg, Flags: RegState::Kill);
11747
11748 BuildMI(BB: TpEntry, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2WhileLoopStart))
11749 .addUse(RegNo: TotalIterationsReg)
11750 .addMBB(MBB: TpExit);
11751
11752 BuildMI(BB: TpEntry, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2B))
11753 .addMBB(MBB: TpLoopBody)
11754 .add(MOs: predOps(Pred: ARMCC::AL));
11755
11756 return TotalIterationsReg;
11757}
11758
11759/// Adds logic in the loopBody MBB to generate MVE_VCTP, t2DoLoopDec and
11760/// t2DoLoopEnd. These are used by later passes to generate tail predicated
11761/// loops.
11762static void genTPLoopBody(MachineBasicBlock *TpLoopBody,
11763 MachineBasicBlock *TpEntry, MachineBasicBlock *TpExit,
11764 const TargetInstrInfo *TII, DebugLoc Dl,
11765 MachineRegisterInfo &MRI, Register OpSrcReg,
11766 Register OpDestReg, Register ElementCountReg,
11767 Register TotalIterationsReg, bool IsMemcpy) {
11768 // First insert 4 PHI nodes for: Current pointer to Src (if memcpy), Dest
11769 // array, loop iteration counter, predication counter.
11770
11771 Register SrcPhiReg, CurrSrcReg;
11772 if (IsMemcpy) {
11773 // Current position in the src array
11774 SrcPhiReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11775 CurrSrcReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11776 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: SrcPhiReg)
11777 .addUse(RegNo: OpSrcReg)
11778 .addMBB(MBB: TpEntry)
11779 .addUse(RegNo: CurrSrcReg)
11780 .addMBB(MBB: TpLoopBody);
11781 }
11782
11783 // Current position in the dest array
11784 Register DestPhiReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11785 Register CurrDestReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11786 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: DestPhiReg)
11787 .addUse(RegNo: OpDestReg)
11788 .addMBB(MBB: TpEntry)
11789 .addUse(RegNo: CurrDestReg)
11790 .addMBB(MBB: TpLoopBody);
11791
11792 // Current loop counter
11793 Register LoopCounterPhiReg = MRI.createVirtualRegister(RegClass: &ARM::GPRlrRegClass);
11794 Register RemainingLoopIterationsReg =
11795 MRI.createVirtualRegister(RegClass: &ARM::GPRlrRegClass);
11796 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: LoopCounterPhiReg)
11797 .addUse(RegNo: TotalIterationsReg)
11798 .addMBB(MBB: TpEntry)
11799 .addUse(RegNo: RemainingLoopIterationsReg)
11800 .addMBB(MBB: TpLoopBody);
11801
11802 // Predication counter
11803 Register PredCounterPhiReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11804 Register RemainingElementsReg = MRI.createVirtualRegister(RegClass: &ARM::rGPRRegClass);
11805 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: PredCounterPhiReg)
11806 .addUse(RegNo: ElementCountReg)
11807 .addMBB(MBB: TpEntry)
11808 .addUse(RegNo: RemainingElementsReg)
11809 .addMBB(MBB: TpLoopBody);
11810
11811 // Pass predication counter to VCTP
11812 Register VccrReg = MRI.createVirtualRegister(RegClass: &ARM::VCCRRegClass);
11813 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::MVE_VCTP8), DestReg: VccrReg)
11814 .addUse(RegNo: PredCounterPhiReg)
11815 .addImm(Val: ARMVCC::None)
11816 .addReg(RegNo: 0)
11817 .addReg(RegNo: 0);
11818
11819 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2SUBri), DestReg: RemainingElementsReg)
11820 .addUse(RegNo: PredCounterPhiReg)
11821 .addImm(Val: 16)
11822 .add(MOs: predOps(Pred: ARMCC::AL))
11823 .addReg(RegNo: 0);
11824
11825 // VLDRB (only if memcpy) and VSTRB instructions, predicated using VPR
11826 Register SrcValueReg;
11827 if (IsMemcpy) {
11828 SrcValueReg = MRI.createVirtualRegister(RegClass: &ARM::MQPRRegClass);
11829 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::MVE_VLDRBU8_post))
11830 .addDef(RegNo: CurrSrcReg)
11831 .addDef(RegNo: SrcValueReg)
11832 .addReg(RegNo: SrcPhiReg)
11833 .addImm(Val: 16)
11834 .addImm(Val: ARMVCC::Then)
11835 .addUse(RegNo: VccrReg)
11836 .addReg(RegNo: 0);
11837 } else
11838 SrcValueReg = OpSrcReg;
11839
11840 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::MVE_VSTRBU8_post))
11841 .addDef(RegNo: CurrDestReg)
11842 .addUse(RegNo: SrcValueReg)
11843 .addReg(RegNo: DestPhiReg)
11844 .addImm(Val: 16)
11845 .addImm(Val: ARMVCC::Then)
11846 .addUse(RegNo: VccrReg)
11847 .addReg(RegNo: 0);
11848
11849 // Add the pseudoInstrs for decrementing the loop counter and marking the
11850 // end:t2DoLoopDec and t2DoLoopEnd
11851 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2LoopDec), DestReg: RemainingLoopIterationsReg)
11852 .addUse(RegNo: LoopCounterPhiReg)
11853 .addImm(Val: 1);
11854
11855 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2LoopEnd))
11856 .addUse(RegNo: RemainingLoopIterationsReg)
11857 .addMBB(MBB: TpLoopBody);
11858
11859 BuildMI(BB: TpLoopBody, MIMD: Dl, MCID: TII->get(Opcode: ARM::t2B))
11860 .addMBB(MBB: TpExit)
11861 .add(MOs: predOps(Pred: ARMCC::AL));
11862}
11863
11864bool ARMTargetLowering::supportKCFIBundles() const {
11865 // KCFI is supported in all ARM/Thumb modes
11866 return true;
11867}
11868
11869MachineInstr *
11870ARMTargetLowering::EmitKCFICheck(MachineBasicBlock &MBB,
11871 MachineBasicBlock::instr_iterator &MBBI,
11872 const TargetInstrInfo *TII) const {
11873 assert(MBBI->isCall() && MBBI->getCFIType() &&
11874 "Invalid call instruction for a KCFI check");
11875
11876 MachineOperand *TargetOp = nullptr;
11877 switch (MBBI->getOpcode()) {
11878 // ARM mode opcodes
11879 case ARM::BLX:
11880 case ARM::BLX_pred:
11881 case ARM::BLX_noip:
11882 case ARM::BLX_pred_noip:
11883 case ARM::BX_CALL:
11884 TargetOp = &MBBI->getOperand(i: 0);
11885 break;
11886 case ARM::TCRETURNri:
11887 case ARM::TCRETURNrinotr12:
11888 case ARM::TAILJMPr:
11889 case ARM::TAILJMPr4:
11890 TargetOp = &MBBI->getOperand(i: 0);
11891 break;
11892 // Thumb mode opcodes (Thumb1 and Thumb2)
11893 // Note: Most Thumb call instructions have predicate operands before the
11894 // target register Format: tBLXr pred, predreg, target_register, ...
11895 case ARM::tBLXr: // Thumb1/Thumb2: BLX register (requires V5T)
11896 case ARM::tBLXr_noip: // Thumb1/Thumb2: BLX register, no IP clobber
11897 case ARM::tBX_CALL: // Thumb1 only: BX call (push LR, BX)
11898 TargetOp = &MBBI->getOperand(i: 2);
11899 break;
11900 // Tail call instructions don't have predicates, target is operand 0
11901 case ARM::tTAILJMPr: // Thumb1/Thumb2: Tail call via register
11902 TargetOp = &MBBI->getOperand(i: 0);
11903 break;
11904 default:
11905 llvm_unreachable("Unexpected CFI call opcode");
11906 }
11907
11908 assert(TargetOp && TargetOp->isReg() && "Invalid target operand");
11909 TargetOp->setIsRenamable(false);
11910
11911 // Select the appropriate KCFI_CHECK variant based on the instruction set
11912 unsigned KCFICheckOpcode;
11913 if (Subtarget->isThumb()) {
11914 if (Subtarget->isThumb2()) {
11915 KCFICheckOpcode = ARM::KCFI_CHECK_Thumb2;
11916 } else {
11917 KCFICheckOpcode = ARM::KCFI_CHECK_Thumb1;
11918 }
11919 } else {
11920 KCFICheckOpcode = ARM::KCFI_CHECK_ARM;
11921 }
11922
11923 return BuildMI(BB&: MBB, I: MBBI, MIMD: MBBI->getDebugLoc(), MCID: TII->get(Opcode: KCFICheckOpcode))
11924 .addReg(RegNo: TargetOp->getReg())
11925 .addImm(Val: MBBI->getCFIType())
11926 .getInstr();
11927}
11928
11929MachineBasicBlock *
11930ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11931 MachineBasicBlock *BB) const {
11932 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11933 DebugLoc dl = MI.getDebugLoc();
11934 bool isThumb2 = Subtarget->isThumb2();
11935 switch (MI.getOpcode()) {
11936 default: {
11937 MI.print(OS&: errs());
11938 llvm_unreachable("Unexpected instr type to insert");
11939 }
11940
11941 // Thumb1 post-indexed loads are really just single-register LDMs.
11942 case ARM::tLDR_postidx: {
11943 MachineOperand Def(MI.getOperand(i: 1));
11944 BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: ARM::tLDMIA_UPD))
11945 .add(MO: Def) // Rn_wb
11946 .add(MO: MI.getOperand(i: 2)) // Rn
11947 .add(MO: MI.getOperand(i: 3)) // PredImm
11948 .add(MO: MI.getOperand(i: 4)) // PredReg
11949 .add(MO: MI.getOperand(i: 0)) // Rt
11950 .cloneMemRefs(OtherMI: MI);
11951 MI.eraseFromParent();
11952 return BB;
11953 }
11954
11955 case ARM::MVE_MEMCPYLOOPINST:
11956 case ARM::MVE_MEMSETLOOPINST: {
11957
11958 // Transformation below expands MVE_MEMCPYLOOPINST/MVE_MEMSETLOOPINST Pseudo
11959 // into a Tail Predicated (TP) Loop. It adds the instructions to calculate
11960 // the iteration count =ceil(size_in_bytes/16)) in the TP entry block and
11961 // adds the relevant instructions in the TP loop Body for generation of a
11962 // WLSTP loop.
11963
11964 // Below is relevant portion of the CFG after the transformation.
11965 // The Machine Basic Blocks are shown along with branch conditions (in
11966 // brackets). Note that TP entry/exit MBBs depict the entry/exit of this
11967 // portion of the CFG and may not necessarily be the entry/exit of the
11968 // function.
11969
11970 // (Relevant) CFG after transformation:
11971 // TP entry MBB
11972 // |
11973 // |-----------------|
11974 // (n <= 0) (n > 0)
11975 // | |
11976 // | TP loop Body MBB<--|
11977 // | | |
11978 // \ |___________|
11979 // \ /
11980 // TP exit MBB
11981
11982 MachineFunction *MF = BB->getParent();
11983 MachineFunctionProperties &Properties = MF->getProperties();
11984 MachineRegisterInfo &MRI = MF->getRegInfo();
11985
11986 Register OpDestReg = MI.getOperand(i: 0).getReg();
11987 Register OpSrcReg = MI.getOperand(i: 1).getReg();
11988 Register OpSizeReg = MI.getOperand(i: 2).getReg();
11989
11990 // Allocate the required MBBs and add to parent function.
11991 MachineBasicBlock *TpEntry = BB;
11992 MachineBasicBlock *TpLoopBody = MF->CreateMachineBasicBlock();
11993 MachineBasicBlock *TpExit;
11994
11995 MF->push_back(MBB: TpLoopBody);
11996
11997 // If any instructions are present in the current block after
11998 // MVE_MEMCPYLOOPINST or MVE_MEMSETLOOPINST, split the current block and
11999 // move the instructions into the newly created exit block. If there are no
12000 // instructions add an explicit branch to the FallThrough block and then
12001 // split.
12002 //
12003 // The split is required for two reasons:
12004 // 1) A terminator(t2WhileLoopStart) will be placed at that site.
12005 // 2) Since a TPLoopBody will be added later, any phis in successive blocks
12006 // need to be updated. splitAt() already handles this.
12007 TpExit = BB->splitAt(SplitInst&: MI, UpdateLiveIns: false);
12008 if (TpExit == BB) {
12009 assert(BB->canFallThrough() && "Exit Block must be Fallthrough of the "
12010 "block containing memcpy/memset Pseudo");
12011 TpExit = BB->getFallThrough();
12012 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2B))
12013 .addMBB(MBB: TpExit)
12014 .add(MOs: predOps(Pred: ARMCC::AL));
12015 TpExit = BB->splitAt(SplitInst&: MI, UpdateLiveIns: false);
12016 }
12017
12018 // Add logic for iteration count
12019 Register TotalIterationsReg =
12020 genTPEntry(TpEntry, TpLoopBody, TpExit, OpSizeReg, TII, Dl: dl, MRI);
12021
12022 // Add the vectorized (and predicated) loads/store instructions
12023 bool IsMemcpy = MI.getOpcode() == ARM::MVE_MEMCPYLOOPINST;
12024 genTPLoopBody(TpLoopBody, TpEntry, TpExit, TII, Dl: dl, MRI, OpSrcReg,
12025 OpDestReg, ElementCountReg: OpSizeReg, TotalIterationsReg, IsMemcpy);
12026
12027 // Required to avoid conflict with the MachineVerifier during testing.
12028 Properties.resetNoPHIs();
12029
12030 // Connect the blocks
12031 TpEntry->addSuccessor(Succ: TpLoopBody);
12032 TpLoopBody->addSuccessor(Succ: TpLoopBody);
12033 TpLoopBody->addSuccessor(Succ: TpExit);
12034
12035 // Reorder for a more natural layout
12036 TpLoopBody->moveAfter(NewBefore: TpEntry);
12037 TpExit->moveAfter(NewBefore: TpLoopBody);
12038
12039 // Finally, remove the memcpy Pseudo Instruction
12040 MI.eraseFromParent();
12041
12042 // Return the exit block as it may contain other instructions requiring a
12043 // custom inserter
12044 return TpExit;
12045 }
12046
12047 // The Thumb2 pre-indexed stores have the same MI operands, they just
12048 // define them differently in the .td files from the isel patterns, so
12049 // they need pseudos.
12050 case ARM::t2STR_preidx:
12051 MI.setDesc(TII->get(Opcode: ARM::t2STR_PRE));
12052 return BB;
12053 case ARM::t2STRB_preidx:
12054 MI.setDesc(TII->get(Opcode: ARM::t2STRB_PRE));
12055 return BB;
12056 case ARM::t2STRH_preidx:
12057 MI.setDesc(TII->get(Opcode: ARM::t2STRH_PRE));
12058 return BB;
12059
12060 case ARM::STRi_preidx:
12061 case ARM::STRBi_preidx: {
12062 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
12063 : ARM::STRB_PRE_IMM;
12064 // Decode the offset.
12065 unsigned Offset = MI.getOperand(i: 4).getImm();
12066 bool isSub = ARM_AM::getAM2Op(AM2Opc: Offset) == ARM_AM::sub;
12067 Offset = ARM_AM::getAM2Offset(AM2Opc: Offset);
12068 if (isSub)
12069 Offset = -Offset;
12070
12071 MachineMemOperand *MMO = *MI.memoperands_begin();
12072 BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: NewOpc))
12073 .add(MO: MI.getOperand(i: 0)) // Rn_wb
12074 .add(MO: MI.getOperand(i: 1)) // Rt
12075 .add(MO: MI.getOperand(i: 2)) // Rn
12076 .addImm(Val: Offset) // offset (skip GPR==zero_reg)
12077 .add(MO: MI.getOperand(i: 5)) // pred
12078 .add(MO: MI.getOperand(i: 6))
12079 .addMemOperand(MMO);
12080 MI.eraseFromParent();
12081 return BB;
12082 }
12083 case ARM::STRr_preidx:
12084 case ARM::STRBr_preidx:
12085 case ARM::STRH_preidx: {
12086 unsigned NewOpc;
12087 switch (MI.getOpcode()) {
12088 default: llvm_unreachable("unexpected opcode!");
12089 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
12090 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
12091 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
12092 }
12093 MachineInstrBuilder MIB = BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII->get(Opcode: NewOpc));
12094 for (const MachineOperand &MO : MI.operands())
12095 MIB.add(MO);
12096 MI.eraseFromParent();
12097 return BB;
12098 }
12099
12100 case ARM::tMOVCCr_pseudo: {
12101 // To "insert" a SELECT_CC instruction, we actually have to insert the
12102 // diamond control-flow pattern. The incoming instruction knows the
12103 // destination vreg to set, the condition code register to branch on, the
12104 // true/false values to select between, and a branch opcode to use.
12105 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12106 MachineFunction::iterator It = ++BB->getIterator();
12107
12108 // thisMBB:
12109 // ...
12110 // TrueVal = ...
12111 // cmpTY ccX, r1, r2
12112 // bCC copy1MBB
12113 // fallthrough --> copy0MBB
12114 MachineBasicBlock *thisMBB = BB;
12115 MachineFunction *F = BB->getParent();
12116 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(BB: LLVM_BB);
12117 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(BB: LLVM_BB);
12118 F->insert(MBBI: It, MBB: copy0MBB);
12119 F->insert(MBBI: It, MBB: sinkMBB);
12120
12121 // Set the call frame size on entry to the new basic blocks.
12122 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
12123 copy0MBB->setCallFrameSize(CallFrameSize);
12124 sinkMBB->setCallFrameSize(CallFrameSize);
12125
12126 // Check whether CPSR is live past the tMOVCCr_pseudo.
12127 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
12128 if (!MI.killsRegister(Reg: ARM::CPSR, /*TRI=*/nullptr) &&
12129 !checkAndUpdateCPSRKill(SelectItr: MI, BB: thisMBB, TRI)) {
12130 copy0MBB->addLiveIn(PhysReg: ARM::CPSR);
12131 sinkMBB->addLiveIn(PhysReg: ARM::CPSR);
12132 }
12133
12134 // Transfer the remainder of BB and its successor edges to sinkMBB.
12135 sinkMBB->splice(Where: sinkMBB->begin(), Other: BB,
12136 From: std::next(x: MachineBasicBlock::iterator(MI)), To: BB->end());
12137 sinkMBB->transferSuccessorsAndUpdatePHIs(FromMBB: BB);
12138
12139 BB->addSuccessor(Succ: copy0MBB);
12140 BB->addSuccessor(Succ: sinkMBB);
12141
12142 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::tBcc))
12143 .addMBB(MBB: sinkMBB)
12144 .addImm(Val: MI.getOperand(i: 3).getImm())
12145 .addReg(RegNo: MI.getOperand(i: 4).getReg());
12146
12147 // copy0MBB:
12148 // %FalseValue = ...
12149 // # fallthrough to sinkMBB
12150 BB = copy0MBB;
12151
12152 // Update machine-CFG edges
12153 BB->addSuccessor(Succ: sinkMBB);
12154
12155 // sinkMBB:
12156 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12157 // ...
12158 BB = sinkMBB;
12159 BuildMI(BB&: *BB, I: BB->begin(), MIMD: dl, MCID: TII->get(Opcode: ARM::PHI), DestReg: MI.getOperand(i: 0).getReg())
12160 .addReg(RegNo: MI.getOperand(i: 1).getReg())
12161 .addMBB(MBB: copy0MBB)
12162 .addReg(RegNo: MI.getOperand(i: 2).getReg())
12163 .addMBB(MBB: thisMBB);
12164
12165 MI.eraseFromParent(); // The pseudo instruction is gone now.
12166 return BB;
12167 }
12168
12169 case ARM::BCCi64:
12170 case ARM::BCCZi64: {
12171 // If there is an unconditional branch to the other successor, remove it.
12172 BB->erase(I: std::next(x: MachineBasicBlock::iterator(MI)), E: BB->end());
12173
12174 // Compare both parts that make up the double comparison separately for
12175 // equality.
12176 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
12177
12178 Register LHS1 = MI.getOperand(i: 1).getReg();
12179 Register LHS2 = MI.getOperand(i: 2).getReg();
12180 if (RHSisZero) {
12181 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12182 .addReg(RegNo: LHS1)
12183 .addImm(Val: 0)
12184 .add(MOs: predOps(Pred: ARMCC::AL));
12185 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12186 .addReg(RegNo: LHS2).addImm(Val: 0)
12187 .addImm(Val: ARMCC::EQ).addReg(RegNo: ARM::CPSR);
12188 } else {
12189 Register RHS1 = MI.getOperand(i: 3).getReg();
12190 Register RHS2 = MI.getOperand(i: 4).getReg();
12191 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12192 .addReg(RegNo: LHS1)
12193 .addReg(RegNo: RHS1)
12194 .add(MOs: predOps(Pred: ARMCC::AL));
12195 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12196 .addReg(RegNo: LHS2).addReg(RegNo: RHS2)
12197 .addImm(Val: ARMCC::EQ).addReg(RegNo: ARM::CPSR);
12198 }
12199
12200 MachineBasicBlock *destMBB = MI.getOperand(i: RHSisZero ? 3 : 5).getMBB();
12201 MachineBasicBlock *exitMBB = OtherSucc(MBB: BB, Succ: destMBB);
12202 if (MI.getOperand(i: 0).getImm() == ARMCC::NE)
12203 std::swap(a&: destMBB, b&: exitMBB);
12204
12205 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: isThumb2 ? ARM::t2Bcc : ARM::Bcc))
12206 .addMBB(MBB: destMBB).addImm(Val: ARMCC::EQ).addReg(RegNo: ARM::CPSR);
12207 if (isThumb2)
12208 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::t2B))
12209 .addMBB(MBB: exitMBB)
12210 .add(MOs: predOps(Pred: ARMCC::AL));
12211 else
12212 BuildMI(BB, MIMD: dl, MCID: TII->get(Opcode: ARM::B)) .addMBB(MBB: exitMBB);
12213
12214 MI.eraseFromParent(); // The pseudo instruction is gone now.
12215 return BB;
12216 }
12217
12218 case ARM::Int_eh_sjlj_setjmp:
12219 case ARM::Int_eh_sjlj_setjmp_nofp:
12220 case ARM::tInt_eh_sjlj_setjmp:
12221 case ARM::t2Int_eh_sjlj_setjmp:
12222 case ARM::t2Int_eh_sjlj_setjmp_nofp:
12223 return BB;
12224
12225 case ARM::Int_eh_sjlj_setup_dispatch:
12226 EmitSjLjDispatchBlock(MI, MBB: BB);
12227 return BB;
12228 case ARM::COPY_STRUCT_BYVAL_I32:
12229 ++NumLoopByVals;
12230 return EmitStructByval(MI, BB);
12231 case ARM::WIN__CHKSTK:
12232 return EmitLowered__chkstk(MI, MBB: BB);
12233 case ARM::WIN__DBZCHK:
12234 return EmitLowered__dbzchk(MI, MBB: BB);
12235 }
12236}
12237
12238/// Attaches vregs to MEMCPY that it will use as scratch registers
12239/// when it is expanded into LDM/STM. This is done as a post-isel lowering
12240/// instead of as a custom inserter because we need the use list from the SDNode.
12241static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
12242 MachineInstr &MI, const SDNode *Node) {
12243 bool isThumb1 = Subtarget->isThumb1Only();
12244
12245 MachineFunction *MF = MI.getParent()->getParent();
12246 MachineRegisterInfo &MRI = MF->getRegInfo();
12247 MachineInstrBuilder MIB(*MF, MI);
12248
12249 // If the new dst/src is unused mark it as dead.
12250 if (!Node->hasAnyUseOfValue(Value: 0)) {
12251 MI.getOperand(i: 0).setIsDead(true);
12252 }
12253 if (!Node->hasAnyUseOfValue(Value: 1)) {
12254 MI.getOperand(i: 1).setIsDead(true);
12255 }
12256
12257 // The MEMCPY both defines and kills the scratch registers.
12258 for (unsigned I = 0; I != MI.getOperand(i: 4).getImm(); ++I) {
12259 Register TmpReg = MRI.createVirtualRegister(RegClass: isThumb1 ? &ARM::tGPRRegClass
12260 : &ARM::GPRRegClass);
12261 MIB.addReg(RegNo: TmpReg, Flags: RegState::Define|RegState::Dead);
12262 }
12263}
12264
12265void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
12266 SDNode *Node) const {
12267 if (MI.getOpcode() == ARM::MEMCPY) {
12268 attachMEMCPYScratchRegs(Subtarget, MI, Node);
12269 return;
12270 }
12271
12272 const MCInstrDesc *MCID = &MI.getDesc();
12273 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
12274 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
12275 // operand is still set to noreg. If needed, set the optional operand's
12276 // register to CPSR, and remove the redundant implicit def.
12277 //
12278 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
12279
12280 // Rename pseudo opcodes.
12281 unsigned NewOpc = convertAddSubFlagsOpcode(OldOpc: MI.getOpcode());
12282 unsigned ccOutIdx;
12283 if (NewOpc) {
12284 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
12285 MCID = &TII->get(Opcode: NewOpc);
12286
12287 assert(MCID->getNumOperands() ==
12288 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
12289 && "converted opcode should be the same except for cc_out"
12290 " (and, on Thumb1, pred)");
12291
12292 MI.setDesc(*MCID);
12293
12294 // Add the optional cc_out operand
12295 MI.addOperand(Op: MachineOperand::CreateReg(Reg: 0, /*isDef=*/true));
12296
12297 // On Thumb1, move all input operands to the end, then add the predicate
12298 if (Subtarget->isThumb1Only()) {
12299 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
12300 MI.addOperand(Op: MI.getOperand(i: 1));
12301 MI.removeOperand(OpNo: 1);
12302 }
12303
12304 // Restore the ties
12305 for (unsigned i = MI.getNumOperands(); i--;) {
12306 const MachineOperand& op = MI.getOperand(i);
12307 if (op.isReg() && op.isUse()) {
12308 int DefIdx = MCID->getOperandConstraint(OpNum: i, Constraint: MCOI::TIED_TO);
12309 if (DefIdx != -1)
12310 MI.tieOperands(DefIdx, UseIdx: i);
12311 }
12312 }
12313
12314 MI.addOperand(Op: MachineOperand::CreateImm(Val: ARMCC::AL));
12315 MI.addOperand(Op: MachineOperand::CreateReg(Reg: 0, /*isDef=*/false));
12316 ccOutIdx = 1;
12317 } else
12318 ccOutIdx = MCID->getNumOperands() - 1;
12319 } else
12320 ccOutIdx = MCID->getNumOperands() - 1;
12321
12322 // Any ARM instruction that sets the 's' bit should specify an optional
12323 // "cc_out" operand in the last operand position.
12324 if (!MI.hasOptionalDef() || !MCID->operands()[ccOutIdx].isOptionalDef()) {
12325 assert(!NewOpc && "Optional cc_out operand required");
12326 return;
12327 }
12328 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
12329 // since we already have an optional CPSR def.
12330 bool definesCPSR = false;
12331 bool deadCPSR = false;
12332 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
12333 ++i) {
12334 const MachineOperand &MO = MI.getOperand(i);
12335 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
12336 definesCPSR = true;
12337 if (MO.isDead())
12338 deadCPSR = true;
12339 MI.removeOperand(OpNo: i);
12340 break;
12341 }
12342 }
12343 if (!definesCPSR) {
12344 assert(!NewOpc && "Optional cc_out operand required");
12345 return;
12346 }
12347 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
12348 if (deadCPSR) {
12349 assert(!MI.getOperand(ccOutIdx).getReg() &&
12350 "expect uninitialized optional cc_out operand");
12351 // Thumb1 instructions must have the S bit even if the CPSR is dead.
12352 if (!Subtarget->isThumb1Only())
12353 return;
12354 }
12355
12356 // If this instruction was defined with an optional CPSR def and its dag node
12357 // had a live implicit CPSR def, then activate the optional CPSR def.
12358 MachineOperand &MO = MI.getOperand(i: ccOutIdx);
12359 MO.setReg(ARM::CPSR);
12360 MO.setIsDef(true);
12361}
12362
12363//===----------------------------------------------------------------------===//
12364// ARM Optimization Hooks
12365//===----------------------------------------------------------------------===//
12366
12367// Helper function that checks if N is a null or all ones constant.
12368static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
12369 return AllOnes ? isAllOnesConstant(V: N) : isNullConstant(V: N);
12370}
12371
12372// Return true if N is conditionally 0 or all ones.
12373// Detects these expressions where cc is an i1 value:
12374//
12375// (select cc 0, y) [AllOnes=0]
12376// (select cc y, 0) [AllOnes=0]
12377// (zext cc) [AllOnes=0]
12378// (sext cc) [AllOnes=0/1]
12379// (select cc -1, y) [AllOnes=1]
12380// (select cc y, -1) [AllOnes=1]
12381//
12382// Invert is set when N is the null/all ones constant when CC is false.
12383// OtherOp is set to the alternative value of N.
12384static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
12385 SDValue &CC, bool &Invert,
12386 SDValue &OtherOp,
12387 SelectionDAG &DAG) {
12388 switch (N->getOpcode()) {
12389 default: return false;
12390 case ISD::SELECT: {
12391 CC = N->getOperand(Num: 0);
12392 SDValue N1 = N->getOperand(Num: 1);
12393 SDValue N2 = N->getOperand(Num: 2);
12394 if (isZeroOrAllOnes(N: N1, AllOnes)) {
12395 Invert = false;
12396 OtherOp = N2;
12397 return true;
12398 }
12399 if (isZeroOrAllOnes(N: N2, AllOnes)) {
12400 Invert = true;
12401 OtherOp = N1;
12402 return true;
12403 }
12404 return false;
12405 }
12406 case ISD::ZERO_EXTEND:
12407 // (zext cc) can never be the all ones value.
12408 if (AllOnes)
12409 return false;
12410 [[fallthrough]];
12411 case ISD::SIGN_EXTEND: {
12412 SDLoc dl(N);
12413 EVT VT = N->getValueType(ResNo: 0);
12414 CC = N->getOperand(Num: 0);
12415 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
12416 return false;
12417 Invert = !AllOnes;
12418 if (AllOnes)
12419 // When looking for an AllOnes constant, N is an sext, and the 'other'
12420 // value is 0.
12421 OtherOp = DAG.getConstant(Val: 0, DL: dl, VT);
12422 else if (N->getOpcode() == ISD::ZERO_EXTEND)
12423 // When looking for a 0 constant, N can be zext or sext.
12424 OtherOp = DAG.getConstant(Val: 1, DL: dl, VT);
12425 else
12426 OtherOp = DAG.getAllOnesConstant(DL: dl, VT);
12427 return true;
12428 }
12429 }
12430}
12431
12432// Combine a constant select operand into its use:
12433//
12434// (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12435// (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12436// (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
12437// (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12438// (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12439//
12440// The transform is rejected if the select doesn't have a constant operand that
12441// is null, or all ones when AllOnes is set.
12442//
12443// Also recognize sext/zext from i1:
12444//
12445// (add (zext cc), x) -> (select cc (add x, 1), x)
12446// (add (sext cc), x) -> (select cc (add x, -1), x)
12447//
12448// These transformations eventually create predicated instructions.
12449//
12450// @param N The node to transform.
12451// @param Slct The N operand that is a select.
12452// @param OtherOp The other N operand (x above).
12453// @param DCI Context.
12454// @param AllOnes Require the select constant to be all ones instead of null.
12455// @returns The new node, or SDValue() on failure.
12456static
12457SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
12458 TargetLowering::DAGCombinerInfo &DCI,
12459 bool AllOnes = false) {
12460 SelectionDAG &DAG = DCI.DAG;
12461 EVT VT = N->getValueType(ResNo: 0);
12462 SDValue NonConstantVal;
12463 SDValue CCOp;
12464 bool SwapSelectOps;
12465 if (!isConditionalZeroOrAllOnes(N: Slct.getNode(), AllOnes, CC&: CCOp, Invert&: SwapSelectOps,
12466 OtherOp&: NonConstantVal, DAG))
12467 return SDValue();
12468
12469 // Slct is now know to be the desired identity constant when CC is true.
12470 SDValue TrueVal = OtherOp;
12471 SDValue FalseVal = DAG.getNode(Opcode: N->getOpcode(), DL: SDLoc(N), VT,
12472 N1: OtherOp, N2: NonConstantVal);
12473 // Unless SwapSelectOps says CC should be false.
12474 if (SwapSelectOps)
12475 std::swap(a&: TrueVal, b&: FalseVal);
12476
12477 return DAG.getNode(Opcode: ISD::SELECT, DL: SDLoc(N), VT,
12478 N1: CCOp, N2: TrueVal, N3: FalseVal);
12479}
12480
12481// Attempt combineSelectAndUse on each operand of a commutative operator N.
12482static
12483SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
12484 TargetLowering::DAGCombinerInfo &DCI) {
12485 SDValue N0 = N->getOperand(Num: 0);
12486 SDValue N1 = N->getOperand(Num: 1);
12487 if (N0.getNode()->hasOneUse())
12488 if (SDValue Result = combineSelectAndUse(N, Slct: N0, OtherOp: N1, DCI, AllOnes))
12489 return Result;
12490 if (N1.getNode()->hasOneUse())
12491 if (SDValue Result = combineSelectAndUse(N, Slct: N1, OtherOp: N0, DCI, AllOnes))
12492 return Result;
12493 return SDValue();
12494}
12495
12496static bool IsVUZPShuffleNode(SDNode *N) {
12497 // VUZP shuffle node.
12498 if (N->getOpcode() == ARMISD::VUZP)
12499 return true;
12500
12501 // "VUZP" on i32 is an alias for VTRN.
12502 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(ResNo: 0) == MVT::v2i32)
12503 return true;
12504
12505 return false;
12506}
12507
12508static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
12509 TargetLowering::DAGCombinerInfo &DCI,
12510 const ARMSubtarget *Subtarget) {
12511 // Look for ADD(VUZP.0, VUZP.1).
12512 if (!IsVUZPShuffleNode(N: N0.getNode()) || N0.getNode() != N1.getNode() ||
12513 N0 == N1)
12514 return SDValue();
12515
12516 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
12517 if (!N->getValueType(ResNo: 0).is64BitVector())
12518 return SDValue();
12519
12520 // Generate vpadd.
12521 SelectionDAG &DAG = DCI.DAG;
12522 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12523 SDLoc dl(N);
12524 SDNode *Unzip = N0.getNode();
12525 EVT VT = N->getValueType(ResNo: 0);
12526
12527 SmallVector<SDValue, 8> Ops;
12528 Ops.push_back(Elt: DAG.getConstant(Val: Intrinsic::arm_neon_vpadd, DL: dl,
12529 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
12530 Ops.push_back(Elt: Unzip->getOperand(Num: 0));
12531 Ops.push_back(Elt: Unzip->getOperand(Num: 1));
12532
12533 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT, Ops);
12534}
12535
12536static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12537 TargetLowering::DAGCombinerInfo &DCI,
12538 const ARMSubtarget *Subtarget) {
12539 // Check for two extended operands.
12540 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
12541 N1.getOpcode() == ISD::SIGN_EXTEND) &&
12542 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
12543 N1.getOpcode() == ISD::ZERO_EXTEND))
12544 return SDValue();
12545
12546 SDValue N00 = N0.getOperand(i: 0);
12547 SDValue N10 = N1.getOperand(i: 0);
12548
12549 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
12550 if (!IsVUZPShuffleNode(N: N00.getNode()) || N00.getNode() != N10.getNode() ||
12551 N00 == N10)
12552 return SDValue();
12553
12554 // We only recognize Q register paddl here; this can't be reached until
12555 // after type legalization.
12556 if (!N00.getValueType().is64BitVector() ||
12557 !N0.getValueType().is128BitVector())
12558 return SDValue();
12559
12560 // Generate vpaddl.
12561 SelectionDAG &DAG = DCI.DAG;
12562 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12563 SDLoc dl(N);
12564 EVT VT = N->getValueType(ResNo: 0);
12565
12566 SmallVector<SDValue, 8> Ops;
12567 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
12568 unsigned Opcode;
12569 if (N0.getOpcode() == ISD::SIGN_EXTEND)
12570 Opcode = Intrinsic::arm_neon_vpaddls;
12571 else
12572 Opcode = Intrinsic::arm_neon_vpaddlu;
12573 Ops.push_back(Elt: DAG.getConstant(Val: Opcode, DL: dl,
12574 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
12575 EVT ElemTy = N00.getValueType().getVectorElementType();
12576 unsigned NumElts = VT.getVectorNumElements();
12577 EVT ConcatVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: ElemTy, NumElements: NumElts * 2);
12578 SDValue Concat = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: SDLoc(N), VT: ConcatVT,
12579 N1: N00.getOperand(i: 0), N2: N00.getOperand(i: 1));
12580 Ops.push_back(Elt: Concat);
12581
12582 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT, Ops);
12583}
12584
12585// FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
12586// an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
12587// much easier to match.
12588static SDValue
12589AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12590 TargetLowering::DAGCombinerInfo &DCI,
12591 const ARMSubtarget *Subtarget) {
12592 // Only perform optimization if after legalize, and if NEON is available. We
12593 // also expected both operands to be BUILD_VECTORs.
12594 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
12595 || N0.getOpcode() != ISD::BUILD_VECTOR
12596 || N1.getOpcode() != ISD::BUILD_VECTOR)
12597 return SDValue();
12598
12599 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
12600 EVT VT = N->getValueType(ResNo: 0);
12601 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
12602 return SDValue();
12603
12604 // Check that the vector operands are of the right form.
12605 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
12606 // operands, where N is the size of the formed vector.
12607 // Each EXTRACT_VECTOR should have the same input vector and odd or even
12608 // index such that we have a pair wise add pattern.
12609
12610 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
12611 if (N0->getOperand(Num: 0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12612 return SDValue();
12613 SDValue Vec = N0->getOperand(Num: 0)->getOperand(Num: 0);
12614 SDNode *V = Vec.getNode();
12615 unsigned nextIndex = 0;
12616
12617 // For each operands to the ADD which are BUILD_VECTORs,
12618 // check to see if each of their operands are an EXTRACT_VECTOR with
12619 // the same vector and appropriate index.
12620 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
12621 if (N0->getOperand(Num: i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
12622 && N1->getOperand(Num: i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12623
12624 SDValue ExtVec0 = N0->getOperand(Num: i);
12625 SDValue ExtVec1 = N1->getOperand(Num: i);
12626
12627 // First operand is the vector, verify its the same.
12628 if (V != ExtVec0->getOperand(Num: 0).getNode() ||
12629 V != ExtVec1->getOperand(Num: 0).getNode())
12630 return SDValue();
12631
12632 // Second is the constant, verify its correct.
12633 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(Val: ExtVec0->getOperand(Num: 1));
12634 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Val: ExtVec1->getOperand(Num: 1));
12635
12636 // For the constant, we want to see all the even or all the odd.
12637 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
12638 || C1->getZExtValue() != nextIndex+1)
12639 return SDValue();
12640
12641 // Increment index.
12642 nextIndex+=2;
12643 } else
12644 return SDValue();
12645 }
12646
12647 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
12648 // we're using the entire input vector, otherwise there's a size/legality
12649 // mismatch somewhere.
12650 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
12651 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
12652 return SDValue();
12653
12654 // Create VPADDL node.
12655 SelectionDAG &DAG = DCI.DAG;
12656 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12657
12658 SDLoc dl(N);
12659
12660 // Build operand list.
12661 SmallVector<SDValue, 8> Ops;
12662 Ops.push_back(Elt: DAG.getConstant(Val: Intrinsic::arm_neon_vpaddls, DL: dl,
12663 VT: TLI.getPointerTy(DL: DAG.getDataLayout())));
12664
12665 // Input is the vector.
12666 Ops.push_back(Elt: Vec);
12667
12668 // Get widened type and narrowed type.
12669 MVT widenType;
12670 unsigned numElem = VT.getVectorNumElements();
12671
12672 EVT inputLaneType = Vec.getValueType().getVectorElementType();
12673 switch (inputLaneType.getSimpleVT().SimpleTy) {
12674 case MVT::i8: widenType = MVT::getVectorVT(VT: MVT::i16, NumElements: numElem); break;
12675 case MVT::i16: widenType = MVT::getVectorVT(VT: MVT::i32, NumElements: numElem); break;
12676 case MVT::i32: widenType = MVT::getVectorVT(VT: MVT::i64, NumElements: numElem); break;
12677 default:
12678 llvm_unreachable("Invalid vector element type for padd optimization.");
12679 }
12680
12681 SDValue tmp = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: widenType, Ops);
12682 unsigned ExtOp = VT.bitsGT(VT: tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
12683 return DAG.getNode(Opcode: ExtOp, DL: dl, VT, Operand: tmp);
12684}
12685
12686static SDValue findMUL_LOHI(SDValue V) {
12687 if (V->getOpcode() == ISD::UMUL_LOHI ||
12688 V->getOpcode() == ISD::SMUL_LOHI)
12689 return V;
12690 return SDValue();
12691}
12692
12693static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
12694 TargetLowering::DAGCombinerInfo &DCI,
12695 const ARMSubtarget *Subtarget) {
12696 if (!Subtarget->hasBaseDSP())
12697 return SDValue();
12698
12699 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
12700 // accumulates the product into a 64-bit value. The 16-bit values will
12701 // be sign extended somehow or SRA'd into 32-bit values
12702 // (addc (adde (mul 16bit, 16bit), lo), hi)
12703 SDValue Mul = AddcNode->getOperand(Num: 0);
12704 SDValue Lo = AddcNode->getOperand(Num: 1);
12705 if (Mul.getOpcode() != ISD::MUL) {
12706 Lo = AddcNode->getOperand(Num: 0);
12707 Mul = AddcNode->getOperand(Num: 1);
12708 if (Mul.getOpcode() != ISD::MUL)
12709 return SDValue();
12710 }
12711
12712 SDValue SRA = AddeNode->getOperand(Num: 0);
12713 SDValue Hi = AddeNode->getOperand(Num: 1);
12714 if (SRA.getOpcode() != ISD::SRA) {
12715 SRA = AddeNode->getOperand(Num: 1);
12716 Hi = AddeNode->getOperand(Num: 0);
12717 if (SRA.getOpcode() != ISD::SRA)
12718 return SDValue();
12719 }
12720 if (auto Const = dyn_cast<ConstantSDNode>(Val: SRA.getOperand(i: 1))) {
12721 if (Const->getZExtValue() != 31)
12722 return SDValue();
12723 } else
12724 return SDValue();
12725
12726 if (SRA.getOperand(i: 0) != Mul)
12727 return SDValue();
12728
12729 SelectionDAG &DAG = DCI.DAG;
12730 SDLoc dl(AddcNode);
12731 unsigned Opcode = 0;
12732 SDValue Op0;
12733 SDValue Op1;
12734
12735 if (isS16(Op: Mul.getOperand(i: 0), DAG) && isS16(Op: Mul.getOperand(i: 1), DAG)) {
12736 Opcode = ARMISD::SMLALBB;
12737 Op0 = Mul.getOperand(i: 0);
12738 Op1 = Mul.getOperand(i: 1);
12739 } else if (isS16(Op: Mul.getOperand(i: 0), DAG) && isSRA16(Op: Mul.getOperand(i: 1))) {
12740 Opcode = ARMISD::SMLALBT;
12741 Op0 = Mul.getOperand(i: 0);
12742 Op1 = Mul.getOperand(i: 1).getOperand(i: 0);
12743 } else if (isSRA16(Op: Mul.getOperand(i: 0)) && isS16(Op: Mul.getOperand(i: 1), DAG)) {
12744 Opcode = ARMISD::SMLALTB;
12745 Op0 = Mul.getOperand(i: 0).getOperand(i: 0);
12746 Op1 = Mul.getOperand(i: 1);
12747 } else if (isSRA16(Op: Mul.getOperand(i: 0)) && isSRA16(Op: Mul.getOperand(i: 1))) {
12748 Opcode = ARMISD::SMLALTT;
12749 Op0 = Mul->getOperand(Num: 0).getOperand(i: 0);
12750 Op1 = Mul->getOperand(Num: 1).getOperand(i: 0);
12751 }
12752
12753 if (!Op0 || !Op1)
12754 return SDValue();
12755
12756 SDValue SMLAL = DAG.getNode(Opcode, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
12757 N1: Op0, N2: Op1, N3: Lo, N4: Hi);
12758 // Replace the ADDs' nodes uses by the MLA node's values.
12759 SDValue HiMLALResult(SMLAL.getNode(), 1);
12760 SDValue LoMLALResult(SMLAL.getNode(), 0);
12761
12762 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddcNode, 0), To: LoMLALResult);
12763 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddeNode, 0), To: HiMLALResult);
12764
12765 // Return original node to notify the driver to stop replacing.
12766 SDValue resNode(AddcNode, 0);
12767 return resNode;
12768}
12769
12770static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
12771 TargetLowering::DAGCombinerInfo &DCI,
12772 const ARMSubtarget *Subtarget) {
12773 // Look for multiply add opportunities.
12774 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
12775 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
12776 // a glue link from the first add to the second add.
12777 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
12778 // a S/UMLAL instruction.
12779 // UMUL_LOHI
12780 // / :lo \ :hi
12781 // V \ [no multiline comment]
12782 // loAdd -> ADDC |
12783 // \ :carry /
12784 // V V
12785 // ADDE <- hiAdd
12786 //
12787 // In the special case where only the higher part of a signed result is used
12788 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
12789 // a constant with the exact value of 0x80000000, we recognize we are dealing
12790 // with a "rounded multiply and add" (or subtract) and transform it into
12791 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
12792
12793 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
12794 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
12795 "Expect an ADDE or SUBE");
12796
12797 assert(AddeSubeNode->getNumOperands() == 3 &&
12798 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
12799 "ADDE node has the wrong inputs");
12800
12801 // Check that we are chained to the right ADDC or SUBC node.
12802 SDNode *AddcSubcNode = AddeSubeNode->getOperand(Num: 2).getNode();
12803 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12804 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
12805 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
12806 AddcSubcNode->getOpcode() != ARMISD::SUBC))
12807 return SDValue();
12808
12809 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(Num: 0);
12810 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(Num: 1);
12811
12812 // Check if the two operands are from the same mul_lohi node.
12813 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
12814 return SDValue();
12815
12816 assert(AddcSubcNode->getNumValues() == 2 &&
12817 AddcSubcNode->getValueType(0) == MVT::i32 &&
12818 "Expect ADDC with two result values. First: i32");
12819
12820 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
12821 // maybe a SMLAL which multiplies two 16-bit values.
12822 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12823 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
12824 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
12825 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
12826 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
12827 return AddCombineTo64BitSMLAL16(AddcNode: AddcSubcNode, AddeNode: AddeSubeNode, DCI, Subtarget);
12828
12829 // Check for the triangle shape.
12830 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(Num: 0);
12831 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(Num: 1);
12832
12833 // Make sure that the ADDE/SUBE operands are not coming from the same node.
12834 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
12835 return SDValue();
12836
12837 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
12838 bool IsLeftOperandMUL = false;
12839 SDValue MULOp = findMUL_LOHI(V: AddeSubeOp0);
12840 if (MULOp == SDValue())
12841 MULOp = findMUL_LOHI(V: AddeSubeOp1);
12842 else
12843 IsLeftOperandMUL = true;
12844 if (MULOp == SDValue())
12845 return SDValue();
12846
12847 // Figure out the right opcode.
12848 unsigned Opc = MULOp->getOpcode();
12849 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
12850
12851 // Figure out the high and low input values to the MLAL node.
12852 SDValue *HiAddSub = nullptr;
12853 SDValue *LoMul = nullptr;
12854 SDValue *LowAddSub = nullptr;
12855
12856 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
12857 if ((AddeSubeOp0 != MULOp.getValue(R: 1)) && (AddeSubeOp1 != MULOp.getValue(R: 1)))
12858 return SDValue();
12859
12860 if (IsLeftOperandMUL)
12861 HiAddSub = &AddeSubeOp1;
12862 else
12863 HiAddSub = &AddeSubeOp0;
12864
12865 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
12866 // whose low result is fed to the ADDC/SUBC we are checking.
12867
12868 if (AddcSubcOp0 == MULOp.getValue(R: 0)) {
12869 LoMul = &AddcSubcOp0;
12870 LowAddSub = &AddcSubcOp1;
12871 }
12872 if (AddcSubcOp1 == MULOp.getValue(R: 0)) {
12873 LoMul = &AddcSubcOp1;
12874 LowAddSub = &AddcSubcOp0;
12875 }
12876
12877 if (!LoMul)
12878 return SDValue();
12879
12880 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
12881 // the replacement below will create a cycle.
12882 if (AddcSubcNode == HiAddSub->getNode() ||
12883 AddcSubcNode->isPredecessorOf(N: HiAddSub->getNode()))
12884 return SDValue();
12885
12886 // Create the merged node.
12887 SelectionDAG &DAG = DCI.DAG;
12888
12889 // Start building operand list.
12890 SmallVector<SDValue, 8> Ops;
12891 Ops.push_back(Elt: LoMul->getOperand(i: 0));
12892 Ops.push_back(Elt: LoMul->getOperand(i: 1));
12893
12894 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
12895 // the case, we must be doing signed multiplication and only use the higher
12896 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
12897 // addition or subtraction with the value of 0x800000.
12898 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
12899 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(Value: 1) &&
12900 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
12901 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
12902 0x80000000) {
12903 Ops.push_back(Elt: *HiAddSub);
12904 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
12905 FinalOpc = ARMISD::SMMLSR;
12906 } else {
12907 FinalOpc = ARMISD::SMMLAR;
12908 }
12909 SDValue NewNode = DAG.getNode(Opcode: FinalOpc, DL: SDLoc(AddcSubcNode), VT: MVT::i32, Ops);
12910 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddeSubeNode, 0), To: NewNode);
12911
12912 return SDValue(AddeSubeNode, 0);
12913 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
12914 // SMMLS is generated during instruction selection and the rest of this
12915 // function can not handle the case where AddcSubcNode is a SUBC.
12916 return SDValue();
12917
12918 // Finish building the operand list for {U/S}MLAL
12919 Ops.push_back(Elt: *LowAddSub);
12920 Ops.push_back(Elt: *HiAddSub);
12921
12922 SDValue MLALNode = DAG.getNode(Opcode: FinalOpc, DL: SDLoc(AddcSubcNode),
12923 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), Ops);
12924
12925 // Replace the ADDs' nodes uses by the MLA node's values.
12926 SDValue HiMLALResult(MLALNode.getNode(), 1);
12927 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddeSubeNode, 0), To: HiMLALResult);
12928
12929 SDValue LoMLALResult(MLALNode.getNode(), 0);
12930 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddcSubcNode, 0), To: LoMLALResult);
12931
12932 // Return original node to notify the driver to stop replacing.
12933 return SDValue(AddeSubeNode, 0);
12934}
12935
12936static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
12937 TargetLowering::DAGCombinerInfo &DCI,
12938 const ARMSubtarget *Subtarget) {
12939 // UMAAL is similar to UMLAL except that it adds two unsigned values.
12940 // While trying to combine for the other MLAL nodes, first search for the
12941 // chance to use UMAAL. Check if Addc uses a node which has already
12942 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
12943 // as the addend, and it's handled in PerformUMLALCombine.
12944
12945 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12946 return AddCombineTo64bitMLAL(AddeSubeNode: AddeNode, DCI, Subtarget);
12947
12948 // Check that we have a glued ADDC node.
12949 SDNode* AddcNode = AddeNode->getOperand(Num: 2).getNode();
12950 if (AddcNode->getOpcode() != ARMISD::ADDC)
12951 return SDValue();
12952
12953 // Find the converted UMAAL or quit if it doesn't exist.
12954 SDNode *UmlalNode = nullptr;
12955 SDValue AddHi;
12956 if (AddcNode->getOperand(Num: 0).getOpcode() == ARMISD::UMLAL) {
12957 UmlalNode = AddcNode->getOperand(Num: 0).getNode();
12958 AddHi = AddcNode->getOperand(Num: 1);
12959 } else if (AddcNode->getOperand(Num: 1).getOpcode() == ARMISD::UMLAL) {
12960 UmlalNode = AddcNode->getOperand(Num: 1).getNode();
12961 AddHi = AddcNode->getOperand(Num: 0);
12962 } else {
12963 return AddCombineTo64bitMLAL(AddeSubeNode: AddeNode, DCI, Subtarget);
12964 }
12965
12966 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
12967 // the ADDC as well as Zero.
12968 if (!isNullConstant(V: UmlalNode->getOperand(Num: 3)))
12969 return SDValue();
12970
12971 if ((isNullConstant(V: AddeNode->getOperand(Num: 0)) &&
12972 AddeNode->getOperand(Num: 1).getNode() == UmlalNode) ||
12973 (AddeNode->getOperand(Num: 0).getNode() == UmlalNode &&
12974 isNullConstant(V: AddeNode->getOperand(Num: 1)))) {
12975 SelectionDAG &DAG = DCI.DAG;
12976 SDValue Ops[] = { UmlalNode->getOperand(Num: 0), UmlalNode->getOperand(Num: 1),
12977 UmlalNode->getOperand(Num: 2), AddHi };
12978 SDValue UMAAL = DAG.getNode(Opcode: ARMISD::UMAAL, DL: SDLoc(AddcNode),
12979 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), Ops);
12980
12981 // Replace the ADDs' nodes uses by the UMAAL node's values.
12982 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddeNode, 0), To: SDValue(UMAAL.getNode(), 1));
12983 DAG.ReplaceAllUsesOfValueWith(From: SDValue(AddcNode, 0), To: SDValue(UMAAL.getNode(), 0));
12984
12985 // Return original node to notify the driver to stop replacing.
12986 return SDValue(AddeNode, 0);
12987 }
12988 return SDValue();
12989}
12990
12991static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
12992 const ARMSubtarget *Subtarget) {
12993 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12994 return SDValue();
12995
12996 // Check that we have a pair of ADDC and ADDE as operands.
12997 // Both addends of the ADDE must be zero.
12998 SDNode* AddcNode = N->getOperand(Num: 2).getNode();
12999 SDNode* AddeNode = N->getOperand(Num: 3).getNode();
13000 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
13001 (AddeNode->getOpcode() == ARMISD::ADDE) &&
13002 isNullConstant(V: AddeNode->getOperand(Num: 0)) &&
13003 isNullConstant(V: AddeNode->getOperand(Num: 1)) &&
13004 (AddeNode->getOperand(Num: 2).getNode() == AddcNode))
13005 return DAG.getNode(Opcode: ARMISD::UMAAL, DL: SDLoc(N),
13006 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
13007 Ops: {N->getOperand(Num: 0), N->getOperand(Num: 1),
13008 AddcNode->getOperand(Num: 0), AddcNode->getOperand(Num: 1)});
13009 else
13010 return SDValue();
13011}
13012
13013static SDValue PerformAddcSubcCombine(SDNode *N,
13014 TargetLowering::DAGCombinerInfo &DCI,
13015 const ARMSubtarget *Subtarget) {
13016 SelectionDAG &DAG(DCI.DAG);
13017
13018 if (N->getOpcode() == ARMISD::SUBC && N->hasAnyUseOfValue(Value: 1)) {
13019 // (SUBC (ADDE 0, 0, C), 1) -> C
13020 SDValue LHS = N->getOperand(Num: 0);
13021 SDValue RHS = N->getOperand(Num: 1);
13022 if (LHS->getOpcode() == ARMISD::ADDE &&
13023 isNullConstant(V: LHS->getOperand(Num: 0)) &&
13024 isNullConstant(V: LHS->getOperand(Num: 1)) && isOneConstant(V: RHS)) {
13025 return DCI.CombineTo(N, Res0: SDValue(N, 0), Res1: LHS->getOperand(Num: 2));
13026 }
13027 }
13028
13029 if (Subtarget->isThumb1Only()) {
13030 SDValue RHS = N->getOperand(Num: 1);
13031 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: RHS)) {
13032 int32_t imm = C->getSExtValue();
13033 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
13034 SDLoc DL(N);
13035 RHS = DAG.getConstant(Val: -imm, DL, VT: MVT::i32);
13036 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
13037 : ARMISD::ADDC;
13038 return DAG.getNode(Opcode, DL, VTList: N->getVTList(), N1: N->getOperand(Num: 0), N2: RHS);
13039 }
13040 }
13041 }
13042
13043 return SDValue();
13044}
13045
13046static SDValue PerformAddeSubeCombine(SDNode *N,
13047 TargetLowering::DAGCombinerInfo &DCI,
13048 const ARMSubtarget *Subtarget) {
13049 if (Subtarget->isThumb1Only()) {
13050 SelectionDAG &DAG = DCI.DAG;
13051 SDValue RHS = N->getOperand(Num: 1);
13052 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: RHS)) {
13053 int64_t imm = C->getSExtValue();
13054 if (imm < 0) {
13055 SDLoc DL(N);
13056
13057 // The with-carry-in form matches bitwise not instead of the negation.
13058 // Effectively, the inverse interpretation of the carry flag already
13059 // accounts for part of the negation.
13060 RHS = DAG.getConstant(Val: ~imm, DL, VT: MVT::i32);
13061
13062 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
13063 : ARMISD::ADDE;
13064 return DAG.getNode(Opcode, DL, VTList: N->getVTList(),
13065 N1: N->getOperand(Num: 0), N2: RHS, N3: N->getOperand(Num: 2));
13066 }
13067 }
13068 } else if (N->getOperand(Num: 1)->getOpcode() == ISD::SMUL_LOHI) {
13069 return AddCombineTo64bitMLAL(AddeSubeNode: N, DCI, Subtarget);
13070 }
13071 return SDValue();
13072}
13073
13074static SDValue PerformSELECTCombine(SDNode *N,
13075 TargetLowering::DAGCombinerInfo &DCI,
13076 const ARMSubtarget *Subtarget) {
13077 if (!Subtarget->hasMVEIntegerOps())
13078 return SDValue();
13079
13080 SDLoc dl(N);
13081 SDValue SetCC;
13082 SDValue LHS;
13083 SDValue RHS;
13084 ISD::CondCode CC;
13085 SDValue TrueVal;
13086 SDValue FalseVal;
13087
13088 if (N->getOpcode() == ISD::SELECT &&
13089 N->getOperand(Num: 0)->getOpcode() == ISD::SETCC) {
13090 SetCC = N->getOperand(Num: 0);
13091 LHS = SetCC->getOperand(Num: 0);
13092 RHS = SetCC->getOperand(Num: 1);
13093 CC = cast<CondCodeSDNode>(Val: SetCC->getOperand(Num: 2))->get();
13094 TrueVal = N->getOperand(Num: 1);
13095 FalseVal = N->getOperand(Num: 2);
13096 } else if (N->getOpcode() == ISD::SELECT_CC) {
13097 LHS = N->getOperand(Num: 0);
13098 RHS = N->getOperand(Num: 1);
13099 CC = cast<CondCodeSDNode>(Val: N->getOperand(Num: 4))->get();
13100 TrueVal = N->getOperand(Num: 2);
13101 FalseVal = N->getOperand(Num: 3);
13102 } else {
13103 return SDValue();
13104 }
13105
13106 unsigned int Opcode = 0;
13107 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
13108 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
13109 (CC == ISD::SETULT || CC == ISD::SETUGT)) {
13110 Opcode = ARMISD::VMINVu;
13111 if (CC == ISD::SETUGT)
13112 std::swap(a&: TrueVal, b&: FalseVal);
13113 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
13114 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
13115 (CC == ISD::SETLT || CC == ISD::SETGT)) {
13116 Opcode = ARMISD::VMINVs;
13117 if (CC == ISD::SETGT)
13118 std::swap(a&: TrueVal, b&: FalseVal);
13119 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
13120 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
13121 (CC == ISD::SETUGT || CC == ISD::SETULT)) {
13122 Opcode = ARMISD::VMAXVu;
13123 if (CC == ISD::SETULT)
13124 std::swap(a&: TrueVal, b&: FalseVal);
13125 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
13126 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
13127 (CC == ISD::SETGT || CC == ISD::SETLT)) {
13128 Opcode = ARMISD::VMAXVs;
13129 if (CC == ISD::SETLT)
13130 std::swap(a&: TrueVal, b&: FalseVal);
13131 } else
13132 return SDValue();
13133
13134 // Normalise to the right hand side being the vector reduction
13135 switch (TrueVal->getOpcode()) {
13136 case ISD::VECREDUCE_UMIN:
13137 case ISD::VECREDUCE_SMIN:
13138 case ISD::VECREDUCE_UMAX:
13139 case ISD::VECREDUCE_SMAX:
13140 std::swap(a&: LHS, b&: RHS);
13141 std::swap(a&: TrueVal, b&: FalseVal);
13142 break;
13143 }
13144
13145 EVT VectorType = FalseVal->getOperand(Num: 0).getValueType();
13146
13147 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
13148 VectorType != MVT::v4i32)
13149 return SDValue();
13150
13151 EVT VectorScalarType = VectorType.getVectorElementType();
13152
13153 // The values being selected must also be the ones being compared
13154 if (TrueVal != LHS || FalseVal != RHS)
13155 return SDValue();
13156
13157 EVT LeftType = LHS->getValueType(ResNo: 0);
13158 EVT RightType = RHS->getValueType(ResNo: 0);
13159
13160 // The types must match the reduced type too
13161 if (LeftType != VectorScalarType || RightType != VectorScalarType)
13162 return SDValue();
13163
13164 // Legalise the scalar to an i32
13165 if (VectorScalarType != MVT::i32)
13166 LHS = DCI.DAG.getNode(Opcode: ISD::ANY_EXTEND, DL: dl, VT: MVT::i32, Operand: LHS);
13167
13168 // Generate the reduction as an i32 for legalisation purposes
13169 auto Reduction =
13170 DCI.DAG.getNode(Opcode, DL: dl, VT: MVT::i32, N1: LHS, N2: RHS->getOperand(Num: 0));
13171
13172 // The result isn't actually an i32 so truncate it back to its original type
13173 if (VectorScalarType != MVT::i32)
13174 Reduction = DCI.DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: VectorScalarType, Operand: Reduction);
13175
13176 return Reduction;
13177}
13178
13179// A special combine for the vqdmulh family of instructions. This is one of the
13180// potential set of patterns that could patch this instruction. The base pattern
13181// you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
13182// This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
13183// which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
13184// the max is unnecessary.
13185static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) {
13186 EVT VT = N->getValueType(ResNo: 0);
13187 SDValue Shft;
13188 ConstantSDNode *Clamp;
13189
13190 if (!VT.isVector() || VT.getScalarSizeInBits() > 64)
13191 return SDValue();
13192
13193 if (N->getOpcode() == ISD::SMIN) {
13194 Shft = N->getOperand(Num: 0);
13195 Clamp = isConstOrConstSplat(N: N->getOperand(Num: 1));
13196 } else if (N->getOpcode() == ISD::VSELECT) {
13197 // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
13198 SDValue Cmp = N->getOperand(Num: 0);
13199 if (Cmp.getOpcode() != ISD::SETCC ||
13200 cast<CondCodeSDNode>(Val: Cmp.getOperand(i: 2))->get() != ISD::SETLT ||
13201 Cmp.getOperand(i: 0) != N->getOperand(Num: 1) ||
13202 Cmp.getOperand(i: 1) != N->getOperand(Num: 2))
13203 return SDValue();
13204 Shft = N->getOperand(Num: 1);
13205 Clamp = isConstOrConstSplat(N: N->getOperand(Num: 2));
13206 } else
13207 return SDValue();
13208
13209 if (!Clamp)
13210 return SDValue();
13211
13212 MVT ScalarType;
13213 int ShftAmt = 0;
13214 switch (Clamp->getSExtValue()) {
13215 case (1 << 7) - 1:
13216 ScalarType = MVT::i8;
13217 ShftAmt = 7;
13218 break;
13219 case (1 << 15) - 1:
13220 ScalarType = MVT::i16;
13221 ShftAmt = 15;
13222 break;
13223 case (1ULL << 31) - 1:
13224 ScalarType = MVT::i32;
13225 ShftAmt = 31;
13226 break;
13227 default:
13228 return SDValue();
13229 }
13230
13231 if (Shft.getOpcode() != ISD::SRA)
13232 return SDValue();
13233 ConstantSDNode *N1 = isConstOrConstSplat(N: Shft.getOperand(i: 1));
13234 if (!N1 || N1->getSExtValue() != ShftAmt)
13235 return SDValue();
13236
13237 SDValue Mul = Shft.getOperand(i: 0);
13238 if (Mul.getOpcode() != ISD::MUL)
13239 return SDValue();
13240
13241 SDValue Ext0 = Mul.getOperand(i: 0);
13242 SDValue Ext1 = Mul.getOperand(i: 1);
13243 if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
13244 Ext1.getOpcode() != ISD::SIGN_EXTEND)
13245 return SDValue();
13246 EVT VecVT = Ext0.getOperand(i: 0).getValueType();
13247 if (!VecVT.isPow2VectorType() || VecVT.getVectorNumElements() == 1)
13248 return SDValue();
13249 if (Ext1.getOperand(i: 0).getValueType() != VecVT ||
13250 VecVT.getScalarType() != ScalarType ||
13251 VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
13252 return SDValue();
13253
13254 SDLoc DL(Mul);
13255 unsigned LegalLanes = 128 / (ShftAmt + 1);
13256 EVT LegalVecVT = MVT::getVectorVT(VT: ScalarType, NumElements: LegalLanes);
13257 // For types smaller than legal vectors extend to be legal and only use needed
13258 // lanes.
13259 if (VecVT.getSizeInBits() < 128) {
13260 EVT ExtVecVT =
13261 MVT::getVectorVT(VT: MVT::getIntegerVT(BitWidth: 128 / VecVT.getVectorNumElements()),
13262 NumElements: VecVT.getVectorNumElements());
13263 SDValue Inp0 =
13264 DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: ExtVecVT, Operand: Ext0.getOperand(i: 0));
13265 SDValue Inp1 =
13266 DAG.getNode(Opcode: ISD::ANY_EXTEND, DL, VT: ExtVecVT, Operand: Ext1.getOperand(i: 0));
13267 Inp0 = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT: LegalVecVT, Operand: Inp0);
13268 Inp1 = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT: LegalVecVT, Operand: Inp1);
13269 SDValue VQDMULH = DAG.getNode(Opcode: ARMISD::VQDMULH, DL, VT: LegalVecVT, N1: Inp0, N2: Inp1);
13270 SDValue Trunc = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT: ExtVecVT, Operand: VQDMULH);
13271 Trunc = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: VecVT, Operand: Trunc);
13272 return DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT, Operand: Trunc);
13273 }
13274
13275 // For larger types, split into legal sized chunks.
13276 assert(VecVT.getSizeInBits() % 128 == 0 && "Expected a power2 type");
13277 unsigned NumParts = VecVT.getSizeInBits() / 128;
13278 SmallVector<SDValue> Parts;
13279 for (unsigned I = 0; I < NumParts; ++I) {
13280 SDValue Inp0 =
13281 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: LegalVecVT, N1: Ext0.getOperand(i: 0),
13282 N2: DAG.getVectorIdxConstant(Val: I * LegalLanes, DL));
13283 SDValue Inp1 =
13284 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: LegalVecVT, N1: Ext1.getOperand(i: 0),
13285 N2: DAG.getVectorIdxConstant(Val: I * LegalLanes, DL));
13286 SDValue VQDMULH = DAG.getNode(Opcode: ARMISD::VQDMULH, DL, VT: LegalVecVT, N1: Inp0, N2: Inp1);
13287 Parts.push_back(Elt: VQDMULH);
13288 }
13289 return DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL, VT,
13290 Operand: DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: VecVT, Ops: Parts));
13291}
13292
13293static SDValue PerformVSELECTCombine(SDNode *N,
13294 TargetLowering::DAGCombinerInfo &DCI,
13295 const ARMSubtarget *Subtarget) {
13296 if (!Subtarget->hasMVEIntegerOps())
13297 return SDValue();
13298
13299 if (SDValue V = PerformVQDMULHCombine(N, DAG&: DCI.DAG))
13300 return V;
13301
13302 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
13303 //
13304 // We need to re-implement this optimization here as the implementation in the
13305 // Target-Independent DAGCombiner does not handle the kind of constant we make
13306 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
13307 // good reason, allowing truncation there would break other targets).
13308 //
13309 // Currently, this is only done for MVE, as it's the only target that benefits
13310 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
13311 if (N->getOperand(Num: 0).getOpcode() != ISD::XOR)
13312 return SDValue();
13313 SDValue XOR = N->getOperand(Num: 0);
13314
13315 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
13316 // It is important to check with truncation allowed as the BUILD_VECTORs we
13317 // generate in those situations will truncate their operands.
13318 ConstantSDNode *Const =
13319 isConstOrConstSplat(N: XOR->getOperand(Num: 1), /*AllowUndefs*/ false,
13320 /*AllowTruncation*/ true);
13321 if (!Const || !Const->isOne())
13322 return SDValue();
13323
13324 // Rewrite into vselect(cond, rhs, lhs).
13325 SDValue Cond = XOR->getOperand(Num: 0);
13326 SDValue LHS = N->getOperand(Num: 1);
13327 SDValue RHS = N->getOperand(Num: 2);
13328 EVT Type = N->getValueType(ResNo: 0);
13329 return DCI.DAG.getNode(Opcode: ISD::VSELECT, DL: SDLoc(N), VT: Type, N1: Cond, N2: RHS, N3: LHS);
13330}
13331
13332// Convert vsetcc([0,1,2,..], splat(n), ult) -> vctp n
13333static SDValue PerformVSetCCToVCTPCombine(SDNode *N,
13334 TargetLowering::DAGCombinerInfo &DCI,
13335 const ARMSubtarget *Subtarget) {
13336 SDValue Op0 = N->getOperand(Num: 0);
13337 SDValue Op1 = N->getOperand(Num: 1);
13338 ISD::CondCode CC = cast<CondCodeSDNode>(Val: N->getOperand(Num: 2))->get();
13339 EVT VT = N->getValueType(ResNo: 0);
13340
13341 if (!Subtarget->hasMVEIntegerOps() ||
13342 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13343 return SDValue();
13344
13345 if (CC == ISD::SETUGE) {
13346 std::swap(a&: Op0, b&: Op1);
13347 CC = ISD::SETULT;
13348 }
13349
13350 if (CC != ISD::SETULT || VT.getScalarSizeInBits() != 1 ||
13351 Op0.getOpcode() != ISD::BUILD_VECTOR)
13352 return SDValue();
13353
13354 // Check first operand is BuildVector of 0,1,2,...
13355 for (unsigned I = 0; I < VT.getVectorNumElements(); I++) {
13356 if (!Op0.getOperand(i: I).isUndef() &&
13357 !(isa<ConstantSDNode>(Val: Op0.getOperand(i: I)) &&
13358 Op0.getConstantOperandVal(i: I) == I))
13359 return SDValue();
13360 }
13361
13362 // The second is a Splat of Op1S
13363 SDValue Op1S = DCI.DAG.getSplatValue(V: Op1);
13364 if (!Op1S)
13365 return SDValue();
13366
13367 unsigned Opc;
13368 switch (VT.getVectorNumElements()) {
13369 case 2:
13370 Opc = Intrinsic::arm_mve_vctp64;
13371 break;
13372 case 4:
13373 Opc = Intrinsic::arm_mve_vctp32;
13374 break;
13375 case 8:
13376 Opc = Intrinsic::arm_mve_vctp16;
13377 break;
13378 case 16:
13379 Opc = Intrinsic::arm_mve_vctp8;
13380 break;
13381 default:
13382 return SDValue();
13383 }
13384
13385 SDLoc DL(N);
13386 return DCI.DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT,
13387 N1: DCI.DAG.getConstant(Val: Opc, DL, VT: MVT::i32),
13388 N2: DCI.DAG.getZExtOrTrunc(Op: Op1S, DL, VT: MVT::i32));
13389}
13390
13391/// PerformADDECombine - Target-specific dag combine transform from
13392/// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
13393/// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
13394static SDValue PerformADDECombine(SDNode *N,
13395 TargetLowering::DAGCombinerInfo &DCI,
13396 const ARMSubtarget *Subtarget) {
13397 // Only ARM and Thumb2 support UMLAL/SMLAL.
13398 if (Subtarget->isThumb1Only())
13399 return PerformAddeSubeCombine(N, DCI, Subtarget);
13400
13401 // Only perform the checks after legalize when the pattern is available.
13402 if (DCI.isBeforeLegalize()) return SDValue();
13403
13404 return AddCombineTo64bitUMAAL(AddeNode: N, DCI, Subtarget);
13405}
13406
13407/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
13408/// operands N0 and N1. This is a helper for PerformADDCombine that is
13409/// called with the default operands, and if that fails, with commuted
13410/// operands.
13411static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
13412 TargetLowering::DAGCombinerInfo &DCI,
13413 const ARMSubtarget *Subtarget){
13414 // Attempt to create vpadd for this add.
13415 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
13416 return Result;
13417
13418 // Attempt to create vpaddl for this add.
13419 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
13420 return Result;
13421 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
13422 Subtarget))
13423 return Result;
13424
13425 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
13426 if (N0.getNode()->hasOneUse())
13427 if (SDValue Result = combineSelectAndUse(N, Slct: N0, OtherOp: N1, DCI))
13428 return Result;
13429 return SDValue();
13430}
13431
13432static SDValue TryDistrubutionADDVecReduce(SDNode *N, SelectionDAG &DAG) {
13433 EVT VT = N->getValueType(ResNo: 0);
13434 SDValue N0 = N->getOperand(Num: 0);
13435 SDValue N1 = N->getOperand(Num: 1);
13436 SDLoc dl(N);
13437
13438 auto IsVecReduce = [](SDValue Op) {
13439 switch (Op.getOpcode()) {
13440 case ISD::VECREDUCE_ADD:
13441 case ARMISD::VADDVs:
13442 case ARMISD::VADDVu:
13443 case ARMISD::VMLAVs:
13444 case ARMISD::VMLAVu:
13445 return true;
13446 }
13447 return false;
13448 };
13449
13450 auto DistrubuteAddAddVecReduce = [&](SDValue N0, SDValue N1) {
13451 // Distribute add(X, add(vecreduce(Y), vecreduce(Z))) ->
13452 // add(add(X, vecreduce(Y)), vecreduce(Z))
13453 // to make better use of vaddva style instructions.
13454 if (VT == MVT::i32 && N1.getOpcode() == ISD::ADD && !IsVecReduce(N0) &&
13455 IsVecReduce(N1.getOperand(i: 0)) && IsVecReduce(N1.getOperand(i: 1)) &&
13456 !isa<ConstantSDNode>(Val: N0) && N1->hasOneUse()) {
13457 SDValue Add0 = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: N0, N2: N1.getOperand(i: 0));
13458 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: Add0, N2: N1.getOperand(i: 1));
13459 }
13460 // And turn add(add(A, reduce(B)), add(C, reduce(D))) ->
13461 // add(add(add(A, C), reduce(B)), reduce(D))
13462 if (VT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
13463 N1.getOpcode() == ISD::ADD && N0->hasOneUse() && N1->hasOneUse()) {
13464 unsigned N0RedOp = 0;
13465 if (!IsVecReduce(N0.getOperand(i: N0RedOp))) {
13466 N0RedOp = 1;
13467 if (!IsVecReduce(N0.getOperand(i: N0RedOp)))
13468 return SDValue();
13469 }
13470
13471 unsigned N1RedOp = 0;
13472 if (!IsVecReduce(N1.getOperand(i: N1RedOp)))
13473 N1RedOp = 1;
13474 if (!IsVecReduce(N1.getOperand(i: N1RedOp)))
13475 return SDValue();
13476
13477 SDValue Add0 = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: N0.getOperand(i: 1 - N0RedOp),
13478 N2: N1.getOperand(i: 1 - N1RedOp));
13479 SDValue Add1 =
13480 DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: Add0, N2: N0.getOperand(i: N0RedOp));
13481 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: Add1, N2: N1.getOperand(i: N1RedOp));
13482 }
13483 return SDValue();
13484 };
13485 if (SDValue R = DistrubuteAddAddVecReduce(N0, N1))
13486 return R;
13487 if (SDValue R = DistrubuteAddAddVecReduce(N1, N0))
13488 return R;
13489
13490 // Distribute add(vecreduce(load(Y)), vecreduce(load(Z)))
13491 // Or add(add(X, vecreduce(load(Y))), vecreduce(load(Z)))
13492 // by ascending load offsets. This can help cores prefetch if the order of
13493 // loads is more predictable.
13494 auto DistrubuteVecReduceLoad = [&](SDValue N0, SDValue N1, bool IsForward) {
13495 // Check if two reductions are known to load data where one is before/after
13496 // another. Return negative if N0 loads data before N1, positive if N1 is
13497 // before N0 and 0 otherwise if nothing is known.
13498 auto IsKnownOrderedLoad = [&](SDValue N0, SDValue N1) {
13499 // Look through to the first operand of a MUL, for the VMLA case.
13500 // Currently only looks at the first operand, in the hope they are equal.
13501 if (N0.getOpcode() == ISD::MUL)
13502 N0 = N0.getOperand(i: 0);
13503 if (N1.getOpcode() == ISD::MUL)
13504 N1 = N1.getOperand(i: 0);
13505
13506 // Return true if the two operands are loads to the same object and the
13507 // offset of the first is known to be less than the offset of the second.
13508 LoadSDNode *Load0 = dyn_cast<LoadSDNode>(Val&: N0);
13509 LoadSDNode *Load1 = dyn_cast<LoadSDNode>(Val&: N1);
13510 if (!Load0 || !Load1 || Load0->getChain() != Load1->getChain() ||
13511 !Load0->isSimple() || !Load1->isSimple() || Load0->isIndexed() ||
13512 Load1->isIndexed())
13513 return 0;
13514
13515 auto BaseLocDecomp0 = BaseIndexOffset::match(N: Load0, DAG);
13516 auto BaseLocDecomp1 = BaseIndexOffset::match(N: Load1, DAG);
13517
13518 if (!BaseLocDecomp0.getBase() ||
13519 BaseLocDecomp0.getBase() != BaseLocDecomp1.getBase() ||
13520 !BaseLocDecomp0.hasValidOffset() || !BaseLocDecomp1.hasValidOffset())
13521 return 0;
13522 if (BaseLocDecomp0.getOffset() < BaseLocDecomp1.getOffset())
13523 return -1;
13524 if (BaseLocDecomp0.getOffset() > BaseLocDecomp1.getOffset())
13525 return 1;
13526 return 0;
13527 };
13528
13529 SDValue X;
13530 if (N0.getOpcode() == ISD::ADD && N0->hasOneUse()) {
13531 if (IsVecReduce(N0.getOperand(i: 0)) && IsVecReduce(N0.getOperand(i: 1))) {
13532 int IsBefore = IsKnownOrderedLoad(N0.getOperand(i: 0).getOperand(i: 0),
13533 N0.getOperand(i: 1).getOperand(i: 0));
13534 if (IsBefore < 0) {
13535 X = N0.getOperand(i: 0);
13536 N0 = N0.getOperand(i: 1);
13537 } else if (IsBefore > 0) {
13538 X = N0.getOperand(i: 1);
13539 N0 = N0.getOperand(i: 0);
13540 } else
13541 return SDValue();
13542 } else if (IsVecReduce(N0.getOperand(i: 0))) {
13543 X = N0.getOperand(i: 1);
13544 N0 = N0.getOperand(i: 0);
13545 } else if (IsVecReduce(N0.getOperand(i: 1))) {
13546 X = N0.getOperand(i: 0);
13547 N0 = N0.getOperand(i: 1);
13548 } else
13549 return SDValue();
13550 } else if (IsForward && IsVecReduce(N0) && IsVecReduce(N1) &&
13551 IsKnownOrderedLoad(N0.getOperand(i: 0), N1.getOperand(i: 0)) < 0) {
13552 // Note this is backward to how you would expect. We create
13553 // add(reduce(load + 16), reduce(load + 0)) so that the
13554 // add(reduce(load+16), X) is combined into VADDVA(X, load+16)), leaving
13555 // the X as VADDV(load + 0)
13556 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1, N2: N0);
13557 } else
13558 return SDValue();
13559
13560 if (!IsVecReduce(N0) || !IsVecReduce(N1))
13561 return SDValue();
13562
13563 if (IsKnownOrderedLoad(N1.getOperand(i: 0), N0.getOperand(i: 0)) >= 0)
13564 return SDValue();
13565
13566 // Switch from add(add(X, N0), N1) to add(add(X, N1), N0)
13567 SDValue Add0 = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: X, N2: N1);
13568 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: Add0, N2: N0);
13569 };
13570 if (SDValue R = DistrubuteVecReduceLoad(N0, N1, true))
13571 return R;
13572 if (SDValue R = DistrubuteVecReduceLoad(N1, N0, false))
13573 return R;
13574 return SDValue();
13575}
13576
13577static SDValue PerformADDVecReduce(SDNode *N, SelectionDAG &DAG,
13578 const ARMSubtarget *Subtarget) {
13579 if (!Subtarget->hasMVEIntegerOps())
13580 return SDValue();
13581
13582 if (SDValue R = TryDistrubutionADDVecReduce(N, DAG))
13583 return R;
13584
13585 EVT VT = N->getValueType(ResNo: 0);
13586 SDValue N0 = N->getOperand(Num: 0);
13587 SDValue N1 = N->getOperand(Num: 1);
13588 SDLoc dl(N);
13589
13590 if (VT != MVT::i64)
13591 return SDValue();
13592
13593 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
13594 // will look like:
13595 // t1: i32,i32 = ARMISD::VADDLVs x
13596 // t2: i64 = build_pair t1, t1:1
13597 // t3: i64 = add t2, y
13598 // Otherwise we try to push the add up above VADDLVAx, to potentially allow
13599 // the add to be simplified separately.
13600 // We also need to check for sext / zext and commutitive adds.
13601 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
13602 SDValue NB) {
13603 if (NB->getOpcode() != ISD::BUILD_PAIR)
13604 return SDValue();
13605 SDValue VecRed = NB->getOperand(Num: 0);
13606 if ((VecRed->getOpcode() != Opcode && VecRed->getOpcode() != OpcodeA) ||
13607 VecRed.getResNo() != 0 ||
13608 NB->getOperand(Num: 1) != SDValue(VecRed.getNode(), 1))
13609 return SDValue();
13610
13611 if (VecRed->getOpcode() == OpcodeA) {
13612 // add(NA, VADDLVA(Inp), Y) -> VADDLVA(add(NA, Inp), Y)
13613 SDValue Inp = DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64,
13614 N1: VecRed.getOperand(i: 0), N2: VecRed.getOperand(i: 1));
13615 NA = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i64, N1: Inp, N2: NA);
13616 }
13617
13618 SmallVector<SDValue, 4> Ops(2);
13619 std::tie(args&: Ops[0], args&: Ops[1]) = DAG.SplitScalar(N: NA, DL: dl, LoVT: MVT::i32, HiVT: MVT::i32);
13620
13621 unsigned S = VecRed->getOpcode() == OpcodeA ? 2 : 0;
13622 for (unsigned I = S, E = VecRed.getNumOperands(); I < E; I++)
13623 Ops.push_back(Elt: VecRed->getOperand(Num: I));
13624 SDValue Red =
13625 DAG.getNode(Opcode: OpcodeA, DL: dl, VTList: DAG.getVTList(VTs: {MVT::i32, MVT::i32}), Ops);
13626 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Red,
13627 N2: SDValue(Red.getNode(), 1));
13628 };
13629
13630 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
13631 return M;
13632 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
13633 return M;
13634 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
13635 return M;
13636 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
13637 return M;
13638 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
13639 return M;
13640 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
13641 return M;
13642 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
13643 return M;
13644 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
13645 return M;
13646 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
13647 return M;
13648 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
13649 return M;
13650 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
13651 return M;
13652 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
13653 return M;
13654 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
13655 return M;
13656 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
13657 return M;
13658 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
13659 return M;
13660 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
13661 return M;
13662 return SDValue();
13663}
13664
13665bool
13666ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
13667 CombineLevel Level) const {
13668 assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||
13669 N->getOpcode() == ISD::SRL) &&
13670 "Expected shift op");
13671
13672 SDValue ShiftLHS = N->getOperand(Num: 0);
13673 if (!ShiftLHS->hasOneUse())
13674 return false;
13675
13676 if (ShiftLHS.getOpcode() == ISD::SIGN_EXTEND &&
13677 !ShiftLHS.getOperand(i: 0)->hasOneUse())
13678 return false;
13679
13680 if (Level == BeforeLegalizeTypes)
13681 return true;
13682
13683 if (N->getOpcode() != ISD::SHL)
13684 return true;
13685
13686 if (Subtarget->isThumb1Only()) {
13687 // Avoid making expensive immediates by commuting shifts. (This logic
13688 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
13689 // for free.)
13690 if (N->getOpcode() != ISD::SHL)
13691 return true;
13692 SDValue N1 = N->getOperand(Num: 0);
13693 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
13694 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
13695 return true;
13696 if (auto *Const = dyn_cast<ConstantSDNode>(Val: N1->getOperand(Num: 1))) {
13697 if (Const->getAPIntValue().ult(RHS: 256))
13698 return false;
13699 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(RHS: 0) &&
13700 Const->getAPIntValue().sgt(RHS: -256))
13701 return false;
13702 }
13703 return true;
13704 }
13705
13706 // Turn off commute-with-shift transform after legalization, so it doesn't
13707 // conflict with PerformSHLSimplify. (We could try to detect when
13708 // PerformSHLSimplify would trigger more precisely, but it isn't
13709 // really necessary.)
13710 return false;
13711}
13712
13713bool ARMTargetLowering::isDesirableToCommuteXorWithShift(
13714 const SDNode *N) const {
13715 assert(N->getOpcode() == ISD::XOR &&
13716 (N->getOperand(0).getOpcode() == ISD::SHL ||
13717 N->getOperand(0).getOpcode() == ISD::SRL) &&
13718 "Expected XOR(SHIFT) pattern");
13719
13720 // Only commute if the entire NOT mask is a hidden shifted mask.
13721 auto *XorC = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
13722 auto *ShiftC = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 0).getOperand(i: 1));
13723 if (XorC && ShiftC) {
13724 unsigned MaskIdx, MaskLen;
13725 if (XorC->getAPIntValue().isShiftedMask(MaskIdx, MaskLen)) {
13726 unsigned ShiftAmt = ShiftC->getZExtValue();
13727 unsigned BitWidth = N->getValueType(ResNo: 0).getScalarSizeInBits();
13728 if (N->getOperand(Num: 0).getOpcode() == ISD::SHL)
13729 return MaskIdx == ShiftAmt && MaskLen == (BitWidth - ShiftAmt);
13730 return MaskIdx == 0 && MaskLen == (BitWidth - ShiftAmt);
13731 }
13732 }
13733
13734 return false;
13735}
13736
13737bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
13738 const SDNode *N) const {
13739 assert(((N->getOpcode() == ISD::SHL &&
13740 N->getOperand(0).getOpcode() == ISD::SRL) ||
13741 (N->getOpcode() == ISD::SRL &&
13742 N->getOperand(0).getOpcode() == ISD::SHL)) &&
13743 "Expected shift-shift mask");
13744
13745 if (!Subtarget->isThumb1Only())
13746 return true;
13747
13748 EVT VT = N->getValueType(ResNo: 0);
13749 if (VT.getScalarSizeInBits() > 32)
13750 return true;
13751
13752 return false;
13753}
13754
13755bool ARMTargetLowering::shouldFoldSelectWithIdentityConstant(
13756 unsigned BinOpcode, EVT VT, unsigned SelectOpcode, SDValue X,
13757 SDValue Y) const {
13758 return Subtarget->hasMVEIntegerOps() && isTypeLegal(VT) &&
13759 SelectOpcode == ISD::VSELECT;
13760}
13761
13762bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13763 if (!Subtarget->hasNEON()) {
13764 if (Subtarget->isThumb1Only())
13765 return VT.getScalarSizeInBits() <= 32;
13766 return true;
13767 }
13768 return VT.isScalarInteger();
13769}
13770
13771bool ARMTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
13772 EVT VT) const {
13773 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
13774 return false;
13775
13776 switch (FPVT.getSimpleVT().SimpleTy) {
13777 case MVT::f16:
13778 return Subtarget->hasVFP2Base();
13779 case MVT::f32:
13780 return Subtarget->hasVFP2Base();
13781 case MVT::f64:
13782 return Subtarget->hasFP64();
13783 case MVT::v4f32:
13784 case MVT::v8f16:
13785 return Subtarget->hasMVEFloatOps();
13786 default:
13787 return false;
13788 }
13789}
13790
13791static SDValue PerformSHLSimplify(SDNode *N,
13792 TargetLowering::DAGCombinerInfo &DCI,
13793 const ARMSubtarget *ST) {
13794 // Allow the generic combiner to identify potential bswaps.
13795 if (DCI.isBeforeLegalize())
13796 return SDValue();
13797
13798 // DAG combiner will fold:
13799 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
13800 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
13801 // Other code patterns that can be also be modified have the following form:
13802 // b + ((a << 1) | 510)
13803 // b + ((a << 1) & 510)
13804 // b + ((a << 1) ^ 510)
13805 // b + ((a << 1) + 510)
13806
13807 // Many instructions can perform the shift for free, but it requires both
13808 // the operands to be registers. If c1 << c2 is too large, a mov immediate
13809 // instruction will needed. So, unfold back to the original pattern if:
13810 // - if c1 and c2 are small enough that they don't require mov imms.
13811 // - the user(s) of the node can perform an shl
13812
13813 // No shifted operands for 16-bit instructions.
13814 if (ST->isThumb() && ST->isThumb1Only())
13815 return SDValue();
13816
13817 // Check that all the users could perform the shl themselves.
13818 for (auto *U : N->users()) {
13819 switch(U->getOpcode()) {
13820 default:
13821 return SDValue();
13822 case ISD::SUB:
13823 case ISD::ADD:
13824 case ISD::AND:
13825 case ISD::OR:
13826 case ISD::XOR:
13827 case ISD::SETCC:
13828 case ARMISD::CMP:
13829 // Check that the user isn't already using a constant because there
13830 // aren't any instructions that support an immediate operand and a
13831 // shifted operand.
13832 if (isa<ConstantSDNode>(Val: U->getOperand(Num: 0)) ||
13833 isa<ConstantSDNode>(Val: U->getOperand(Num: 1)))
13834 return SDValue();
13835
13836 // Check that it's not already using a shift.
13837 if (U->getOperand(Num: 0).getOpcode() == ISD::SHL ||
13838 U->getOperand(Num: 1).getOpcode() == ISD::SHL)
13839 return SDValue();
13840 break;
13841 }
13842 }
13843
13844 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
13845 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
13846 return SDValue();
13847
13848 if (N->getOperand(Num: 0).getOpcode() != ISD::SHL)
13849 return SDValue();
13850
13851 SDValue SHL = N->getOperand(Num: 0);
13852
13853 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
13854 auto *C2 = dyn_cast<ConstantSDNode>(Val: SHL.getOperand(i: 1));
13855 if (!C1ShlC2 || !C2)
13856 return SDValue();
13857
13858 APInt C2Int = C2->getAPIntValue();
13859 APInt C1Int = C1ShlC2->getAPIntValue();
13860 unsigned C2Width = C2Int.getBitWidth();
13861 if (C2Int.uge(RHS: C2Width))
13862 return SDValue();
13863 uint64_t C2Value = C2Int.getZExtValue();
13864
13865 // Check that performing a lshr will not lose any information.
13866 APInt Mask = APInt::getHighBitsSet(numBits: C2Width, hiBitsSet: C2Width - C2Value);
13867 if ((C1Int & Mask) != C1Int)
13868 return SDValue();
13869
13870 // Shift the first constant.
13871 C1Int.lshrInPlace(ShiftAmt: C2Int);
13872
13873 // The immediates are encoded as an 8-bit value that can be rotated.
13874 auto LargeImm = [](const APInt &Imm) {
13875 unsigned Zeros = Imm.countl_zero() + Imm.countr_zero();
13876 return Imm.getBitWidth() - Zeros > 8;
13877 };
13878
13879 if (LargeImm(C1Int) || LargeImm(C2Int))
13880 return SDValue();
13881
13882 SelectionDAG &DAG = DCI.DAG;
13883 SDLoc dl(N);
13884 SDValue X = SHL.getOperand(i: 0);
13885 SDValue BinOp = DAG.getNode(Opcode: N->getOpcode(), DL: dl, VT: MVT::i32, N1: X,
13886 N2: DAG.getConstant(Val: C1Int, DL: dl, VT: MVT::i32));
13887 // Shift left to compensate for the lshr of C1Int.
13888 SDValue Res = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT: MVT::i32, N1: BinOp, N2: SHL.getOperand(i: 1));
13889
13890 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
13891 SHL.dump(); N->dump());
13892 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
13893 return Res;
13894}
13895
13896
13897/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
13898///
13899static SDValue PerformADDCombine(SDNode *N,
13900 TargetLowering::DAGCombinerInfo &DCI,
13901 const ARMSubtarget *Subtarget) {
13902 SDValue N0 = N->getOperand(Num: 0);
13903 SDValue N1 = N->getOperand(Num: 1);
13904
13905 // Only works one way, because it needs an immediate operand.
13906 if (SDValue Result = PerformSHLSimplify(N, DCI, ST: Subtarget))
13907 return Result;
13908
13909 if (SDValue Result = PerformADDVecReduce(N, DAG&: DCI.DAG, Subtarget))
13910 return Result;
13911
13912 // First try with the default operand order.
13913 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
13914 return Result;
13915
13916 // If that didn't work, try again with the operands commuted.
13917 return PerformADDCombineWithOperands(N, N0: N1, N1: N0, DCI, Subtarget);
13918}
13919
13920// Combine (sub 0, (csinc X, Y, CC)) -> (csinv -X, Y, CC)
13921// providing -X is as cheap as X (currently, just a constant).
13922static SDValue PerformSubCSINCCombine(SDNode *N, SelectionDAG &DAG) {
13923 if (N->getValueType(ResNo: 0) != MVT::i32 || !isNullConstant(V: N->getOperand(Num: 0)))
13924 return SDValue();
13925 SDValue CSINC = N->getOperand(Num: 1);
13926 if (CSINC.getOpcode() != ARMISD::CSINC || !CSINC.hasOneUse())
13927 return SDValue();
13928
13929 ConstantSDNode *X = dyn_cast<ConstantSDNode>(Val: CSINC.getOperand(i: 0));
13930 if (!X)
13931 return SDValue();
13932
13933 return DAG.getNode(Opcode: ARMISD::CSINV, DL: SDLoc(N), VT: MVT::i32,
13934 N1: DAG.getNode(Opcode: ISD::SUB, DL: SDLoc(N), VT: MVT::i32, N1: N->getOperand(Num: 0),
13935 N2: CSINC.getOperand(i: 0)),
13936 N2: CSINC.getOperand(i: 1), N3: CSINC.getOperand(i: 2),
13937 N4: CSINC.getOperand(i: 3));
13938}
13939
13940static bool isNegatedInteger(SDValue Op) {
13941 return Op.getOpcode() == ISD::SUB && isNullConstant(V: Op.getOperand(i: 0));
13942}
13943
13944// Try to fold
13945//
13946// (neg (cmov X, Y)) -> (cmov (neg X), (neg Y))
13947//
13948// The folding helps cmov to be matched with csneg without generating
13949// redundant neg instruction.
13950static SDValue performNegCMovCombine(SDNode *N, SelectionDAG &DAG) {
13951 if (!isNegatedInteger(Op: SDValue(N, 0)))
13952 return SDValue();
13953
13954 SDValue CMov = N->getOperand(Num: 1);
13955 if (CMov.getOpcode() != ARMISD::CMOV || !CMov->hasOneUse())
13956 return SDValue();
13957
13958 SDValue N0 = CMov.getOperand(i: 0);
13959 SDValue N1 = CMov.getOperand(i: 1);
13960
13961 // If neither of them are negations, it's not worth the folding as it
13962 // introduces two additional negations while reducing one negation.
13963 if (!isNegatedInteger(Op: N0) && !isNegatedInteger(Op: N1))
13964 return SDValue();
13965
13966 SDLoc DL(N);
13967 EVT VT = CMov.getValueType();
13968
13969 SDValue N0N = DAG.getNegative(Val: N0, DL, VT);
13970 SDValue N1N = DAG.getNegative(Val: N1, DL, VT);
13971 return DAG.getNode(Opcode: ARMISD::CMOV, DL, VT, N1: N0N, N2: N1N, N3: CMov.getOperand(i: 2),
13972 N4: CMov.getOperand(i: 3));
13973}
13974
13975/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
13976///
13977static SDValue PerformSUBCombine(SDNode *N,
13978 TargetLowering::DAGCombinerInfo &DCI,
13979 const ARMSubtarget *Subtarget) {
13980 SDValue N0 = N->getOperand(Num: 0);
13981 SDValue N1 = N->getOperand(Num: 1);
13982
13983 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
13984 if (N1.getNode()->hasOneUse())
13985 if (SDValue Result = combineSelectAndUse(N, Slct: N1, OtherOp: N0, DCI))
13986 return Result;
13987
13988 if (SDValue R = PerformSubCSINCCombine(N, DAG&: DCI.DAG))
13989 return R;
13990
13991 if (SDValue Val = performNegCMovCombine(N, DAG&: DCI.DAG))
13992 return Val;
13993
13994 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(ResNo: 0).isVector())
13995 return SDValue();
13996
13997 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
13998 // so that we can readily pattern match more mve instructions which can use
13999 // a scalar operand.
14000 SDValue VDup = N->getOperand(Num: 1);
14001 if (VDup->getOpcode() != ARMISD::VDUP)
14002 return SDValue();
14003
14004 SDValue VMov = N->getOperand(Num: 0);
14005 if (VMov->getOpcode() == ISD::BITCAST)
14006 VMov = VMov->getOperand(Num: 0);
14007
14008 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(N: VMov))
14009 return SDValue();
14010
14011 SDLoc dl(N);
14012 SDValue Negate = DCI.DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
14013 N1: DCI.DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32),
14014 N2: VDup->getOperand(Num: 0));
14015 return DCI.DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT: N->getValueType(ResNo: 0), Operand: Negate);
14016}
14017
14018/// PerformVMULCombine
14019/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
14020/// special multiplier accumulator forwarding.
14021/// vmul d3, d0, d2
14022/// vmla d3, d1, d2
14023/// is faster than
14024/// vadd d3, d0, d1
14025/// vmul d3, d3, d2
14026// However, for (A + B) * (A + B),
14027// vadd d2, d0, d1
14028// vmul d3, d0, d2
14029// vmla d3, d1, d2
14030// is slower than
14031// vadd d2, d0, d1
14032// vmul d3, d2, d2
14033static SDValue PerformVMULCombine(SDNode *N,
14034 TargetLowering::DAGCombinerInfo &DCI,
14035 const ARMSubtarget *Subtarget) {
14036 if (!Subtarget->hasVMLxForwarding())
14037 return SDValue();
14038
14039 SelectionDAG &DAG = DCI.DAG;
14040 SDValue N0 = N->getOperand(Num: 0);
14041 SDValue N1 = N->getOperand(Num: 1);
14042 unsigned Opcode = N0.getOpcode();
14043 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14044 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
14045 Opcode = N1.getOpcode();
14046 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14047 Opcode != ISD::FADD && Opcode != ISD::FSUB)
14048 return SDValue();
14049 std::swap(a&: N0, b&: N1);
14050 }
14051
14052 if (N0 == N1)
14053 return SDValue();
14054
14055 EVT VT = N->getValueType(ResNo: 0);
14056 SDLoc DL(N);
14057 SDValue N00 = N0->getOperand(Num: 0);
14058 SDValue N01 = N0->getOperand(Num: 1);
14059 return DAG.getNode(Opcode, DL, VT,
14060 N1: DAG.getNode(Opcode: ISD::MUL, DL, VT, N1: N00, N2: N1),
14061 N2: DAG.getNode(Opcode: ISD::MUL, DL, VT, N1: N01, N2: N1));
14062}
14063
14064static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
14065 const ARMSubtarget *Subtarget) {
14066 EVT VT = N->getValueType(ResNo: 0);
14067 if (VT != MVT::v2i64)
14068 return SDValue();
14069
14070 SDValue N0 = N->getOperand(Num: 0);
14071 SDValue N1 = N->getOperand(Num: 1);
14072
14073 auto IsSignExt = [&](SDValue Op) {
14074 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
14075 return SDValue();
14076 EVT VT = cast<VTSDNode>(Val: Op->getOperand(Num: 1))->getVT();
14077 if (VT.getScalarSizeInBits() == 32)
14078 return Op->getOperand(Num: 0);
14079 return SDValue();
14080 };
14081 auto IsZeroExt = [&](SDValue Op) {
14082 // Zero extends are a little more awkward. At the point we are matching
14083 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
14084 // That might be before of after a bitcast depending on how the and is
14085 // placed. Because this has to look through bitcasts, it is currently only
14086 // supported on LE.
14087 if (!Subtarget->isLittle())
14088 return SDValue();
14089
14090 SDValue And = Op;
14091 if (And->getOpcode() == ISD::BITCAST)
14092 And = And->getOperand(Num: 0);
14093 if (And->getOpcode() != ISD::AND)
14094 return SDValue();
14095 SDValue Mask = And->getOperand(Num: 1);
14096 if (Mask->getOpcode() == ISD::BITCAST)
14097 Mask = Mask->getOperand(Num: 0);
14098
14099 if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
14100 Mask.getValueType() != MVT::v4i32)
14101 return SDValue();
14102 if (isAllOnesConstant(V: Mask->getOperand(Num: 0)) &&
14103 isNullConstant(V: Mask->getOperand(Num: 1)) &&
14104 isAllOnesConstant(V: Mask->getOperand(Num: 2)) &&
14105 isNullConstant(V: Mask->getOperand(Num: 3)))
14106 return And->getOperand(Num: 0);
14107 return SDValue();
14108 };
14109
14110 SDLoc dl(N);
14111 if (SDValue Op0 = IsSignExt(N0)) {
14112 if (SDValue Op1 = IsSignExt(N1)) {
14113 SDValue New0a = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: Op0);
14114 SDValue New1a = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: Op1);
14115 return DAG.getNode(Opcode: ARMISD::VMULLs, DL: dl, VT, N1: New0a, N2: New1a);
14116 }
14117 }
14118 if (SDValue Op0 = IsZeroExt(N0)) {
14119 if (SDValue Op1 = IsZeroExt(N1)) {
14120 SDValue New0a = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: Op0);
14121 SDValue New1a = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v4i32, Operand: Op1);
14122 return DAG.getNode(Opcode: ARMISD::VMULLu, DL: dl, VT, N1: New0a, N2: New1a);
14123 }
14124 }
14125
14126 return SDValue();
14127}
14128
14129static SDValue PerformMULCombine(SDNode *N,
14130 TargetLowering::DAGCombinerInfo &DCI,
14131 const ARMSubtarget *Subtarget) {
14132 SelectionDAG &DAG = DCI.DAG;
14133
14134 EVT VT = N->getValueType(ResNo: 0);
14135 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
14136 return PerformMVEVMULLCombine(N, DAG, Subtarget);
14137
14138 if (Subtarget->isThumb1Only())
14139 return SDValue();
14140
14141 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14142 return SDValue();
14143
14144 if (VT.is64BitVector() || VT.is128BitVector())
14145 return PerformVMULCombine(N, DCI, Subtarget);
14146 if (VT != MVT::i32)
14147 return SDValue();
14148
14149 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
14150 if (!C)
14151 return SDValue();
14152
14153 int64_t MulAmt = C->getSExtValue();
14154 unsigned ShiftAmt = llvm::countr_zero<uint64_t>(Val: MulAmt);
14155
14156 ShiftAmt = ShiftAmt & (32 - 1);
14157 SDValue V = N->getOperand(Num: 0);
14158 SDLoc DL(N);
14159
14160 SDValue Res;
14161 MulAmt >>= ShiftAmt;
14162
14163 if (MulAmt >= 0) {
14164 if (llvm::has_single_bit<uint32_t>(Value: MulAmt - 1)) {
14165 // (mul x, 2^N + 1) => (add (shl x, N), x)
14166 Res = DAG.getNode(Opcode: ISD::ADD, DL, VT,
14167 N1: V,
14168 N2: DAG.getNode(Opcode: ISD::SHL, DL, VT,
14169 N1: V,
14170 N2: DAG.getConstant(Val: Log2_32(Value: MulAmt - 1), DL,
14171 VT: MVT::i32)));
14172 } else if (llvm::has_single_bit<uint32_t>(Value: MulAmt + 1)) {
14173 // (mul x, 2^N - 1) => (sub (shl x, N), x)
14174 Res = DAG.getNode(Opcode: ISD::SUB, DL, VT,
14175 N1: DAG.getNode(Opcode: ISD::SHL, DL, VT,
14176 N1: V,
14177 N2: DAG.getConstant(Val: Log2_32(Value: MulAmt + 1), DL,
14178 VT: MVT::i32)),
14179 N2: V);
14180 } else
14181 return SDValue();
14182 } else {
14183 uint64_t MulAmtAbs = -MulAmt;
14184 if (llvm::has_single_bit<uint32_t>(Value: MulAmtAbs + 1)) {
14185 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
14186 Res = DAG.getNode(Opcode: ISD::SUB, DL, VT,
14187 N1: V,
14188 N2: DAG.getNode(Opcode: ISD::SHL, DL, VT,
14189 N1: V,
14190 N2: DAG.getConstant(Val: Log2_32(Value: MulAmtAbs + 1), DL,
14191 VT: MVT::i32)));
14192 } else if (llvm::has_single_bit<uint32_t>(Value: MulAmtAbs - 1)) {
14193 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
14194 Res = DAG.getNode(Opcode: ISD::ADD, DL, VT,
14195 N1: V,
14196 N2: DAG.getNode(Opcode: ISD::SHL, DL, VT,
14197 N1: V,
14198 N2: DAG.getConstant(Val: Log2_32(Value: MulAmtAbs - 1), DL,
14199 VT: MVT::i32)));
14200 Res = DAG.getNode(Opcode: ISD::SUB, DL, VT,
14201 N1: DAG.getConstant(Val: 0, DL, VT: MVT::i32), N2: Res);
14202 } else
14203 return SDValue();
14204 }
14205
14206 if (ShiftAmt != 0)
14207 Res = DAG.getNode(Opcode: ISD::SHL, DL, VT,
14208 N1: Res, N2: DAG.getConstant(Val: ShiftAmt, DL, VT: MVT::i32));
14209
14210 // Do not add new nodes to DAG combiner worklist.
14211 DCI.CombineTo(N, Res, AddTo: false);
14212 return SDValue();
14213}
14214
14215static SDValue CombineANDShift(SDNode *N,
14216 TargetLowering::DAGCombinerInfo &DCI,
14217 const ARMSubtarget *Subtarget) {
14218 // Allow DAGCombine to pattern-match before we touch the canonical form.
14219 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14220 return SDValue();
14221
14222 if (N->getValueType(ResNo: 0) != MVT::i32)
14223 return SDValue();
14224
14225 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
14226 if (!N1C)
14227 return SDValue();
14228
14229 uint32_t C1 = (uint32_t)N1C->getZExtValue();
14230 // Don't transform uxtb/uxth.
14231 if (C1 == 255 || C1 == 65535)
14232 return SDValue();
14233
14234 SDNode *N0 = N->getOperand(Num: 0).getNode();
14235 if (!N0->hasOneUse())
14236 return SDValue();
14237
14238 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
14239 return SDValue();
14240
14241 bool LeftShift = N0->getOpcode() == ISD::SHL;
14242
14243 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(Val: N0->getOperand(Num: 1));
14244 if (!N01C)
14245 return SDValue();
14246
14247 uint32_t C2 = (uint32_t)N01C->getZExtValue();
14248 if (!C2 || C2 >= 32)
14249 return SDValue();
14250
14251 // Clear irrelevant bits in the mask.
14252 if (LeftShift)
14253 C1 &= (-1U << C2);
14254 else
14255 C1 &= (-1U >> C2);
14256
14257 SelectionDAG &DAG = DCI.DAG;
14258 SDLoc DL(N);
14259
14260 // We have a pattern of the form "(and (shl x, c2) c1)" or
14261 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
14262 // transform to a pair of shifts, to save materializing c1.
14263
14264 // First pattern: right shift, then mask off leading bits.
14265 // FIXME: Use demanded bits?
14266 if (!LeftShift && isMask_32(Value: C1)) {
14267 uint32_t C3 = llvm::countl_zero(Val: C1);
14268 if (C2 < C3) {
14269 SDValue SHL = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
14270 N2: DAG.getConstant(Val: C3 - C2, DL, VT: MVT::i32));
14271 return DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: SHL,
14272 N2: DAG.getConstant(Val: C3, DL, VT: MVT::i32));
14273 }
14274 }
14275
14276 // First pattern, reversed: left shift, then mask off trailing bits.
14277 if (LeftShift && isMask_32(Value: ~C1)) {
14278 uint32_t C3 = llvm::countr_zero(Val: C1);
14279 if (C2 < C3) {
14280 SDValue SHL = DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
14281 N2: DAG.getConstant(Val: C3 - C2, DL, VT: MVT::i32));
14282 return DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: SHL,
14283 N2: DAG.getConstant(Val: C3, DL, VT: MVT::i32));
14284 }
14285 }
14286
14287 // Second pattern: left shift, then mask off leading bits.
14288 // FIXME: Use demanded bits?
14289 if (LeftShift && isShiftedMask_32(Value: C1)) {
14290 uint32_t Trailing = llvm::countr_zero(Val: C1);
14291 uint32_t C3 = llvm::countl_zero(Val: C1);
14292 if (Trailing == C2 && C2 + C3 < 32) {
14293 SDValue SHL = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
14294 N2: DAG.getConstant(Val: C2 + C3, DL, VT: MVT::i32));
14295 return DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: SHL,
14296 N2: DAG.getConstant(Val: C3, DL, VT: MVT::i32));
14297 }
14298 }
14299
14300 // Second pattern, reversed: right shift, then mask off trailing bits.
14301 // FIXME: Handle other patterns of known/demanded bits.
14302 if (!LeftShift && isShiftedMask_32(Value: C1)) {
14303 uint32_t Leading = llvm::countl_zero(Val: C1);
14304 uint32_t C3 = llvm::countr_zero(Val: C1);
14305 if (Leading == C2 && C2 + C3 < 32) {
14306 SDValue SHL = DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
14307 N2: DAG.getConstant(Val: C2 + C3, DL, VT: MVT::i32));
14308 return DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: SHL,
14309 N2: DAG.getConstant(Val: C3, DL, VT: MVT::i32));
14310 }
14311 }
14312
14313 // Transform "(and (shl x, c2) c1)" into "(shl (and x, c1>>c2), c2)"
14314 // if "c1 >> c2" is a cheaper immediate than "c1"
14315 if (LeftShift &&
14316 HasLowerConstantMaterializationCost(Val1: C1 >> C2, Val2: C1, Subtarget)) {
14317
14318 SDValue And = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
14319 N2: DAG.getConstant(Val: C1 >> C2, DL, VT: MVT::i32));
14320 return DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: And,
14321 N2: DAG.getConstant(Val: C2, DL, VT: MVT::i32));
14322 }
14323
14324 return SDValue();
14325}
14326
14327static SDValue PerformANDCombine(SDNode *N,
14328 TargetLowering::DAGCombinerInfo &DCI,
14329 const ARMSubtarget *Subtarget) {
14330 // Attempt to use immediate-form VBIC
14331 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Val: N->getOperand(Num: 1));
14332 SDLoc dl(N);
14333 EVT VT = N->getValueType(ResNo: 0);
14334 SelectionDAG &DAG = DCI.DAG;
14335
14336 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v2i1 ||
14337 VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)
14338 return SDValue();
14339
14340 APInt SplatBits, SplatUndef;
14341 unsigned SplatBitSize;
14342 bool HasAnyUndefs;
14343 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14344 BVN->isConstantSplat(SplatValue&: SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14345 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14346 SplatBitSize == 64) {
14347 EVT VbicVT;
14348 SDValue Val = isVMOVModifiedImm(SplatBits: (~SplatBits).getZExtValue(),
14349 SplatUndef: SplatUndef.getZExtValue(), SplatBitSize,
14350 DAG, dl, VT&: VbicVT, VectorVT: VT, type: OtherModImm);
14351 if (Val.getNode()) {
14352 SDValue Input =
14353 DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: VbicVT, Operand: N->getOperand(Num: 0));
14354 SDValue Vbic = DAG.getNode(Opcode: ARMISD::VBICIMM, DL: dl, VT: VbicVT, N1: Input, N2: Val);
14355 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Vbic);
14356 }
14357 }
14358 }
14359
14360 if (!Subtarget->isThumb1Only()) {
14361 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
14362 if (SDValue Result = combineSelectAndUseCommutative(N, AllOnes: true, DCI))
14363 return Result;
14364
14365 if (SDValue Result = PerformSHLSimplify(N, DCI, ST: Subtarget))
14366 return Result;
14367 }
14368
14369 if (Subtarget->isThumb1Only())
14370 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
14371 return Result;
14372
14373 return SDValue();
14374}
14375
14376// Try combining OR nodes to SMULWB, SMULWT.
14377static SDValue PerformORCombineToSMULWBT(SDNode *OR,
14378 TargetLowering::DAGCombinerInfo &DCI,
14379 const ARMSubtarget *Subtarget) {
14380 if (!Subtarget->hasV6Ops() ||
14381 (Subtarget->isThumb() &&
14382 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
14383 return SDValue();
14384
14385 SDValue SRL = OR->getOperand(Num: 0);
14386 SDValue SHL = OR->getOperand(Num: 1);
14387
14388 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
14389 SRL = OR->getOperand(Num: 1);
14390 SHL = OR->getOperand(Num: 0);
14391 }
14392 if (!isSRL16(Op: SRL) || !isSHL16(Op: SHL))
14393 return SDValue();
14394
14395 // The first operands to the shifts need to be the two results from the
14396 // same smul_lohi node.
14397 if ((SRL.getOperand(i: 0).getNode() != SHL.getOperand(i: 0).getNode()) ||
14398 SRL.getOperand(i: 0).getOpcode() != ISD::SMUL_LOHI)
14399 return SDValue();
14400
14401 SDNode *SMULLOHI = SRL.getOperand(i: 0).getNode();
14402 if (SRL.getOperand(i: 0) != SDValue(SMULLOHI, 0) ||
14403 SHL.getOperand(i: 0) != SDValue(SMULLOHI, 1))
14404 return SDValue();
14405
14406 // Now we have:
14407 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
14408 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
14409 // For SMUWB the 16-bit value will signed extended somehow.
14410 // For SMULWT only the SRA is required.
14411 // Check both sides of SMUL_LOHI
14412 SDValue OpS16 = SMULLOHI->getOperand(Num: 0);
14413 SDValue OpS32 = SMULLOHI->getOperand(Num: 1);
14414
14415 SelectionDAG &DAG = DCI.DAG;
14416 if (!isS16(Op: OpS16, DAG) && !isSRA16(Op: OpS16)) {
14417 OpS16 = OpS32;
14418 OpS32 = SMULLOHI->getOperand(Num: 0);
14419 }
14420
14421 SDLoc dl(OR);
14422 unsigned Opcode = 0;
14423 if (isS16(Op: OpS16, DAG))
14424 Opcode = ARMISD::SMULWB;
14425 else if (isSRA16(Op: OpS16)) {
14426 Opcode = ARMISD::SMULWT;
14427 OpS16 = OpS16->getOperand(Num: 0);
14428 }
14429 else
14430 return SDValue();
14431
14432 SDValue Res = DAG.getNode(Opcode, DL: dl, VT: MVT::i32, N1: OpS32, N2: OpS16);
14433 DAG.ReplaceAllUsesOfValueWith(From: SDValue(OR, 0), To: Res);
14434 return SDValue(OR, 0);
14435}
14436
14437static SDValue PerformORCombineToBFI(SDNode *N,
14438 TargetLowering::DAGCombinerInfo &DCI,
14439 const ARMSubtarget *Subtarget) {
14440 // BFI is only available on V6T2+
14441 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
14442 return SDValue();
14443
14444 EVT VT = N->getValueType(ResNo: 0);
14445 SDValue N0 = N->getOperand(Num: 0);
14446 SDValue N1 = N->getOperand(Num: 1);
14447 SelectionDAG &DAG = DCI.DAG;
14448 SDLoc DL(N);
14449 // 1) or (and A, mask), val => ARMbfi A, val, mask
14450 // iff (val & mask) == val
14451 //
14452 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14453 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
14454 // && mask == ~mask2
14455 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
14456 // && ~mask == mask2
14457 // (i.e., copy a bitfield value into another bitfield of the same width)
14458
14459 if (VT != MVT::i32)
14460 return SDValue();
14461
14462 SDValue N00 = N0.getOperand(i: 0);
14463
14464 // The value and the mask need to be constants so we can verify this is
14465 // actually a bitfield set. If the mask is 0xffff, we can do better
14466 // via a movt instruction, so don't use BFI in that case.
14467 SDValue MaskOp = N0.getOperand(i: 1);
14468 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Val&: MaskOp);
14469 if (!MaskC)
14470 return SDValue();
14471 unsigned Mask = MaskC->getZExtValue();
14472 if (Mask == 0xffff)
14473 return SDValue();
14474 SDValue Res;
14475 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
14476 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Val&: N1);
14477 if (N1C) {
14478 unsigned Val = N1C->getZExtValue();
14479 if ((Val & ~Mask) != Val)
14480 return SDValue();
14481
14482 if (ARM::isBitFieldInvertedMask(v: Mask)) {
14483 Val >>= llvm::countr_zero(Val: ~Mask);
14484
14485 Res = DAG.getNode(Opcode: ARMISD::BFI, DL, VT, N1: N00,
14486 N2: DAG.getConstant(Val, DL, VT: MVT::i32),
14487 N3: DAG.getConstant(Val: Mask, DL, VT: MVT::i32));
14488
14489 DCI.CombineTo(N, Res, AddTo: false);
14490 // Return value from the original node to inform the combiner than N is
14491 // now dead.
14492 return SDValue(N, 0);
14493 }
14494 } else if (N1.getOpcode() == ISD::AND) {
14495 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14496 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(Val: N1.getOperand(i: 1));
14497 if (!N11C)
14498 return SDValue();
14499 unsigned Mask2 = N11C->getZExtValue();
14500
14501 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
14502 // as is to match.
14503 if (ARM::isBitFieldInvertedMask(v: Mask) &&
14504 (Mask == ~Mask2)) {
14505 // The pack halfword instruction works better for masks that fit it,
14506 // so use that when it's available.
14507 if (Subtarget->hasDSP() &&
14508 (Mask == 0xffff || Mask == 0xffff0000))
14509 return SDValue();
14510 // 2a
14511 unsigned amt = llvm::countr_zero(Val: Mask2);
14512 Res = DAG.getNode(Opcode: ISD::SRL, DL, VT, N1: N1.getOperand(i: 0),
14513 N2: DAG.getConstant(Val: amt, DL, VT: MVT::i32));
14514 Res = DAG.getNode(Opcode: ARMISD::BFI, DL, VT, N1: N00, N2: Res,
14515 N3: DAG.getConstant(Val: Mask, DL, VT: MVT::i32));
14516 DCI.CombineTo(N, Res, AddTo: false);
14517 // Return value from the original node to inform the combiner than N is
14518 // now dead.
14519 return SDValue(N, 0);
14520 } else if (ARM::isBitFieldInvertedMask(v: ~Mask) &&
14521 (~Mask == Mask2)) {
14522 // The pack halfword instruction works better for masks that fit it,
14523 // so use that when it's available.
14524 if (Subtarget->hasDSP() &&
14525 (Mask2 == 0xffff || Mask2 == 0xffff0000))
14526 return SDValue();
14527 // 2b
14528 unsigned lsb = llvm::countr_zero(Val: Mask);
14529 Res = DAG.getNode(Opcode: ISD::SRL, DL, VT, N1: N00,
14530 N2: DAG.getConstant(Val: lsb, DL, VT: MVT::i32));
14531 Res = DAG.getNode(Opcode: ARMISD::BFI, DL, VT, N1: N1.getOperand(i: 0), N2: Res,
14532 N3: DAG.getConstant(Val: Mask2, DL, VT: MVT::i32));
14533 DCI.CombineTo(N, Res, AddTo: false);
14534 // Return value from the original node to inform the combiner than N is
14535 // now dead.
14536 return SDValue(N, 0);
14537 }
14538 }
14539
14540 if (DAG.MaskedValueIsZero(Op: N1, Mask: MaskC->getAPIntValue()) &&
14541 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(Val: N00.getOperand(i: 1)) &&
14542 ARM::isBitFieldInvertedMask(v: ~Mask)) {
14543 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
14544 // where lsb(mask) == #shamt and masked bits of B are known zero.
14545 SDValue ShAmt = N00.getOperand(i: 1);
14546 unsigned ShAmtC = ShAmt->getAsZExtVal();
14547 unsigned LSB = llvm::countr_zero(Val: Mask);
14548 if (ShAmtC != LSB)
14549 return SDValue();
14550
14551 Res = DAG.getNode(Opcode: ARMISD::BFI, DL, VT, N1, N2: N00.getOperand(i: 0),
14552 N3: DAG.getConstant(Val: ~Mask, DL, VT: MVT::i32));
14553
14554 DCI.CombineTo(N, Res, AddTo: false);
14555 // Return value from the original node to inform the combiner than N is
14556 // now dead.
14557 return SDValue(N, 0);
14558 }
14559
14560 return SDValue();
14561}
14562
14563static bool isValidMVECond(unsigned CC, bool IsFloat) {
14564 switch (CC) {
14565 case ARMCC::EQ:
14566 case ARMCC::NE:
14567 case ARMCC::LE:
14568 case ARMCC::GT:
14569 case ARMCC::GE:
14570 case ARMCC::LT:
14571 return true;
14572 case ARMCC::HS:
14573 case ARMCC::HI:
14574 return !IsFloat;
14575 default:
14576 return false;
14577 };
14578}
14579
14580static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
14581 if (N->getOpcode() == ARMISD::VCMP)
14582 return (ARMCC::CondCodes)N->getConstantOperandVal(Num: 2);
14583 else if (N->getOpcode() == ARMISD::VCMPZ)
14584 return (ARMCC::CondCodes)N->getConstantOperandVal(Num: 1);
14585 else
14586 llvm_unreachable("Not a VCMP/VCMPZ!");
14587}
14588
14589static bool CanInvertMVEVCMP(SDValue N) {
14590 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(CC: getVCMPCondCode(N));
14591 return isValidMVECond(CC, IsFloat: N->getOperand(Num: 0).getValueType().isFloatingPoint());
14592}
14593
14594static SDValue PerformORCombine_i1(SDNode *N, SelectionDAG &DAG,
14595 const ARMSubtarget *Subtarget) {
14596 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
14597 // together with predicates
14598 EVT VT = N->getValueType(ResNo: 0);
14599 SDLoc DL(N);
14600 SDValue N0 = N->getOperand(Num: 0);
14601 SDValue N1 = N->getOperand(Num: 1);
14602
14603 auto IsFreelyInvertable = [&](SDValue V) {
14604 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
14605 return CanInvertMVEVCMP(N: V);
14606 return false;
14607 };
14608
14609 // At least one operand must be freely invertable.
14610 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
14611 return SDValue();
14612
14613 SDValue NewN0 = DAG.getLogicalNOT(DL, Val: N0, VT);
14614 SDValue NewN1 = DAG.getLogicalNOT(DL, Val: N1, VT);
14615 SDValue And = DAG.getNode(Opcode: ISD::AND, DL, VT, N1: NewN0, N2: NewN1);
14616 return DAG.getLogicalNOT(DL, Val: And, VT);
14617}
14618
14619// Try to form a NEON shift-{right, left}-and-insert (VSRI/VSLI) from:
14620// (or (and X, splat (i32 C1)), (srl Y, splat (i32 C2))) -> VSRI X, Y, #C2
14621// (or (and X, splat (i32 C1)), (shl Y, splat (i32 C2))) -> VSLI X, Y, #C2
14622// where C1 is a mask that preserves the bits not written by the shift/insert,
14623// i.e. `C1 == (1 << C2) - 1`.
14624static SDValue PerformORCombineToShiftInsert(SelectionDAG &DAG, SDValue AndOp,
14625 SDValue ShiftOp, EVT VT,
14626 SDLoc dl) {
14627 // Match (and X, Mask)
14628 if (AndOp.getOpcode() != ISD::AND)
14629 return SDValue();
14630
14631 SDValue X = AndOp.getOperand(i: 0);
14632 SDValue Mask = AndOp.getOperand(i: 1);
14633
14634 ConstantSDNode *MaskC = isConstOrConstSplat(N: Mask, AllowUndefs: false, AllowTruncation: true);
14635 if (!MaskC)
14636 return SDValue();
14637 APInt MaskBits =
14638 MaskC->getAPIntValue().trunc(width: Mask.getScalarValueSizeInBits());
14639
14640 // Match shift (srl/shl Y, CntVec)
14641 int64_t Cnt = 0;
14642 bool IsShiftRight = false;
14643 SDValue Y;
14644
14645 if (ShiftOp.getOpcode() == ARMISD::VSHRuIMM) {
14646 IsShiftRight = true;
14647 Y = ShiftOp.getOperand(i: 0);
14648 Cnt = ShiftOp.getConstantOperandVal(i: 1);
14649 } else if (ShiftOp.getOpcode() == ARMISD::VSHLIMM) {
14650 Y = ShiftOp.getOperand(i: 0);
14651 Cnt = ShiftOp.getConstantOperandVal(i: 1);
14652 } else {
14653 return SDValue();
14654 }
14655
14656 unsigned ElemBits = VT.getScalarSizeInBits();
14657 APInt RequiredMask = IsShiftRight
14658 ? APInt::getHighBitsSet(numBits: ElemBits, hiBitsSet: (unsigned)Cnt)
14659 : APInt::getLowBitsSet(numBits: ElemBits, loBitsSet: (unsigned)Cnt);
14660 if (MaskBits != RequiredMask)
14661 return SDValue();
14662
14663 unsigned Opc = IsShiftRight ? ARMISD::VSRIIMM : ARMISD::VSLIIMM;
14664 return DAG.getNode(Opcode: Opc, DL: dl, VT, N1: X, N2: Y, N3: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
14665}
14666
14667/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
14668static SDValue PerformORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
14669 const ARMSubtarget *Subtarget) {
14670 // Attempt to use immediate-form VORR
14671 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Val: N->getOperand(Num: 1));
14672 SDLoc dl(N);
14673 EVT VT = N->getValueType(ResNo: 0);
14674 SelectionDAG &DAG = DCI.DAG;
14675
14676 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14677 return SDValue();
14678
14679 if (Subtarget->hasMVEIntegerOps() && (VT == MVT::v2i1 || VT == MVT::v4i1 ||
14680 VT == MVT::v8i1 || VT == MVT::v16i1))
14681 return PerformORCombine_i1(N, DAG, Subtarget);
14682
14683 APInt SplatBits, SplatUndef;
14684 unsigned SplatBitSize;
14685 bool HasAnyUndefs;
14686 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14687 BVN->isConstantSplat(SplatValue&: SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14688 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14689 SplatBitSize == 64) {
14690 EVT VorrVT;
14691 SDValue Val =
14692 isVMOVModifiedImm(SplatBits: SplatBits.getZExtValue(), SplatUndef: SplatUndef.getZExtValue(),
14693 SplatBitSize, DAG, dl, VT&: VorrVT, VectorVT: VT, type: OtherModImm);
14694 if (Val.getNode()) {
14695 SDValue Input =
14696 DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: VorrVT, Operand: N->getOperand(Num: 0));
14697 SDValue Vorr = DAG.getNode(Opcode: ARMISD::VORRIMM, DL: dl, VT: VorrVT, N1: Input, N2: Val);
14698 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Vorr);
14699 }
14700 }
14701 }
14702
14703 if (!Subtarget->isThumb1Only()) {
14704 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
14705 if (SDValue Result = combineSelectAndUseCommutative(N, AllOnes: false, DCI))
14706 return Result;
14707 if (SDValue Result = PerformORCombineToSMULWBT(OR: N, DCI, Subtarget))
14708 return Result;
14709 }
14710
14711 SDValue N0 = N->getOperand(Num: 0);
14712 SDValue N1 = N->getOperand(Num: 1);
14713
14714 // (or (and X, C1), (srl Y, C2)) -> VSRI X, Y, #C2
14715 // (or (and X, C1), (shl Y, C2)) -> VSLI X, Y, #C2
14716 if (VT.isVector() &&
14717 ((Subtarget->hasNEON() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) ||
14718 (Subtarget->hasMVEIntegerOps() &&
14719 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32)))) {
14720 if (SDValue ShiftInsert =
14721 PerformORCombineToShiftInsert(DAG, AndOp: N0, ShiftOp: N1, VT, dl))
14722 return ShiftInsert;
14723
14724 if (SDValue ShiftInsert =
14725 PerformORCombineToShiftInsert(DAG, AndOp: N1, ShiftOp: N0, VT, dl))
14726 return ShiftInsert;
14727 }
14728
14729 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
14730 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
14731 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14732
14733 // The code below optimizes (or (and X, Y), Z).
14734 // The AND operand needs to have a single user to make these optimizations
14735 // profitable.
14736 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
14737 return SDValue();
14738
14739 APInt SplatUndef;
14740 unsigned SplatBitSize;
14741 bool HasAnyUndefs;
14742
14743 APInt SplatBits0, SplatBits1;
14744 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(Val: N0->getOperand(Num: 1));
14745 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(Val: N1->getOperand(Num: 1));
14746 // Ensure that the second operand of both ands are constants
14747 if (BVN0 && BVN0->isConstantSplat(SplatValue&: SplatBits0, SplatUndef, SplatBitSize,
14748 HasAnyUndefs) && !HasAnyUndefs) {
14749 if (BVN1 && BVN1->isConstantSplat(SplatValue&: SplatBits1, SplatUndef, SplatBitSize,
14750 HasAnyUndefs) && !HasAnyUndefs) {
14751 // Ensure that the bit width of the constants are the same and that
14752 // the splat arguments are logical inverses as per the pattern we
14753 // are trying to simplify.
14754 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
14755 SplatBits0 == ~SplatBits1) {
14756 // Canonicalize the vector type to make instruction selection
14757 // simpler.
14758 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
14759 SDValue Result = DAG.getNode(Opcode: ARMISD::VBSP, DL: dl, VT: CanonicalVT,
14760 N1: N0->getOperand(Num: 1),
14761 N2: N0->getOperand(Num: 0),
14762 N3: N1->getOperand(Num: 0));
14763 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Result);
14764 }
14765 }
14766 }
14767 }
14768
14769 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
14770 // reasonable.
14771 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
14772 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
14773 return Res;
14774 }
14775
14776 if (SDValue Result = PerformSHLSimplify(N, DCI, ST: Subtarget))
14777 return Result;
14778
14779 return SDValue();
14780}
14781
14782static SDValue PerformXORCombine(SDNode *N,
14783 TargetLowering::DAGCombinerInfo &DCI,
14784 const ARMSubtarget *Subtarget) {
14785 EVT VT = N->getValueType(ResNo: 0);
14786 SelectionDAG &DAG = DCI.DAG;
14787
14788 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14789 return SDValue();
14790
14791 if (!Subtarget->isThumb1Only()) {
14792 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
14793 if (SDValue Result = combineSelectAndUseCommutative(N, AllOnes: false, DCI))
14794 return Result;
14795
14796 if (SDValue Result = PerformSHLSimplify(N, DCI, ST: Subtarget))
14797 return Result;
14798 }
14799
14800 if (Subtarget->hasMVEIntegerOps()) {
14801 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
14802 SDValue N0 = N->getOperand(Num: 0);
14803 SDValue N1 = N->getOperand(Num: 1);
14804 const TargetLowering *TLI = Subtarget->getTargetLowering();
14805 if (TLI->isConstTrueVal(N: N1) &&
14806 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
14807 if (CanInvertMVEVCMP(N: N0)) {
14808 SDLoc DL(N0);
14809 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(CC: getVCMPCondCode(N: N0));
14810
14811 SmallVector<SDValue, 4> Ops;
14812 Ops.push_back(Elt: N0->getOperand(Num: 0));
14813 if (N0->getOpcode() == ARMISD::VCMP)
14814 Ops.push_back(Elt: N0->getOperand(Num: 1));
14815 Ops.push_back(Elt: DAG.getConstant(Val: CC, DL, VT: MVT::i32));
14816 return DAG.getNode(Opcode: N0->getOpcode(), DL, VT: N0->getValueType(ResNo: 0), Ops);
14817 }
14818 }
14819 }
14820
14821 return SDValue();
14822}
14823
14824// ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
14825// and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
14826// their position in "to" (Rd).
14827static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
14828 assert(N->getOpcode() == ARMISD::BFI);
14829
14830 SDValue From = N->getOperand(Num: 1);
14831 ToMask = ~N->getConstantOperandAPInt(Num: 2);
14832 FromMask = APInt::getLowBitsSet(numBits: ToMask.getBitWidth(), loBitsSet: ToMask.popcount());
14833
14834 // If the Base came from a SHR #C, we can deduce that it is really testing bit
14835 // #C in the base of the SHR.
14836 if (From->getOpcode() == ISD::SRL &&
14837 isa<ConstantSDNode>(Val: From->getOperand(Num: 1))) {
14838 APInt Shift = From->getConstantOperandAPInt(Num: 1);
14839 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
14840 FromMask <<= Shift.getLimitedValue(Limit: 31);
14841 From = From->getOperand(Num: 0);
14842 }
14843
14844 return From;
14845}
14846
14847// If A and B contain one contiguous set of bits, does A | B == A . B?
14848//
14849// Neither A nor B must be zero.
14850static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
14851 unsigned LastActiveBitInA = A.countr_zero();
14852 unsigned FirstActiveBitInB = B.getBitWidth() - B.countl_zero() - 1;
14853 return LastActiveBitInA - 1 == FirstActiveBitInB;
14854}
14855
14856static SDValue FindBFIToCombineWith(SDNode *N) {
14857 // We have a BFI in N. Find a BFI it can combine with, if one exists.
14858 APInt ToMask, FromMask;
14859 SDValue From = ParseBFI(N, ToMask, FromMask);
14860 SDValue To = N->getOperand(Num: 0);
14861
14862 SDValue V = To;
14863 if (V.getOpcode() != ARMISD::BFI)
14864 return SDValue();
14865
14866 APInt NewToMask, NewFromMask;
14867 SDValue NewFrom = ParseBFI(N: V.getNode(), ToMask&: NewToMask, FromMask&: NewFromMask);
14868 if (NewFrom != From)
14869 return SDValue();
14870
14871 // Do the written bits conflict with any we've seen so far?
14872 if ((NewToMask & ToMask).getBoolValue())
14873 // Conflicting bits.
14874 return SDValue();
14875
14876 // Are the new bits contiguous when combined with the old bits?
14877 if (BitsProperlyConcatenate(A: ToMask, B: NewToMask) &&
14878 BitsProperlyConcatenate(A: FromMask, B: NewFromMask))
14879 return V;
14880 if (BitsProperlyConcatenate(A: NewToMask, B: ToMask) &&
14881 BitsProperlyConcatenate(A: NewFromMask, B: FromMask))
14882 return V;
14883
14884 return SDValue();
14885}
14886
14887static SDValue PerformBFICombine(SDNode *N, SelectionDAG &DAG) {
14888 SDValue N0 = N->getOperand(Num: 0);
14889 SDValue N1 = N->getOperand(Num: 1);
14890
14891 if (N1.getOpcode() == ISD::AND) {
14892 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
14893 // the bits being cleared by the AND are not demanded by the BFI.
14894 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(Val: N1.getOperand(i: 1));
14895 if (!N11C)
14896 return SDValue();
14897 unsigned InvMask = N->getConstantOperandVal(Num: 2);
14898 unsigned LSB = llvm::countr_zero(Val: ~InvMask);
14899 unsigned Width = llvm::bit_width<unsigned>(Value: ~InvMask) - LSB;
14900 assert(Width <
14901 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
14902 "undefined behavior");
14903 unsigned Mask = (1u << Width) - 1;
14904 unsigned Mask2 = N11C->getZExtValue();
14905 if ((Mask & (~Mask2)) == 0)
14906 return DAG.getNode(Opcode: ARMISD::BFI, DL: SDLoc(N), VT: N->getValueType(ResNo: 0),
14907 N1: N->getOperand(Num: 0), N2: N1.getOperand(i: 0), N3: N->getOperand(Num: 2));
14908 return SDValue();
14909 }
14910
14911 // Look for another BFI to combine with.
14912 if (SDValue CombineBFI = FindBFIToCombineWith(N)) {
14913 // We've found a BFI.
14914 APInt ToMask1, FromMask1;
14915 SDValue From1 = ParseBFI(N, ToMask&: ToMask1, FromMask&: FromMask1);
14916
14917 APInt ToMask2, FromMask2;
14918 SDValue From2 = ParseBFI(N: CombineBFI.getNode(), ToMask&: ToMask2, FromMask&: FromMask2);
14919 assert(From1 == From2);
14920 (void)From2;
14921
14922 // Create a new BFI, combining the two together.
14923 APInt NewFromMask = FromMask1 | FromMask2;
14924 APInt NewToMask = ToMask1 | ToMask2;
14925
14926 EVT VT = N->getValueType(ResNo: 0);
14927 SDLoc dl(N);
14928
14929 if (NewFromMask[0] == 0)
14930 From1 = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: From1,
14931 N2: DAG.getConstant(Val: NewFromMask.countr_zero(), DL: dl, VT));
14932 return DAG.getNode(Opcode: ARMISD::BFI, DL: dl, VT, N1: CombineBFI.getOperand(i: 0), N2: From1,
14933 N3: DAG.getConstant(Val: ~NewToMask, DL: dl, VT));
14934 }
14935
14936 // Reassociate BFI(BFI (A, B, M1), C, M2) to BFI(BFI (A, C, M2), B, M1) so
14937 // that lower bit insertions are performed first, providing that M1 and M2
14938 // do no overlap. This can allow multiple BFI instructions to be combined
14939 // together by the other folds above.
14940 if (N->getOperand(Num: 0).getOpcode() == ARMISD::BFI) {
14941 APInt ToMask1 = ~N->getConstantOperandAPInt(Num: 2);
14942 APInt ToMask2 = ~N0.getConstantOperandAPInt(i: 2);
14943
14944 if (!N0.hasOneUse() || (ToMask1 & ToMask2) != 0 ||
14945 ToMask1.countl_zero() < ToMask2.countl_zero())
14946 return SDValue();
14947
14948 EVT VT = N->getValueType(ResNo: 0);
14949 SDLoc dl(N);
14950 SDValue BFI1 = DAG.getNode(Opcode: ARMISD::BFI, DL: dl, VT, N1: N0.getOperand(i: 0),
14951 N2: N->getOperand(Num: 1), N3: N->getOperand(Num: 2));
14952 return DAG.getNode(Opcode: ARMISD::BFI, DL: dl, VT, N1: BFI1, N2: N0.getOperand(i: 1),
14953 N3: N0.getOperand(i: 2));
14954 }
14955
14956 return SDValue();
14957}
14958
14959// Check that N is CMPZ(CSINC(0, 0, CC, X)),
14960// or CMPZ(CMOV(1, 0, CC, X))
14961// return X if valid.
14962static SDValue IsCMPZCSINC(SDNode *Cmp, ARMCC::CondCodes &CC) {
14963 if (Cmp->getOpcode() != ARMISD::CMPZ || !isNullConstant(V: Cmp->getOperand(Num: 1)))
14964 return SDValue();
14965 SDValue CSInc = Cmp->getOperand(Num: 0);
14966
14967 // Ignore any `And 1` nodes that may not yet have been removed. We are
14968 // looking for a value that produces 1/0, so these have no effect on the
14969 // code.
14970 while (CSInc.getOpcode() == ISD::AND &&
14971 isa<ConstantSDNode>(Val: CSInc.getOperand(i: 1)) &&
14972 CSInc.getConstantOperandVal(i: 1) == 1 && CSInc->hasOneUse())
14973 CSInc = CSInc.getOperand(i: 0);
14974
14975 if (CSInc.getOpcode() == ARMISD::CSINC &&
14976 isNullConstant(V: CSInc.getOperand(i: 0)) &&
14977 isNullConstant(V: CSInc.getOperand(i: 1)) && CSInc->hasOneUse()) {
14978 CC = (ARMCC::CondCodes)CSInc.getConstantOperandVal(i: 2);
14979 return CSInc.getOperand(i: 3);
14980 }
14981 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(V: CSInc.getOperand(i: 0)) &&
14982 isNullConstant(V: CSInc.getOperand(i: 1)) && CSInc->hasOneUse()) {
14983 CC = (ARMCC::CondCodes)CSInc.getConstantOperandVal(i: 2);
14984 return CSInc.getOperand(i: 3);
14985 }
14986 if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(V: CSInc.getOperand(i: 1)) &&
14987 isNullConstant(V: CSInc.getOperand(i: 0)) && CSInc->hasOneUse()) {
14988 CC = ARMCC::getOppositeCondition(
14989 CC: (ARMCC::CondCodes)CSInc.getConstantOperandVal(i: 2));
14990 return CSInc.getOperand(i: 3);
14991 }
14992 return SDValue();
14993}
14994
14995static SDValue PerformCMPZCombine(SDNode *N, SelectionDAG &DAG) {
14996 // Given CMPZ(CSINC(C, 0, 0, EQ), 0), we can just use C directly. As in
14997 // t92: flags = ARMISD::CMPZ t74, 0
14998 // t93: i32 = ARMISD::CSINC 0, 0, 1, t92
14999 // t96: flags = ARMISD::CMPZ t93, 0
15000 // t114: i32 = ARMISD::CSINV 0, 0, 0, t96
15001 ARMCC::CondCodes Cond;
15002 if (SDValue C = IsCMPZCSINC(Cmp: N, CC&: Cond))
15003 if (Cond == ARMCC::EQ)
15004 return C;
15005 return SDValue();
15006}
15007
15008static SDValue PerformCSETCombine(SDNode *N, SelectionDAG &DAG) {
15009 // Fold away an unnecessary CMPZ/CSINC
15010 // CSXYZ A, B, C1 (CMPZ (CSINC 0, 0, C2, D), 0) ->
15011 // if C1==EQ -> CSXYZ A, B, C2, D
15012 // if C1==NE -> CSXYZ A, B, NOT(C2), D
15013 ARMCC::CondCodes Cond;
15014 if (SDValue C = IsCMPZCSINC(Cmp: N->getOperand(Num: 3).getNode(), CC&: Cond)) {
15015 if (N->getConstantOperandVal(Num: 2) == ARMCC::EQ)
15016 return DAG.getNode(Opcode: N->getOpcode(), DL: SDLoc(N), VT: MVT::i32, N1: N->getOperand(Num: 0),
15017 N2: N->getOperand(Num: 1),
15018 N3: DAG.getConstant(Val: Cond, DL: SDLoc(N), VT: MVT::i32), N4: C);
15019 if (N->getConstantOperandVal(Num: 2) == ARMCC::NE)
15020 return DAG.getNode(
15021 Opcode: N->getOpcode(), DL: SDLoc(N), VT: MVT::i32, N1: N->getOperand(Num: 0),
15022 N2: N->getOperand(Num: 1),
15023 N3: DAG.getConstant(Val: ARMCC::getOppositeCondition(CC: Cond), DL: SDLoc(N), VT: MVT::i32), N4: C);
15024 }
15025 return SDValue();
15026}
15027
15028/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
15029/// ARMISD::VMOVRRD.
15030static SDValue PerformVMOVRRDCombine(SDNode *N,
15031 TargetLowering::DAGCombinerInfo &DCI,
15032 const ARMSubtarget *Subtarget) {
15033 // vmovrrd(vmovdrr x, y) -> x,y
15034 SDValue InDouble = N->getOperand(Num: 0);
15035 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
15036 return DCI.CombineTo(N, Res0: InDouble.getOperand(i: 0), Res1: InDouble.getOperand(i: 1));
15037
15038 // vmovrrd(load f64) -> (load i32), (load i32)
15039 SDNode *InNode = InDouble.getNode();
15040 if (ISD::isNormalLoad(N: InNode) && InNode->hasOneUse() &&
15041 InNode->getValueType(ResNo: 0) == MVT::f64 &&
15042 InNode->getOperand(Num: 1).getOpcode() == ISD::FrameIndex &&
15043 !cast<LoadSDNode>(Val: InNode)->isVolatile()) {
15044 // TODO: Should this be done for non-FrameIndex operands?
15045 LoadSDNode *LD = cast<LoadSDNode>(Val: InNode);
15046
15047 SelectionDAG &DAG = DCI.DAG;
15048 SDLoc DL(LD);
15049 SDValue BasePtr = LD->getBasePtr();
15050 SDValue NewLD1 =
15051 DAG.getLoad(VT: MVT::i32, dl: DL, Chain: LD->getChain(), Ptr: BasePtr, PtrInfo: LD->getPointerInfo(),
15052 Alignment: LD->getAlign(), MMOFlags: LD->getMemOperand()->getFlags());
15053
15054 SDValue OffsetPtr = DAG.getNode(Opcode: ISD::ADD, DL, VT: MVT::i32, N1: BasePtr,
15055 N2: DAG.getConstant(Val: 4, DL, VT: MVT::i32));
15056
15057 SDValue NewLD2 = DAG.getLoad(VT: MVT::i32, dl: DL, Chain: LD->getChain(), Ptr: OffsetPtr,
15058 PtrInfo: LD->getPointerInfo().getWithOffset(O: 4),
15059 Alignment: commonAlignment(A: LD->getAlign(), Offset: 4),
15060 MMOFlags: LD->getMemOperand()->getFlags());
15061
15062 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 1), To: NewLD2.getValue(R: 1));
15063 if (DCI.DAG.getDataLayout().isBigEndian())
15064 std::swap (a&: NewLD1, b&: NewLD2);
15065 SDValue Result = DCI.CombineTo(N, Res0: NewLD1, Res1: NewLD2);
15066 return Result;
15067 }
15068
15069 // VMOVRRD(extract(..(build_vector(a, b, c, d)))) -> a,b or c,d
15070 // VMOVRRD(extract(insert_vector(insert_vector(.., a, l1), b, l2))) -> a,b
15071 if (InDouble.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15072 isa<ConstantSDNode>(Val: InDouble.getOperand(i: 1))) {
15073 SDValue BV = InDouble.getOperand(i: 0);
15074 // Look up through any nop bitcasts and vector_reg_casts. bitcasts may
15075 // change lane order under big endian.
15076 bool BVSwap = BV.getOpcode() == ISD::BITCAST;
15077 while (
15078 (BV.getOpcode() == ISD::BITCAST ||
15079 BV.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
15080 (BV.getValueType() == MVT::v2f64 || BV.getValueType() == MVT::v2i64)) {
15081 BVSwap = BV.getOpcode() == ISD::BITCAST;
15082 BV = BV.getOperand(i: 0);
15083 }
15084 if (BV.getValueType() != MVT::v4i32)
15085 return SDValue();
15086
15087 // Handle buildvectors, pulling out the correct lane depending on
15088 // endianness.
15089 unsigned Offset = InDouble.getConstantOperandVal(i: 1) == 1 ? 2 : 0;
15090 if (BV.getOpcode() == ISD::BUILD_VECTOR) {
15091 SDValue Op0 = BV.getOperand(i: Offset);
15092 SDValue Op1 = BV.getOperand(i: Offset + 1);
15093 if (!Subtarget->isLittle() && BVSwap)
15094 std::swap(a&: Op0, b&: Op1);
15095
15096 return DCI.DAG.getMergeValues(Ops: {Op0, Op1}, dl: SDLoc(N));
15097 }
15098
15099 // A chain of insert_vectors, grabbing the correct value of the chain of
15100 // inserts.
15101 SDValue Op0, Op1;
15102 while (BV.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15103 if (isa<ConstantSDNode>(Val: BV.getOperand(i: 2))) {
15104 if (BV.getConstantOperandVal(i: 2) == Offset && !Op0)
15105 Op0 = BV.getOperand(i: 1);
15106 if (BV.getConstantOperandVal(i: 2) == Offset + 1 && !Op1)
15107 Op1 = BV.getOperand(i: 1);
15108 }
15109 BV = BV.getOperand(i: 0);
15110 }
15111 if (!Subtarget->isLittle() && BVSwap)
15112 std::swap(a&: Op0, b&: Op1);
15113 if (Op0 && Op1)
15114 return DCI.DAG.getMergeValues(Ops: {Op0, Op1}, dl: SDLoc(N));
15115 }
15116
15117 return SDValue();
15118}
15119
15120/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
15121/// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
15122static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
15123 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
15124 SDValue Op0 = N->getOperand(Num: 0);
15125 SDValue Op1 = N->getOperand(Num: 1);
15126 if (Op0.getOpcode() == ISD::BITCAST)
15127 Op0 = Op0.getOperand(i: 0);
15128 if (Op1.getOpcode() == ISD::BITCAST)
15129 Op1 = Op1.getOperand(i: 0);
15130 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
15131 Op0.getNode() == Op1.getNode() &&
15132 Op0.getResNo() == 0 && Op1.getResNo() == 1)
15133 return DAG.getNode(Opcode: ISD::BITCAST, DL: SDLoc(N),
15134 VT: N->getValueType(ResNo: 0), Operand: Op0.getOperand(i: 0));
15135 return SDValue();
15136}
15137
15138static SDValue PerformVMOVhrCombine(SDNode *N,
15139 TargetLowering::DAGCombinerInfo &DCI) {
15140 SDValue Op0 = N->getOperand(Num: 0);
15141
15142 // VMOVhr (VMOVrh (X)) -> X
15143 if (Op0->getOpcode() == ARMISD::VMOVrh)
15144 return Op0->getOperand(Num: 0);
15145
15146 // FullFP16: half values are passed in S-registers, and we don't
15147 // need any of the bitcast and moves:
15148 //
15149 // t2: f32,ch1,gl1? = CopyFromReg ch, Register:f32 %0, gl?
15150 // t5: i32 = bitcast t2
15151 // t18: f16 = ARMISD::VMOVhr t5
15152 // =>
15153 // tN: f16,ch2,gl2? = CopyFromReg ch, Register::f32 %0, gl?
15154 if (Op0->getOpcode() == ISD::BITCAST) {
15155 SDValue Copy = Op0->getOperand(Num: 0);
15156 if (Copy.getValueType() == MVT::f32 &&
15157 Copy->getOpcode() == ISD::CopyFromReg) {
15158 bool HasGlue = Copy->getNumOperands() == 3;
15159 SDValue Ops[] = {Copy->getOperand(Num: 0), Copy->getOperand(Num: 1),
15160 HasGlue ? Copy->getOperand(Num: 2) : SDValue()};
15161 EVT OutTys[] = {N->getValueType(ResNo: 0), MVT::Other, MVT::Glue};
15162 SDValue NewCopy =
15163 DCI.DAG.getNode(Opcode: ISD::CopyFromReg, DL: SDLoc(N),
15164 VTList: DCI.DAG.getVTList(VTs: ArrayRef(OutTys, HasGlue ? 3 : 2)),
15165 Ops: ArrayRef(Ops, HasGlue ? 3 : 2));
15166
15167 // Update Users, Chains, and Potential Glue.
15168 DCI.DAG.ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: NewCopy.getValue(R: 0));
15169 DCI.DAG.ReplaceAllUsesOfValueWith(From: Copy.getValue(R: 1), To: NewCopy.getValue(R: 1));
15170 if (HasGlue)
15171 DCI.DAG.ReplaceAllUsesOfValueWith(From: Copy.getValue(R: 2),
15172 To: NewCopy.getValue(R: 2));
15173
15174 return NewCopy;
15175 }
15176 }
15177
15178 // fold (VMOVhr (load x)) -> (load (f16*)x)
15179 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Val&: Op0)) {
15180 if (LN0->hasOneUse() && LN0->isUnindexed() &&
15181 LN0->getMemoryVT() == MVT::i16) {
15182 SDValue Load =
15183 DCI.DAG.getLoad(VT: N->getValueType(ResNo: 0), dl: SDLoc(N), Chain: LN0->getChain(),
15184 Ptr: LN0->getBasePtr(), MMO: LN0->getMemOperand());
15185 DCI.DAG.ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: Load.getValue(R: 0));
15186 DCI.DAG.ReplaceAllUsesOfValueWith(From: Op0.getValue(R: 1), To: Load.getValue(R: 1));
15187 return Load;
15188 }
15189 }
15190
15191 // Only the bottom 16 bits of the source register are used.
15192 APInt DemandedMask = APInt::getLowBitsSet(numBits: 32, loBitsSet: 16);
15193 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15194 if (TLI.SimplifyDemandedBits(Op: Op0, DemandedBits: DemandedMask, DCI))
15195 return SDValue(N, 0);
15196
15197 return SDValue();
15198}
15199
15200static SDValue PerformVMOVrhCombine(SDNode *N, SelectionDAG &DAG) {
15201 SDValue N0 = N->getOperand(Num: 0);
15202 EVT VT = N->getValueType(ResNo: 0);
15203
15204 // fold (VMOVrh (fpconst x)) -> const x
15205 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val&: N0)) {
15206 APFloat V = C->getValueAPF();
15207 return DAG.getConstant(Val: V.bitcastToAPInt().getZExtValue(), DL: SDLoc(N), VT);
15208 }
15209
15210 // fold (VMOVrh (load x)) -> (zextload (i16*)x)
15211 if (ISD::isNormalLoad(N: N0.getNode()) && N0.hasOneUse()) {
15212 LoadSDNode *LN0 = cast<LoadSDNode>(Val&: N0);
15213
15214 SDValue Load =
15215 DAG.getExtLoad(ExtType: ISD::ZEXTLOAD, dl: SDLoc(N), VT, Chain: LN0->getChain(),
15216 Ptr: LN0->getBasePtr(), MemVT: MVT::i16, MMO: LN0->getMemOperand());
15217 DAG.ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: Load.getValue(R: 0));
15218 DAG.ReplaceAllUsesOfValueWith(From: N0.getValue(R: 1), To: Load.getValue(R: 1));
15219 return Load;
15220 }
15221
15222 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
15223 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15224 isa<ConstantSDNode>(Val: N0->getOperand(Num: 1)))
15225 return DAG.getNode(Opcode: ARMISD::VGETLANEu, DL: SDLoc(N), VT, N1: N0->getOperand(Num: 0),
15226 N2: N0->getOperand(Num: 1));
15227
15228 return SDValue();
15229}
15230
15231/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
15232/// are normal, non-volatile loads. If so, it is profitable to bitcast an
15233/// i64 vector to have f64 elements, since the value can then be loaded
15234/// directly into a VFP register.
15235static bool hasNormalLoadOperand(SDNode *N) {
15236 unsigned NumElts = N->getValueType(ResNo: 0).getVectorNumElements();
15237 for (unsigned i = 0; i < NumElts; ++i) {
15238 SDNode *Elt = N->getOperand(Num: i).getNode();
15239 if (ISD::isNormalLoad(N: Elt) && !cast<LoadSDNode>(Val: Elt)->isVolatile())
15240 return true;
15241 }
15242 return false;
15243}
15244
15245/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
15246/// ISD::BUILD_VECTOR.
15247static SDValue PerformBUILD_VECTORCombine(SDNode *N,
15248 TargetLowering::DAGCombinerInfo &DCI,
15249 const ARMSubtarget *Subtarget) {
15250 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
15251 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
15252 // into a pair of GPRs, which is fine when the value is used as a scalar,
15253 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
15254 SelectionDAG &DAG = DCI.DAG;
15255 if (N->getNumOperands() == 2)
15256 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
15257 return RV;
15258
15259 // Load i64 elements as f64 values so that type legalization does not split
15260 // them up into i32 values.
15261 EVT VT = N->getValueType(ResNo: 0);
15262 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
15263 return SDValue();
15264 SDLoc dl(N);
15265 SmallVector<SDValue, 8> Ops;
15266 unsigned NumElts = VT.getVectorNumElements();
15267 for (unsigned i = 0; i < NumElts; ++i) {
15268 SDValue V = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f64, Operand: N->getOperand(Num: i));
15269 Ops.push_back(Elt: V);
15270 // Make the DAGCombiner fold the bitcast.
15271 DCI.AddToWorklist(N: V.getNode());
15272 }
15273 EVT FloatVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::f64, NumElements: NumElts);
15274 SDValue BV = DAG.getBuildVector(VT: FloatVT, DL: dl, Ops);
15275 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: BV);
15276}
15277
15278/// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
15279static SDValue
15280PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15281 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
15282 // At that time, we may have inserted bitcasts from integer to float.
15283 // If these bitcasts have survived DAGCombine, change the lowering of this
15284 // BUILD_VECTOR in something more vector friendly, i.e., that does not
15285 // force to use floating point types.
15286
15287 // Make sure we can change the type of the vector.
15288 // This is possible iff:
15289 // 1. The vector is only used in a bitcast to a integer type. I.e.,
15290 // 1.1. Vector is used only once.
15291 // 1.2. Use is a bit convert to an integer type.
15292 // 2. The size of its operands are 32-bits (64-bits are not legal).
15293 EVT VT = N->getValueType(ResNo: 0);
15294 EVT EltVT = VT.getVectorElementType();
15295
15296 // Check 1.1. and 2.
15297 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
15298 return SDValue();
15299
15300 // By construction, the input type must be float.
15301 assert(EltVT == MVT::f32 && "Unexpected type!");
15302
15303 // Check 1.2.
15304 SDNode *Use = *N->user_begin();
15305 if (Use->getOpcode() != ISD::BITCAST ||
15306 Use->getValueType(ResNo: 0).isFloatingPoint())
15307 return SDValue();
15308
15309 // Check profitability.
15310 // Model is, if more than half of the relevant operands are bitcast from
15311 // i32, turn the build_vector into a sequence of insert_vector_elt.
15312 // Relevant operands are everything that is not statically
15313 // (i.e., at compile time) bitcasted.
15314 unsigned NumOfBitCastedElts = 0;
15315 unsigned NumElts = VT.getVectorNumElements();
15316 unsigned NumOfRelevantElts = NumElts;
15317 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
15318 SDValue Elt = N->getOperand(Num: Idx);
15319 if (Elt->getOpcode() == ISD::BITCAST) {
15320 // Assume only bit cast to i32 will go away.
15321 if (Elt->getOperand(Num: 0).getValueType() == MVT::i32)
15322 ++NumOfBitCastedElts;
15323 } else if (Elt.isUndef() || isa<ConstantSDNode>(Val: Elt))
15324 // Constants are statically casted, thus do not count them as
15325 // relevant operands.
15326 --NumOfRelevantElts;
15327 }
15328
15329 // Check if more than half of the elements require a non-free bitcast.
15330 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
15331 return SDValue();
15332
15333 SelectionDAG &DAG = DCI.DAG;
15334 // Create the new vector type.
15335 EVT VecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::i32, NumElements: NumElts);
15336 // Check if the type is legal.
15337 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15338 if (!TLI.isTypeLegal(VT: VecVT))
15339 return SDValue();
15340
15341 // Combine:
15342 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
15343 // => BITCAST INSERT_VECTOR_ELT
15344 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
15345 // (BITCAST EN), N.
15346 SDValue Vec = DAG.getUNDEF(VT: VecVT);
15347 SDLoc dl(N);
15348 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
15349 SDValue V = N->getOperand(Num: Idx);
15350 if (V.isUndef())
15351 continue;
15352 if (V.getOpcode() == ISD::BITCAST &&
15353 V->getOperand(Num: 0).getValueType() == MVT::i32)
15354 // Fold obvious case.
15355 V = V.getOperand(i: 0);
15356 else {
15357 V = DAG.getNode(Opcode: ISD::BITCAST, DL: SDLoc(V), VT: MVT::i32, Operand: V);
15358 // Make the DAGCombiner fold the bitcasts.
15359 DCI.AddToWorklist(N: V.getNode());
15360 }
15361 SDValue LaneIdx = DAG.getConstant(Val: Idx, DL: dl, VT: MVT::i32);
15362 Vec = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: VecVT, N1: Vec, N2: V, N3: LaneIdx);
15363 }
15364 Vec = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Vec);
15365 // Make the DAGCombiner fold the bitcasts.
15366 DCI.AddToWorklist(N: Vec.getNode());
15367 return Vec;
15368}
15369
15370static SDValue
15371PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15372 EVT VT = N->getValueType(ResNo: 0);
15373 SDValue Op = N->getOperand(Num: 0);
15374 SDLoc dl(N);
15375
15376 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
15377 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
15378 // If the valuetypes are the same, we can remove the cast entirely.
15379 if (Op->getOperand(Num: 0).getValueType() == VT)
15380 return Op->getOperand(Num: 0);
15381 return DCI.DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT, Operand: Op->getOperand(Num: 0));
15382 }
15383
15384 // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
15385 // more VPNOT which might get folded as else predicates.
15386 if (Op.getValueType() == MVT::i32 && isBitwiseNot(V: Op)) {
15387 SDValue X =
15388 DCI.DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT, Operand: Op->getOperand(Num: 0));
15389 SDValue C = DCI.DAG.getNode(Opcode: ARMISD::PREDICATE_CAST, DL: dl, VT,
15390 Operand: DCI.DAG.getConstant(Val: 65535, DL: dl, VT: MVT::i32));
15391 return DCI.DAG.getNode(Opcode: ISD::XOR, DL: dl, VT, N1: X, N2: C);
15392 }
15393
15394 // Only the bottom 16 bits of the source register are used.
15395 if (Op.getValueType() == MVT::i32) {
15396 APInt DemandedMask = APInt::getLowBitsSet(numBits: 32, loBitsSet: 16);
15397 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15398 if (TLI.SimplifyDemandedBits(Op, DemandedBits: DemandedMask, DCI))
15399 return SDValue(N, 0);
15400 }
15401 return SDValue();
15402}
15403
15404static SDValue PerformVECTOR_REG_CASTCombine(SDNode *N, SelectionDAG &DAG,
15405 const ARMSubtarget *ST) {
15406 EVT VT = N->getValueType(ResNo: 0);
15407 SDValue Op = N->getOperand(Num: 0);
15408 SDLoc dl(N);
15409
15410 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
15411 if (ST->isLittle())
15412 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: Op);
15413
15414 // VT VECTOR_REG_CAST (VT Op) -> Op
15415 if (Op.getValueType() == VT)
15416 return Op;
15417 // VECTOR_REG_CAST undef -> undef
15418 if (Op.isUndef())
15419 return DAG.getUNDEF(VT);
15420
15421 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
15422 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
15423 // If the valuetypes are the same, we can remove the cast entirely.
15424 if (Op->getOperand(Num: 0).getValueType() == VT)
15425 return Op->getOperand(Num: 0);
15426 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT, Operand: Op->getOperand(Num: 0));
15427 }
15428
15429 return SDValue();
15430}
15431
15432static SDValue PerformVCMPCombine(SDNode *N, SelectionDAG &DAG,
15433 const ARMSubtarget *Subtarget) {
15434 if (!Subtarget->hasMVEIntegerOps())
15435 return SDValue();
15436
15437 EVT VT = N->getValueType(ResNo: 0);
15438 SDValue Op0 = N->getOperand(Num: 0);
15439 SDValue Op1 = N->getOperand(Num: 1);
15440 ARMCC::CondCodes Cond = (ARMCC::CondCodes)N->getConstantOperandVal(Num: 2);
15441 SDLoc dl(N);
15442
15443 // vcmp X, 0, cc -> vcmpz X, cc
15444 if (isZeroVector(N: Op1))
15445 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: Op0, N2: N->getOperand(Num: 2));
15446
15447 unsigned SwappedCond = getSwappedCondition(CC: Cond);
15448 if (isValidMVECond(CC: SwappedCond, IsFloat: VT.isFloatingPoint())) {
15449 // vcmp 0, X, cc -> vcmpz X, reversed(cc)
15450 if (isZeroVector(N: Op0))
15451 return DAG.getNode(Opcode: ARMISD::VCMPZ, DL: dl, VT, N1: Op1,
15452 N2: DAG.getConstant(Val: SwappedCond, DL: dl, VT: MVT::i32));
15453 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
15454 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
15455 return DAG.getNode(Opcode: ARMISD::VCMP, DL: dl, VT, N1: Op1, N2: Op0,
15456 N3: DAG.getConstant(Val: SwappedCond, DL: dl, VT: MVT::i32));
15457 }
15458
15459 return SDValue();
15460}
15461
15462/// PerformInsertEltCombine - Target-specific dag combine xforms for
15463/// ISD::INSERT_VECTOR_ELT.
15464static SDValue PerformInsertEltCombine(SDNode *N,
15465 TargetLowering::DAGCombinerInfo &DCI) {
15466 // Bitcast an i64 load inserted into a vector to f64.
15467 // Otherwise, the i64 value will be legalized to a pair of i32 values.
15468 EVT VT = N->getValueType(ResNo: 0);
15469 SDNode *Elt = N->getOperand(Num: 1).getNode();
15470 if (VT.getVectorElementType() != MVT::i64 ||
15471 !ISD::isNormalLoad(N: Elt) || cast<LoadSDNode>(Val: Elt)->isVolatile())
15472 return SDValue();
15473
15474 SelectionDAG &DAG = DCI.DAG;
15475 SDLoc dl(N);
15476 EVT FloatVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::f64,
15477 NumElements: VT.getVectorNumElements());
15478 SDValue Vec = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: FloatVT, Operand: N->getOperand(Num: 0));
15479 SDValue V = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::f64, Operand: N->getOperand(Num: 1));
15480 // Make the DAGCombiner fold the bitcasts.
15481 DCI.AddToWorklist(N: Vec.getNode());
15482 DCI.AddToWorklist(N: V.getNode());
15483 SDValue InsElt = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL: dl, VT: FloatVT,
15484 N1: Vec, N2: V, N3: N->getOperand(Num: 2));
15485 return DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: InsElt);
15486}
15487
15488// Convert a pair of extracts from the same base vector to a VMOVRRD. Either
15489// directly or bitcast to an integer if the original is a float vector.
15490// extract(x, n); extract(x, n+1) -> VMOVRRD(extract v2f64 x, n/2)
15491// bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD(extract x, n/2)
15492static SDValue
15493PerformExtractEltToVMOVRRD(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15494 EVT VT = N->getValueType(ResNo: 0);
15495 SDLoc dl(N);
15496
15497 if (!DCI.isAfterLegalizeDAG() || VT != MVT::i32 ||
15498 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT: MVT::f64))
15499 return SDValue();
15500
15501 SDValue Ext = SDValue(N, 0);
15502 if (Ext.getOpcode() == ISD::BITCAST &&
15503 Ext.getOperand(i: 0).getValueType() == MVT::f32)
15504 Ext = Ext.getOperand(i: 0);
15505 if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
15506 !isa<ConstantSDNode>(Val: Ext.getOperand(i: 1)) ||
15507 Ext.getConstantOperandVal(i: 1) % 2 != 0)
15508 return SDValue();
15509 if (Ext->hasOneUse() && (Ext->user_begin()->getOpcode() == ISD::SINT_TO_FP ||
15510 Ext->user_begin()->getOpcode() == ISD::UINT_TO_FP))
15511 return SDValue();
15512
15513 SDValue Op0 = Ext.getOperand(i: 0);
15514 EVT VecVT = Op0.getValueType();
15515 unsigned ResNo = Op0.getResNo();
15516 unsigned Lane = Ext.getConstantOperandVal(i: 1);
15517 if (VecVT.getVectorNumElements() != 4)
15518 return SDValue();
15519
15520 // Find another extract, of Lane + 1
15521 auto OtherIt = find_if(Range: Op0->users(), P: [&](SDNode *V) {
15522 return V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15523 isa<ConstantSDNode>(Val: V->getOperand(Num: 1)) &&
15524 V->getConstantOperandVal(Num: 1) == Lane + 1 &&
15525 V->getOperand(Num: 0).getResNo() == ResNo;
15526 });
15527 if (OtherIt == Op0->users().end())
15528 return SDValue();
15529
15530 // For float extracts, we need to be converting to a i32 for both vector
15531 // lanes.
15532 SDValue OtherExt(*OtherIt, 0);
15533 if (OtherExt.getValueType() != MVT::i32) {
15534 if (!OtherExt->hasOneUse() ||
15535 OtherExt->user_begin()->getOpcode() != ISD::BITCAST ||
15536 OtherExt->user_begin()->getValueType(ResNo: 0) != MVT::i32)
15537 return SDValue();
15538 OtherExt = SDValue(*OtherExt->user_begin(), 0);
15539 }
15540
15541 // Convert the type to a f64 and extract with a VMOVRRD.
15542 SDValue F64 = DCI.DAG.getNode(
15543 Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f64,
15544 N1: DCI.DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: dl, VT: MVT::v2f64, Operand: Op0),
15545 N2: DCI.DAG.getConstant(Val: Ext.getConstantOperandVal(i: 1) / 2, DL: dl, VT: MVT::i32));
15546 SDValue VMOVRRD =
15547 DCI.DAG.getNode(Opcode: ARMISD::VMOVRRD, DL: dl, ResultTys: {MVT::i32, MVT::i32}, Ops: F64);
15548
15549 DCI.CombineTo(N: OtherExt.getNode(), Res: SDValue(VMOVRRD.getNode(), 1));
15550 return VMOVRRD;
15551}
15552
15553static SDValue PerformExtractEltCombine(SDNode *N,
15554 TargetLowering::DAGCombinerInfo &DCI,
15555 const ARMSubtarget *ST) {
15556 SDValue Op0 = N->getOperand(Num: 0);
15557 EVT VT = N->getValueType(ResNo: 0);
15558 SDLoc dl(N);
15559
15560 // extract (vdup x) -> x
15561 if (Op0->getOpcode() == ARMISD::VDUP) {
15562 SDValue X = Op0->getOperand(Num: 0);
15563 if (VT == MVT::f16 && X.getValueType() == MVT::i32)
15564 return DCI.DAG.getNode(Opcode: ARMISD::VMOVhr, DL: dl, VT, Operand: X);
15565 if (VT == MVT::i32 && X.getValueType() == MVT::f16)
15566 return DCI.DAG.getNode(Opcode: ARMISD::VMOVrh, DL: dl, VT, Operand: X);
15567 if (VT == MVT::f32 && X.getValueType() == MVT::i32)
15568 return DCI.DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT, Operand: X);
15569
15570 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
15571 X = X->getOperand(Num: 0);
15572 if (X.getValueType() == VT)
15573 return X;
15574 }
15575
15576 // extract ARM_BUILD_VECTOR -> x
15577 if (Op0->getOpcode() == ARMISD::BUILD_VECTOR &&
15578 isa<ConstantSDNode>(Val: N->getOperand(Num: 1)) &&
15579 N->getConstantOperandVal(Num: 1) < Op0.getNumOperands()) {
15580 return Op0.getOperand(i: N->getConstantOperandVal(Num: 1));
15581 }
15582
15583 // extract(bitcast(BUILD_VECTOR(VMOVDRR(a, b), ..))) -> a or b
15584 if (Op0.getValueType() == MVT::v4i32 &&
15585 isa<ConstantSDNode>(Val: N->getOperand(Num: 1)) &&
15586 Op0.getOpcode() == ISD::BITCAST &&
15587 Op0.getOperand(i: 0).getOpcode() == ISD::BUILD_VECTOR &&
15588 Op0.getOperand(i: 0).getValueType() == MVT::v2f64) {
15589 SDValue BV = Op0.getOperand(i: 0);
15590 unsigned Offset = N->getConstantOperandVal(Num: 1);
15591 SDValue MOV = BV.getOperand(i: Offset < 2 ? 0 : 1);
15592 if (MOV.getOpcode() == ARMISD::VMOVDRR)
15593 return MOV.getOperand(i: ST->isLittle() ? Offset % 2 : 1 - Offset % 2);
15594 }
15595
15596 // extract x, n; extract x, n+1 -> VMOVRRD x
15597 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
15598 return R;
15599
15600 // extract (MVETrunc(x)) -> extract x
15601 if (Op0->getOpcode() == ARMISD::MVETRUNC) {
15602 unsigned Idx = N->getConstantOperandVal(Num: 1);
15603 unsigned Vec =
15604 Idx / Op0->getOperand(Num: 0).getValueType().getVectorNumElements();
15605 unsigned SubIdx =
15606 Idx % Op0->getOperand(Num: 0).getValueType().getVectorNumElements();
15607 return DCI.DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT, N1: Op0.getOperand(i: Vec),
15608 N2: DCI.DAG.getConstant(Val: SubIdx, DL: dl, VT: MVT::i32));
15609 }
15610
15611 return SDValue();
15612}
15613
15614static SDValue PerformSignExtendInregCombine(SDNode *N, SelectionDAG &DAG) {
15615 SDValue Op = N->getOperand(Num: 0);
15616 EVT VT = N->getValueType(ResNo: 0);
15617
15618 // sext_inreg(VGETLANEu) -> VGETLANEs
15619 if (Op.getOpcode() == ARMISD::VGETLANEu &&
15620 cast<VTSDNode>(Val: N->getOperand(Num: 1))->getVT() ==
15621 Op.getOperand(i: 0).getValueType().getScalarType())
15622 return DAG.getNode(Opcode: ARMISD::VGETLANEs, DL: SDLoc(N), VT, N1: Op.getOperand(i: 0),
15623 N2: Op.getOperand(i: 1));
15624
15625 return SDValue();
15626}
15627
15628static SDValue
15629PerformInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15630 SDValue Vec = N->getOperand(Num: 0);
15631 SDValue SubVec = N->getOperand(Num: 1);
15632 uint64_t IdxVal = N->getConstantOperandVal(Num: 2);
15633 EVT VecVT = Vec.getValueType();
15634 EVT SubVT = SubVec.getValueType();
15635
15636 // Only do this for legal fixed vector types.
15637 if (!VecVT.isFixedLengthVector() ||
15638 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT: VecVT) ||
15639 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT: SubVT))
15640 return SDValue();
15641
15642 // Ignore widening patterns.
15643 if (IdxVal == 0 && Vec.isUndef())
15644 return SDValue();
15645
15646 // Subvector must be half the width and an "aligned" insertion.
15647 unsigned NumSubElts = SubVT.getVectorNumElements();
15648 if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
15649 (IdxVal != 0 && IdxVal != NumSubElts))
15650 return SDValue();
15651
15652 // Fold insert_subvector -> concat_vectors
15653 // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
15654 // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
15655 SDLoc DL(N);
15656 SDValue Lo, Hi;
15657 if (IdxVal == 0) {
15658 Lo = SubVec;
15659 Hi = DCI.DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: SubVT, N1: Vec,
15660 N2: DCI.DAG.getVectorIdxConstant(Val: NumSubElts, DL));
15661 } else {
15662 Lo = DCI.DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: SubVT, N1: Vec,
15663 N2: DCI.DAG.getVectorIdxConstant(Val: 0, DL));
15664 Hi = SubVec;
15665 }
15666 return DCI.DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: VecVT, N1: Lo, N2: Hi);
15667}
15668
15669// shuffle(MVETrunc(x, y)) -> VMOVN(x, y)
15670static SDValue PerformShuffleVMOVNCombine(ShuffleVectorSDNode *N,
15671 SelectionDAG &DAG) {
15672 SDValue Trunc = N->getOperand(Num: 0);
15673 EVT VT = Trunc.getValueType();
15674 if (Trunc.getOpcode() != ARMISD::MVETRUNC || !N->getOperand(Num: 1).isUndef())
15675 return SDValue();
15676
15677 SDLoc DL(Trunc);
15678 if (isVMOVNTruncMask(M: N->getMask(), ToVT: VT, rev: false))
15679 return DAG.getNode(
15680 Opcode: ARMISD::VMOVN, DL, VT,
15681 N1: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: Trunc.getOperand(i: 0)),
15682 N2: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: Trunc.getOperand(i: 1)),
15683 N3: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
15684 else if (isVMOVNTruncMask(M: N->getMask(), ToVT: VT, rev: true))
15685 return DAG.getNode(
15686 Opcode: ARMISD::VMOVN, DL, VT,
15687 N1: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: Trunc.getOperand(i: 1)),
15688 N2: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: Trunc.getOperand(i: 0)),
15689 N3: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
15690 return SDValue();
15691}
15692
15693/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
15694/// ISD::VECTOR_SHUFFLE.
15695static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
15696 if (SDValue R = PerformShuffleVMOVNCombine(N: cast<ShuffleVectorSDNode>(Val: N), DAG))
15697 return R;
15698
15699 // The LLVM shufflevector instruction does not require the shuffle mask
15700 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
15701 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
15702 // operands do not match the mask length, they are extended by concatenating
15703 // them with undef vectors. That is probably the right thing for other
15704 // targets, but for NEON it is better to concatenate two double-register
15705 // size vector operands into a single quad-register size vector. Do that
15706 // transformation here:
15707 // shuffle(concat(v1, undef), concat(v2, undef)) ->
15708 // shuffle(concat(v1, v2), undef)
15709 SDValue Op0 = N->getOperand(Num: 0);
15710 SDValue Op1 = N->getOperand(Num: 1);
15711 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
15712 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
15713 Op0.getNumOperands() != 2 ||
15714 Op1.getNumOperands() != 2)
15715 return SDValue();
15716 SDValue Concat0Op1 = Op0.getOperand(i: 1);
15717 SDValue Concat1Op1 = Op1.getOperand(i: 1);
15718 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
15719 return SDValue();
15720 // Skip the transformation if any of the types are illegal.
15721 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15722 EVT VT = N->getValueType(ResNo: 0);
15723 if (!TLI.isTypeLegal(VT) ||
15724 !TLI.isTypeLegal(VT: Concat0Op1.getValueType()) ||
15725 !TLI.isTypeLegal(VT: Concat1Op1.getValueType()))
15726 return SDValue();
15727
15728 SDValue NewConcat = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL: SDLoc(N), VT,
15729 N1: Op0.getOperand(i: 0), N2: Op1.getOperand(i: 0));
15730 // Translate the shuffle mask.
15731 SmallVector<int, 16> NewMask;
15732 unsigned NumElts = VT.getVectorNumElements();
15733 unsigned HalfElts = NumElts/2;
15734 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Val: N);
15735 for (unsigned n = 0; n < NumElts; ++n) {
15736 int MaskElt = SVN->getMaskElt(Idx: n);
15737 int NewElt = -1;
15738 if (MaskElt < (int)HalfElts)
15739 NewElt = MaskElt;
15740 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
15741 NewElt = HalfElts + MaskElt - NumElts;
15742 NewMask.push_back(Elt: NewElt);
15743 }
15744 return DAG.getVectorShuffle(VT, dl: SDLoc(N), N1: NewConcat,
15745 N2: DAG.getUNDEF(VT), Mask: NewMask);
15746}
15747
15748/// Load/store instruction that can be merged with a base address
15749/// update
15750struct BaseUpdateTarget {
15751 SDNode *N;
15752 bool isIntrinsic;
15753 bool isStore;
15754 unsigned AddrOpIdx;
15755};
15756
15757struct BaseUpdateUser {
15758 /// Instruction that updates a pointer
15759 SDNode *N;
15760 /// Pointer increment operand
15761 SDValue Inc;
15762 /// Pointer increment value if it is a constant, or 0 otherwise
15763 unsigned ConstInc;
15764};
15765
15766static bool isValidBaseUpdate(SDNode *N, SDNode *User) {
15767 // Check that the add is independent of the load/store.
15768 // Otherwise, folding it would create a cycle. Search through Addr
15769 // as well, since the User may not be a direct user of Addr and
15770 // only share a base pointer.
15771 SmallPtrSet<const SDNode *, 32> Visited;
15772 SmallVector<const SDNode *, 16> Worklist;
15773 Worklist.push_back(Elt: N);
15774 Worklist.push_back(Elt: User);
15775 const unsigned MaxSteps = 1024;
15776 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
15777 SDNode::hasPredecessorHelper(N: User, Visited, Worklist, MaxSteps))
15778 return false;
15779 return true;
15780}
15781
15782static bool TryCombineBaseUpdate(struct BaseUpdateTarget &Target,
15783 struct BaseUpdateUser &User,
15784 bool SimpleConstIncOnly,
15785 TargetLowering::DAGCombinerInfo &DCI) {
15786 SelectionDAG &DAG = DCI.DAG;
15787 SDNode *N = Target.N;
15788 MemSDNode *MemN = cast<MemSDNode>(Val: N);
15789 SDLoc dl(N);
15790
15791 // Find the new opcode for the updating load/store.
15792 bool isLoadOp = true;
15793 bool isLaneOp = false;
15794 // Workaround for vst1x and vld1x intrinsics which do not have alignment
15795 // as an operand.
15796 bool hasAlignment = true;
15797 unsigned NewOpc = 0;
15798 unsigned NumVecs = 0;
15799 if (Target.isIntrinsic) {
15800 unsigned IntNo = N->getConstantOperandVal(Num: 1);
15801 switch (IntNo) {
15802 default:
15803 llvm_unreachable("unexpected intrinsic for Neon base update");
15804 case Intrinsic::arm_neon_vld1:
15805 NewOpc = ARMISD::VLD1_UPD;
15806 NumVecs = 1;
15807 break;
15808 case Intrinsic::arm_neon_vld2:
15809 NewOpc = ARMISD::VLD2_UPD;
15810 NumVecs = 2;
15811 break;
15812 case Intrinsic::arm_neon_vld3:
15813 NewOpc = ARMISD::VLD3_UPD;
15814 NumVecs = 3;
15815 break;
15816 case Intrinsic::arm_neon_vld4:
15817 NewOpc = ARMISD::VLD4_UPD;
15818 NumVecs = 4;
15819 break;
15820 case Intrinsic::arm_neon_vld1x2:
15821 NewOpc = ARMISD::VLD1x2_UPD;
15822 NumVecs = 2;
15823 hasAlignment = false;
15824 break;
15825 case Intrinsic::arm_neon_vld1x3:
15826 NewOpc = ARMISD::VLD1x3_UPD;
15827 NumVecs = 3;
15828 hasAlignment = false;
15829 break;
15830 case Intrinsic::arm_neon_vld1x4:
15831 NewOpc = ARMISD::VLD1x4_UPD;
15832 NumVecs = 4;
15833 hasAlignment = false;
15834 break;
15835 case Intrinsic::arm_neon_vld2dup:
15836 NewOpc = ARMISD::VLD2DUP_UPD;
15837 NumVecs = 2;
15838 break;
15839 case Intrinsic::arm_neon_vld3dup:
15840 NewOpc = ARMISD::VLD3DUP_UPD;
15841 NumVecs = 3;
15842 break;
15843 case Intrinsic::arm_neon_vld4dup:
15844 NewOpc = ARMISD::VLD4DUP_UPD;
15845 NumVecs = 4;
15846 break;
15847 case Intrinsic::arm_neon_vld2lane:
15848 NewOpc = ARMISD::VLD2LN_UPD;
15849 NumVecs = 2;
15850 isLaneOp = true;
15851 break;
15852 case Intrinsic::arm_neon_vld3lane:
15853 NewOpc = ARMISD::VLD3LN_UPD;
15854 NumVecs = 3;
15855 isLaneOp = true;
15856 break;
15857 case Intrinsic::arm_neon_vld4lane:
15858 NewOpc = ARMISD::VLD4LN_UPD;
15859 NumVecs = 4;
15860 isLaneOp = true;
15861 break;
15862 case Intrinsic::arm_neon_vst1:
15863 NewOpc = ARMISD::VST1_UPD;
15864 NumVecs = 1;
15865 isLoadOp = false;
15866 break;
15867 case Intrinsic::arm_neon_vst2:
15868 NewOpc = ARMISD::VST2_UPD;
15869 NumVecs = 2;
15870 isLoadOp = false;
15871 break;
15872 case Intrinsic::arm_neon_vst3:
15873 NewOpc = ARMISD::VST3_UPD;
15874 NumVecs = 3;
15875 isLoadOp = false;
15876 break;
15877 case Intrinsic::arm_neon_vst4:
15878 NewOpc = ARMISD::VST4_UPD;
15879 NumVecs = 4;
15880 isLoadOp = false;
15881 break;
15882 case Intrinsic::arm_neon_vst2lane:
15883 NewOpc = ARMISD::VST2LN_UPD;
15884 NumVecs = 2;
15885 isLoadOp = false;
15886 isLaneOp = true;
15887 break;
15888 case Intrinsic::arm_neon_vst3lane:
15889 NewOpc = ARMISD::VST3LN_UPD;
15890 NumVecs = 3;
15891 isLoadOp = false;
15892 isLaneOp = true;
15893 break;
15894 case Intrinsic::arm_neon_vst4lane:
15895 NewOpc = ARMISD::VST4LN_UPD;
15896 NumVecs = 4;
15897 isLoadOp = false;
15898 isLaneOp = true;
15899 break;
15900 case Intrinsic::arm_neon_vst1x2:
15901 NewOpc = ARMISD::VST1x2_UPD;
15902 NumVecs = 2;
15903 isLoadOp = false;
15904 hasAlignment = false;
15905 break;
15906 case Intrinsic::arm_neon_vst1x3:
15907 NewOpc = ARMISD::VST1x3_UPD;
15908 NumVecs = 3;
15909 isLoadOp = false;
15910 hasAlignment = false;
15911 break;
15912 case Intrinsic::arm_neon_vst1x4:
15913 NewOpc = ARMISD::VST1x4_UPD;
15914 NumVecs = 4;
15915 isLoadOp = false;
15916 hasAlignment = false;
15917 break;
15918 }
15919 } else {
15920 isLaneOp = true;
15921 switch (N->getOpcode()) {
15922 default:
15923 llvm_unreachable("unexpected opcode for Neon base update");
15924 case ARMISD::VLD1DUP:
15925 NewOpc = ARMISD::VLD1DUP_UPD;
15926 NumVecs = 1;
15927 break;
15928 case ARMISD::VLD2DUP:
15929 NewOpc = ARMISD::VLD2DUP_UPD;
15930 NumVecs = 2;
15931 break;
15932 case ARMISD::VLD3DUP:
15933 NewOpc = ARMISD::VLD3DUP_UPD;
15934 NumVecs = 3;
15935 break;
15936 case ARMISD::VLD4DUP:
15937 NewOpc = ARMISD::VLD4DUP_UPD;
15938 NumVecs = 4;
15939 break;
15940 case ISD::LOAD:
15941 NewOpc = ARMISD::VLD1_UPD;
15942 NumVecs = 1;
15943 isLaneOp = false;
15944 break;
15945 case ISD::STORE:
15946 NewOpc = ARMISD::VST1_UPD;
15947 NumVecs = 1;
15948 isLaneOp = false;
15949 isLoadOp = false;
15950 break;
15951 }
15952 }
15953
15954 // Find the size of memory referenced by the load/store.
15955 EVT VecTy;
15956 if (isLoadOp) {
15957 VecTy = N->getValueType(ResNo: 0);
15958 } else if (Target.isIntrinsic) {
15959 VecTy = N->getOperand(Num: Target.AddrOpIdx + 1).getValueType();
15960 } else {
15961 assert(Target.isStore &&
15962 "Node has to be a load, a store, or an intrinsic!");
15963 VecTy = N->getOperand(Num: 1).getValueType();
15964 }
15965
15966 bool isVLDDUPOp =
15967 NewOpc == ARMISD::VLD1DUP_UPD || NewOpc == ARMISD::VLD2DUP_UPD ||
15968 NewOpc == ARMISD::VLD3DUP_UPD || NewOpc == ARMISD::VLD4DUP_UPD;
15969
15970 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
15971 if (isLaneOp || isVLDDUPOp)
15972 NumBytes /= VecTy.getVectorNumElements();
15973
15974 if (NumBytes >= 3 * 16 && User.ConstInc != NumBytes) {
15975 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
15976 // separate instructions that make it harder to use a non-constant update.
15977 return false;
15978 }
15979
15980 if (SimpleConstIncOnly && User.ConstInc != NumBytes)
15981 return false;
15982
15983 if (!isValidBaseUpdate(N, User: User.N))
15984 return false;
15985
15986 // OK, we found an ADD we can fold into the base update.
15987 // Now, create a _UPD node, taking care of not breaking alignment.
15988
15989 EVT AlignedVecTy = VecTy;
15990 Align Alignment = MemN->getAlign();
15991
15992 // If this is a less-than-standard-aligned load/store, change the type to
15993 // match the standard alignment.
15994 // The alignment is overlooked when selecting _UPD variants; and it's
15995 // easier to introduce bitcasts here than fix that.
15996 // There are 3 ways to get to this base-update combine:
15997 // - intrinsics: they are assumed to be properly aligned (to the standard
15998 // alignment of the memory type), so we don't need to do anything.
15999 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
16000 // intrinsics, so, likewise, there's nothing to do.
16001 // - generic load/store instructions: the alignment is specified as an
16002 // explicit operand, rather than implicitly as the standard alignment
16003 // of the memory type (like the intrinsics). We need to change the
16004 // memory type to match the explicit alignment. That way, we don't
16005 // generate non-standard-aligned ARMISD::VLDx nodes.
16006 if (isa<LSBaseSDNode>(Val: N)) {
16007 if (Alignment.value() < VecTy.getScalarSizeInBits() / 8) {
16008 MVT EltTy = MVT::getIntegerVT(BitWidth: Alignment.value() * 8);
16009 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
16010 assert(!isLaneOp && "Unexpected generic load/store lane.");
16011 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
16012 AlignedVecTy = MVT::getVectorVT(VT: EltTy, NumElements: NumElts);
16013 }
16014 // Don't set an explicit alignment on regular load/stores that we want
16015 // to transform to VLD/VST 1_UPD nodes.
16016 // This matches the behavior of regular load/stores, which only get an
16017 // explicit alignment if the MMO alignment is larger than the standard
16018 // alignment of the memory type.
16019 // Intrinsics, however, always get an explicit alignment, set to the
16020 // alignment of the MMO.
16021 Alignment = Align(1);
16022 }
16023
16024 // Create the new updating load/store node.
16025 // First, create an SDVTList for the new updating node's results.
16026 EVT Tys[6];
16027 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16028 unsigned n;
16029 for (n = 0; n < NumResultVecs; ++n)
16030 Tys[n] = AlignedVecTy;
16031 Tys[n++] = MVT::i32;
16032 Tys[n] = MVT::Other;
16033 SDVTList SDTys = DAG.getVTList(VTs: ArrayRef(Tys, NumResultVecs + 2));
16034
16035 // Then, gather the new node's operands.
16036 SmallVector<SDValue, 8> Ops;
16037 Ops.push_back(Elt: N->getOperand(Num: 0)); // incoming chain
16038 Ops.push_back(Elt: N->getOperand(Num: Target.AddrOpIdx));
16039 Ops.push_back(Elt: User.Inc);
16040
16041 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(Val: N)) {
16042 // Try to match the intrinsic's signature
16043 Ops.push_back(Elt: StN->getValue());
16044 } else {
16045 // Loads (and of course intrinsics) match the intrinsics' signature,
16046 // so just add all but the alignment operand.
16047 unsigned LastOperand =
16048 hasAlignment ? N->getNumOperands() - 1 : N->getNumOperands();
16049 for (unsigned i = Target.AddrOpIdx + 1; i < LastOperand; ++i)
16050 Ops.push_back(Elt: N->getOperand(Num: i));
16051 }
16052
16053 // For all node types, the alignment operand is always the last one.
16054 Ops.push_back(Elt: DAG.getConstant(Val: Alignment.value(), DL: dl, VT: MVT::i32));
16055
16056 // If this is a non-standard-aligned STORE, the penultimate operand is the
16057 // stored value. Bitcast it to the aligned type.
16058 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
16059 SDValue &StVal = Ops[Ops.size() - 2];
16060 StVal = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: AlignedVecTy, Operand: StVal);
16061 }
16062
16063 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
16064 SDValue UpdN = DAG.getMemIntrinsicNode(Opcode: NewOpc, dl, VTList: SDTys, Ops, MemVT: LoadVT,
16065 MMO: MemN->getMemOperand());
16066
16067 // Update the uses.
16068 SmallVector<SDValue, 5> NewResults;
16069 for (unsigned i = 0; i < NumResultVecs; ++i)
16070 NewResults.push_back(Elt: SDValue(UpdN.getNode(), i));
16071
16072 // If this is an non-standard-aligned LOAD, the first result is the loaded
16073 // value. Bitcast it to the expected result type.
16074 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
16075 SDValue &LdVal = NewResults[0];
16076 LdVal = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: VecTy, Operand: LdVal);
16077 }
16078
16079 NewResults.push_back(Elt: SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16080 DCI.CombineTo(N, To: NewResults);
16081 DCI.CombineTo(N: User.N, Res: SDValue(UpdN.getNode(), NumResultVecs));
16082
16083 return true;
16084}
16085
16086// If (opcode ptr inc) is and ADD-like instruction, return the
16087// increment value. Otherwise return 0.
16088static unsigned getPointerConstIncrement(unsigned Opcode, SDValue Ptr,
16089 SDValue Inc, const SelectionDAG &DAG) {
16090 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Val: Inc.getNode());
16091 if (!CInc)
16092 return 0;
16093
16094 switch (Opcode) {
16095 case ARMISD::VLD1_UPD:
16096 case ISD::ADD:
16097 return CInc->getZExtValue();
16098 case ISD::OR: {
16099 if (DAG.haveNoCommonBitsSet(A: Ptr, B: Inc)) {
16100 // (OR ptr inc) is the same as (ADD ptr inc)
16101 return CInc->getZExtValue();
16102 }
16103 return 0;
16104 }
16105 default:
16106 return 0;
16107 }
16108}
16109
16110static bool findPointerConstIncrement(SDNode *N, SDValue *Ptr, SDValue *CInc) {
16111 switch (N->getOpcode()) {
16112 case ISD::ADD:
16113 case ISD::OR: {
16114 if (isa<ConstantSDNode>(Val: N->getOperand(Num: 1))) {
16115 *Ptr = N->getOperand(Num: 0);
16116 *CInc = N->getOperand(Num: 1);
16117 return true;
16118 }
16119 return false;
16120 }
16121 case ARMISD::VLD1_UPD: {
16122 if (isa<ConstantSDNode>(Val: N->getOperand(Num: 2))) {
16123 *Ptr = N->getOperand(Num: 1);
16124 *CInc = N->getOperand(Num: 2);
16125 return true;
16126 }
16127 return false;
16128 }
16129 default:
16130 return false;
16131 }
16132}
16133
16134/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
16135/// NEON load/store intrinsics, and generic vector load/stores, to merge
16136/// base address updates.
16137/// For generic load/stores, the memory type is assumed to be a vector.
16138/// The caller is assumed to have checked legality.
16139static SDValue CombineBaseUpdate(SDNode *N,
16140 TargetLowering::DAGCombinerInfo &DCI) {
16141 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
16142 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
16143 const bool isStore = N->getOpcode() == ISD::STORE;
16144 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
16145 BaseUpdateTarget Target = {.N: N, .isIntrinsic: isIntrinsic, .isStore: isStore, .AddrOpIdx: AddrOpIdx};
16146
16147 // Limit the number of possible base-updates we look at to prevent degenerate
16148 // cases.
16149 unsigned MaxBaseUpdates = ArmMaxBaseUpdatesToCheck;
16150
16151 SDValue Addr = N->getOperand(Num: AddrOpIdx);
16152
16153 SmallVector<BaseUpdateUser, 8> BaseUpdates;
16154
16155 // Search for a use of the address operand that is an increment.
16156 for (SDUse &Use : Addr->uses()) {
16157 SDNode *User = Use.getUser();
16158 if (Use.getResNo() != Addr.getResNo() || User->getNumOperands() != 2)
16159 continue;
16160
16161 SDValue Inc = User->getOperand(Num: Use.getOperandNo() == 1 ? 0 : 1);
16162 unsigned ConstInc =
16163 getPointerConstIncrement(Opcode: User->getOpcode(), Ptr: Addr, Inc, DAG: DCI.DAG);
16164
16165 if (ConstInc || User->getOpcode() == ISD::ADD) {
16166 BaseUpdates.push_back(Elt: {.N: User, .Inc: Inc, .ConstInc: ConstInc});
16167 if (BaseUpdates.size() >= MaxBaseUpdates)
16168 break;
16169 }
16170 }
16171
16172 // If the address is a constant pointer increment itself, find
16173 // another constant increment that has the same base operand
16174 SDValue Base;
16175 SDValue CInc;
16176 if (findPointerConstIncrement(N: Addr.getNode(), Ptr: &Base, CInc: &CInc)) {
16177 unsigned Offset =
16178 getPointerConstIncrement(Opcode: Addr->getOpcode(), Ptr: Base, Inc: CInc, DAG: DCI.DAG);
16179 for (SDUse &Use : Base->uses()) {
16180
16181 SDNode *User = Use.getUser();
16182 if (Use.getResNo() != Base.getResNo() || User == Addr.getNode() ||
16183 User->getNumOperands() != 2)
16184 continue;
16185
16186 SDValue UserInc = User->getOperand(Num: Use.getOperandNo() == 0 ? 1 : 0);
16187 unsigned UserOffset =
16188 getPointerConstIncrement(Opcode: User->getOpcode(), Ptr: Base, Inc: UserInc, DAG: DCI.DAG);
16189
16190 if (!UserOffset || UserOffset <= Offset)
16191 continue;
16192
16193 unsigned NewConstInc = UserOffset - Offset;
16194 SDValue NewInc = DCI.DAG.getConstant(Val: NewConstInc, DL: SDLoc(N), VT: MVT::i32);
16195 BaseUpdates.push_back(Elt: {.N: User, .Inc: NewInc, .ConstInc: NewConstInc});
16196 if (BaseUpdates.size() >= MaxBaseUpdates)
16197 break;
16198 }
16199 }
16200
16201 // Try to fold the load/store with an update that matches memory
16202 // access size. This should work well for sequential loads.
16203 unsigned NumValidUpd = BaseUpdates.size();
16204 for (unsigned I = 0; I < NumValidUpd; I++) {
16205 BaseUpdateUser &User = BaseUpdates[I];
16206 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/true, DCI))
16207 return SDValue();
16208 }
16209
16210 // Try to fold with other users. Non-constant updates are considered
16211 // first, and constant updates are sorted to not break a sequence of
16212 // strided accesses (if there is any).
16213 llvm::stable_sort(Range&: BaseUpdates,
16214 C: [](const BaseUpdateUser &LHS, const BaseUpdateUser &RHS) {
16215 return LHS.ConstInc < RHS.ConstInc;
16216 });
16217 for (BaseUpdateUser &User : BaseUpdates) {
16218 if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/false, DCI))
16219 return SDValue();
16220 }
16221 return SDValue();
16222}
16223
16224static SDValue PerformVLDCombine(SDNode *N,
16225 TargetLowering::DAGCombinerInfo &DCI) {
16226 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16227 return SDValue();
16228
16229 return CombineBaseUpdate(N, DCI);
16230}
16231
16232static SDValue PerformMVEVLDCombine(SDNode *N,
16233 TargetLowering::DAGCombinerInfo &DCI) {
16234 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16235 return SDValue();
16236
16237 SelectionDAG &DAG = DCI.DAG;
16238 SDValue Addr = N->getOperand(Num: 2);
16239 MemSDNode *MemN = cast<MemSDNode>(Val: N);
16240 SDLoc dl(N);
16241
16242 // For the stores, where there are multiple intrinsics we only actually want
16243 // to post-inc the last of the them.
16244 unsigned IntNo = N->getConstantOperandVal(Num: 1);
16245 if (IntNo == Intrinsic::arm_mve_vst2q && N->getConstantOperandVal(Num: 5) != 1)
16246 return SDValue();
16247 if (IntNo == Intrinsic::arm_mve_vst4q && N->getConstantOperandVal(Num: 7) != 3)
16248 return SDValue();
16249
16250 // Search for a use of the address operand that is an increment.
16251 for (SDUse &Use : Addr->uses()) {
16252 SDNode *User = Use.getUser();
16253 if (User->getOpcode() != ISD::ADD || Use.getResNo() != Addr.getResNo())
16254 continue;
16255
16256 // Check that the add is independent of the load/store. Otherwise, folding
16257 // it would create a cycle. We can avoid searching through Addr as it's a
16258 // predecessor to both.
16259 SmallPtrSet<const SDNode *, 32> Visited;
16260 SmallVector<const SDNode *, 16> Worklist;
16261 Visited.insert(Ptr: Addr.getNode());
16262 Worklist.push_back(Elt: N);
16263 Worklist.push_back(Elt: User);
16264 const unsigned MaxSteps = 1024;
16265 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
16266 SDNode::hasPredecessorHelper(N: User, Visited, Worklist, MaxSteps))
16267 continue;
16268
16269 // Find the new opcode for the updating load/store.
16270 bool isLoadOp = true;
16271 unsigned NewOpc = 0;
16272 unsigned NumVecs = 0;
16273 switch (IntNo) {
16274 default:
16275 llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
16276 case Intrinsic::arm_mve_vld2q:
16277 NewOpc = ARMISD::VLD2_UPD;
16278 NumVecs = 2;
16279 break;
16280 case Intrinsic::arm_mve_vld4q:
16281 NewOpc = ARMISD::VLD4_UPD;
16282 NumVecs = 4;
16283 break;
16284 case Intrinsic::arm_mve_vst2q:
16285 NewOpc = ARMISD::VST2_UPD;
16286 NumVecs = 2;
16287 isLoadOp = false;
16288 break;
16289 case Intrinsic::arm_mve_vst4q:
16290 NewOpc = ARMISD::VST4_UPD;
16291 NumVecs = 4;
16292 isLoadOp = false;
16293 break;
16294 }
16295
16296 // Find the size of memory referenced by the load/store.
16297 EVT VecTy;
16298 if (isLoadOp) {
16299 VecTy = N->getValueType(ResNo: 0);
16300 } else {
16301 VecTy = N->getOperand(Num: 3).getValueType();
16302 }
16303
16304 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16305
16306 // If the increment is a constant, it must match the memory ref size.
16307 SDValue Inc = User->getOperand(Num: User->getOperand(Num: 0) == Addr ? 1 : 0);
16308 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Val: Inc.getNode());
16309 if (!CInc || CInc->getZExtValue() != NumBytes)
16310 continue;
16311
16312 // Create the new updating load/store node.
16313 // First, create an SDVTList for the new updating node's results.
16314 EVT Tys[6];
16315 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16316 unsigned n;
16317 for (n = 0; n < NumResultVecs; ++n)
16318 Tys[n] = VecTy;
16319 Tys[n++] = MVT::i32;
16320 Tys[n] = MVT::Other;
16321 SDVTList SDTys = DAG.getVTList(VTs: ArrayRef(Tys, NumResultVecs + 2));
16322
16323 // Then, gather the new node's operands.
16324 SmallVector<SDValue, 8> Ops;
16325 Ops.push_back(Elt: N->getOperand(Num: 0)); // incoming chain
16326 Ops.push_back(Elt: N->getOperand(Num: 2)); // ptr
16327 Ops.push_back(Elt: Inc);
16328
16329 for (unsigned i = 3; i < N->getNumOperands(); ++i)
16330 Ops.push_back(Elt: N->getOperand(Num: i));
16331
16332 SDValue UpdN = DAG.getMemIntrinsicNode(Opcode: NewOpc, dl, VTList: SDTys, Ops, MemVT: VecTy,
16333 MMO: MemN->getMemOperand());
16334
16335 // Update the uses.
16336 SmallVector<SDValue, 5> NewResults;
16337 for (unsigned i = 0; i < NumResultVecs; ++i)
16338 NewResults.push_back(Elt: SDValue(UpdN.getNode(), i));
16339
16340 NewResults.push_back(Elt: SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16341 DCI.CombineTo(N, To: NewResults);
16342 DCI.CombineTo(N: User, Res: SDValue(UpdN.getNode(), NumResultVecs));
16343
16344 break;
16345 }
16346
16347 return SDValue();
16348}
16349
16350/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
16351/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
16352/// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
16353/// return true.
16354static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
16355 SelectionDAG &DAG = DCI.DAG;
16356 EVT VT = N->getValueType(ResNo: 0);
16357 // vldN-dup instructions only support 64-bit vectors for N > 1.
16358 if (!VT.is64BitVector())
16359 return false;
16360
16361 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
16362 SDNode *VLD = N->getOperand(Num: 0).getNode();
16363 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
16364 return false;
16365 unsigned NumVecs = 0;
16366 unsigned NewOpc = 0;
16367 unsigned IntNo = VLD->getConstantOperandVal(Num: 1);
16368 if (IntNo == Intrinsic::arm_neon_vld2lane) {
16369 NumVecs = 2;
16370 NewOpc = ARMISD::VLD2DUP;
16371 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
16372 NumVecs = 3;
16373 NewOpc = ARMISD::VLD3DUP;
16374 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
16375 NumVecs = 4;
16376 NewOpc = ARMISD::VLD4DUP;
16377 } else {
16378 return false;
16379 }
16380
16381 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
16382 // numbers match the load.
16383 unsigned VLDLaneNo = VLD->getConstantOperandVal(Num: NumVecs + 3);
16384 for (SDUse &Use : VLD->uses()) {
16385 // Ignore uses of the chain result.
16386 if (Use.getResNo() == NumVecs)
16387 continue;
16388 SDNode *User = Use.getUser();
16389 if (User->getOpcode() != ARMISD::VDUPLANE ||
16390 VLDLaneNo != User->getConstantOperandVal(Num: 1))
16391 return false;
16392 }
16393
16394 // Create the vldN-dup node.
16395 EVT Tys[5];
16396 unsigned n;
16397 for (n = 0; n < NumVecs; ++n)
16398 Tys[n] = VT;
16399 Tys[n] = MVT::Other;
16400 SDVTList SDTys = DAG.getVTList(VTs: ArrayRef(Tys, NumVecs + 1));
16401 SDValue Ops[] = { VLD->getOperand(Num: 0), VLD->getOperand(Num: 2) };
16402 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(Val: VLD);
16403 SDValue VLDDup = DAG.getMemIntrinsicNode(Opcode: NewOpc, dl: SDLoc(VLD), VTList: SDTys,
16404 Ops, MemVT: VLDMemInt->getMemoryVT(),
16405 MMO: VLDMemInt->getMemOperand());
16406
16407 // Update the uses.
16408 for (SDUse &Use : VLD->uses()) {
16409 unsigned ResNo = Use.getResNo();
16410 // Ignore uses of the chain result.
16411 if (ResNo == NumVecs)
16412 continue;
16413 DCI.CombineTo(N: Use.getUser(), Res: SDValue(VLDDup.getNode(), ResNo));
16414 }
16415
16416 // Now the vldN-lane intrinsic is dead except for its chain result.
16417 // Update uses of the chain.
16418 std::vector<SDValue> VLDDupResults;
16419 for (unsigned n = 0; n < NumVecs; ++n)
16420 VLDDupResults.push_back(x: SDValue(VLDDup.getNode(), n));
16421 VLDDupResults.push_back(x: SDValue(VLDDup.getNode(), NumVecs));
16422 DCI.CombineTo(N: VLD, To: VLDDupResults);
16423
16424 return true;
16425}
16426
16427/// PerformVDUPLANECombine - Target-specific dag combine xforms for
16428/// ARMISD::VDUPLANE.
16429static SDValue PerformVDUPLANECombine(SDNode *N,
16430 TargetLowering::DAGCombinerInfo &DCI,
16431 const ARMSubtarget *Subtarget) {
16432 SDValue Op = N->getOperand(Num: 0);
16433 EVT VT = N->getValueType(ResNo: 0);
16434
16435 // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
16436 if (Subtarget->hasMVEIntegerOps()) {
16437 EVT ExtractVT = VT.getVectorElementType();
16438 // We need to ensure we are creating a legal type.
16439 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT: ExtractVT))
16440 ExtractVT = MVT::i32;
16441 SDValue Extract = DCI.DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: SDLoc(N), VT: ExtractVT,
16442 N1: N->getOperand(Num: 0), N2: N->getOperand(Num: 1));
16443 return DCI.DAG.getNode(Opcode: ARMISD::VDUP, DL: SDLoc(N), VT, Operand: Extract);
16444 }
16445
16446 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
16447 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
16448 if (CombineVLDDUP(N, DCI))
16449 return SDValue(N, 0);
16450
16451 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
16452 // redundant. Ignore bit_converts for now; element sizes are checked below.
16453 while (Op.getOpcode() == ISD::BITCAST)
16454 Op = Op.getOperand(i: 0);
16455 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
16456 return SDValue();
16457
16458 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
16459 unsigned EltSize = Op.getScalarValueSizeInBits();
16460 // The canonical VMOV for a zero vector uses a 32-bit element size.
16461 unsigned Imm = Op.getConstantOperandVal(i: 0);
16462 unsigned EltBits;
16463 if (ARM_AM::decodeVMOVModImm(ModImm: Imm, EltBits) == 0)
16464 EltSize = 8;
16465 if (EltSize > VT.getScalarSizeInBits())
16466 return SDValue();
16467
16468 return DCI.DAG.getNode(Opcode: ISD::BITCAST, DL: SDLoc(N), VT, Operand: Op);
16469}
16470
16471/// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
16472static SDValue PerformVDUPCombine(SDNode *N, SelectionDAG &DAG,
16473 const ARMSubtarget *Subtarget) {
16474 SDValue Op = N->getOperand(Num: 0);
16475 SDLoc dl(N);
16476
16477 if (Subtarget->hasMVEIntegerOps()) {
16478 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
16479 // need to come from a GPR.
16480 if (Op.getValueType() == MVT::f32)
16481 return DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT: N->getValueType(ResNo: 0),
16482 Operand: DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i32, Operand: Op));
16483 else if (Op.getValueType() == MVT::f16)
16484 return DAG.getNode(Opcode: ARMISD::VDUP, DL: dl, VT: N->getValueType(ResNo: 0),
16485 Operand: DAG.getNode(Opcode: ARMISD::VMOVrh, DL: dl, VT: MVT::i32, Operand: Op));
16486 }
16487
16488 if (!Subtarget->hasNEON())
16489 return SDValue();
16490
16491 // Match VDUP(LOAD) -> VLD1DUP.
16492 // We match this pattern here rather than waiting for isel because the
16493 // transform is only legal for unindexed loads.
16494 LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: Op.getNode());
16495 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
16496 LD->getMemoryVT() == N->getValueType(ResNo: 0).getVectorElementType()) {
16497 SDValue Ops[] = {LD->getOperand(Num: 0), LD->getOperand(Num: 1),
16498 DAG.getConstant(Val: LD->getAlign().value(), DL: SDLoc(N), VT: MVT::i32)};
16499 SDVTList SDTys = DAG.getVTList(VT1: N->getValueType(ResNo: 0), VT2: MVT::Other);
16500 SDValue VLDDup =
16501 DAG.getMemIntrinsicNode(Opcode: ARMISD::VLD1DUP, dl: SDLoc(N), VTList: SDTys, Ops,
16502 MemVT: LD->getMemoryVT(), MMO: LD->getMemOperand());
16503 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 1), To: VLDDup.getValue(R: 1));
16504 return VLDDup;
16505 }
16506
16507 return SDValue();
16508}
16509
16510static SDValue PerformLOADCombine(SDNode *N,
16511 TargetLowering::DAGCombinerInfo &DCI,
16512 const ARMSubtarget *Subtarget) {
16513 EVT VT = N->getValueType(ResNo: 0);
16514
16515 // If this is a legal vector load, try to combine it into a VLD1_UPD.
16516 if (Subtarget->hasNEON() && ISD::isNormalLoad(N) && VT.isVector() &&
16517 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16518 return CombineBaseUpdate(N, DCI);
16519
16520 return SDValue();
16521}
16522
16523// Optimize trunc store (of multiple scalars) to shuffle and store. First,
16524// pack all of the elements in one place. Next, store to memory in fewer
16525// chunks.
16526static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
16527 SelectionDAG &DAG) {
16528 SDValue StVal = St->getValue();
16529 EVT VT = StVal.getValueType();
16530 if (!St->isTruncatingStore() || !VT.isVector())
16531 return SDValue();
16532 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16533 EVT StVT = St->getMemoryVT();
16534 unsigned NumElems = VT.getVectorNumElements();
16535 assert(StVT != VT && "Cannot truncate to the same type");
16536 unsigned FromEltSz = VT.getScalarSizeInBits();
16537 unsigned ToEltSz = StVT.getScalarSizeInBits();
16538
16539 // From, To sizes and ElemCount must be pow of two
16540 if (!isPowerOf2_32(Value: NumElems * FromEltSz * ToEltSz))
16541 return SDValue();
16542
16543 // We are going to use the original vector elt for storing.
16544 // Accumulated smaller vector elements must be a multiple of the store size.
16545 if (0 != (NumElems * FromEltSz) % ToEltSz)
16546 return SDValue();
16547
16548 unsigned SizeRatio = FromEltSz / ToEltSz;
16549 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
16550
16551 // Create a type on which we perform the shuffle.
16552 EVT WideVecVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: StVT.getScalarType(),
16553 NumElements: NumElems * SizeRatio);
16554 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16555
16556 SDLoc DL(St);
16557 SDValue WideVec = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: WideVecVT, Operand: StVal);
16558 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16559 for (unsigned i = 0; i < NumElems; ++i)
16560 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
16561 : i * SizeRatio;
16562
16563 // Can't shuffle using an illegal type.
16564 if (!TLI.isTypeLegal(VT: WideVecVT))
16565 return SDValue();
16566
16567 SDValue Shuff = DAG.getVectorShuffle(
16568 VT: WideVecVT, dl: DL, N1: WideVec, N2: DAG.getUNDEF(VT: WideVec.getValueType()), Mask: ShuffleVec);
16569 // At this point all of the data is stored at the bottom of the
16570 // register. We now need to save it to mem.
16571
16572 // Find the largest store unit
16573 MVT StoreType = MVT::i8;
16574 for (MVT Tp : MVT::integer_valuetypes()) {
16575 if (TLI.isTypeLegal(VT: Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
16576 StoreType = Tp;
16577 }
16578 // Didn't find a legal store type.
16579 if (!TLI.isTypeLegal(VT: StoreType))
16580 return SDValue();
16581
16582 // Bitcast the original vector into a vector of store-size units
16583 EVT StoreVecVT =
16584 EVT::getVectorVT(Context&: *DAG.getContext(), VT: StoreType,
16585 NumElements: VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
16586 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16587 SDValue ShuffWide = DAG.getNode(Opcode: ISD::BITCAST, DL, VT: StoreVecVT, Operand: Shuff);
16588 SmallVector<SDValue, 8> Chains;
16589 SDValue Increment = DAG.getConstant(Val: StoreType.getSizeInBits() / 8, DL,
16590 VT: TLI.getPointerTy(DL: DAG.getDataLayout()));
16591 SDValue BasePtr = St->getBasePtr();
16592
16593 // Perform one or more big stores into memory.
16594 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
16595 for (unsigned I = 0; I < E; I++) {
16596 SDValue SubVec = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: StoreType,
16597 N1: ShuffWide, N2: DAG.getIntPtrConstant(Val: I, DL));
16598 SDValue Ch =
16599 DAG.getStore(Chain: St->getChain(), dl: DL, Val: SubVec, Ptr: BasePtr, PtrInfo: St->getPointerInfo(),
16600 Alignment: St->getAlign(), MMOFlags: St->getMemOperand()->getFlags());
16601 BasePtr =
16602 DAG.getNode(Opcode: ISD::ADD, DL, VT: BasePtr.getValueType(), N1: BasePtr, N2: Increment);
16603 Chains.push_back(Elt: Ch);
16604 }
16605 return DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Chains);
16606}
16607
16608// Try taking a single vector store from an fpround (which would otherwise turn
16609// into an expensive buildvector) and splitting it into a series of narrowing
16610// stores.
16611static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
16612 SelectionDAG &DAG) {
16613 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16614 return SDValue();
16615 SDValue Trunc = St->getValue();
16616 if (Trunc->getOpcode() != ISD::FP_ROUND)
16617 return SDValue();
16618 EVT FromVT = Trunc->getOperand(Num: 0).getValueType();
16619 EVT ToVT = Trunc.getValueType();
16620 if (!ToVT.isVector())
16621 return SDValue();
16622 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
16623 EVT ToEltVT = ToVT.getVectorElementType();
16624 EVT FromEltVT = FromVT.getVectorElementType();
16625
16626 if (FromEltVT != MVT::f32 || ToEltVT != MVT::f16)
16627 return SDValue();
16628
16629 unsigned NumElements = 4;
16630 if (FromVT.getVectorNumElements() % NumElements != 0)
16631 return SDValue();
16632
16633 // Test if the Trunc will be convertible to a VMOVN with a shuffle, and if so
16634 // use the VMOVN over splitting the store. We are looking for patterns of:
16635 // !rev: 0 N 1 N+1 2 N+2 ...
16636 // rev: N 0 N+1 1 N+2 2 ...
16637 // The shuffle may either be a single source (in which case N = NumElts/2) or
16638 // two inputs extended with concat to the same size (in which case N =
16639 // NumElts).
16640 auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) {
16641 ArrayRef<int> M = SVN->getMask();
16642 unsigned NumElts = ToVT.getVectorNumElements();
16643 if (SVN->getOperand(Num: 1).isUndef())
16644 NumElts /= 2;
16645
16646 unsigned Off0 = Rev ? NumElts : 0;
16647 unsigned Off1 = Rev ? 0 : NumElts;
16648
16649 for (unsigned I = 0; I < NumElts; I += 2) {
16650 if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2))
16651 return false;
16652 if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2))
16653 return false;
16654 }
16655
16656 return true;
16657 };
16658
16659 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Val: Trunc.getOperand(i: 0)))
16660 if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true))
16661 return SDValue();
16662
16663 LLVMContext &C = *DAG.getContext();
16664 SDLoc DL(St);
16665 // Details about the old store
16666 SDValue Ch = St->getChain();
16667 SDValue BasePtr = St->getBasePtr();
16668 Align Alignment = St->getBaseAlign();
16669 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16670 AAMDNodes AAInfo = St->getAAInfo();
16671
16672 // We split the store into slices of NumElements. fp16 trunc stores are vcvt
16673 // and then stored as truncating integer stores.
16674 EVT NewFromVT = EVT::getVectorVT(Context&: C, VT: FromEltVT, NumElements);
16675 EVT NewToVT = EVT::getVectorVT(
16676 Context&: C, VT: EVT::getIntegerVT(Context&: C, BitWidth: ToEltVT.getSizeInBits()), NumElements);
16677
16678 SmallVector<SDValue, 4> Stores;
16679 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
16680 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
16681 SDValue NewPtr =
16682 DAG.getObjectPtrOffset(SL: DL, Ptr: BasePtr, Offset: TypeSize::getFixed(ExactSize: NewOffset));
16683
16684 SDValue Extract =
16685 DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: NewFromVT, N1: Trunc.getOperand(i: 0),
16686 N2: DAG.getConstant(Val: i * NumElements, DL, VT: MVT::i32));
16687
16688 SDValue FPTrunc =
16689 DAG.getNode(Opcode: ARMISD::VCVTN, DL, VT: MVT::v8f16, N1: DAG.getUNDEF(VT: MVT::v8f16),
16690 N2: Extract, N3: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
16691 Extract = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT: MVT::v4i32, Operand: FPTrunc);
16692
16693 SDValue Store = DAG.getTruncStore(
16694 Chain: Ch, dl: DL, Val: Extract, Ptr: NewPtr, PtrInfo: St->getPointerInfo().getWithOffset(O: NewOffset),
16695 SVT: NewToVT, Alignment, MMOFlags, AAInfo);
16696 Stores.push_back(Elt: Store);
16697 }
16698 return DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Stores);
16699}
16700
16701// Try taking a single vector store from an MVETRUNC (which would otherwise turn
16702// into an expensive buildvector) and splitting it into a series of narrowing
16703// stores.
16704static SDValue PerformSplittingMVETruncToNarrowingStores(StoreSDNode *St,
16705 SelectionDAG &DAG) {
16706 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16707 return SDValue();
16708 SDValue Trunc = St->getValue();
16709 if (Trunc->getOpcode() != ARMISD::MVETRUNC)
16710 return SDValue();
16711 EVT FromVT = Trunc->getOperand(Num: 0).getValueType();
16712 EVT ToVT = Trunc.getValueType();
16713
16714 LLVMContext &C = *DAG.getContext();
16715 SDLoc DL(St);
16716 // Details about the old store
16717 SDValue Ch = St->getChain();
16718 SDValue BasePtr = St->getBasePtr();
16719 Align Alignment = St->getBaseAlign();
16720 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16721 AAMDNodes AAInfo = St->getAAInfo();
16722
16723 EVT NewToVT = EVT::getVectorVT(Context&: C, VT: ToVT.getVectorElementType(),
16724 NumElements: FromVT.getVectorNumElements());
16725
16726 SmallVector<SDValue, 4> Stores;
16727 for (unsigned i = 0; i < Trunc.getNumOperands(); i++) {
16728 unsigned NewOffset =
16729 i * FromVT.getVectorNumElements() * ToVT.getScalarSizeInBits() / 8;
16730 SDValue NewPtr =
16731 DAG.getObjectPtrOffset(SL: DL, Ptr: BasePtr, Offset: TypeSize::getFixed(ExactSize: NewOffset));
16732
16733 SDValue Extract = Trunc.getOperand(i);
16734 SDValue Store = DAG.getTruncStore(
16735 Chain: Ch, dl: DL, Val: Extract, Ptr: NewPtr, PtrInfo: St->getPointerInfo().getWithOffset(O: NewOffset),
16736 SVT: NewToVT, Alignment, MMOFlags, AAInfo);
16737 Stores.push_back(Elt: Store);
16738 }
16739 return DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Stores);
16740}
16741
16742// Given a floating point store from an extracted vector, with an integer
16743// VGETLANE that already exists, store the existing VGETLANEu directly. This can
16744// help reduce fp register pressure, doesn't require the fp extract and allows
16745// use of more integer post-inc stores not available with vstr.
16746static SDValue PerformExtractFpToIntStores(StoreSDNode *St, SelectionDAG &DAG) {
16747 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16748 return SDValue();
16749 SDValue Extract = St->getValue();
16750 EVT VT = Extract.getValueType();
16751 // For now only uses f16. This may be useful for f32 too, but that will
16752 // be bitcast(extract), not the VGETLANEu we currently check here.
16753 if (VT != MVT::f16 || Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16754 return SDValue();
16755
16756 SDNode *GetLane =
16757 DAG.getNodeIfExists(Opcode: ARMISD::VGETLANEu, VTList: DAG.getVTList(VT: MVT::i32),
16758 Ops: {Extract.getOperand(i: 0), Extract.getOperand(i: 1)});
16759 if (!GetLane)
16760 return SDValue();
16761
16762 LLVMContext &C = *DAG.getContext();
16763 SDLoc DL(St);
16764 // Create a new integer store to replace the existing floating point version.
16765 SDValue Ch = St->getChain();
16766 SDValue BasePtr = St->getBasePtr();
16767 Align Alignment = St->getBaseAlign();
16768 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16769 AAMDNodes AAInfo = St->getAAInfo();
16770 EVT NewToVT = EVT::getIntegerVT(Context&: C, BitWidth: VT.getSizeInBits());
16771 SDValue Store = DAG.getTruncStore(Chain: Ch, dl: DL, Val: SDValue(GetLane, 0), Ptr: BasePtr,
16772 PtrInfo: St->getPointerInfo(), SVT: NewToVT, Alignment,
16773 MMOFlags, AAInfo);
16774
16775 return Store;
16776}
16777
16778/// PerformSTORECombine - Target-specific dag combine xforms for
16779/// ISD::STORE.
16780static SDValue PerformSTORECombine(SDNode *N,
16781 TargetLowering::DAGCombinerInfo &DCI,
16782 const ARMSubtarget *Subtarget) {
16783 StoreSDNode *St = cast<StoreSDNode>(Val: N);
16784 if (St->isVolatile())
16785 return SDValue();
16786 SDValue StVal = St->getValue();
16787 EVT VT = StVal.getValueType();
16788
16789 if (Subtarget->hasNEON())
16790 if (SDValue Store = PerformTruncatingStoreCombine(St, DAG&: DCI.DAG))
16791 return Store;
16792
16793 if (Subtarget->hasMVEFloatOps())
16794 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DAG&: DCI.DAG))
16795 return NewToken;
16796
16797 if (Subtarget->hasMVEIntegerOps()) {
16798 if (SDValue NewChain = PerformExtractFpToIntStores(St, DAG&: DCI.DAG))
16799 return NewChain;
16800 if (SDValue NewToken =
16801 PerformSplittingMVETruncToNarrowingStores(St, DAG&: DCI.DAG))
16802 return NewToken;
16803 }
16804
16805 if (!ISD::isNormalStore(N: St))
16806 return SDValue();
16807
16808 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
16809 // ARM stores of arguments in the same cache line.
16810 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
16811 StVal.getNode()->hasOneUse()) {
16812 SelectionDAG &DAG = DCI.DAG;
16813 bool isBigEndian = DAG.getDataLayout().isBigEndian();
16814 SDLoc DL(St);
16815 SDValue BasePtr = St->getBasePtr();
16816 SDValue NewST1 = DAG.getStore(
16817 Chain: St->getChain(), dl: DL, Val: StVal.getNode()->getOperand(Num: isBigEndian ? 1 : 0),
16818 Ptr: BasePtr, PtrInfo: St->getPointerInfo(), Alignment: St->getBaseAlign(),
16819 MMOFlags: St->getMemOperand()->getFlags());
16820
16821 SDValue OffsetPtr = DAG.getNode(Opcode: ISD::ADD, DL, VT: MVT::i32, N1: BasePtr,
16822 N2: DAG.getConstant(Val: 4, DL, VT: MVT::i32));
16823 return DAG.getStore(Chain: NewST1.getValue(R: 0), dl: DL,
16824 Val: StVal.getNode()->getOperand(Num: isBigEndian ? 0 : 1),
16825 Ptr: OffsetPtr, PtrInfo: St->getPointerInfo().getWithOffset(O: 4),
16826 Alignment: St->getBaseAlign(), MMOFlags: St->getMemOperand()->getFlags());
16827 }
16828
16829 if (StVal.getValueType() == MVT::i64 &&
16830 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16831
16832 // Bitcast an i64 store extracted from a vector to f64.
16833 // Otherwise, the i64 value will be legalized to a pair of i32 values.
16834 SelectionDAG &DAG = DCI.DAG;
16835 SDLoc dl(StVal);
16836 SDValue IntVec = StVal.getOperand(i: 0);
16837 EVT FloatVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: MVT::f64,
16838 NumElements: IntVec.getValueType().getVectorNumElements());
16839 SDValue Vec = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: FloatVT, Operand: IntVec);
16840 SDValue ExtElt = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: dl, VT: MVT::f64,
16841 N1: Vec, N2: StVal.getOperand(i: 1));
16842 dl = SDLoc(N);
16843 SDValue V = DAG.getNode(Opcode: ISD::BITCAST, DL: dl, VT: MVT::i64, Operand: ExtElt);
16844 // Make the DAGCombiner fold the bitcasts.
16845 DCI.AddToWorklist(N: Vec.getNode());
16846 DCI.AddToWorklist(N: ExtElt.getNode());
16847 DCI.AddToWorklist(N: V.getNode());
16848 return DAG.getStore(Chain: St->getChain(), dl, Val: V, Ptr: St->getBasePtr(),
16849 PtrInfo: St->getPointerInfo(), Alignment: St->getAlign(),
16850 MMOFlags: St->getMemOperand()->getFlags(), AAInfo: St->getAAInfo());
16851 }
16852
16853 // If this is a legal vector store, try to combine it into a VST1_UPD.
16854 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
16855 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16856 return CombineBaseUpdate(N, DCI);
16857
16858 return SDValue();
16859}
16860
16861/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
16862/// can replace combinations of VMUL and VCVT (floating-point to integer)
16863/// when the VMUL has a constant operand that is a power of 2.
16864///
16865/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
16866/// vmul.f32 d16, d17, d16
16867/// vcvt.s32.f32 d16, d16
16868/// becomes:
16869/// vcvt.s32.f32 d16, d16, #3
16870static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
16871 const ARMSubtarget *Subtarget) {
16872 if (!Subtarget->hasNEON())
16873 return SDValue();
16874
16875 SDValue Op = N->getOperand(Num: 0);
16876 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
16877 Op.getOpcode() != ISD::FMUL)
16878 return SDValue();
16879
16880 SDValue ConstVec = Op->getOperand(Num: 1);
16881 if (!isa<BuildVectorSDNode>(Val: ConstVec))
16882 return SDValue();
16883
16884 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
16885 uint32_t FloatBits = FloatTy.getSizeInBits();
16886 MVT IntTy = N->getSimpleValueType(ResNo: 0).getVectorElementType();
16887 uint32_t IntBits = IntTy.getSizeInBits();
16888 unsigned NumLanes = Op.getValueType().getVectorNumElements();
16889 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
16890 // These instructions only exist converting from f32 to i32. We can handle
16891 // smaller integers by generating an extra truncate, but larger ones would
16892 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
16893 // these instructions only support v2i32/v4i32 types.
16894 return SDValue();
16895 }
16896
16897 BitVector UndefElements;
16898 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Val&: ConstVec);
16899 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(UndefElements: &UndefElements, BitWidth: 33);
16900 if (C == -1 || C == 0 || C > 32)
16901 return SDValue();
16902
16903 SDLoc dl(N);
16904 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
16905 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
16906 Intrinsic::arm_neon_vcvtfp2fxu;
16907 SDValue FixConv = DAG.getNode(
16908 Opcode: ISD::INTRINSIC_WO_CHAIN, DL: dl, VT: NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
16909 N1: DAG.getConstant(Val: IntrinsicOpcode, DL: dl, VT: MVT::i32), N2: Op->getOperand(Num: 0),
16910 N3: DAG.getConstant(Val: C, DL: dl, VT: MVT::i32));
16911
16912 if (IntBits < FloatBits)
16913 FixConv = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: N->getValueType(ResNo: 0), Operand: FixConv);
16914
16915 return FixConv;
16916}
16917
16918static SDValue PerformFAddVSelectCombine(SDNode *N, SelectionDAG &DAG,
16919 const ARMSubtarget *Subtarget) {
16920 if (!Subtarget->hasMVEFloatOps())
16921 return SDValue();
16922
16923 // Turn (fadd x, (vselect c, y, -0.0)) into (vselect c, (fadd x, y), x)
16924 // The second form can be more easily turned into a predicated vadd, and
16925 // possibly combined into a fma to become a predicated vfma.
16926 SDValue Op0 = N->getOperand(Num: 0);
16927 SDValue Op1 = N->getOperand(Num: 1);
16928 EVT VT = N->getValueType(ResNo: 0);
16929 SDLoc DL(N);
16930
16931 // The identity element for a fadd is -0.0 or +0.0 when the nsz flag is set,
16932 // which these VMOV's represent.
16933 auto isIdentitySplat = [&](SDValue Op, bool NSZ) {
16934 if (Op.getOpcode() != ISD::BITCAST ||
16935 Op.getOperand(i: 0).getOpcode() != ARMISD::VMOVIMM)
16936 return false;
16937 uint64_t ImmVal = Op.getOperand(i: 0).getConstantOperandVal(i: 0);
16938 if (VT == MVT::v4f32 && (ImmVal == 1664 || (ImmVal == 0 && NSZ)))
16939 return true;
16940 if (VT == MVT::v8f16 && (ImmVal == 2688 || (ImmVal == 0 && NSZ)))
16941 return true;
16942 return false;
16943 };
16944
16945 if (Op0.getOpcode() == ISD::VSELECT && Op1.getOpcode() != ISD::VSELECT)
16946 std::swap(a&: Op0, b&: Op1);
16947
16948 if (Op1.getOpcode() != ISD::VSELECT)
16949 return SDValue();
16950
16951 SDNodeFlags FaddFlags = N->getFlags();
16952 bool NSZ = FaddFlags.hasNoSignedZeros();
16953 if (!isIdentitySplat(Op1.getOperand(i: 2), NSZ))
16954 return SDValue();
16955
16956 SDValue FAdd =
16957 DAG.getNode(Opcode: ISD::FADD, DL, VT, N1: Op0, N2: Op1.getOperand(i: 1), Flags: FaddFlags);
16958 return DAG.getNode(Opcode: ISD::VSELECT, DL, VT, N1: Op1.getOperand(i: 0), N2: FAdd, N3: Op0, Flags: FaddFlags);
16959}
16960
16961static SDValue PerformFADDVCMLACombine(SDNode *N, SelectionDAG &DAG) {
16962 SDValue LHS = N->getOperand(Num: 0);
16963 SDValue RHS = N->getOperand(Num: 1);
16964 EVT VT = N->getValueType(ResNo: 0);
16965 SDLoc DL(N);
16966
16967 if (!N->getFlags().hasAllowReassociation())
16968 return SDValue();
16969
16970 // Combine fadd(a, vcmla(b, c, d)) -> vcmla(fadd(a, b), b, c)
16971 auto ReassocComplex = [&](SDValue A, SDValue B) {
16972 if (A.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
16973 return SDValue();
16974 unsigned Opc = A.getConstantOperandVal(i: 0);
16975 if (Opc != Intrinsic::arm_mve_vcmlaq)
16976 return SDValue();
16977 SDValue VCMLA = DAG.getNode(
16978 Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT, N1: A.getOperand(i: 0), N2: A.getOperand(i: 1),
16979 N3: DAG.getNode(Opcode: ISD::FADD, DL, VT, N1: A.getOperand(i: 2), N2: B, Flags: N->getFlags()),
16980 N4: A.getOperand(i: 3), N5: A.getOperand(i: 4));
16981 VCMLA->setFlags(A->getFlags());
16982 return VCMLA;
16983 };
16984 if (SDValue R = ReassocComplex(LHS, RHS))
16985 return R;
16986 if (SDValue R = ReassocComplex(RHS, LHS))
16987 return R;
16988
16989 return SDValue();
16990}
16991
16992static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16993 const ARMSubtarget *Subtarget) {
16994 if (SDValue S = PerformFAddVSelectCombine(N, DAG, Subtarget))
16995 return S;
16996 if (SDValue S = PerformFADDVCMLACombine(N, DAG))
16997 return S;
16998 return SDValue();
16999}
17000
17001/// PerformVMulVCTPCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
17002/// can replace combinations of VCVT (integer to floating-point) and VMUL
17003/// when the VMUL has a constant operand that is a power of 2.
17004///
17005/// Example (assume d17 = <float 0.125, float 0.125>):
17006/// vcvt.f32.s32 d16, d16
17007/// vmul.f32 d16, d16, d17
17008/// becomes:
17009/// vcvt.f32.s32 d16, d16, #3
17010static SDValue PerformVMulVCTPCombine(SDNode *N, SelectionDAG &DAG,
17011 const ARMSubtarget *Subtarget) {
17012 if (!Subtarget->hasNEON())
17013 return SDValue();
17014
17015 SDValue Op = N->getOperand(Num: 0);
17016 unsigned OpOpcode = Op.getNode()->getOpcode();
17017 if (!N->getValueType(ResNo: 0).isVector() || !N->getValueType(ResNo: 0).isSimple() ||
17018 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
17019 return SDValue();
17020
17021 SDValue ConstVec = N->getOperand(Num: 1);
17022 if (!isa<BuildVectorSDNode>(Val: ConstVec))
17023 return SDValue();
17024
17025 MVT FloatTy = N->getSimpleValueType(ResNo: 0).getVectorElementType();
17026 uint32_t FloatBits = FloatTy.getSizeInBits();
17027 MVT IntTy = Op.getOperand(i: 0).getSimpleValueType().getVectorElementType();
17028 uint32_t IntBits = IntTy.getSizeInBits();
17029 unsigned NumLanes = Op.getValueType().getVectorNumElements();
17030 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
17031 // These instructions only exist converting from i32 to f32. We can handle
17032 // smaller integers by generating an extra extend, but larger ones would
17033 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
17034 // these instructions only support v2i32/v4i32 types.
17035 return SDValue();
17036 }
17037
17038 ConstantFPSDNode *CN = isConstOrConstSplatFP(N: ConstVec, AllowUndefs: true);
17039 APFloat Recip(0.0f);
17040 if (!CN || !CN->getValueAPF().getExactInverse(Inv: &Recip))
17041 return SDValue();
17042
17043 bool IsExact;
17044 APSInt IntVal(33);
17045 if (Recip.convertToInteger(Result&: IntVal, RM: APFloat::rmTowardZero, IsExact: &IsExact) !=
17046 APFloat::opOK ||
17047 !IsExact)
17048 return SDValue();
17049
17050 int32_t C = IntVal.exactLogBase2();
17051 if (C == -1 || C == 0 || C > 32)
17052 return SDValue();
17053
17054 SDLoc DL(N);
17055 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
17056 SDValue ConvInput = Op.getOperand(i: 0);
17057 if (IntBits < FloatBits)
17058 ConvInput = DAG.getNode(Opcode: isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
17059 VT: NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, Operand: ConvInput);
17060
17061 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp
17062 : Intrinsic::arm_neon_vcvtfxu2fp;
17063 return DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT: Op.getValueType(),
17064 N1: DAG.getConstant(Val: IntrinsicOpcode, DL, VT: MVT::i32), N2: ConvInput,
17065 N3: DAG.getConstant(Val: C, DL, VT: MVT::i32));
17066}
17067
17068static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
17069 const ARMSubtarget *ST) {
17070 if (!ST->hasMVEIntegerOps())
17071 return SDValue();
17072
17073 assert(N->getOpcode() == ISD::VECREDUCE_ADD);
17074 EVT ResVT = N->getValueType(ResNo: 0);
17075 SDValue N0 = N->getOperand(Num: 0);
17076 SDLoc dl(N);
17077
17078 // Try to turn vecreduce_add(add(x, y)) into vecreduce(x) + vecreduce(y)
17079 if (ResVT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
17080 (N0.getValueType() == MVT::v4i32 || N0.getValueType() == MVT::v8i16 ||
17081 N0.getValueType() == MVT::v16i8)) {
17082 SDValue Red0 = DAG.getNode(Opcode: ISD::VECREDUCE_ADD, DL: dl, VT: ResVT, Operand: N0.getOperand(i: 0));
17083 SDValue Red1 = DAG.getNode(Opcode: ISD::VECREDUCE_ADD, DL: dl, VT: ResVT, Operand: N0.getOperand(i: 1));
17084 return DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: ResVT, N1: Red0, N2: Red1);
17085 }
17086
17087 // We are looking for something that will have illegal types if left alone,
17088 // but that we can convert to a single instruction under MVE. For example
17089 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
17090 // or
17091 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
17092
17093 // The legal cases are:
17094 // VADDV u/s 8/16/32
17095 // VMLAV u/s 8/16/32
17096 // VADDLV u/s 32
17097 // VMLALV u/s 16/32
17098
17099 // If the input vector is smaller than legal (v4i8/v4i16 for example) we can
17100 // extend it and use v4i32 instead.
17101 auto ExtTypeMatches = [](SDValue A, ArrayRef<MVT> ExtTypes) {
17102 EVT AVT = A.getValueType();
17103 return any_of(Range&: ExtTypes, P: [&](MVT Ty) {
17104 return AVT.getVectorNumElements() == Ty.getVectorNumElements() &&
17105 AVT.bitsLE(VT: Ty);
17106 });
17107 };
17108 auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) {
17109 EVT AVT = A.getValueType();
17110 if (!AVT.is128BitVector())
17111 A = DAG.getNode(
17112 Opcode: ExtendCode, DL: dl,
17113 VT: AVT.changeVectorElementType(
17114 Context&: *DAG.getContext(),
17115 EltVT: MVT::getIntegerVT(BitWidth: 128 / AVT.getVectorMinNumElements())),
17116 Operand: A);
17117 return A;
17118 };
17119 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
17120 if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
17121 return SDValue();
17122 SDValue A = N0->getOperand(Num: 0);
17123 if (ExtTypeMatches(A, ExtTypes))
17124 return ExtendIfNeeded(A, ExtendCode);
17125 return SDValue();
17126 };
17127 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
17128 ArrayRef<MVT> ExtTypes, SDValue &Mask) {
17129 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17130 !ISD::isBuildVectorAllZeros(N: N0->getOperand(Num: 2).getNode()))
17131 return SDValue();
17132 Mask = N0->getOperand(Num: 0);
17133 SDValue Ext = N0->getOperand(Num: 1);
17134 if (Ext->getOpcode() != ExtendCode)
17135 return SDValue();
17136 SDValue A = Ext->getOperand(Num: 0);
17137 if (ExtTypeMatches(A, ExtTypes))
17138 return ExtendIfNeeded(A, ExtendCode);
17139 return SDValue();
17140 };
17141 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17142 SDValue &A, SDValue &B) {
17143 // For a vmla we are trying to match a larger pattern:
17144 // ExtA = sext/zext A
17145 // ExtB = sext/zext B
17146 // Mul = mul ExtA, ExtB
17147 // vecreduce.add Mul
17148 // There might also be en extra extend between the mul and the addreduce, so
17149 // long as the bitwidth is high enough to make them equivalent (for example
17150 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
17151 if (ResVT != RetTy)
17152 return false;
17153 SDValue Mul = N0;
17154 if (Mul->getOpcode() == ExtendCode &&
17155 Mul->getOperand(Num: 0).getScalarValueSizeInBits() * 2 >=
17156 ResVT.getScalarSizeInBits())
17157 Mul = Mul->getOperand(Num: 0);
17158 if (Mul->getOpcode() != ISD::MUL)
17159 return false;
17160 SDValue ExtA = Mul->getOperand(Num: 0);
17161 SDValue ExtB = Mul->getOperand(Num: 1);
17162 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17163 return false;
17164 A = ExtA->getOperand(Num: 0);
17165 B = ExtB->getOperand(Num: 0);
17166 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17167 A = ExtendIfNeeded(A, ExtendCode);
17168 B = ExtendIfNeeded(B, ExtendCode);
17169 return true;
17170 }
17171 return false;
17172 };
17173 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17174 SDValue &A, SDValue &B, SDValue &Mask) {
17175 // Same as the pattern above with a select for the zero predicated lanes
17176 // ExtA = sext/zext A
17177 // ExtB = sext/zext B
17178 // Mul = mul ExtA, ExtB
17179 // N0 = select Mask, Mul, 0
17180 // vecreduce.add N0
17181 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17182 !ISD::isBuildVectorAllZeros(N: N0->getOperand(Num: 2).getNode()))
17183 return false;
17184 Mask = N0->getOperand(Num: 0);
17185 SDValue Mul = N0->getOperand(Num: 1);
17186 if (Mul->getOpcode() == ExtendCode &&
17187 Mul->getOperand(Num: 0).getScalarValueSizeInBits() * 2 >=
17188 ResVT.getScalarSizeInBits())
17189 Mul = Mul->getOperand(Num: 0);
17190 if (Mul->getOpcode() != ISD::MUL)
17191 return false;
17192 SDValue ExtA = Mul->getOperand(Num: 0);
17193 SDValue ExtB = Mul->getOperand(Num: 1);
17194 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17195 return false;
17196 A = ExtA->getOperand(Num: 0);
17197 B = ExtB->getOperand(Num: 0);
17198 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17199 A = ExtendIfNeeded(A, ExtendCode);
17200 B = ExtendIfNeeded(B, ExtendCode);
17201 return true;
17202 }
17203 return false;
17204 };
17205 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
17206 // Split illegal MVT::v16i8->i64 vector reductions into two legal v8i16->i64
17207 // reductions. The operands are extended with MVEEXT, but as they are
17208 // reductions the lane orders do not matter. MVEEXT may be combined with
17209 // loads to produce two extending loads, or else they will be expanded to
17210 // VREV/VMOVL.
17211 EVT VT = Ops[0].getValueType();
17212 if (VT == MVT::v16i8) {
17213 assert((Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) &&
17214 "Unexpected illegal long reduction opcode");
17215 bool IsUnsigned = Opcode == ARMISD::VMLALVu;
17216
17217 SDValue Ext0 =
17218 DAG.getNode(Opcode: IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, DL: dl,
17219 VTList: DAG.getVTList(VT1: MVT::v8i16, VT2: MVT::v8i16), N: Ops[0]);
17220 SDValue Ext1 =
17221 DAG.getNode(Opcode: IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, DL: dl,
17222 VTList: DAG.getVTList(VT1: MVT::v8i16, VT2: MVT::v8i16), N: Ops[1]);
17223
17224 SDValue MLA0 = DAG.getNode(Opcode, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
17225 N1: Ext0, N2: Ext1);
17226 SDValue MLA1 =
17227 DAG.getNode(Opcode: IsUnsigned ? ARMISD::VMLALVAu : ARMISD::VMLALVAs, DL: dl,
17228 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N1: MLA0, N2: MLA0.getValue(R: 1),
17229 N3: Ext0.getValue(R: 1), N4: Ext1.getValue(R: 1));
17230 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: MLA1, N2: MLA1.getValue(R: 1));
17231 }
17232 SDValue Node = DAG.getNode(Opcode, DL: dl, ResultTys: {MVT::i32, MVT::i32}, Ops);
17233 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Node,
17234 N2: SDValue(Node.getNode(), 1));
17235 };
17236
17237 SDValue A, B;
17238 SDValue Mask;
17239 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17240 return DAG.getNode(Opcode: ARMISD::VMLAVs, DL: dl, VT: ResVT, N1: A, N2: B);
17241 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17242 return DAG.getNode(Opcode: ARMISD::VMLAVu, DL: dl, VT: ResVT, N1: A, N2: B);
17243 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17244 A, B))
17245 return Create64bitNode(ARMISD::VMLALVs, {A, B});
17246 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17247 A, B))
17248 return Create64bitNode(ARMISD::VMLALVu, {A, B});
17249 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
17250 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17251 Operand: DAG.getNode(Opcode: ARMISD::VMLAVs, DL: dl, VT: MVT::i32, N1: A, N2: B));
17252 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
17253 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17254 Operand: DAG.getNode(Opcode: ARMISD::VMLAVu, DL: dl, VT: MVT::i32, N1: A, N2: B));
17255
17256 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17257 Mask))
17258 return DAG.getNode(Opcode: ARMISD::VMLAVps, DL: dl, VT: ResVT, N1: A, N2: B, N3: Mask);
17259 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17260 Mask))
17261 return DAG.getNode(Opcode: ARMISD::VMLAVpu, DL: dl, VT: ResVT, N1: A, N2: B, N3: Mask);
17262 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17263 Mask))
17264 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
17265 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17266 Mask))
17267 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
17268 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
17269 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17270 Operand: DAG.getNode(Opcode: ARMISD::VMLAVps, DL: dl, VT: MVT::i32, N1: A, N2: B, N3: Mask));
17271 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
17272 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17273 Operand: DAG.getNode(Opcode: ARMISD::VMLAVpu, DL: dl, VT: MVT::i32, N1: A, N2: B, N3: Mask));
17274
17275 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
17276 return DAG.getNode(Opcode: ARMISD::VADDVs, DL: dl, VT: ResVT, Operand: A);
17277 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
17278 return DAG.getNode(Opcode: ARMISD::VADDVu, DL: dl, VT: ResVT, Operand: A);
17279 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
17280 return Create64bitNode(ARMISD::VADDLVs, {A});
17281 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
17282 return Create64bitNode(ARMISD::VADDLVu, {A});
17283 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
17284 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17285 Operand: DAG.getNode(Opcode: ARMISD::VADDVs, DL: dl, VT: MVT::i32, Operand: A));
17286 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
17287 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17288 Operand: DAG.getNode(Opcode: ARMISD::VADDVu, DL: dl, VT: MVT::i32, Operand: A));
17289
17290 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17291 return DAG.getNode(Opcode: ARMISD::VADDVps, DL: dl, VT: ResVT, N1: A, N2: Mask);
17292 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17293 return DAG.getNode(Opcode: ARMISD::VADDVpu, DL: dl, VT: ResVT, N1: A, N2: Mask);
17294 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
17295 return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
17296 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
17297 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
17298 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
17299 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17300 Operand: DAG.getNode(Opcode: ARMISD::VADDVps, DL: dl, VT: MVT::i32, N1: A, N2: Mask));
17301 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
17302 return DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: ResVT,
17303 Operand: DAG.getNode(Opcode: ARMISD::VADDVpu, DL: dl, VT: MVT::i32, N1: A, N2: Mask));
17304
17305 // Some complications. We can get a case where the two inputs of the mul are
17306 // the same, then the output sext will have been helpfully converted to a
17307 // zext. Turn it back.
17308 SDValue Op = N0;
17309 if (Op->getOpcode() == ISD::VSELECT)
17310 Op = Op->getOperand(Num: 1);
17311 if (Op->getOpcode() == ISD::ZERO_EXTEND &&
17312 Op->getOperand(Num: 0)->getOpcode() == ISD::MUL) {
17313 SDValue Mul = Op->getOperand(Num: 0);
17314 if (Mul->getOperand(Num: 0) == Mul->getOperand(Num: 1) &&
17315 Mul->getOperand(Num: 0)->getOpcode() == ISD::SIGN_EXTEND) {
17316 SDValue Ext = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: N0->getValueType(ResNo: 0), Operand: Mul);
17317 if (Op != N0)
17318 Ext = DAG.getNode(Opcode: ISD::VSELECT, DL: dl, VT: N0->getValueType(ResNo: 0),
17319 N1: N0->getOperand(Num: 0), N2: Ext, N3: N0->getOperand(Num: 2));
17320 return DAG.getNode(Opcode: ISD::VECREDUCE_ADD, DL: dl, VT: ResVT, Operand: Ext);
17321 }
17322 }
17323
17324 return SDValue();
17325}
17326
17327// Looks for vaddv(shuffle) or vmlav(shuffle, shuffle), with a shuffle where all
17328// the lanes are used. Due to the reduction being commutative the shuffle can be
17329// removed.
17330static SDValue PerformReduceShuffleCombine(SDNode *N, SelectionDAG &DAG) {
17331 unsigned VecOp = N->getOperand(Num: 0).getValueType().isVector() ? 0 : 2;
17332 auto *Shuf = dyn_cast<ShuffleVectorSDNode>(Val: N->getOperand(Num: VecOp));
17333 if (!Shuf || !Shuf->getOperand(Num: 1).isUndef())
17334 return SDValue();
17335
17336 // Check all elements are used once in the mask.
17337 ArrayRef<int> Mask = Shuf->getMask();
17338 APInt SetElts(Mask.size(), 0);
17339 for (int E : Mask) {
17340 if (E < 0 || E >= (int)Mask.size())
17341 return SDValue();
17342 SetElts.setBit(E);
17343 }
17344 if (!SetElts.isAllOnes())
17345 return SDValue();
17346
17347 if (N->getNumOperands() != VecOp + 1) {
17348 auto *Shuf2 = dyn_cast<ShuffleVectorSDNode>(Val: N->getOperand(Num: VecOp + 1));
17349 if (!Shuf2 || !Shuf2->getOperand(Num: 1).isUndef() || Shuf2->getMask() != Mask)
17350 return SDValue();
17351 }
17352
17353 SmallVector<SDValue> Ops;
17354 for (SDValue Op : N->ops()) {
17355 if (Op.getValueType().isVector())
17356 Ops.push_back(Elt: Op.getOperand(i: 0));
17357 else
17358 Ops.push_back(Elt: Op);
17359 }
17360 return DAG.getNode(Opcode: N->getOpcode(), DL: SDLoc(N), VTList: N->getVTList(), Ops);
17361}
17362
17363static SDValue PerformVMOVNCombine(SDNode *N,
17364 TargetLowering::DAGCombinerInfo &DCI) {
17365 SDValue Op0 = N->getOperand(Num: 0);
17366 SDValue Op1 = N->getOperand(Num: 1);
17367 unsigned IsTop = N->getConstantOperandVal(Num: 2);
17368
17369 // VMOVNT a undef -> a
17370 // VMOVNB a undef -> a
17371 // VMOVNB undef a -> a
17372 if (Op1->isUndef())
17373 return Op0;
17374 if (Op0->isUndef() && !IsTop)
17375 return Op1;
17376
17377 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
17378 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
17379 if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
17380 Op1->getOpcode() == ARMISD::VQMOVNu) &&
17381 Op1->getConstantOperandVal(Num: 2) == 0)
17382 return DCI.DAG.getNode(Opcode: Op1->getOpcode(), DL: SDLoc(Op1), VT: N->getValueType(ResNo: 0),
17383 N1: Op0, N2: Op1->getOperand(Num: 1), N3: N->getOperand(Num: 2));
17384
17385 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
17386 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
17387 // into the top or bottom lanes.
17388 unsigned NumElts = N->getValueType(ResNo: 0).getVectorNumElements();
17389 APInt Op1DemandedElts = APInt::getSplat(NewLen: NumElts, V: APInt::getLowBitsSet(numBits: 2, loBitsSet: 1));
17390 APInt Op0DemandedElts =
17391 IsTop ? Op1DemandedElts
17392 : APInt::getSplat(NewLen: NumElts, V: APInt::getHighBitsSet(numBits: 2, hiBitsSet: 1));
17393
17394 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17395 if (TLI.SimplifyDemandedVectorElts(Op: Op0, DemandedElts: Op0DemandedElts, DCI))
17396 return SDValue(N, 0);
17397 if (TLI.SimplifyDemandedVectorElts(Op: Op1, DemandedElts: Op1DemandedElts, DCI))
17398 return SDValue(N, 0);
17399
17400 return SDValue();
17401}
17402
17403static SDValue PerformVQMOVNCombine(SDNode *N,
17404 TargetLowering::DAGCombinerInfo &DCI) {
17405 SDValue Op0 = N->getOperand(Num: 0);
17406 unsigned IsTop = N->getConstantOperandVal(Num: 2);
17407
17408 unsigned NumElts = N->getValueType(ResNo: 0).getVectorNumElements();
17409 APInt Op0DemandedElts =
17410 APInt::getSplat(NewLen: NumElts, V: IsTop ? APInt::getLowBitsSet(numBits: 2, loBitsSet: 1)
17411 : APInt::getHighBitsSet(numBits: 2, hiBitsSet: 1));
17412
17413 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17414 if (TLI.SimplifyDemandedVectorElts(Op: Op0, DemandedElts: Op0DemandedElts, DCI))
17415 return SDValue(N, 0);
17416 return SDValue();
17417}
17418
17419static SDValue PerformVQDMULHCombine(SDNode *N,
17420 TargetLowering::DAGCombinerInfo &DCI) {
17421 EVT VT = N->getValueType(ResNo: 0);
17422 SDValue LHS = N->getOperand(Num: 0);
17423 SDValue RHS = N->getOperand(Num: 1);
17424
17425 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(Val&: LHS);
17426 auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(Val&: RHS);
17427 // Turn VQDMULH(shuffle, shuffle) -> shuffle(VQDMULH)
17428 if (Shuf0 && Shuf1 && Shuf0->getMask().equals(RHS: Shuf1->getMask()) &&
17429 LHS.getOperand(i: 1).isUndef() && RHS.getOperand(i: 1).isUndef() &&
17430 (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
17431 SDLoc DL(N);
17432 SDValue NewBinOp = DCI.DAG.getNode(Opcode: N->getOpcode(), DL, VT,
17433 N1: LHS.getOperand(i: 0), N2: RHS.getOperand(i: 0));
17434 SDValue UndefV = LHS.getOperand(i: 1);
17435 return DCI.DAG.getVectorShuffle(VT, dl: DL, N1: NewBinOp, N2: UndefV, Mask: Shuf0->getMask());
17436 }
17437 return SDValue();
17438}
17439
17440static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
17441 SDLoc DL(N);
17442 SDValue Op0 = N->getOperand(Num: 0);
17443 SDValue Op1 = N->getOperand(Num: 1);
17444
17445 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
17446 // uses of the intrinsics.
17447 if (auto C = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 2))) {
17448 int ShiftAmt = C->getSExtValue();
17449 if (ShiftAmt == 0) {
17450 SDValue Merge = DAG.getMergeValues(Ops: {Op0, Op1}, dl: DL);
17451 DAG.ReplaceAllUsesWith(From: N, To: Merge.getNode());
17452 return SDValue();
17453 }
17454
17455 if (ShiftAmt >= -32 && ShiftAmt < 0) {
17456 unsigned NewOpcode =
17457 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
17458 SDValue NewShift = DAG.getNode(Opcode: NewOpcode, DL, VTList: N->getVTList(), N1: Op0, N2: Op1,
17459 N3: DAG.getConstant(Val: -ShiftAmt, DL, VT: MVT::i32));
17460 DAG.ReplaceAllUsesWith(From: N, To: NewShift.getNode());
17461 return NewShift;
17462 }
17463 }
17464
17465 return SDValue();
17466}
17467
17468/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
17469SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
17470 DAGCombinerInfo &DCI) const {
17471 SelectionDAG &DAG = DCI.DAG;
17472 unsigned IntNo = N->getConstantOperandVal(Num: 0);
17473 switch (IntNo) {
17474 default:
17475 // Don't do anything for most intrinsics.
17476 break;
17477
17478 // Vector shifts: check for immediate versions and lower them.
17479 // Note: This is done during DAG combining instead of DAG legalizing because
17480 // the build_vectors for 64-bit vector element shift counts are generally
17481 // not legal, and it is hard to see their values after they get legalized to
17482 // loads from a constant pool.
17483 case Intrinsic::arm_neon_vshifts:
17484 case Intrinsic::arm_neon_vshiftu:
17485 case Intrinsic::arm_neon_vrshifts:
17486 case Intrinsic::arm_neon_vrshiftu:
17487 case Intrinsic::arm_neon_vrshiftn:
17488 case Intrinsic::arm_neon_vqshifts:
17489 case Intrinsic::arm_neon_vqshiftu:
17490 case Intrinsic::arm_neon_vqshiftsu:
17491 case Intrinsic::arm_neon_vqshiftns:
17492 case Intrinsic::arm_neon_vqshiftnu:
17493 case Intrinsic::arm_neon_vqshiftnsu:
17494 case Intrinsic::arm_neon_vqrshiftns:
17495 case Intrinsic::arm_neon_vqrshiftnu:
17496 case Intrinsic::arm_neon_vqrshiftnsu: {
17497 EVT VT = N->getOperand(Num: 1).getValueType();
17498 int64_t Cnt;
17499 unsigned VShiftOpc = 0;
17500
17501 switch (IntNo) {
17502 case Intrinsic::arm_neon_vshifts:
17503 case Intrinsic::arm_neon_vshiftu:
17504 if (isVShiftLImm(Op: N->getOperand(Num: 2), VT, isLong: false, Cnt)) {
17505 VShiftOpc = ARMISD::VSHLIMM;
17506 break;
17507 }
17508 if (isVShiftRImm(Op: N->getOperand(Num: 2), VT, isNarrow: false, isIntrinsic: true, Cnt)) {
17509 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
17510 : ARMISD::VSHRuIMM);
17511 break;
17512 }
17513 return SDValue();
17514
17515 case Intrinsic::arm_neon_vrshifts:
17516 case Intrinsic::arm_neon_vrshiftu:
17517 if (isVShiftRImm(Op: N->getOperand(Num: 2), VT, isNarrow: false, isIntrinsic: true, Cnt))
17518 break;
17519 return SDValue();
17520
17521 case Intrinsic::arm_neon_vqshifts:
17522 case Intrinsic::arm_neon_vqshiftu:
17523 if (isVShiftLImm(Op: N->getOperand(Num: 2), VT, isLong: false, Cnt))
17524 break;
17525 return SDValue();
17526
17527 case Intrinsic::arm_neon_vqshiftsu:
17528 if (isVShiftLImm(Op: N->getOperand(Num: 2), VT, isLong: false, Cnt))
17529 break;
17530 llvm_unreachable("invalid shift count for vqshlu intrinsic");
17531
17532 case Intrinsic::arm_neon_vrshiftn:
17533 case Intrinsic::arm_neon_vqshiftns:
17534 case Intrinsic::arm_neon_vqshiftnu:
17535 case Intrinsic::arm_neon_vqshiftnsu:
17536 case Intrinsic::arm_neon_vqrshiftns:
17537 case Intrinsic::arm_neon_vqrshiftnu:
17538 case Intrinsic::arm_neon_vqrshiftnsu:
17539 // Narrowing shifts require an immediate right shift.
17540 if (isVShiftRImm(Op: N->getOperand(Num: 2), VT, isNarrow: true, isIntrinsic: true, Cnt))
17541 break;
17542 llvm_unreachable("invalid shift count for narrowing vector shift "
17543 "intrinsic");
17544
17545 default:
17546 llvm_unreachable("unhandled vector shift");
17547 }
17548
17549 switch (IntNo) {
17550 case Intrinsic::arm_neon_vshifts:
17551 case Intrinsic::arm_neon_vshiftu:
17552 // Opcode already set above.
17553 break;
17554 case Intrinsic::arm_neon_vrshifts:
17555 VShiftOpc = ARMISD::VRSHRsIMM;
17556 break;
17557 case Intrinsic::arm_neon_vrshiftu:
17558 VShiftOpc = ARMISD::VRSHRuIMM;
17559 break;
17560 case Intrinsic::arm_neon_vrshiftn:
17561 VShiftOpc = ARMISD::VRSHRNIMM;
17562 break;
17563 case Intrinsic::arm_neon_vqshifts:
17564 VShiftOpc = ARMISD::VQSHLsIMM;
17565 break;
17566 case Intrinsic::arm_neon_vqshiftu:
17567 VShiftOpc = ARMISD::VQSHLuIMM;
17568 break;
17569 case Intrinsic::arm_neon_vqshiftsu:
17570 VShiftOpc = ARMISD::VQSHLsuIMM;
17571 break;
17572 case Intrinsic::arm_neon_vqshiftns:
17573 VShiftOpc = ARMISD::VQSHRNsIMM;
17574 break;
17575 case Intrinsic::arm_neon_vqshiftnu:
17576 VShiftOpc = ARMISD::VQSHRNuIMM;
17577 break;
17578 case Intrinsic::arm_neon_vqshiftnsu:
17579 VShiftOpc = ARMISD::VQSHRNsuIMM;
17580 break;
17581 case Intrinsic::arm_neon_vqrshiftns:
17582 VShiftOpc = ARMISD::VQRSHRNsIMM;
17583 break;
17584 case Intrinsic::arm_neon_vqrshiftnu:
17585 VShiftOpc = ARMISD::VQRSHRNuIMM;
17586 break;
17587 case Intrinsic::arm_neon_vqrshiftnsu:
17588 VShiftOpc = ARMISD::VQRSHRNsuIMM;
17589 break;
17590 }
17591
17592 SDLoc dl(N);
17593 return DAG.getNode(Opcode: VShiftOpc, DL: dl, VT: N->getValueType(ResNo: 0),
17594 N1: N->getOperand(Num: 1), N2: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
17595 }
17596
17597 case Intrinsic::arm_neon_vshiftins: {
17598 EVT VT = N->getOperand(Num: 1).getValueType();
17599 int64_t Cnt;
17600 unsigned VShiftOpc = 0;
17601
17602 if (isVShiftLImm(Op: N->getOperand(Num: 3), VT, isLong: false, Cnt))
17603 VShiftOpc = ARMISD::VSLIIMM;
17604 else if (isVShiftRImm(Op: N->getOperand(Num: 3), VT, isNarrow: false, isIntrinsic: true, Cnt))
17605 VShiftOpc = ARMISD::VSRIIMM;
17606 else {
17607 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
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: N->getOperand(Num: 2),
17613 N3: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
17614 }
17615
17616 case Intrinsic::arm_neon_vqrshifts:
17617 case Intrinsic::arm_neon_vqrshiftu:
17618 // No immediate versions of these to check for.
17619 break;
17620
17621 case Intrinsic::arm_neon_vbsl: {
17622 SDLoc dl(N);
17623 return DAG.getNode(Opcode: ARMISD::VBSP, DL: dl, VT: N->getValueType(ResNo: 0), N1: N->getOperand(Num: 1),
17624 N2: N->getOperand(Num: 2), N3: N->getOperand(Num: 3));
17625 }
17626 case Intrinsic::arm_mve_vqdmlah:
17627 case Intrinsic::arm_mve_vqdmlash:
17628 case Intrinsic::arm_mve_vqrdmlah:
17629 case Intrinsic::arm_mve_vqrdmlash:
17630 case Intrinsic::arm_mve_vmla_n_predicated:
17631 case Intrinsic::arm_mve_vmlas_n_predicated:
17632 case Intrinsic::arm_mve_vqdmlah_predicated:
17633 case Intrinsic::arm_mve_vqdmlash_predicated:
17634 case Intrinsic::arm_mve_vqrdmlah_predicated:
17635 case Intrinsic::arm_mve_vqrdmlash_predicated: {
17636 // These intrinsics all take an i32 scalar operand which is narrowed to the
17637 // size of a single lane of the vector type they return. So we don't need
17638 // any bits of that operand above that point, which allows us to eliminate
17639 // uxth/sxth.
17640 unsigned BitWidth = N->getValueType(ResNo: 0).getScalarSizeInBits();
17641 APInt DemandedMask = APInt::getLowBitsSet(numBits: 32, loBitsSet: BitWidth);
17642 if (SimplifyDemandedBits(Op: N->getOperand(Num: 3), DemandedBits: DemandedMask, DCI))
17643 return SDValue();
17644 break;
17645 }
17646
17647 case Intrinsic::arm_mve_minv:
17648 case Intrinsic::arm_mve_maxv:
17649 case Intrinsic::arm_mve_minav:
17650 case Intrinsic::arm_mve_maxav:
17651 case Intrinsic::arm_mve_minv_predicated:
17652 case Intrinsic::arm_mve_maxv_predicated:
17653 case Intrinsic::arm_mve_minav_predicated:
17654 case Intrinsic::arm_mve_maxav_predicated: {
17655 // These intrinsics all take an i32 scalar operand which is narrowed to the
17656 // size of a single lane of the vector type they take as the other input.
17657 unsigned BitWidth = N->getOperand(Num: 2)->getValueType(ResNo: 0).getScalarSizeInBits();
17658 APInt DemandedMask = APInt::getLowBitsSet(numBits: 32, loBitsSet: BitWidth);
17659 if (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI))
17660 return SDValue();
17661 break;
17662 }
17663
17664 case Intrinsic::arm_mve_addv: {
17665 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
17666 // which allow PerformADDVecReduce to turn it into VADDLV when possible.
17667 bool Unsigned = N->getConstantOperandVal(Num: 2);
17668 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
17669 return DAG.getNode(Opcode: Opc, DL: SDLoc(N), VTList: N->getVTList(), N: N->getOperand(Num: 1));
17670 }
17671
17672 case Intrinsic::arm_mve_addlv:
17673 case Intrinsic::arm_mve_addlv_predicated: {
17674 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
17675 // which recombines the two outputs into an i64
17676 bool Unsigned = N->getConstantOperandVal(Num: 2);
17677 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
17678 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
17679 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
17680
17681 SmallVector<SDValue, 4> Ops;
17682 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
17683 if (i != 2) // skip the unsigned flag
17684 Ops.push_back(Elt: N->getOperand(Num: i));
17685
17686 SDLoc dl(N);
17687 SDValue val = DAG.getNode(Opcode: Opc, DL: dl, ResultTys: {MVT::i32, MVT::i32}, Ops);
17688 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: val.getValue(R: 0),
17689 N2: val.getValue(R: 1));
17690 }
17691 }
17692
17693 return SDValue();
17694}
17695
17696/// PerformShiftCombine - Checks for immediate versions of vector shifts and
17697/// lowers them. As with the vector shift intrinsics, this is done during DAG
17698/// combining instead of DAG legalizing because the build_vectors for 64-bit
17699/// vector element shift counts are generally not legal, and it is hard to see
17700/// their values after they get legalized to loads from a constant pool.
17701static SDValue PerformShiftCombine(SDNode *N,
17702 TargetLowering::DAGCombinerInfo &DCI,
17703 const ARMSubtarget *ST) {
17704 SelectionDAG &DAG = DCI.DAG;
17705 EVT VT = N->getValueType(ResNo: 0);
17706
17707 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
17708 N->getOperand(Num: 0)->getOpcode() == ISD::AND &&
17709 N->getOperand(Num: 0)->hasOneUse()) {
17710 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17711 return SDValue();
17712 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
17713 // usually show up because instcombine prefers to canonicalize it to
17714 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
17715 // out of GEP lowering in some cases.
17716 SDValue N0 = N->getOperand(Num: 0);
17717 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
17718 if (!ShiftAmtNode)
17719 return SDValue();
17720 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
17721 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(Val: N0->getOperand(Num: 1));
17722 if (!AndMaskNode)
17723 return SDValue();
17724 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
17725 // Don't transform uxtb/uxth.
17726 if (AndMask == 255 || AndMask == 65535)
17727 return SDValue();
17728 if (isMask_32(Value: AndMask)) {
17729 uint32_t MaskedBits = llvm::countl_zero(Val: AndMask);
17730 if (MaskedBits > ShiftAmt) {
17731 SDLoc DL(N);
17732 SDValue SHL = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: N0->getOperand(Num: 0),
17733 N2: DAG.getConstant(Val: MaskedBits, DL, VT: MVT::i32));
17734 return DAG.getNode(
17735 Opcode: ISD::SRL, DL, VT: MVT::i32, N1: SHL,
17736 N2: DAG.getConstant(Val: MaskedBits - ShiftAmt, DL, VT: MVT::i32));
17737 }
17738 }
17739 }
17740
17741 // Nothing to be done for scalar shifts.
17742 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17743 if (!VT.isVector() || !TLI.isTypeLegal(VT))
17744 return SDValue();
17745 if (ST->hasMVEIntegerOps())
17746 return SDValue();
17747
17748 int64_t Cnt;
17749
17750 switch (N->getOpcode()) {
17751 default: llvm_unreachable("unexpected shift opcode");
17752
17753 case ISD::SHL:
17754 if (isVShiftLImm(Op: N->getOperand(Num: 1), VT, isLong: false, Cnt)) {
17755 SDLoc dl(N);
17756 return DAG.getNode(Opcode: ARMISD::VSHLIMM, DL: dl, VT, N1: N->getOperand(Num: 0),
17757 N2: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
17758 }
17759 break;
17760
17761 case ISD::SRA:
17762 case ISD::SRL:
17763 if (isVShiftRImm(Op: N->getOperand(Num: 1), VT, isNarrow: false, isIntrinsic: false, Cnt)) {
17764 unsigned VShiftOpc =
17765 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
17766 SDLoc dl(N);
17767 return DAG.getNode(Opcode: VShiftOpc, DL: dl, VT, N1: N->getOperand(Num: 0),
17768 N2: DAG.getConstant(Val: Cnt, DL: dl, VT: MVT::i32));
17769 }
17770 }
17771 return SDValue();
17772}
17773
17774// Look for a sign/zero/fpextend extend of a larger than legal load. This can be
17775// split into multiple extending loads, which are simpler to deal with than an
17776// arbitrary extend. For fp extends we use an integer extending load and a VCVTL
17777// to convert the type to an f32.
17778static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
17779 SDValue N0 = N->getOperand(Num: 0);
17780 if (N0.getOpcode() != ISD::LOAD)
17781 return SDValue();
17782 LoadSDNode *LD = cast<LoadSDNode>(Val: N0.getNode());
17783 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
17784 LD->getExtensionType() != ISD::NON_EXTLOAD)
17785 return SDValue();
17786 EVT FromVT = LD->getValueType(ResNo: 0);
17787 EVT ToVT = N->getValueType(ResNo: 0);
17788 if (!ToVT.isVector())
17789 return SDValue();
17790 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
17791 EVT ToEltVT = ToVT.getVectorElementType();
17792 EVT FromEltVT = FromVT.getVectorElementType();
17793
17794 unsigned NumElements = 0;
17795 if (ToEltVT == MVT::i32 && FromEltVT == MVT::i8)
17796 NumElements = 4;
17797 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
17798 NumElements = 4;
17799 if (NumElements == 0 ||
17800 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
17801 FromVT.getVectorNumElements() % NumElements != 0 ||
17802 !isPowerOf2_32(Value: NumElements))
17803 return SDValue();
17804
17805 LLVMContext &C = *DAG.getContext();
17806 SDLoc DL(LD);
17807 // Details about the old load
17808 SDValue Ch = LD->getChain();
17809 SDValue BasePtr = LD->getBasePtr();
17810 Align Alignment = LD->getBaseAlign();
17811 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
17812 AAMDNodes AAInfo = LD->getAAInfo();
17813
17814 ISD::LoadExtType NewExtType =
17815 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
17816 SDValue Offset = DAG.getUNDEF(VT: BasePtr.getValueType());
17817 EVT NewFromVT = EVT::getVectorVT(
17818 Context&: C, VT: EVT::getIntegerVT(Context&: C, BitWidth: FromEltVT.getScalarSizeInBits()), NumElements);
17819 EVT NewToVT = EVT::getVectorVT(
17820 Context&: C, VT: EVT::getIntegerVT(Context&: C, BitWidth: ToEltVT.getScalarSizeInBits()), NumElements);
17821
17822 SmallVector<SDValue, 4> Loads;
17823 SmallVector<SDValue, 4> Chains;
17824 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
17825 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
17826 SDValue NewPtr =
17827 DAG.getObjectPtrOffset(SL: DL, Ptr: BasePtr, Offset: TypeSize::getFixed(ExactSize: NewOffset));
17828
17829 SDValue NewLoad =
17830 DAG.getLoad(AM: ISD::UNINDEXED, ExtType: NewExtType, VT: NewToVT, dl: DL, Chain: Ch, Ptr: NewPtr, Offset,
17831 PtrInfo: LD->getPointerInfo().getWithOffset(O: NewOffset), MemVT: NewFromVT,
17832 Alignment, MMOFlags, AAInfo);
17833 Loads.push_back(Elt: NewLoad);
17834 Chains.push_back(Elt: SDValue(NewLoad.getNode(), 1));
17835 }
17836
17837 // Float truncs need to extended with VCVTB's into their floating point types.
17838 if (FromEltVT == MVT::f16) {
17839 SmallVector<SDValue, 4> Extends;
17840
17841 for (unsigned i = 0; i < Loads.size(); i++) {
17842 SDValue LoadBC =
17843 DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT: MVT::v8f16, Operand: Loads[i]);
17844 SDValue FPExt = DAG.getNode(Opcode: ARMISD::VCVTL, DL, VT: MVT::v4f32, N1: LoadBC,
17845 N2: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
17846 Extends.push_back(Elt: FPExt);
17847 }
17848
17849 Loads = Extends;
17850 }
17851
17852 SDValue NewChain = DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Chains);
17853 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 1), To: NewChain);
17854 return DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: ToVT, Ops: Loads);
17855}
17856
17857/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
17858/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
17859static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
17860 const ARMSubtarget *ST) {
17861 SDValue N0 = N->getOperand(Num: 0);
17862
17863 // Check for sign- and zero-extensions of vector extract operations of 8- and
17864 // 16-bit vector elements. NEON and MVE support these directly. They are
17865 // handled during DAG combining because type legalization will promote them
17866 // to 32-bit types and it is messy to recognize the operations after that.
17867 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
17868 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17869 SDValue Vec = N0.getOperand(i: 0);
17870 SDValue Lane = N0.getOperand(i: 1);
17871 EVT VT = N->getValueType(ResNo: 0);
17872 EVT EltVT = N0.getValueType();
17873 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17874
17875 if (VT == MVT::i32 &&
17876 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
17877 TLI.isTypeLegal(VT: Vec.getValueType()) &&
17878 isa<ConstantSDNode>(Val: Lane)) {
17879
17880 unsigned Opc = 0;
17881 switch (N->getOpcode()) {
17882 default: llvm_unreachable("unexpected opcode");
17883 case ISD::SIGN_EXTEND:
17884 Opc = ARMISD::VGETLANEs;
17885 break;
17886 case ISD::ZERO_EXTEND:
17887 case ISD::ANY_EXTEND:
17888 Opc = ARMISD::VGETLANEu;
17889 break;
17890 }
17891 return DAG.getNode(Opcode: Opc, DL: SDLoc(N), VT, N1: Vec, N2: Lane);
17892 }
17893 }
17894
17895 if (ST->hasMVEIntegerOps())
17896 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
17897 return NewLoad;
17898
17899 return SDValue();
17900}
17901
17902static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG,
17903 const ARMSubtarget *ST) {
17904 if (ST->hasMVEFloatOps())
17905 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
17906 return NewLoad;
17907
17908 return SDValue();
17909}
17910
17911// Lower smin(smax(x, C1), C2) to ssat or usat, if they have saturating
17912// constant bounds.
17913static SDValue PerformMinMaxToSatCombine(SDValue Op, SelectionDAG &DAG,
17914 const ARMSubtarget *Subtarget) {
17915 if ((Subtarget->isThumb() || !Subtarget->hasV6Ops()) &&
17916 !Subtarget->isThumb2())
17917 return SDValue();
17918
17919 EVT VT = Op.getValueType();
17920 SDValue Op0 = Op.getOperand(i: 0);
17921
17922 if (VT != MVT::i32 ||
17923 (Op0.getOpcode() != ISD::SMIN && Op0.getOpcode() != ISD::SMAX) ||
17924 !isa<ConstantSDNode>(Val: Op.getOperand(i: 1)) ||
17925 !isa<ConstantSDNode>(Val: Op0.getOperand(i: 1)))
17926 return SDValue();
17927
17928 SDValue Min = Op;
17929 SDValue Max = Op0;
17930 SDValue Input = Op0.getOperand(i: 0);
17931 if (Min.getOpcode() == ISD::SMAX)
17932 std::swap(a&: Min, b&: Max);
17933
17934 APInt MinC = Min.getConstantOperandAPInt(i: 1);
17935 APInt MaxC = Max.getConstantOperandAPInt(i: 1);
17936
17937 if (Min.getOpcode() != ISD::SMIN || Max.getOpcode() != ISD::SMAX ||
17938 !(MinC + 1).isPowerOf2())
17939 return SDValue();
17940
17941 SDLoc DL(Op);
17942 if (MinC == ~MaxC)
17943 return DAG.getNode(Opcode: ARMISD::SSAT, DL, VT, N1: Input,
17944 N2: DAG.getConstant(Val: MinC.countr_one(), DL, VT));
17945 if (MaxC == 0)
17946 return DAG.getNode(Opcode: ARMISD::USAT, DL, VT, N1: Input,
17947 N2: DAG.getConstant(Val: MinC.countr_one(), DL, VT));
17948
17949 return SDValue();
17950}
17951
17952/// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
17953/// saturates.
17954static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
17955 const ARMSubtarget *ST) {
17956 EVT VT = N->getValueType(ResNo: 0);
17957 SDValue N0 = N->getOperand(Num: 0);
17958
17959 if (VT == MVT::i32)
17960 return PerformMinMaxToSatCombine(Op: SDValue(N, 0), DAG, Subtarget: ST);
17961
17962 if (!ST->hasMVEIntegerOps())
17963 return SDValue();
17964
17965 if (SDValue V = PerformVQDMULHCombine(N, DAG))
17966 return V;
17967
17968 if (VT != MVT::v4i32 && VT != MVT::v8i16)
17969 return SDValue();
17970
17971 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
17972 // Check one is a smin and the other is a smax
17973 if (Min->getOpcode() != ISD::SMIN)
17974 std::swap(a&: Min, b&: Max);
17975 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
17976 return false;
17977
17978 APInt SaturateC;
17979 if (VT == MVT::v4i32)
17980 SaturateC = APInt(32, (1 << 15) - 1, true);
17981 else //if (VT == MVT::v8i16)
17982 SaturateC = APInt(16, (1 << 7) - 1, true);
17983
17984 APInt MinC, MaxC;
17985 if (!ISD::isConstantSplatVector(N: Min->getOperand(Num: 1).getNode(), SplatValue&: MinC) ||
17986 MinC != SaturateC)
17987 return false;
17988 if (!ISD::isConstantSplatVector(N: Max->getOperand(Num: 1).getNode(), SplatValue&: MaxC) ||
17989 MaxC != ~SaturateC)
17990 return false;
17991 return true;
17992 };
17993
17994 if (IsSignedSaturate(N, N0.getNode())) {
17995 SDLoc DL(N);
17996 MVT ExtVT, HalfVT;
17997 if (VT == MVT::v4i32) {
17998 HalfVT = MVT::v8i16;
17999 ExtVT = MVT::v4i16;
18000 } else { // if (VT == MVT::v8i16)
18001 HalfVT = MVT::v16i8;
18002 ExtVT = MVT::v8i8;
18003 }
18004
18005 // Create a VQMOVNB with undef top lanes, then signed extended into the top
18006 // half. That extend will hopefully be removed if only the bottom bits are
18007 // demanded (though a truncating store, for example).
18008 SDValue VQMOVN =
18009 DAG.getNode(Opcode: ARMISD::VQMOVNs, DL, VT: HalfVT, N1: DAG.getUNDEF(VT: HalfVT),
18010 N2: N0->getOperand(Num: 0), N3: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
18011 SDValue Bitcast = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: VQMOVN);
18012 return DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL, VT, N1: Bitcast,
18013 N2: DAG.getValueType(ExtVT));
18014 }
18015
18016 auto IsUnsignedSaturate = [&](SDNode *Min) {
18017 // For unsigned, we just need to check for <= 0xffff
18018 if (Min->getOpcode() != ISD::UMIN)
18019 return false;
18020
18021 APInt SaturateC;
18022 if (VT == MVT::v4i32)
18023 SaturateC = APInt(32, (1 << 16) - 1, true);
18024 else //if (VT == MVT::v8i16)
18025 SaturateC = APInt(16, (1 << 8) - 1, true);
18026
18027 APInt MinC;
18028 if (!ISD::isConstantSplatVector(N: Min->getOperand(Num: 1).getNode(), SplatValue&: MinC) ||
18029 MinC != SaturateC)
18030 return false;
18031 return true;
18032 };
18033
18034 if (IsUnsignedSaturate(N)) {
18035 SDLoc DL(N);
18036 MVT HalfVT;
18037 unsigned ExtConst;
18038 if (VT == MVT::v4i32) {
18039 HalfVT = MVT::v8i16;
18040 ExtConst = 0x0000FFFF;
18041 } else { //if (VT == MVT::v8i16)
18042 HalfVT = MVT::v16i8;
18043 ExtConst = 0x00FF;
18044 }
18045
18046 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
18047 // an AND. That extend will hopefully be removed if only the bottom bits are
18048 // demanded (though a truncating store, for example).
18049 SDValue VQMOVN =
18050 DAG.getNode(Opcode: ARMISD::VQMOVNu, DL, VT: HalfVT, N1: DAG.getUNDEF(VT: HalfVT), N2: N0,
18051 N3: DAG.getConstant(Val: 0, DL, VT: MVT::i32));
18052 SDValue Bitcast = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: VQMOVN);
18053 return DAG.getNode(Opcode: ISD::AND, DL, VT, N1: Bitcast,
18054 N2: DAG.getConstant(Val: ExtConst, DL, VT));
18055 }
18056
18057 return SDValue();
18058}
18059
18060static const APInt *isPowerOf2Constant(SDValue V) {
18061 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: V);
18062 if (!C)
18063 return nullptr;
18064 const APInt *CV = &C->getAPIntValue();
18065 return CV->isPowerOf2() ? CV : nullptr;
18066}
18067
18068SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
18069 // If we have a CMOV, OR and AND combination such as:
18070 // if (x & CN)
18071 // y |= CM;
18072 //
18073 // And:
18074 // * CN is a single bit;
18075 // * All bits covered by CM are known zero in y
18076 //
18077 // Then we can convert this into a sequence of BFI instructions. This will
18078 // always be a win if CM is a single bit, will always be no worse than the
18079 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
18080 // three bits (due to the extra IT instruction).
18081
18082 SDValue Op0 = CMOV->getOperand(Num: 0);
18083 SDValue Op1 = CMOV->getOperand(Num: 1);
18084 auto CC = CMOV->getConstantOperandAPInt(Num: 2).getLimitedValue();
18085 SDValue CmpZ = CMOV->getOperand(Num: 3);
18086
18087 // The compare must be against zero.
18088 if (!isNullConstant(V: CmpZ->getOperand(Num: 1)))
18089 return SDValue();
18090
18091 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
18092 SDValue And = CmpZ->getOperand(Num: 0);
18093 if (And->getOpcode() != ISD::AND)
18094 return SDValue();
18095 const APInt *AndC = isPowerOf2Constant(V: And->getOperand(Num: 1));
18096 if (!AndC)
18097 return SDValue();
18098 SDValue X = And->getOperand(Num: 0);
18099
18100 if (CC == ARMCC::EQ) {
18101 // We're performing an "equal to zero" compare. Swap the operands so we
18102 // canonicalize on a "not equal to zero" compare.
18103 std::swap(a&: Op0, b&: Op1);
18104 } else {
18105 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
18106 }
18107
18108 if (Op1->getOpcode() != ISD::OR)
18109 return SDValue();
18110
18111 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Val: Op1->getOperand(Num: 1));
18112 if (!OrC)
18113 return SDValue();
18114 SDValue Y = Op1->getOperand(Num: 0);
18115
18116 if (Op0 != Y)
18117 return SDValue();
18118
18119 // Now, is it profitable to continue?
18120 APInt OrCI = OrC->getAPIntValue();
18121 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
18122 if (OrCI.popcount() > Heuristic)
18123 return SDValue();
18124
18125 // Lastly, can we determine that the bits defined by OrCI
18126 // are zero in Y?
18127 KnownBits Known = DAG.computeKnownBits(Op: Y);
18128 if ((OrCI & Known.Zero) != OrCI)
18129 return SDValue();
18130
18131 // OK, we can do the combine.
18132 SDValue V = Y;
18133 SDLoc dl(X);
18134 EVT VT = X.getValueType();
18135 unsigned BitInX = AndC->logBase2();
18136
18137 if (BitInX != 0) {
18138 // We must shift X first.
18139 X = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: X,
18140 N2: DAG.getConstant(Val: BitInX, DL: dl, VT));
18141 }
18142
18143 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
18144 BitInY < NumActiveBits; ++BitInY) {
18145 if (OrCI[BitInY] == 0)
18146 continue;
18147 APInt Mask(VT.getSizeInBits(), 0);
18148 Mask.setBit(BitInY);
18149 V = DAG.getNode(Opcode: ARMISD::BFI, DL: dl, VT, N1: V, N2: X,
18150 // Confusingly, the operand is an *inverted* mask.
18151 N3: DAG.getConstant(Val: ~Mask, DL: dl, VT));
18152 }
18153
18154 return V;
18155}
18156
18157// Given N, the value controlling the conditional branch, search for the loop
18158// intrinsic, returning it, along with how the value is used. We need to handle
18159// patterns such as the following:
18160// (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
18161// (brcond (setcc (loop.decrement), 0, eq), exit)
18162// (brcond (setcc (loop.decrement), 0, ne), header)
18163static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
18164 bool &Negate) {
18165 switch (N->getOpcode()) {
18166 default:
18167 break;
18168 case ISD::XOR: {
18169 if (!isa<ConstantSDNode>(Val: N.getOperand(i: 1)))
18170 return SDValue();
18171 if (!cast<ConstantSDNode>(Val: N.getOperand(i: 1))->isOne())
18172 return SDValue();
18173 Negate = !Negate;
18174 return SearchLoopIntrinsic(N: N.getOperand(i: 0), CC, Imm, Negate);
18175 }
18176 case ISD::SETCC: {
18177 auto *Const = dyn_cast<ConstantSDNode>(Val: N.getOperand(i: 1));
18178 if (!Const)
18179 return SDValue();
18180 if (Const->isZero())
18181 Imm = 0;
18182 else if (Const->isOne())
18183 Imm = 1;
18184 else
18185 return SDValue();
18186 CC = cast<CondCodeSDNode>(Val: N.getOperand(i: 2))->get();
18187 return SearchLoopIntrinsic(N: N->getOperand(Num: 0), CC, Imm, Negate);
18188 }
18189 case ISD::INTRINSIC_W_CHAIN: {
18190 unsigned IntOp = N.getConstantOperandVal(i: 1);
18191 if (IntOp != Intrinsic::test_start_loop_iterations &&
18192 IntOp != Intrinsic::loop_decrement_reg)
18193 return SDValue();
18194 return N;
18195 }
18196 }
18197 return SDValue();
18198}
18199
18200static SDValue PerformHWLoopCombine(SDNode *N,
18201 TargetLowering::DAGCombinerInfo &DCI,
18202 const ARMSubtarget *ST) {
18203
18204 // The hwloop intrinsics that we're interested are used for control-flow,
18205 // either for entering or exiting the loop:
18206 // - test.start.loop.iterations will test whether its operand is zero. If it
18207 // is zero, the proceeding branch should not enter the loop.
18208 // - loop.decrement.reg also tests whether its operand is zero. If it is
18209 // zero, the proceeding branch should not branch back to the beginning of
18210 // the loop.
18211 // So here, we need to check that how the brcond is using the result of each
18212 // of the intrinsics to ensure that we're branching to the right place at the
18213 // right time.
18214
18215 ISD::CondCode CC;
18216 SDValue Cond;
18217 int Imm = 1;
18218 bool Negate = false;
18219 SDValue Chain = N->getOperand(Num: 0);
18220 SDValue Dest;
18221
18222 if (N->getOpcode() == ISD::BRCOND) {
18223 CC = ISD::SETEQ;
18224 Cond = N->getOperand(Num: 1);
18225 Dest = N->getOperand(Num: 2);
18226 } else {
18227 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
18228 CC = cast<CondCodeSDNode>(Val: N->getOperand(Num: 1))->get();
18229 Cond = N->getOperand(Num: 2);
18230 Dest = N->getOperand(Num: 4);
18231 if (auto *Const = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 3))) {
18232 if (!Const->isOne() && !Const->isZero())
18233 return SDValue();
18234 Imm = Const->getZExtValue();
18235 } else
18236 return SDValue();
18237 }
18238
18239 SDValue Int = SearchLoopIntrinsic(N: Cond, CC, Imm, Negate);
18240 if (!Int)
18241 return SDValue();
18242
18243 if (Negate)
18244 CC = ISD::getSetCCInverse(Operation: CC, /* Integer inverse */ Type: MVT::i32);
18245
18246 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
18247 return (CC == ISD::SETEQ && Imm == 0) ||
18248 (CC == ISD::SETNE && Imm == 1) ||
18249 (CC == ISD::SETLT && Imm == 1) ||
18250 (CC == ISD::SETULT && Imm == 1);
18251 };
18252
18253 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
18254 return (CC == ISD::SETEQ && Imm == 1) ||
18255 (CC == ISD::SETNE && Imm == 0) ||
18256 (CC == ISD::SETGT && Imm == 0) ||
18257 (CC == ISD::SETUGT && Imm == 0) ||
18258 (CC == ISD::SETGE && Imm == 1) ||
18259 (CC == ISD::SETUGE && Imm == 1);
18260 };
18261
18262 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
18263 "unsupported condition");
18264
18265 SDLoc dl(Int);
18266 SelectionDAG &DAG = DCI.DAG;
18267 SDValue Elements = Int.getOperand(i: 2);
18268 unsigned IntOp = Int->getConstantOperandVal(Num: 1);
18269 assert((N->hasOneUse() && N->user_begin()->getOpcode() == ISD::BR) &&
18270 "expected single br user");
18271 SDNode *Br = *N->user_begin();
18272 SDValue OtherTarget = Br->getOperand(Num: 1);
18273
18274 // Update the unconditional branch to branch to the given Dest.
18275 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
18276 SDValue NewBrOps[] = { Br->getOperand(Num: 0), Dest };
18277 SDValue NewBr = DAG.getNode(Opcode: ISD::BR, DL: SDLoc(Br), VT: MVT::Other, Ops: NewBrOps);
18278 DAG.ReplaceAllUsesOfValueWith(From: SDValue(Br, 0), To: NewBr);
18279 };
18280
18281 if (IntOp == Intrinsic::test_start_loop_iterations) {
18282 SDValue Res;
18283 SDValue Setup = DAG.getNode(Opcode: ARMISD::WLSSETUP, DL: dl, VT: MVT::i32, Operand: Elements);
18284 // We expect this 'instruction' to branch when the counter is zero.
18285 if (IsTrueIfZero(CC, Imm)) {
18286 SDValue Ops[] = {Chain, Setup, Dest};
18287 Res = DAG.getNode(Opcode: ARMISD::WLS, DL: dl, VT: MVT::Other, Ops);
18288 } else {
18289 // The logic is the reverse of what we need for WLS, so find the other
18290 // basic block target: the target of the proceeding br.
18291 UpdateUncondBr(Br, Dest, DAG);
18292
18293 SDValue Ops[] = {Chain, Setup, OtherTarget};
18294 Res = DAG.getNode(Opcode: ARMISD::WLS, DL: dl, VT: MVT::Other, Ops);
18295 }
18296 // Update LR count to the new value
18297 DAG.ReplaceAllUsesOfValueWith(From: Int.getValue(R: 0), To: Setup);
18298 // Update chain
18299 DAG.ReplaceAllUsesOfValueWith(From: Int.getValue(R: 2), To: Int.getOperand(i: 0));
18300 return Res;
18301 } else {
18302 SDValue Size =
18303 DAG.getTargetConstant(Val: Int.getConstantOperandVal(i: 3), DL: dl, VT: MVT::i32);
18304 SDValue Args[] = { Int.getOperand(i: 0), Elements, Size, };
18305 SDValue LoopDec = DAG.getNode(Opcode: ARMISD::LOOP_DEC, DL: dl,
18306 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other), Ops: Args);
18307 DAG.ReplaceAllUsesWith(From: Int.getNode(), To: LoopDec.getNode());
18308
18309 // We expect this instruction to branch when the count is not zero.
18310 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
18311
18312 // Update the unconditional branch to target the loop preheader if we've
18313 // found the condition has been reversed.
18314 if (Target == OtherTarget)
18315 UpdateUncondBr(Br, Dest, DAG);
18316
18317 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other,
18318 N1: SDValue(LoopDec.getNode(), 1), N2: Chain);
18319
18320 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
18321 return DAG.getNode(Opcode: ARMISD::LE, DL: dl, VT: MVT::Other, Ops: EndArgs);
18322 }
18323 return SDValue();
18324}
18325
18326/// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
18327SDValue
18328ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
18329 SDValue Cmp = N->getOperand(Num: 3);
18330 if (Cmp.getOpcode() != ARMISD::CMPZ)
18331 // Only looking at NE cases.
18332 return SDValue();
18333
18334 SDLoc dl(N);
18335 SDValue LHS = Cmp.getOperand(i: 0);
18336 SDValue RHS = Cmp.getOperand(i: 1);
18337 SDValue Chain = N->getOperand(Num: 0);
18338 SDValue BB = N->getOperand(Num: 1);
18339 SDValue ARMcc = N->getOperand(Num: 2);
18340 ARMCC::CondCodes CC = (ARMCC::CondCodes)ARMcc->getAsZExtVal();
18341
18342 // (brcond Chain BB ne (cmpz (and (cmov 0 1 CC Flags) 1) 0))
18343 // -> (brcond Chain BB CC Flags)
18344 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
18345 LHS->getOperand(Num: 0)->getOpcode() == ARMISD::CMOV &&
18346 LHS->getOperand(Num: 0)->hasOneUse() &&
18347 isNullConstant(V: LHS->getOperand(Num: 0)->getOperand(Num: 0)) &&
18348 isOneConstant(V: LHS->getOperand(Num: 0)->getOperand(Num: 1)) &&
18349 isOneConstant(V: LHS->getOperand(Num: 1)) && isNullConstant(V: RHS)) {
18350 return DAG.getNode(Opcode: ARMISD::BRCOND, DL: dl, VT: MVT::Other, N1: Chain, N2: BB,
18351 N3: LHS->getOperand(Num: 0)->getOperand(Num: 2),
18352 N4: LHS->getOperand(Num: 0)->getOperand(Num: 3));
18353 }
18354
18355 return SDValue();
18356}
18357
18358/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
18359SDValue
18360ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
18361 SDValue Cmp = N->getOperand(Num: 3);
18362 if (Cmp.getOpcode() != ARMISD::CMPZ)
18363 // Only looking at EQ and NE cases.
18364 return SDValue();
18365
18366 EVT VT = N->getValueType(ResNo: 0);
18367 SDLoc dl(N);
18368 SDValue LHS = Cmp.getOperand(i: 0);
18369 SDValue RHS = Cmp.getOperand(i: 1);
18370 SDValue FalseVal = N->getOperand(Num: 0);
18371 SDValue TrueVal = N->getOperand(Num: 1);
18372 SDValue ARMcc = N->getOperand(Num: 2);
18373 ARMCC::CondCodes CC = (ARMCC::CondCodes)ARMcc->getAsZExtVal();
18374
18375 // BFI is only available on V6T2+.
18376 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
18377 SDValue R = PerformCMOVToBFICombine(CMOV: N, DAG);
18378 if (R)
18379 return R;
18380 }
18381
18382 // Simplify
18383 // mov r1, r0
18384 // cmp r1, x
18385 // mov r0, y
18386 // moveq r0, x
18387 // to
18388 // cmp r0, x
18389 // movne r0, y
18390 //
18391 // mov r1, r0
18392 // cmp r1, x
18393 // mov r0, x
18394 // movne r0, y
18395 // to
18396 // cmp r0, x
18397 // movne r0, y
18398 /// FIXME: Turn this into a target neutral optimization?
18399 SDValue Res;
18400 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
18401 Res = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: LHS, N2: TrueVal, N3: ARMcc, N4: Cmp);
18402 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
18403 SDValue ARMcc;
18404 SDValue NewCmp = getARMCmp(LHS, RHS, CC: ISD::SETNE, ARMcc, DAG, dl);
18405 Res = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: LHS, N2: FalseVal, N3: ARMcc, N4: NewCmp);
18406 }
18407
18408 // (cmov F T ne (cmpz (cmov 0 1 CC Flags) 0))
18409 // -> (cmov F T CC Flags)
18410 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse() &&
18411 isNullConstant(V: LHS->getOperand(Num: 0)) && isOneConstant(V: LHS->getOperand(Num: 1)) &&
18412 isNullConstant(V: RHS)) {
18413 return DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: FalseVal, N2: TrueVal,
18414 N3: LHS->getOperand(Num: 2), N4: LHS->getOperand(Num: 3));
18415 }
18416
18417 if (!VT.isInteger())
18418 return SDValue();
18419
18420 // Fold away an unnecessary CMPZ/CMOV
18421 // CMOV A, B, C1, (CMPZ (CMOV 1, 0, C2, D), 0) ->
18422 // if C1==EQ -> CMOV A, B, C2, D
18423 // if C1==NE -> CMOV A, B, NOT(C2), D
18424 if (N->getConstantOperandVal(Num: 2) == ARMCC::EQ ||
18425 N->getConstantOperandVal(Num: 2) == ARMCC::NE) {
18426 ARMCC::CondCodes Cond;
18427 if (SDValue C = IsCMPZCSINC(Cmp: N->getOperand(Num: 3).getNode(), CC&: Cond)) {
18428 if (N->getConstantOperandVal(Num: 2) == ARMCC::NE)
18429 Cond = ARMCC::getOppositeCondition(CC: Cond);
18430 return DAG.getNode(Opcode: N->getOpcode(), DL: SDLoc(N), VT: MVT::i32, N1: N->getOperand(Num: 0),
18431 N2: N->getOperand(Num: 1),
18432 N3: DAG.getConstant(Val: Cond, DL: SDLoc(N), VT: MVT::i32), N4: C);
18433 }
18434 }
18435
18436 // Materialize a boolean comparison for integers so we can avoid branching.
18437 if (isNullConstant(V: FalseVal)) {
18438 if (CC == ARMCC::EQ && isOneConstant(V: TrueVal)) {
18439 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
18440 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
18441 // right 5 bits will make that 32 be 1, otherwise it will be 0.
18442 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
18443 SDValue Sub = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: LHS, N2: RHS);
18444 Res = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT, N1: DAG.getNode(Opcode: ISD::CTLZ, DL: dl, VT, Operand: Sub),
18445 N2: DAG.getConstant(Val: 5, DL: dl, VT: MVT::i32));
18446 } else {
18447 // CMOV 0, 1, ==, (CMPZ x, y) ->
18448 // (UADDO_CARRY (SUB x, y), t:0, t:1)
18449 // where t = (USUBO_CARRY 0, (SUB x, y), 0)
18450 //
18451 // The USUBO_CARRY computes 0 - (x - y) and this will give a borrow when
18452 // x != y. In other words, a carry C == 1 when x == y, C == 0
18453 // otherwise.
18454 // The final UADDO_CARRY computes
18455 // x - y + (0 - (x - y)) + C == C
18456 SDValue Sub = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: LHS, N2: RHS);
18457 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::i32);
18458 SDValue Neg = DAG.getNode(Opcode: ISD::USUBO, DL: dl, VTList: VTs, N1: FalseVal, N2: Sub);
18459 // ISD::USUBO_CARRY returns a borrow but we want the carry here
18460 // actually.
18461 SDValue Carry =
18462 DAG.getNode(Opcode: ISD::SUB, DL: dl, VT: MVT::i32,
18463 N1: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32), N2: Neg.getValue(R: 1));
18464 Res = DAG.getNode(Opcode: ISD::UADDO_CARRY, DL: dl, VTList: VTs, N1: Sub, N2: Neg, N3: Carry);
18465 }
18466 } else if (CC == ARMCC::NE && !isNullConstant(V: RHS) &&
18467 (!Subtarget->isThumb1Only() || isPowerOf2Constant(V: TrueVal))) {
18468 // This seems pointless but will allow us to combine it further below.
18469 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
18470 SDValue Sub =
18471 DAG.getNode(Opcode: ARMISD::SUBC, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: MVT::i32), N1: LHS, N2: RHS);
18472 Res = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: Sub, N2: TrueVal, N3: ARMcc,
18473 N4: Sub.getValue(R: 1));
18474 FalseVal = Sub;
18475 }
18476 } else if (isNullConstant(V: TrueVal)) {
18477 if (CC == ARMCC::EQ && !isNullConstant(V: RHS) &&
18478 (!Subtarget->isThumb1Only() || isPowerOf2Constant(V: FalseVal))) {
18479 // This seems pointless but will allow us to combine it further below
18480 // Note that we change == for != as this is the dual for the case above.
18481 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
18482 SDValue Sub =
18483 DAG.getNode(Opcode: ARMISD::SUBC, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: MVT::i32), N1: LHS, N2: RHS);
18484 Res = DAG.getNode(Opcode: ARMISD::CMOV, DL: dl, VT, N1: Sub, N2: FalseVal,
18485 N3: DAG.getConstant(Val: ARMCC::NE, DL: dl, VT: MVT::i32),
18486 N4: Sub.getValue(R: 1));
18487 FalseVal = Sub;
18488 }
18489 }
18490
18491 // On Thumb1, the DAG above may be further combined if z is a power of 2
18492 // (z == 2 ^ K).
18493 // CMOV (SUBC x, y), z, !=, (SUBC x, y):1 ->
18494 // t1 = (USUBO (SUB x, y), 1)
18495 // t2 = (USUBO_CARRY (SUB x, y), t1:0, t1:1)
18496 // Result = if K != 0 then (SHL t2:0, K) else t2:0
18497 //
18498 // This also handles the special case of comparing against zero; it's
18499 // essentially, the same pattern, except there's no SUBC:
18500 // CMOV x, z, !=, (CMPZ x, 0) ->
18501 // t1 = (USUBO x, 1)
18502 // t2 = (USUBO_CARRY x, t1:0, t1:1)
18503 // Result = if K != 0 then (SHL t2:0, K) else t2:0
18504 const APInt *TrueConst;
18505 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
18506 ((FalseVal.getOpcode() == ARMISD::SUBC && FalseVal.getOperand(i: 0) == LHS &&
18507 FalseVal.getOperand(i: 1) == RHS) ||
18508 (FalseVal == LHS && isNullConstant(V: RHS))) &&
18509 (TrueConst = isPowerOf2Constant(V: TrueVal))) {
18510 SDVTList VTs = DAG.getVTList(VT1: VT, VT2: MVT::i32);
18511 unsigned ShiftAmount = TrueConst->logBase2();
18512 if (ShiftAmount)
18513 TrueVal = DAG.getConstant(Val: 1, DL: dl, VT);
18514 SDValue Subc = DAG.getNode(Opcode: ISD::USUBO, DL: dl, VTList: VTs, N1: FalseVal, N2: TrueVal);
18515 Res = DAG.getNode(Opcode: ISD::USUBO_CARRY, DL: dl, VTList: VTs, N1: FalseVal, N2: Subc,
18516 N3: Subc.getValue(R: 1));
18517
18518 if (ShiftAmount)
18519 Res = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT, N1: Res,
18520 N2: DAG.getConstant(Val: ShiftAmount, DL: dl, VT: MVT::i32));
18521 }
18522
18523 if (Res.getNode()) {
18524 KnownBits Known = DAG.computeKnownBits(Op: SDValue(N,0));
18525 // Capture demanded bits information that would be otherwise lost.
18526 if (Known.Zero == 0xfffffffe)
18527 Res = DAG.getNode(Opcode: ISD::AssertZext, DL: dl, VT: MVT::i32, N1: Res,
18528 N2: DAG.getValueType(MVT::i1));
18529 else if (Known.Zero == 0xffffff00)
18530 Res = DAG.getNode(Opcode: ISD::AssertZext, DL: dl, VT: MVT::i32, N1: Res,
18531 N2: DAG.getValueType(MVT::i8));
18532 else if (Known.Zero == 0xffff0000)
18533 Res = DAG.getNode(Opcode: ISD::AssertZext, DL: dl, VT: MVT::i32, N1: Res,
18534 N2: DAG.getValueType(MVT::i16));
18535 }
18536
18537 return Res;
18538}
18539
18540static SDValue PerformBITCASTCombine(SDNode *N,
18541 TargetLowering::DAGCombinerInfo &DCI,
18542 const ARMSubtarget *ST) {
18543 SelectionDAG &DAG = DCI.DAG;
18544 SDValue Src = N->getOperand(Num: 0);
18545 EVT DstVT = N->getValueType(ResNo: 0);
18546
18547 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
18548 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
18549 EVT SrcVT = Src.getValueType();
18550 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
18551 return DAG.getNode(Opcode: ARMISD::VDUP, DL: SDLoc(N), VT: DstVT, Operand: Src.getOperand(i: 0));
18552 }
18553
18554 // We may have a bitcast of something that has already had this bitcast
18555 // combine performed on it, so skip past any VECTOR_REG_CASTs.
18556 if (Src.getOpcode() == ARMISD::VECTOR_REG_CAST &&
18557 Src.getOperand(i: 0).getValueType().getScalarSizeInBits() <=
18558 Src.getValueType().getScalarSizeInBits())
18559 Src = Src.getOperand(i: 0);
18560
18561 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
18562 // would be generated is at least the width of the element type.
18563 EVT SrcVT = Src.getValueType();
18564 if ((Src.getOpcode() == ARMISD::VMOVIMM ||
18565 Src.getOpcode() == ARMISD::VMVNIMM ||
18566 Src.getOpcode() == ARMISD::VMOVFPIMM) &&
18567 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
18568 DAG.getDataLayout().isBigEndian())
18569 return DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL: SDLoc(N), VT: DstVT, Operand: Src);
18570
18571 // bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD x
18572 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
18573 return R;
18574
18575 return SDValue();
18576}
18577
18578// Some combines for the MVETrunc truncations legalizer helper. Also lowers the
18579// node into stack operations after legalizeOps.
18580SDValue ARMTargetLowering::PerformMVETruncCombine(
18581 SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
18582 SelectionDAG &DAG = DCI.DAG;
18583 EVT VT = N->getValueType(ResNo: 0);
18584 SDLoc DL(N);
18585
18586 // MVETrunc(Undef, Undef) -> Undef
18587 if (all_of(Range: N->ops(), P: [](SDValue Op) { return Op.isUndef(); }))
18588 return DAG.getUNDEF(VT);
18589
18590 // MVETrunc(MVETrunc a b, MVETrunc c, d) -> MVETrunc
18591 if (N->getNumOperands() == 2 &&
18592 N->getOperand(Num: 0).getOpcode() == ARMISD::MVETRUNC &&
18593 N->getOperand(Num: 1).getOpcode() == ARMISD::MVETRUNC)
18594 return DAG.getNode(Opcode: ARMISD::MVETRUNC, DL, VT, N1: N->getOperand(Num: 0).getOperand(i: 0),
18595 N2: N->getOperand(Num: 0).getOperand(i: 1),
18596 N3: N->getOperand(Num: 1).getOperand(i: 0),
18597 N4: N->getOperand(Num: 1).getOperand(i: 1));
18598
18599 // MVETrunc(shuffle, shuffle) -> VMOVN
18600 if (N->getNumOperands() == 2 &&
18601 N->getOperand(Num: 0).getOpcode() == ISD::VECTOR_SHUFFLE &&
18602 N->getOperand(Num: 1).getOpcode() == ISD::VECTOR_SHUFFLE) {
18603 auto *S0 = cast<ShuffleVectorSDNode>(Val: N->getOperand(Num: 0).getNode());
18604 auto *S1 = cast<ShuffleVectorSDNode>(Val: N->getOperand(Num: 1).getNode());
18605
18606 if (S0->getOperand(Num: 0) == S1->getOperand(Num: 0) &&
18607 S0->getOperand(Num: 1) == S1->getOperand(Num: 1)) {
18608 // Construct complete shuffle mask
18609 SmallVector<int, 8> Mask(S0->getMask());
18610 Mask.append(in_start: S1->getMask().begin(), in_end: S1->getMask().end());
18611
18612 if (isVMOVNTruncMask(M: Mask, ToVT: VT, rev: false))
18613 return DAG.getNode(
18614 Opcode: ARMISD::VMOVN, DL, VT,
18615 N1: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: S0->getOperand(Num: 0)),
18616 N2: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: S0->getOperand(Num: 1)),
18617 N3: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
18618 if (isVMOVNTruncMask(M: Mask, ToVT: VT, rev: true))
18619 return DAG.getNode(
18620 Opcode: ARMISD::VMOVN, DL, VT,
18621 N1: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: S0->getOperand(Num: 1)),
18622 N2: DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: S0->getOperand(Num: 0)),
18623 N3: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
18624 }
18625 }
18626
18627 // For MVETrunc of a buildvector or shuffle, it can be beneficial to lower the
18628 // truncate to a buildvector to allow the generic optimisations to kick in.
18629 if (all_of(Range: N->ops(), P: [](SDValue Op) {
18630 return Op.getOpcode() == ISD::BUILD_VECTOR ||
18631 Op.getOpcode() == ISD::VECTOR_SHUFFLE ||
18632 (Op.getOpcode() == ISD::BITCAST &&
18633 Op.getOperand(i: 0).getOpcode() == ISD::BUILD_VECTOR);
18634 })) {
18635 SmallVector<SDValue, 8> Extracts;
18636 for (unsigned Op = 0; Op < N->getNumOperands(); Op++) {
18637 SDValue O = N->getOperand(Num: Op);
18638 for (unsigned i = 0; i < O.getValueType().getVectorNumElements(); i++) {
18639 SDValue Ext = DAG.getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: MVT::i32, N1: O,
18640 N2: DAG.getConstant(Val: i, DL, VT: MVT::i32));
18641 Extracts.push_back(Elt: Ext);
18642 }
18643 }
18644 return DAG.getBuildVector(VT, DL, Ops: Extracts);
18645 }
18646
18647 // If we are late in the legalization process and nothing has optimised
18648 // the trunc to anything better, lower it to a stack store and reload,
18649 // performing the truncation whilst keeping the lanes in the correct order:
18650 // VSTRH.32 a, stack; VSTRH.32 b, stack+8; VLDRW.32 stack;
18651 if (!DCI.isAfterLegalizeDAG())
18652 return SDValue();
18653
18654 SDValue StackPtr = DAG.CreateStackTemporary(Bytes: TypeSize::getFixed(ExactSize: 16), Alignment: Align(4));
18655 int SPFI = cast<FrameIndexSDNode>(Val: StackPtr.getNode())->getIndex();
18656 int NumIns = N->getNumOperands();
18657 assert((NumIns == 2 || NumIns == 4) &&
18658 "Expected 2 or 4 inputs to an MVETrunc");
18659 EVT StoreVT = VT.getHalfNumVectorElementsVT(Context&: *DAG.getContext());
18660 if (N->getNumOperands() == 4)
18661 StoreVT = StoreVT.getHalfNumVectorElementsVT(Context&: *DAG.getContext());
18662
18663 SmallVector<SDValue> Chains;
18664 for (int I = 0; I < NumIns; I++) {
18665 SDValue Ptr = DAG.getNode(
18666 Opcode: ISD::ADD, DL, VT: StackPtr.getValueType(), N1: StackPtr,
18667 N2: DAG.getConstant(Val: I * 16 / NumIns, DL, VT: StackPtr.getValueType()));
18668 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
18669 MF&: DAG.getMachineFunction(), FI: SPFI, Offset: I * 16 / NumIns);
18670 SDValue Ch = DAG.getTruncStore(Chain: DAG.getEntryNode(), dl: DL, Val: N->getOperand(Num: I),
18671 Ptr, PtrInfo: MPI, SVT: StoreVT, Alignment: Align(4));
18672 Chains.push_back(Elt: Ch);
18673 }
18674
18675 SDValue Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Chains);
18676 MachinePointerInfo MPI =
18677 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI, Offset: 0);
18678 return DAG.getLoad(VT, dl: DL, Chain, Ptr: StackPtr, PtrInfo: MPI, Alignment: Align(4));
18679}
18680
18681// Take a MVEEXT(load x) and split that into (extload x, extload x+8)
18682static SDValue PerformSplittingMVEEXTToWideningLoad(SDNode *N,
18683 SelectionDAG &DAG) {
18684 SDValue N0 = N->getOperand(Num: 0);
18685 LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: N0.getNode());
18686 if (!LD || !LD->isSimple() || !N0.hasOneUse() || LD->isIndexed())
18687 return SDValue();
18688
18689 EVT FromVT = LD->getMemoryVT();
18690 EVT ToVT = N->getValueType(ResNo: 0);
18691 if (!ToVT.isVector())
18692 return SDValue();
18693 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2);
18694 EVT ToEltVT = ToVT.getVectorElementType();
18695 EVT FromEltVT = FromVT.getVectorElementType();
18696
18697 unsigned NumElements = 0;
18698 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
18699 NumElements = 4;
18700 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
18701 NumElements = 8;
18702 assert(NumElements != 0);
18703
18704 ISD::LoadExtType NewExtType =
18705 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
18706 if (LD->getExtensionType() != ISD::NON_EXTLOAD &&
18707 LD->getExtensionType() != ISD::EXTLOAD &&
18708 LD->getExtensionType() != NewExtType)
18709 return SDValue();
18710
18711 LLVMContext &C = *DAG.getContext();
18712 SDLoc DL(LD);
18713 // Details about the old load
18714 SDValue Ch = LD->getChain();
18715 SDValue BasePtr = LD->getBasePtr();
18716 Align Alignment = LD->getBaseAlign();
18717 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
18718 AAMDNodes AAInfo = LD->getAAInfo();
18719
18720 SDValue Offset = DAG.getUNDEF(VT: BasePtr.getValueType());
18721 EVT NewFromVT = EVT::getVectorVT(
18722 Context&: C, VT: EVT::getIntegerVT(Context&: C, BitWidth: FromEltVT.getScalarSizeInBits()), NumElements);
18723 EVT NewToVT = EVT::getVectorVT(
18724 Context&: C, VT: EVT::getIntegerVT(Context&: C, BitWidth: ToEltVT.getScalarSizeInBits()), NumElements);
18725
18726 SmallVector<SDValue, 4> Loads;
18727 SmallVector<SDValue, 4> Chains;
18728 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
18729 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
18730 SDValue NewPtr =
18731 DAG.getObjectPtrOffset(SL: DL, Ptr: BasePtr, Offset: TypeSize::getFixed(ExactSize: NewOffset));
18732
18733 SDValue NewLoad =
18734 DAG.getLoad(AM: ISD::UNINDEXED, ExtType: NewExtType, VT: NewToVT, dl: DL, Chain: Ch, Ptr: NewPtr, Offset,
18735 PtrInfo: LD->getPointerInfo().getWithOffset(O: NewOffset), MemVT: NewFromVT,
18736 Alignment, MMOFlags, AAInfo);
18737 Loads.push_back(Elt: NewLoad);
18738 Chains.push_back(Elt: SDValue(NewLoad.getNode(), 1));
18739 }
18740
18741 SDValue NewChain = DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Chains);
18742 DAG.ReplaceAllUsesOfValueWith(From: SDValue(LD, 1), To: NewChain);
18743 return DAG.getMergeValues(Ops: Loads, dl: DL);
18744}
18745
18746// Perform combines for MVEEXT. If it has not be optimized to anything better
18747// before lowering, it gets converted to stack store and extloads performing the
18748// extend whilst still keeping the same lane ordering.
18749SDValue ARMTargetLowering::PerformMVEExtCombine(
18750 SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
18751 SelectionDAG &DAG = DCI.DAG;
18752 EVT VT = N->getValueType(ResNo: 0);
18753 SDLoc DL(N);
18754 assert(N->getNumValues() == 2 && "Expected MVEEXT with 2 elements");
18755 assert((VT == MVT::v4i32 || VT == MVT::v8i16) && "Unexpected MVEEXT type");
18756
18757 EVT ExtVT = N->getOperand(Num: 0).getValueType().getHalfNumVectorElementsVT(
18758 Context&: *DAG.getContext());
18759 auto Extend = [&](SDValue V) {
18760 SDValue VVT = DAG.getNode(Opcode: ARMISD::VECTOR_REG_CAST, DL, VT, Operand: V);
18761 return N->getOpcode() == ARMISD::MVESEXT
18762 ? DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL, VT, N1: VVT,
18763 N2: DAG.getValueType(ExtVT))
18764 : DAG.getZeroExtendInReg(Op: VVT, DL, VT: ExtVT);
18765 };
18766
18767 // MVEEXT(VDUP) -> SIGN_EXTEND_INREG(VDUP)
18768 if (N->getOperand(Num: 0).getOpcode() == ARMISD::VDUP) {
18769 SDValue Ext = Extend(N->getOperand(Num: 0));
18770 return DAG.getMergeValues(Ops: {Ext, Ext}, dl: DL);
18771 }
18772
18773 // MVEEXT(shuffle) -> SIGN_EXTEND_INREG/ZERO_EXTEND_INREG
18774 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Val: N->getOperand(Num: 0))) {
18775 ArrayRef<int> Mask = SVN->getMask();
18776 assert(Mask.size() == 2 * VT.getVectorNumElements());
18777 assert(Mask.size() == SVN->getValueType(0).getVectorNumElements());
18778 unsigned Rev = VT == MVT::v4i32 ? ARMISD::VREV32 : ARMISD::VREV16;
18779 SDValue Op0 = SVN->getOperand(Num: 0);
18780 SDValue Op1 = SVN->getOperand(Num: 1);
18781
18782 auto CheckInregMask = [&](int Start, int Offset) {
18783 for (int Idx = 0, E = VT.getVectorNumElements(); Idx < E; ++Idx)
18784 if (Mask[Start + Idx] >= 0 && Mask[Start + Idx] != Idx * 2 + Offset)
18785 return false;
18786 return true;
18787 };
18788 SDValue V0 = SDValue(N, 0);
18789 SDValue V1 = SDValue(N, 1);
18790 if (CheckInregMask(0, 0))
18791 V0 = Extend(Op0);
18792 else if (CheckInregMask(0, 1))
18793 V0 = Extend(DAG.getNode(Opcode: Rev, DL, VT: SVN->getValueType(ResNo: 0), Operand: Op0));
18794 else if (CheckInregMask(0, Mask.size()))
18795 V0 = Extend(Op1);
18796 else if (CheckInregMask(0, Mask.size() + 1))
18797 V0 = Extend(DAG.getNode(Opcode: Rev, DL, VT: SVN->getValueType(ResNo: 0), Operand: Op1));
18798
18799 if (CheckInregMask(VT.getVectorNumElements(), Mask.size()))
18800 V1 = Extend(Op1);
18801 else if (CheckInregMask(VT.getVectorNumElements(), Mask.size() + 1))
18802 V1 = Extend(DAG.getNode(Opcode: Rev, DL, VT: SVN->getValueType(ResNo: 0), Operand: Op1));
18803 else if (CheckInregMask(VT.getVectorNumElements(), 0))
18804 V1 = Extend(Op0);
18805 else if (CheckInregMask(VT.getVectorNumElements(), 1))
18806 V1 = Extend(DAG.getNode(Opcode: Rev, DL, VT: SVN->getValueType(ResNo: 0), Operand: Op0));
18807
18808 if (V0.getNode() != N || V1.getNode() != N)
18809 return DAG.getMergeValues(Ops: {V0, V1}, dl: DL);
18810 }
18811
18812 // MVEEXT(load) -> extload, extload
18813 if (N->getOperand(Num: 0)->getOpcode() == ISD::LOAD)
18814 if (SDValue L = PerformSplittingMVEEXTToWideningLoad(N, DAG))
18815 return L;
18816
18817 if (!DCI.isAfterLegalizeDAG())
18818 return SDValue();
18819
18820 // Lower to a stack store and reload:
18821 // VSTRW.32 a, stack; VLDRH.32 stack; VLDRH.32 stack+8;
18822 SDValue StackPtr = DAG.CreateStackTemporary(Bytes: TypeSize::getFixed(ExactSize: 16), Alignment: Align(4));
18823 int SPFI = cast<FrameIndexSDNode>(Val: StackPtr.getNode())->getIndex();
18824 int NumOuts = N->getNumValues();
18825 assert((NumOuts == 2 || NumOuts == 4) &&
18826 "Expected 2 or 4 outputs to an MVEEXT");
18827 EVT LoadVT = N->getOperand(Num: 0).getValueType().getHalfNumVectorElementsVT(
18828 Context&: *DAG.getContext());
18829 if (N->getNumOperands() == 4)
18830 LoadVT = LoadVT.getHalfNumVectorElementsVT(Context&: *DAG.getContext());
18831
18832 MachinePointerInfo MPI =
18833 MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI: SPFI, Offset: 0);
18834 SDValue Chain = DAG.getStore(Chain: DAG.getEntryNode(), dl: DL, Val: N->getOperand(Num: 0),
18835 Ptr: StackPtr, PtrInfo: MPI, Alignment: Align(4));
18836
18837 SmallVector<SDValue> Loads;
18838 for (int I = 0; I < NumOuts; I++) {
18839 SDValue Ptr = DAG.getNode(
18840 Opcode: ISD::ADD, DL, VT: StackPtr.getValueType(), N1: StackPtr,
18841 N2: DAG.getConstant(Val: I * 16 / NumOuts, DL, VT: StackPtr.getValueType()));
18842 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
18843 MF&: DAG.getMachineFunction(), FI: SPFI, Offset: I * 16 / NumOuts);
18844 SDValue Load = DAG.getExtLoad(
18845 ExtType: N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD, dl: DL,
18846 VT, Chain, Ptr, PtrInfo: MPI, MemVT: LoadVT, Alignment: Align(4));
18847 Loads.push_back(Elt: Load);
18848 }
18849
18850 return DAG.getMergeValues(Ops: Loads, dl: DL);
18851}
18852
18853SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
18854 DAGCombinerInfo &DCI) const {
18855 switch (N->getOpcode()) {
18856 default: break;
18857 case ISD::SELECT_CC:
18858 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget);
18859 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget);
18860 case ISD::SETCC: return PerformVSetCCToVCTPCombine(N, DCI, Subtarget);
18861 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
18862 case ARMISD::UMLAL: return PerformUMLALCombine(N, DAG&: DCI.DAG, Subtarget);
18863 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
18864 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget);
18865 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
18866 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
18867 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
18868 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
18869 case ISD::BRCOND:
18870 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, ST: Subtarget);
18871 case ARMISD::ADDC:
18872 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
18873 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
18874 case ARMISD::BFI: return PerformBFICombine(N, DAG&: DCI.DAG);
18875 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
18876 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DAG&: DCI.DAG);
18877 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI);
18878 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DAG&: DCI.DAG);
18879 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
18880 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
18881 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
18882 case ISD::EXTRACT_VECTOR_ELT:
18883 return PerformExtractEltCombine(N, DCI, ST: Subtarget);
18884 case ISD::SIGN_EXTEND_INREG: return PerformSignExtendInregCombine(N, DAG&: DCI.DAG);
18885 case ISD::INSERT_SUBVECTOR: return PerformInsertSubvectorCombine(N, DCI);
18886 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DAG&: DCI.DAG);
18887 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
18888 case ARMISD::VDUP: return PerformVDUPCombine(N, DAG&: DCI.DAG, Subtarget);
18889 case ISD::FP_TO_SINT:
18890 case ISD::FP_TO_UINT:
18891 return PerformVCVTCombine(N, DAG&: DCI.DAG, Subtarget);
18892 case ISD::FADD:
18893 return PerformFADDCombine(N, DAG&: DCI.DAG, Subtarget);
18894 case ISD::FMUL:
18895 return PerformVMulVCTPCombine(N, DAG&: DCI.DAG, Subtarget);
18896 case ISD::INTRINSIC_WO_CHAIN:
18897 return PerformIntrinsicCombine(N, DCI);
18898 case ISD::SHL:
18899 case ISD::SRA:
18900 case ISD::SRL:
18901 return PerformShiftCombine(N, DCI, ST: Subtarget);
18902 case ISD::SIGN_EXTEND:
18903 case ISD::ZERO_EXTEND:
18904 case ISD::ANY_EXTEND:
18905 return PerformExtendCombine(N, DAG&: DCI.DAG, ST: Subtarget);
18906 case ISD::FP_EXTEND:
18907 return PerformFPExtendCombine(N, DAG&: DCI.DAG, ST: Subtarget);
18908 case ISD::SMIN:
18909 case ISD::UMIN:
18910 case ISD::SMAX:
18911 case ISD::UMAX:
18912 return PerformMinMaxCombine(N, DAG&: DCI.DAG, ST: Subtarget);
18913 case ARMISD::CMOV:
18914 return PerformCMOVCombine(N, DAG&: DCI.DAG);
18915 case ARMISD::BRCOND:
18916 return PerformBRCONDCombine(N, DAG&: DCI.DAG);
18917 case ARMISD::CMPZ:
18918 return PerformCMPZCombine(N, DAG&: DCI.DAG);
18919 case ARMISD::CSINC:
18920 case ARMISD::CSINV:
18921 case ARMISD::CSNEG:
18922 return PerformCSETCombine(N, DAG&: DCI.DAG);
18923 case ISD::LOAD:
18924 return PerformLOADCombine(N, DCI, Subtarget);
18925 case ARMISD::VLD1DUP:
18926 case ARMISD::VLD2DUP:
18927 case ARMISD::VLD3DUP:
18928 case ARMISD::VLD4DUP:
18929 return PerformVLDCombine(N, DCI);
18930 case ARMISD::BUILD_VECTOR:
18931 return PerformARMBUILD_VECTORCombine(N, DCI);
18932 case ISD::BITCAST:
18933 return PerformBITCASTCombine(N, DCI, ST: Subtarget);
18934 case ARMISD::PREDICATE_CAST:
18935 return PerformPREDICATE_CASTCombine(N, DCI);
18936 case ARMISD::VECTOR_REG_CAST:
18937 return PerformVECTOR_REG_CASTCombine(N, DAG&: DCI.DAG, ST: Subtarget);
18938 case ARMISD::MVETRUNC:
18939 return PerformMVETruncCombine(N, DCI);
18940 case ARMISD::MVESEXT:
18941 case ARMISD::MVEZEXT:
18942 return PerformMVEExtCombine(N, DCI);
18943 case ARMISD::VCMP:
18944 return PerformVCMPCombine(N, DAG&: DCI.DAG, Subtarget);
18945 case ISD::VECREDUCE_ADD:
18946 return PerformVECREDUCE_ADDCombine(N, DAG&: DCI.DAG, ST: Subtarget);
18947 case ARMISD::VADDVs:
18948 case ARMISD::VADDVu:
18949 case ARMISD::VADDLVs:
18950 case ARMISD::VADDLVu:
18951 case ARMISD::VADDLVAs:
18952 case ARMISD::VADDLVAu:
18953 case ARMISD::VMLAVs:
18954 case ARMISD::VMLAVu:
18955 case ARMISD::VMLALVs:
18956 case ARMISD::VMLALVu:
18957 case ARMISD::VMLALVAs:
18958 case ARMISD::VMLALVAu:
18959 return PerformReduceShuffleCombine(N, DAG&: DCI.DAG);
18960 case ARMISD::VMOVN:
18961 return PerformVMOVNCombine(N, DCI);
18962 case ARMISD::VQMOVNs:
18963 case ARMISD::VQMOVNu:
18964 return PerformVQMOVNCombine(N, DCI);
18965 case ARMISD::VQDMULH:
18966 return PerformVQDMULHCombine(N, DCI);
18967 case ARMISD::ASRL:
18968 case ARMISD::LSRL:
18969 case ARMISD::LSLL:
18970 return PerformLongShiftCombine(N, DAG&: DCI.DAG);
18971 case ARMISD::SMULWB: {
18972 unsigned BitWidth = N->getValueType(ResNo: 0).getSizeInBits();
18973 APInt DemandedMask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: 16);
18974 if (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI))
18975 return SDValue();
18976 break;
18977 }
18978 case ARMISD::SMULWT: {
18979 unsigned BitWidth = N->getValueType(ResNo: 0).getSizeInBits();
18980 APInt DemandedMask = APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: 16);
18981 if (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI))
18982 return SDValue();
18983 break;
18984 }
18985 case ARMISD::SMLALBB:
18986 case ARMISD::QADD16b:
18987 case ARMISD::QSUB16b:
18988 case ARMISD::UQADD16b:
18989 case ARMISD::UQSUB16b: {
18990 unsigned BitWidth = N->getValueType(ResNo: 0).getSizeInBits();
18991 APInt DemandedMask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: 16);
18992 if ((SimplifyDemandedBits(Op: N->getOperand(Num: 0), DemandedBits: DemandedMask, DCI)) ||
18993 (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI)))
18994 return SDValue();
18995 break;
18996 }
18997 case ARMISD::SMLALBT: {
18998 unsigned LowWidth = N->getOperand(Num: 0).getValueType().getSizeInBits();
18999 APInt LowMask = APInt::getLowBitsSet(numBits: LowWidth, loBitsSet: 16);
19000 unsigned HighWidth = N->getOperand(Num: 1).getValueType().getSizeInBits();
19001 APInt HighMask = APInt::getHighBitsSet(numBits: HighWidth, hiBitsSet: 16);
19002 if ((SimplifyDemandedBits(Op: N->getOperand(Num: 0), DemandedBits: LowMask, DCI)) ||
19003 (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: HighMask, DCI)))
19004 return SDValue();
19005 break;
19006 }
19007 case ARMISD::SMLALTB: {
19008 unsigned HighWidth = N->getOperand(Num: 0).getValueType().getSizeInBits();
19009 APInt HighMask = APInt::getHighBitsSet(numBits: HighWidth, hiBitsSet: 16);
19010 unsigned LowWidth = N->getOperand(Num: 1).getValueType().getSizeInBits();
19011 APInt LowMask = APInt::getLowBitsSet(numBits: LowWidth, loBitsSet: 16);
19012 if ((SimplifyDemandedBits(Op: N->getOperand(Num: 0), DemandedBits: HighMask, DCI)) ||
19013 (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: LowMask, DCI)))
19014 return SDValue();
19015 break;
19016 }
19017 case ARMISD::SMLALTT: {
19018 unsigned BitWidth = N->getValueType(ResNo: 0).getSizeInBits();
19019 APInt DemandedMask = APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: 16);
19020 if ((SimplifyDemandedBits(Op: N->getOperand(Num: 0), DemandedBits: DemandedMask, DCI)) ||
19021 (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI)))
19022 return SDValue();
19023 break;
19024 }
19025 case ARMISD::QADD8b:
19026 case ARMISD::QSUB8b:
19027 case ARMISD::UQADD8b:
19028 case ARMISD::UQSUB8b: {
19029 unsigned BitWidth = N->getValueType(ResNo: 0).getSizeInBits();
19030 APInt DemandedMask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: 8);
19031 if ((SimplifyDemandedBits(Op: N->getOperand(Num: 0), DemandedBits: DemandedMask, DCI)) ||
19032 (SimplifyDemandedBits(Op: N->getOperand(Num: 1), DemandedBits: DemandedMask, DCI)))
19033 return SDValue();
19034 break;
19035 }
19036 case ARMISD::VBSP:
19037 if (N->getOperand(Num: 1) == N->getOperand(Num: 2))
19038 return N->getOperand(Num: 1);
19039 return SDValue();
19040 case ISD::INTRINSIC_VOID:
19041 case ISD::INTRINSIC_W_CHAIN:
19042 switch (N->getConstantOperandVal(Num: 1)) {
19043 case Intrinsic::arm_neon_vld1:
19044 case Intrinsic::arm_neon_vld1x2:
19045 case Intrinsic::arm_neon_vld1x3:
19046 case Intrinsic::arm_neon_vld1x4:
19047 case Intrinsic::arm_neon_vld2:
19048 case Intrinsic::arm_neon_vld3:
19049 case Intrinsic::arm_neon_vld4:
19050 case Intrinsic::arm_neon_vld2lane:
19051 case Intrinsic::arm_neon_vld3lane:
19052 case Intrinsic::arm_neon_vld4lane:
19053 case Intrinsic::arm_neon_vld2dup:
19054 case Intrinsic::arm_neon_vld3dup:
19055 case Intrinsic::arm_neon_vld4dup:
19056 case Intrinsic::arm_neon_vst1:
19057 case Intrinsic::arm_neon_vst1x2:
19058 case Intrinsic::arm_neon_vst1x3:
19059 case Intrinsic::arm_neon_vst1x4:
19060 case Intrinsic::arm_neon_vst2:
19061 case Intrinsic::arm_neon_vst3:
19062 case Intrinsic::arm_neon_vst4:
19063 case Intrinsic::arm_neon_vst2lane:
19064 case Intrinsic::arm_neon_vst3lane:
19065 case Intrinsic::arm_neon_vst4lane:
19066 return PerformVLDCombine(N, DCI);
19067 case Intrinsic::arm_mve_vld2q:
19068 case Intrinsic::arm_mve_vld4q:
19069 case Intrinsic::arm_mve_vst2q:
19070 case Intrinsic::arm_mve_vst4q:
19071 return PerformMVEVLDCombine(N, DCI);
19072 default: break;
19073 }
19074 break;
19075 }
19076 return SDValue();
19077}
19078
19079bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
19080 EVT VT) const {
19081 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
19082}
19083
19084bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
19085 Align Alignment,
19086 MachineMemOperand::Flags,
19087 unsigned *Fast) const {
19088 // Depends what it gets converted into if the type is weird.
19089 if (!VT.isSimple())
19090 return false;
19091
19092 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
19093 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
19094 auto Ty = VT.getSimpleVT().SimpleTy;
19095
19096 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
19097 // Unaligned access can use (for example) LRDB, LRDH, LDR
19098 if (AllowsUnaligned) {
19099 if (Fast)
19100 *Fast = Subtarget->hasV7Ops();
19101 return true;
19102 }
19103 }
19104
19105 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
19106 // For any little-endian targets with neon, we can support unaligned ld/st
19107 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
19108 // A big-endian target may also explicitly support unaligned accesses
19109 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
19110 if (Fast)
19111 *Fast = 1;
19112 return true;
19113 }
19114 }
19115
19116 if (!Subtarget->hasMVEIntegerOps())
19117 return false;
19118
19119 // These are for predicates
19120 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1 ||
19121 Ty == MVT::v2i1)) {
19122 if (Fast)
19123 *Fast = 1;
19124 return true;
19125 }
19126
19127 // These are for truncated stores/narrowing loads. They are fine so long as
19128 // the alignment is at least the size of the item being loaded
19129 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
19130 Alignment >= VT.getScalarSizeInBits() / 8) {
19131 if (Fast)
19132 *Fast = true;
19133 return true;
19134 }
19135
19136 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
19137 // VSTRW.U32 all store the vector register in exactly the same format, and
19138 // differ only in the range of their immediate offset field and the required
19139 // alignment. So there is always a store that can be used, regardless of
19140 // actual type.
19141 //
19142 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
19143 // VREV64.8) pair and get the same effect. This will likely be better than
19144 // aligning the vector through the stack.
19145 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
19146 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
19147 Ty == MVT::v2f64) {
19148 if (Fast)
19149 *Fast = 1;
19150 return true;
19151 }
19152
19153 return false;
19154}
19155
19156EVT ARMTargetLowering::getOptimalMemOpType(
19157 LLVMContext &Context, const MemOp &Op,
19158 const AttributeList &FuncAttributes) const {
19159 // See if we can use NEON instructions for this...
19160 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
19161 !FuncAttributes.hasFnAttr(Kind: Attribute::NoImplicitFloat)) {
19162 unsigned Fast;
19163 if (Op.size() >= 16 &&
19164 (Op.isAligned(AlignCheck: Align(16)) ||
19165 (allowsMisalignedMemoryAccesses(VT: MVT::v2f64, 0, Alignment: Align(1),
19166 MachineMemOperand::MONone, Fast: &Fast) &&
19167 Fast))) {
19168 return MVT::v2f64;
19169 } else if (Op.size() >= 8 &&
19170 (Op.isAligned(AlignCheck: Align(8)) ||
19171 (allowsMisalignedMemoryAccesses(
19172 VT: MVT::f64, 0, Alignment: Align(1), MachineMemOperand::MONone, Fast: &Fast) &&
19173 Fast))) {
19174 return MVT::f64;
19175 }
19176 }
19177
19178 // Let the target-independent logic figure it out.
19179 return MVT::Other;
19180}
19181
19182// 64-bit integers are split into their high and low parts and held in two
19183// different registers, so the trunc is free since the low register can just
19184// be used.
19185bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
19186 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
19187 return false;
19188 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
19189 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
19190 return (SrcBits == 64 && DestBits == 32);
19191}
19192
19193bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
19194 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
19195 !DstVT.isInteger())
19196 return false;
19197 unsigned SrcBits = SrcVT.getSizeInBits();
19198 unsigned DestBits = DstVT.getSizeInBits();
19199 return (SrcBits == 64 && DestBits == 32);
19200}
19201
19202bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19203 if (Val.getOpcode() != ISD::LOAD)
19204 return false;
19205
19206 EVT VT1 = Val.getValueType();
19207 if (!VT1.isSimple() || !VT1.isInteger() ||
19208 !VT2.isSimple() || !VT2.isInteger())
19209 return false;
19210
19211 switch (VT1.getSimpleVT().SimpleTy) {
19212 default: break;
19213 case MVT::i1:
19214 case MVT::i8:
19215 case MVT::i16:
19216 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
19217 return true;
19218 }
19219
19220 return false;
19221}
19222
19223bool ARMTargetLowering::isFNegFree(EVT VT) const {
19224 if (!VT.isSimple())
19225 return false;
19226
19227 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
19228 // negate values directly (fneg is free). So, we don't want to let the DAG
19229 // combiner rewrite fneg into xors and some other instructions. For f16 and
19230 // FullFP16 argument passing, some bitcast nodes may be introduced,
19231 // triggering this DAG combine rewrite, so we are avoiding that with this.
19232 switch (VT.getSimpleVT().SimpleTy) {
19233 default: break;
19234 case MVT::f16:
19235 return Subtarget->hasFullFP16();
19236 }
19237
19238 return false;
19239}
19240
19241Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
19242 if (!Subtarget->hasMVEIntegerOps())
19243 return nullptr;
19244 Type *SVIType = SVI->getType();
19245 Type *ScalarType = SVIType->getScalarType();
19246
19247 if (ScalarType->isFloatTy())
19248 return Type::getInt32Ty(C&: SVIType->getContext());
19249 if (ScalarType->isHalfTy())
19250 return Type::getInt16Ty(C&: SVIType->getContext());
19251 return nullptr;
19252}
19253
19254bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
19255 EVT VT = ExtVal.getValueType();
19256
19257 if (!isTypeLegal(VT))
19258 return false;
19259
19260 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(Val: ExtVal.getOperand(i: 0))) {
19261 if (Ld->isExpandingLoad())
19262 return false;
19263 }
19264
19265 if (Subtarget->hasMVEIntegerOps())
19266 return true;
19267
19268 // Don't create a loadext if we can fold the extension into a wide/long
19269 // instruction.
19270 // If there's more than one user instruction, the loadext is desirable no
19271 // matter what. There can be two uses by the same instruction.
19272 if (ExtVal->use_empty() ||
19273 !ExtVal->user_begin()->isOnlyUserOf(N: ExtVal.getNode()))
19274 return true;
19275
19276 SDNode *U = *ExtVal->user_begin();
19277 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
19278 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
19279 return false;
19280
19281 return true;
19282}
19283
19284bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19285 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19286 return false;
19287
19288 if (!isTypeLegal(VT: EVT::getEVT(Ty: Ty1)))
19289 return false;
19290
19291 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19292
19293 // Assuming the caller doesn't have a zeroext or signext return parameter,
19294 // truncation all the way down to i1 is valid.
19295 return true;
19296}
19297
19298/// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
19299/// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
19300/// expanded to FMAs when this method returns true, otherwise fmuladd is
19301/// expanded to fmul + fadd.
19302///
19303/// ARM supports both fused and unfused multiply-add operations; we already
19304/// lower a pair of fmul and fadd to the latter so it's not clear that there
19305/// would be a gain or that the gain would be worthwhile enough to risk
19306/// correctness bugs.
19307///
19308/// For MVE, we set this to true as it helps simplify the need for some
19309/// patterns (and we don't have the non-fused floating point instruction).
19310bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
19311 EVT VT) const {
19312 if (Subtarget->useSoftFloat())
19313 return false;
19314
19315 if (!VT.isSimple())
19316 return false;
19317
19318 switch (VT.getSimpleVT().SimpleTy) {
19319 case MVT::v4f32:
19320 case MVT::v8f16:
19321 return Subtarget->hasMVEFloatOps();
19322 case MVT::f16:
19323 return Subtarget->useFPVFMx16();
19324 case MVT::f32:
19325 return Subtarget->useFPVFMx();
19326 case MVT::f64:
19327 return Subtarget->useFPVFMx64();
19328 default:
19329 break;
19330 }
19331
19332 return false;
19333}
19334
19335static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
19336 if (V < 0)
19337 return false;
19338
19339 unsigned Scale = 1;
19340 switch (VT.getSimpleVT().SimpleTy) {
19341 case MVT::i1:
19342 case MVT::i8:
19343 // Scale == 1;
19344 break;
19345 case MVT::i16:
19346 // Scale == 2;
19347 Scale = 2;
19348 break;
19349 default:
19350 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
19351 // Scale == 4;
19352 Scale = 4;
19353 break;
19354 }
19355
19356 if ((V & (Scale - 1)) != 0)
19357 return false;
19358 return isUInt<5>(x: V / Scale);
19359}
19360
19361static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
19362 const ARMSubtarget *Subtarget) {
19363 if (!VT.isInteger() && !VT.isFloatingPoint())
19364 return false;
19365 if (VT.isVector() && Subtarget->hasNEON())
19366 return false;
19367 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
19368 !Subtarget->hasMVEFloatOps())
19369 return false;
19370
19371 bool IsNeg = false;
19372 if (V < 0) {
19373 IsNeg = true;
19374 V = -V;
19375 }
19376
19377 unsigned NumBytes = std::max(a: (unsigned)VT.getSizeInBits() / 8, b: 1U);
19378
19379 // MVE: size * imm7
19380 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
19381 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
19382 case MVT::i32:
19383 case MVT::f32:
19384 return isShiftedUInt<7,2>(x: V);
19385 case MVT::i16:
19386 case MVT::f16:
19387 return isShiftedUInt<7,1>(x: V);
19388 case MVT::i8:
19389 return isUInt<7>(x: V);
19390 default:
19391 return false;
19392 }
19393 }
19394
19395 // half VLDR: 2 * imm8
19396 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
19397 return isShiftedUInt<8, 1>(x: V);
19398 // VLDR and LDRD: 4 * imm8
19399 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
19400 return isShiftedUInt<8, 2>(x: V);
19401
19402 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
19403 // + imm12 or - imm8
19404 if (IsNeg)
19405 return isUInt<8>(x: V);
19406 return isUInt<12>(x: V);
19407 }
19408
19409 return false;
19410}
19411
19412/// isLegalAddressImmediate - Return true if the integer value can be used
19413/// as the offset of the target addressing mode for load / store of the
19414/// given type.
19415static bool isLegalAddressImmediate(int64_t V, EVT VT,
19416 const ARMSubtarget *Subtarget) {
19417 if (V == 0)
19418 return true;
19419
19420 if (!VT.isSimple())
19421 return false;
19422
19423 if (Subtarget->isThumb1Only())
19424 return isLegalT1AddressImmediate(V, VT);
19425 else if (Subtarget->isThumb2())
19426 return isLegalT2AddressImmediate(V, VT, Subtarget);
19427
19428 // ARM mode.
19429 if (V < 0)
19430 V = - V;
19431 switch (VT.getSimpleVT().SimpleTy) {
19432 default: return false;
19433 case MVT::i1:
19434 case MVT::i8:
19435 case MVT::i32:
19436 // +- imm12
19437 return isUInt<12>(x: V);
19438 case MVT::i16:
19439 // +- imm8
19440 return isUInt<8>(x: V);
19441 case MVT::f32:
19442 case MVT::f64:
19443 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
19444 return false;
19445 return isShiftedUInt<8, 2>(x: V);
19446 }
19447}
19448
19449bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
19450 EVT VT) const {
19451 int Scale = AM.Scale;
19452 if (Scale < 0)
19453 return false;
19454
19455 switch (VT.getSimpleVT().SimpleTy) {
19456 default: return false;
19457 case MVT::i1:
19458 case MVT::i8:
19459 case MVT::i16:
19460 case MVT::i32:
19461 if (Scale == 1)
19462 return true;
19463 // r + r << imm
19464 Scale = Scale & ~1;
19465 return Scale == 2 || Scale == 4 || Scale == 8;
19466 case MVT::i64:
19467 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
19468 // version in Thumb mode.
19469 // r + r
19470 if (Scale == 1)
19471 return true;
19472 // r * 2 (this can be lowered to r + r).
19473 if (!AM.HasBaseReg && Scale == 2)
19474 return true;
19475 return false;
19476 case MVT::isVoid:
19477 // Note, we allow "void" uses (basically, uses that aren't loads or
19478 // stores), because arm allows folding a scale into many arithmetic
19479 // operations. This should be made more precise and revisited later.
19480
19481 // Allow r << imm, but the imm has to be a multiple of two.
19482 if (Scale & 1) return false;
19483 return isPowerOf2_32(Value: Scale);
19484 }
19485}
19486
19487bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
19488 EVT VT) const {
19489 const int Scale = AM.Scale;
19490
19491 // Negative scales are not supported in Thumb1.
19492 if (Scale < 0)
19493 return false;
19494
19495 // Thumb1 addressing modes do not support register scaling excepting the
19496 // following cases:
19497 // 1. Scale == 1 means no scaling.
19498 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
19499 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
19500}
19501
19502/// isLegalAddressingMode - Return true if the addressing mode represented
19503/// by AM is legal for this target, for a load/store of the specified type.
19504bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
19505 const AddrMode &AM, Type *Ty,
19506 unsigned AS, Instruction *I) const {
19507 EVT VT = getValueType(DL, Ty, AllowUnknown: true);
19508 if (!isLegalAddressImmediate(V: AM.BaseOffs, VT, Subtarget))
19509 return false;
19510
19511 // Can never fold addr of global into load/store.
19512 if (AM.BaseGV)
19513 return false;
19514
19515 switch (AM.Scale) {
19516 case 0: // no scale reg, must be "r+i" or "r", or "i".
19517 break;
19518 default:
19519 // ARM doesn't support any R+R*scale+imm addr modes.
19520 if (AM.BaseOffs)
19521 return false;
19522
19523 if (!VT.isSimple())
19524 return false;
19525
19526 if (Subtarget->isThumb1Only())
19527 return isLegalT1ScaledAddressingMode(AM, VT);
19528
19529 if (Subtarget->isThumb2())
19530 return isLegalT2ScaledAddressingMode(AM, VT);
19531
19532 int Scale = AM.Scale;
19533 switch (VT.getSimpleVT().SimpleTy) {
19534 default: return false;
19535 case MVT::i1:
19536 case MVT::i8:
19537 case MVT::i32:
19538 if (Scale < 0) Scale = -Scale;
19539 if (Scale == 1)
19540 return true;
19541 // r + r << imm
19542 return isPowerOf2_32(Value: Scale & ~1);
19543 case MVT::i16:
19544 case MVT::i64:
19545 // r +/- r
19546 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
19547 return true;
19548 // r * 2 (this can be lowered to r + r).
19549 if (!AM.HasBaseReg && Scale == 2)
19550 return true;
19551 return false;
19552
19553 case MVT::isVoid:
19554 // Note, we allow "void" uses (basically, uses that aren't loads or
19555 // stores), because arm allows folding a scale into many arithmetic
19556 // operations. This should be made more precise and revisited later.
19557
19558 // Allow r << imm, but the imm has to be a multiple of two.
19559 if (Scale & 1) return false;
19560 return isPowerOf2_32(Value: Scale);
19561 }
19562 }
19563 return true;
19564}
19565
19566/// isLegalICmpImmediate - Return true if the specified immediate is legal
19567/// icmp immediate, that is the target has icmp instructions which can compare
19568/// a register against the immediate without having to materialize the
19569/// immediate into a register.
19570bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19571 // Thumb2 and ARM modes can use cmn for negative immediates.
19572 if (!Subtarget->isThumb())
19573 return ARM_AM::getSOImmVal(Arg: (uint32_t)Imm) != -1 ||
19574 ARM_AM::getSOImmVal(Arg: -(uint32_t)Imm) != -1;
19575 if (Subtarget->isThumb2())
19576 return ARM_AM::getT2SOImmVal(Arg: (uint32_t)Imm) != -1 ||
19577 ARM_AM::getT2SOImmVal(Arg: -(uint32_t)Imm) != -1;
19578 // Thumb1 doesn't have cmn, and only 8-bit immediates.
19579 return Imm >= 0 && Imm <= 255;
19580}
19581
19582/// isLegalAddImmediate - Return true if the specified immediate is a legal add
19583/// *or sub* immediate, that is the target has add or sub instructions which can
19584/// add a register with the immediate without having to materialize the
19585/// immediate into a register.
19586bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
19587 // Same encoding for add/sub, just flip the sign.
19588 uint64_t AbsImm = AbsoluteValue(X: Imm);
19589 if (!Subtarget->isThumb())
19590 return ARM_AM::getSOImmVal(Arg: AbsImm) != -1;
19591 if (Subtarget->isThumb2())
19592 return ARM_AM::getT2SOImmVal(Arg: AbsImm) != -1;
19593 // Thumb1 only has 8-bit unsigned immediate.
19594 return AbsImm <= 255;
19595}
19596
19597// Return false to prevent folding
19598// (mul (add r, c0), c1) -> (add (mul r, c1), c0*c1) in DAGCombine,
19599// if the folding leads to worse code.
19600bool ARMTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
19601 SDValue ConstNode) const {
19602 // Let the DAGCombiner decide for vector types and large types.
19603 const EVT VT = AddNode.getValueType();
19604 if (VT.isVector() || VT.getScalarSizeInBits() > 32)
19605 return true;
19606
19607 // It is worse if c0 is legal add immediate, while c1*c0 is not
19608 // and has to be composed by at least two instructions.
19609 const ConstantSDNode *C0Node = cast<ConstantSDNode>(Val: AddNode.getOperand(i: 1));
19610 const ConstantSDNode *C1Node = cast<ConstantSDNode>(Val&: ConstNode);
19611 const int64_t C0 = C0Node->getSExtValue();
19612 APInt CA = C0Node->getAPIntValue() * C1Node->getAPIntValue();
19613 if (!isLegalAddImmediate(Imm: C0) || isLegalAddImmediate(Imm: CA.getSExtValue()))
19614 return true;
19615 if (ConstantMaterializationCost(Val: (unsigned)CA.getZExtValue(), Subtarget) > 1)
19616 return false;
19617
19618 // Default to true and let the DAGCombiner decide.
19619 return true;
19620}
19621
19622static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
19623 bool isSEXTLoad, SDValue &Base,
19624 SDValue &Offset, bool &isInc,
19625 SelectionDAG &DAG) {
19626 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19627 return false;
19628
19629 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
19630 // AddressingMode 3
19631 Base = Ptr->getOperand(Num: 0);
19632 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Val: Ptr->getOperand(Num: 1))) {
19633 int RHSC = (int)RHS->getZExtValue();
19634 if (RHSC < 0 && RHSC > -256) {
19635 assert(Ptr->getOpcode() == ISD::ADD);
19636 isInc = false;
19637 Offset = DAG.getConstant(Val: -RHSC, DL: SDLoc(Ptr), VT: RHS->getValueType(ResNo: 0));
19638 return true;
19639 }
19640 }
19641 isInc = (Ptr->getOpcode() == ISD::ADD);
19642 Offset = Ptr->getOperand(Num: 1);
19643 return true;
19644 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
19645 // AddressingMode 2
19646 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Val: Ptr->getOperand(Num: 1))) {
19647 int RHSC = (int)RHS->getZExtValue();
19648 if (RHSC < 0 && RHSC > -0x1000) {
19649 assert(Ptr->getOpcode() == ISD::ADD);
19650 isInc = false;
19651 Offset = DAG.getConstant(Val: -RHSC, DL: SDLoc(Ptr), VT: RHS->getValueType(ResNo: 0));
19652 Base = Ptr->getOperand(Num: 0);
19653 return true;
19654 }
19655 }
19656
19657 if (Ptr->getOpcode() == ISD::ADD) {
19658 isInc = true;
19659 ARM_AM::ShiftOpc ShOpcVal=
19660 ARM_AM::getShiftOpcForNode(Opcode: Ptr->getOperand(Num: 0).getOpcode());
19661 if (ShOpcVal != ARM_AM::no_shift) {
19662 Base = Ptr->getOperand(Num: 1);
19663 Offset = Ptr->getOperand(Num: 0);
19664 } else {
19665 Base = Ptr->getOperand(Num: 0);
19666 Offset = Ptr->getOperand(Num: 1);
19667 }
19668 return true;
19669 }
19670
19671 isInc = (Ptr->getOpcode() == ISD::ADD);
19672 Base = Ptr->getOperand(Num: 0);
19673 Offset = Ptr->getOperand(Num: 1);
19674 return true;
19675 }
19676
19677 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
19678 return false;
19679}
19680
19681static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
19682 bool isSEXTLoad, SDValue &Base,
19683 SDValue &Offset, bool &isInc,
19684 SelectionDAG &DAG) {
19685 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19686 return false;
19687
19688 Base = Ptr->getOperand(Num: 0);
19689 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Val: Ptr->getOperand(Num: 1))) {
19690 int RHSC = (int)RHS->getZExtValue();
19691 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
19692 assert(Ptr->getOpcode() == ISD::ADD);
19693 isInc = false;
19694 Offset = DAG.getConstant(Val: -RHSC, DL: SDLoc(Ptr), VT: RHS->getValueType(ResNo: 0));
19695 return true;
19696 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
19697 isInc = Ptr->getOpcode() == ISD::ADD;
19698 Offset = DAG.getConstant(Val: RHSC, DL: SDLoc(Ptr), VT: RHS->getValueType(ResNo: 0));
19699 return true;
19700 }
19701 }
19702
19703 return false;
19704}
19705
19706static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
19707 bool isSEXTLoad, bool IsMasked, bool isLE,
19708 SDValue &Base, SDValue &Offset,
19709 bool &isInc, SelectionDAG &DAG) {
19710 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19711 return false;
19712 if (!isa<ConstantSDNode>(Val: Ptr->getOperand(Num: 1)))
19713 return false;
19714
19715 // We allow LE non-masked loads to change the type (for example use a vldrb.8
19716 // as opposed to a vldrw.32). This can allow extra addressing modes or
19717 // alignments for what is otherwise an equivalent instruction.
19718 bool CanChangeType = isLE && !IsMasked;
19719
19720 ConstantSDNode *RHS = cast<ConstantSDNode>(Val: Ptr->getOperand(Num: 1));
19721 int RHSC = (int)RHS->getZExtValue();
19722
19723 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
19724 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
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 < Limit * Scale && RHSC % Scale == 0) {
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 return false;
19735 };
19736
19737 // Try to find a matching instruction based on s/zext, Alignment, Offset and
19738 // (in BE/masked) type.
19739 Base = Ptr->getOperand(Num: 0);
19740 if (VT == MVT::v4i16) {
19741 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
19742 return true;
19743 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
19744 if (IsInRange(RHSC, 0x80, 1))
19745 return true;
19746 } else if (Alignment >= 4 &&
19747 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
19748 IsInRange(RHSC, 0x80, 4))
19749 return true;
19750 else if (Alignment >= 2 &&
19751 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
19752 IsInRange(RHSC, 0x80, 2))
19753 return true;
19754 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
19755 return true;
19756 return false;
19757}
19758
19759/// getPreIndexedAddressParts - returns true by value, base pointer and
19760/// offset pointer and addressing mode by reference if the node's address
19761/// can be legally represented as pre-indexed load / store address.
19762bool
19763ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
19764 SDValue &Offset,
19765 ISD::MemIndexedMode &AM,
19766 SelectionDAG &DAG) const {
19767 if (Subtarget->isThumb1Only())
19768 return false;
19769
19770 EVT VT;
19771 SDValue Ptr;
19772 Align Alignment;
19773 unsigned AS = 0;
19774 bool isSEXTLoad = false;
19775 bool IsMasked = false;
19776 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: N)) {
19777 Ptr = LD->getBasePtr();
19778 VT = LD->getMemoryVT();
19779 Alignment = LD->getAlign();
19780 AS = LD->getAddressSpace();
19781 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19782 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Val: N)) {
19783 Ptr = ST->getBasePtr();
19784 VT = ST->getMemoryVT();
19785 Alignment = ST->getAlign();
19786 AS = ST->getAddressSpace();
19787 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Val: N)) {
19788 Ptr = LD->getBasePtr();
19789 VT = LD->getMemoryVT();
19790 Alignment = LD->getAlign();
19791 AS = LD->getAddressSpace();
19792 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19793 IsMasked = true;
19794 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Val: N)) {
19795 Ptr = ST->getBasePtr();
19796 VT = ST->getMemoryVT();
19797 Alignment = ST->getAlign();
19798 AS = ST->getAddressSpace();
19799 IsMasked = true;
19800 } else
19801 return false;
19802
19803 unsigned Fast = 0;
19804 if (!allowsMisalignedMemoryAccesses(VT, AS, Alignment,
19805 MachineMemOperand::MONone, Fast: &Fast)) {
19806 // Only generate post-increment or pre-increment forms when a real
19807 // hardware instruction exists for them. Do not emit postinc/preinc
19808 // if the operation will end up as a libcall.
19809 return false;
19810 }
19811
19812 bool isInc;
19813 bool isLegal = false;
19814 if (VT.isVector())
19815 isLegal = Subtarget->hasMVEIntegerOps() &&
19816 getMVEIndexedAddressParts(
19817 Ptr: Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
19818 isLE: Subtarget->isLittle(), Base, Offset, isInc, DAG);
19819 else {
19820 if (Subtarget->isThumb2())
19821 isLegal = getT2IndexedAddressParts(Ptr: Ptr.getNode(), VT, isSEXTLoad, Base,
19822 Offset, isInc, DAG);
19823 else
19824 isLegal = getARMIndexedAddressParts(Ptr: Ptr.getNode(), VT, isSEXTLoad, Base,
19825 Offset, isInc, DAG);
19826 }
19827 if (!isLegal)
19828 return false;
19829
19830 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
19831 return true;
19832}
19833
19834/// getPostIndexedAddressParts - returns true by value, base pointer and
19835/// offset pointer and addressing mode by reference if this node can be
19836/// combined with a load / store to form a post-indexed load / store.
19837bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
19838 SDValue &Base,
19839 SDValue &Offset,
19840 ISD::MemIndexedMode &AM,
19841 SelectionDAG &DAG) const {
19842 EVT VT;
19843 SDValue Ptr;
19844 Align Alignment;
19845 bool isSEXTLoad = false, isNonExt;
19846 bool IsMasked = false;
19847 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: N)) {
19848 VT = LD->getMemoryVT();
19849 Ptr = LD->getBasePtr();
19850 Alignment = LD->getAlign();
19851 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19852 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19853 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Val: N)) {
19854 VT = ST->getMemoryVT();
19855 Ptr = ST->getBasePtr();
19856 Alignment = ST->getAlign();
19857 isNonExt = !ST->isTruncatingStore();
19858 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Val: N)) {
19859 VT = LD->getMemoryVT();
19860 Ptr = LD->getBasePtr();
19861 Alignment = LD->getAlign();
19862 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19863 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19864 IsMasked = true;
19865 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Val: N)) {
19866 VT = ST->getMemoryVT();
19867 Ptr = ST->getBasePtr();
19868 Alignment = ST->getAlign();
19869 isNonExt = !ST->isTruncatingStore();
19870 IsMasked = true;
19871 } else
19872 return false;
19873
19874 if (Subtarget->isThumb1Only()) {
19875 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
19876 // must be non-extending/truncating, i32, with an offset of 4.
19877 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
19878 if (Op->getOpcode() != ISD::ADD || !isNonExt)
19879 return false;
19880 auto *RHS = dyn_cast<ConstantSDNode>(Val: Op->getOperand(Num: 1));
19881 if (!RHS || RHS->getZExtValue() != 4)
19882 return false;
19883 if (Alignment < Align(4))
19884 return false;
19885
19886 Offset = Op->getOperand(Num: 1);
19887 Base = Op->getOperand(Num: 0);
19888 AM = ISD::POST_INC;
19889 return true;
19890 }
19891
19892 bool isInc;
19893 bool isLegal = false;
19894 if (VT.isVector())
19895 isLegal = Subtarget->hasMVEIntegerOps() &&
19896 getMVEIndexedAddressParts(Ptr: Op, VT, Alignment, isSEXTLoad, IsMasked,
19897 isLE: Subtarget->isLittle(), Base, Offset,
19898 isInc, DAG);
19899 else {
19900 if (Subtarget->isThumb2())
19901 isLegal = getT2IndexedAddressParts(Ptr: Op, VT, isSEXTLoad, Base, Offset,
19902 isInc, DAG);
19903 else
19904 isLegal = getARMIndexedAddressParts(Ptr: Op, VT, isSEXTLoad, Base, Offset,
19905 isInc, DAG);
19906 }
19907 if (!isLegal)
19908 return false;
19909
19910 if (Ptr != Base) {
19911 // Swap base ptr and offset to catch more post-index load / store when
19912 // it's legal. In Thumb2 mode, offset must be an immediate.
19913 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
19914 !Subtarget->isThumb2())
19915 std::swap(a&: Base, b&: Offset);
19916
19917 // Post-indexed load / store update the base pointer.
19918 if (Ptr != Base)
19919 return false;
19920 }
19921
19922 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
19923 return true;
19924}
19925
19926void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19927 KnownBits &Known,
19928 const APInt &DemandedElts,
19929 const SelectionDAG &DAG,
19930 unsigned Depth) const {
19931 unsigned BitWidth = Known.getBitWidth();
19932 Known.resetAll();
19933 switch (Op.getOpcode()) {
19934 default: break;
19935 case ARMISD::ADDC:
19936 case ARMISD::ADDE:
19937 case ARMISD::SUBC:
19938 case ARMISD::SUBE:
19939 // Special cases when we convert a carry to a boolean.
19940 if (Op.getResNo() == 0) {
19941 SDValue LHS = Op.getOperand(i: 0);
19942 SDValue RHS = Op.getOperand(i: 1);
19943 // (ADDE 0, 0, C) will give us a single bit.
19944 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(V: LHS) &&
19945 isNullConstant(V: RHS)) {
19946 Known.Zero |= APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - 1);
19947 return;
19948 }
19949 }
19950 break;
19951 case ARMISD::CMOV: {
19952 // Bits are known zero/one if known on the LHS and RHS.
19953 Known = DAG.computeKnownBits(Op: Op.getOperand(i: 0), Depth: Depth+1);
19954 if (Known.isUnknown())
19955 return;
19956
19957 KnownBits KnownRHS = DAG.computeKnownBits(Op: Op.getOperand(i: 1), Depth: Depth+1);
19958 Known = Known.intersectWith(RHS: KnownRHS);
19959 return;
19960 }
19961 case ISD::INTRINSIC_W_CHAIN: {
19962 Intrinsic::ID IntID =
19963 static_cast<Intrinsic::ID>(Op->getConstantOperandVal(Num: 1));
19964 switch (IntID) {
19965 default: return;
19966 case Intrinsic::arm_ldaex:
19967 case Intrinsic::arm_ldrex: {
19968 EVT VT = cast<MemIntrinsicSDNode>(Val: Op)->getMemoryVT();
19969 unsigned MemBits = VT.getScalarSizeInBits();
19970 Known.Zero |= APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - MemBits);
19971 return;
19972 }
19973 }
19974 }
19975 case ARMISD::BFI: {
19976 // Conservatively, we can recurse down the first operand
19977 // and just mask out all affected bits.
19978 Known = DAG.computeKnownBits(Op: Op.getOperand(i: 0), Depth: Depth + 1);
19979
19980 // The operand to BFI is already a mask suitable for removing the bits it
19981 // sets.
19982 const APInt &Mask = Op.getConstantOperandAPInt(i: 2);
19983 Known.Zero &= Mask;
19984 Known.One &= Mask;
19985 return;
19986 }
19987 case ARMISD::VGETLANEs:
19988 case ARMISD::VGETLANEu: {
19989 const SDValue &SrcSV = Op.getOperand(i: 0);
19990 EVT VecVT = SrcSV.getValueType();
19991 assert(VecVT.isVector() && "VGETLANE expected a vector type");
19992 const unsigned NumSrcElts = VecVT.getVectorNumElements();
19993 ConstantSDNode *Pos = cast<ConstantSDNode>(Val: Op.getOperand(i: 1).getNode());
19994 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
19995 "VGETLANE index out of bounds");
19996 unsigned Idx = Pos->getZExtValue();
19997 APInt DemandedElt = APInt::getOneBitSet(numBits: NumSrcElts, BitNo: Idx);
19998 Known = DAG.computeKnownBits(Op: SrcSV, DemandedElts: DemandedElt, Depth: Depth + 1);
19999
20000 EVT VT = Op.getValueType();
20001 const unsigned DstSz = VT.getScalarSizeInBits();
20002 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
20003 (void)SrcSz;
20004 assert(SrcSz == Known.getBitWidth());
20005 assert(DstSz > SrcSz);
20006 if (Op.getOpcode() == ARMISD::VGETLANEs)
20007 Known = Known.sext(BitWidth: DstSz);
20008 else {
20009 Known = Known.zext(BitWidth: DstSz);
20010 }
20011 assert(DstSz == Known.getBitWidth());
20012 break;
20013 }
20014 case ARMISD::VMOVrh: {
20015 KnownBits KnownOp = DAG.computeKnownBits(Op: Op->getOperand(Num: 0), Depth: Depth + 1);
20016 assert(KnownOp.getBitWidth() == 16);
20017 Known = KnownOp.zext(BitWidth: 32);
20018 break;
20019 }
20020 case ARMISD::CSINC:
20021 case ARMISD::CSINV:
20022 case ARMISD::CSNEG: {
20023 KnownBits KnownOp0 = DAG.computeKnownBits(Op: Op->getOperand(Num: 0), Depth: Depth + 1);
20024 KnownBits KnownOp1 = DAG.computeKnownBits(Op: Op->getOperand(Num: 1), Depth: Depth + 1);
20025
20026 // The result is either:
20027 // CSINC: KnownOp0 or KnownOp1 + 1
20028 // CSINV: KnownOp0 or ~KnownOp1
20029 // CSNEG: KnownOp0 or KnownOp1 * -1
20030 if (Op.getOpcode() == ARMISD::CSINC)
20031 KnownOp1 =
20032 KnownBits::add(LHS: KnownOp1, RHS: KnownBits::makeConstant(C: APInt(32, 1)));
20033 else if (Op.getOpcode() == ARMISD::CSINV)
20034 std::swap(a&: KnownOp1.Zero, b&: KnownOp1.One);
20035 else if (Op.getOpcode() == ARMISD::CSNEG)
20036 KnownOp1 = KnownBits::mul(LHS: KnownOp1,
20037 RHS: KnownBits::makeConstant(C: APInt::getAllOnes(numBits: 32)));
20038
20039 Known = KnownOp0.intersectWith(RHS: KnownOp1);
20040 break;
20041 }
20042 case ARMISD::VORRIMM:
20043 case ARMISD::VBICIMM: {
20044 unsigned Encoded = Op.getConstantOperandVal(i: 1);
20045 unsigned DecEltBits = 0;
20046 uint64_t DecodedVal = ARM_AM::decodeVMOVModImm(ModImm: Encoded, EltBits&: DecEltBits);
20047
20048 unsigned EltBits = Op.getScalarValueSizeInBits();
20049 if (EltBits != DecEltBits) {
20050 // Be conservative: only update Known when EltBits == DecEltBits.
20051 // This is believed to always be true for VORRIMM/VBICIMM today, but if
20052 // that changes in the future, doing nothing here is safer than risking
20053 // subtle bugs.
20054 break;
20055 }
20056
20057 KnownBits KnownLHS = DAG.computeKnownBits(Op: Op.getOperand(i: 0), Depth: Depth + 1);
20058 bool IsVORR = Op.getOpcode() == ARMISD::VORRIMM;
20059 APInt Imm(DecEltBits, DecodedVal);
20060
20061 Known.One = IsVORR ? (KnownLHS.One | Imm) : (KnownLHS.One & ~Imm);
20062 Known.Zero = IsVORR ? (KnownLHS.Zero & ~Imm) : (KnownLHS.Zero | Imm);
20063 break;
20064 }
20065 }
20066}
20067
20068bool ARMTargetLowering::targetShrinkDemandedConstant(
20069 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
20070 TargetLoweringOpt &TLO) const {
20071 // Delay optimization, so we don't have to deal with illegal types, or block
20072 // optimizations.
20073 if (!TLO.LegalOps)
20074 return false;
20075
20076 // Only optimize AND for now.
20077 if (Op.getOpcode() != ISD::AND)
20078 return false;
20079
20080 EVT VT = Op.getValueType();
20081
20082 // Ignore vectors.
20083 if (VT.isVector())
20084 return false;
20085
20086 assert(VT == MVT::i32 && "Unexpected integer type");
20087
20088 // Make sure the RHS really is a constant.
20089 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 1));
20090 if (!C)
20091 return false;
20092
20093 unsigned Mask = C->getZExtValue();
20094
20095 unsigned Demanded = DemandedBits.getZExtValue();
20096 unsigned ShrunkMask = Mask & Demanded;
20097 unsigned ExpandedMask = Mask | ~Demanded;
20098
20099 // If the mask is all zeros, let the target-independent code replace the
20100 // result with zero.
20101 if (ShrunkMask == 0)
20102 return false;
20103
20104 // If the mask is all ones, erase the AND. (Currently, the target-independent
20105 // code won't do this, so we have to do it explicitly to avoid an infinite
20106 // loop in obscure cases.)
20107 if (ExpandedMask == ~0U)
20108 return TLO.CombineTo(O: Op, N: Op.getOperand(i: 0));
20109
20110 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
20111 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
20112 };
20113 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
20114 if (NewMask == Mask)
20115 return true;
20116 SDLoc DL(Op);
20117 SDValue NewC = TLO.DAG.getConstant(Val: NewMask, DL, VT);
20118 SDValue NewOp = TLO.DAG.getNode(Opcode: ISD::AND, DL, VT, N1: Op.getOperand(i: 0), N2: NewC);
20119 return TLO.CombineTo(O: Op, N: NewOp);
20120 };
20121
20122 // Prefer uxtb mask.
20123 if (IsLegalMask(0xFF))
20124 return UseMask(0xFF);
20125
20126 // Prefer uxth mask.
20127 if (IsLegalMask(0xFFFF))
20128 return UseMask(0xFFFF);
20129
20130 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
20131 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
20132 if (ShrunkMask < 256)
20133 return UseMask(ShrunkMask);
20134
20135 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
20136 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
20137 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
20138 return UseMask(ExpandedMask);
20139
20140 // Potential improvements:
20141 //
20142 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
20143 // We could try to prefer Thumb1 immediates which can be lowered to a
20144 // two-instruction sequence.
20145 // We could try to recognize more legal ARM/Thumb2 immediates here.
20146
20147 return false;
20148}
20149
20150bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
20151 SDValue Op, const APInt &OriginalDemandedBits,
20152 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
20153 unsigned Depth) const {
20154 unsigned Opc = Op.getOpcode();
20155
20156 switch (Opc) {
20157 case ARMISD::ASRL:
20158 case ARMISD::LSRL: {
20159 // If this is result 0 and the other result is unused, see if the demand
20160 // bits allow us to shrink this long shift into a standard small shift in
20161 // the opposite direction.
20162 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(Value: 1) &&
20163 isa<ConstantSDNode>(Val: Op->getOperand(Num: 2))) {
20164 unsigned ShAmt = Op->getConstantOperandVal(Num: 2);
20165 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(RHS: APInt::getAllOnes(numBits: 32)
20166 << (32 - ShAmt)))
20167 return TLO.CombineTo(
20168 O: Op, N: TLO.DAG.getNode(
20169 Opcode: ISD::SHL, DL: SDLoc(Op), VT: MVT::i32, N1: Op.getOperand(i: 1),
20170 N2: TLO.DAG.getConstant(Val: 32 - ShAmt, DL: SDLoc(Op), VT: MVT::i32)));
20171 }
20172 break;
20173 }
20174 case ARMISD::VBICIMM: {
20175 SDValue Op0 = Op.getOperand(i: 0);
20176 unsigned ModImm = Op.getConstantOperandVal(i: 1);
20177 unsigned EltBits = 0;
20178 uint64_t Mask = ARM_AM::decodeVMOVModImm(ModImm, EltBits);
20179 if ((OriginalDemandedBits & Mask) == 0)
20180 return TLO.CombineTo(O: Op, N: Op0);
20181 }
20182 }
20183
20184 return TargetLowering::SimplifyDemandedBitsForTargetNode(
20185 Op, DemandedBits: OriginalDemandedBits, DemandedElts: OriginalDemandedElts, Known, TLO, Depth);
20186}
20187
20188//===----------------------------------------------------------------------===//
20189// ARM Inline Assembly Support
20190//===----------------------------------------------------------------------===//
20191
20192const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
20193 // At this point, we have to lower this constraint to something else, so we
20194 // lower it to an "r" or "w". However, by doing this we will force the result
20195 // to be in register, while the X constraint is much more permissive.
20196 //
20197 // Although we are correct (we are free to emit anything, without
20198 // constraints), we might break use cases that would expect us to be more
20199 // efficient and emit something else.
20200 if (!Subtarget->hasVFP2Base())
20201 return "r";
20202 if (ConstraintVT.isFloatingPoint())
20203 return "w";
20204 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
20205 (ConstraintVT.getSizeInBits() == 64 ||
20206 ConstraintVT.getSizeInBits() == 128))
20207 return "w";
20208
20209 return "r";
20210}
20211
20212/// getConstraintType - Given a constraint letter, return the type of
20213/// constraint it is for this target.
20214ARMTargetLowering::ConstraintType
20215ARMTargetLowering::getConstraintType(StringRef Constraint) const {
20216 unsigned S = Constraint.size();
20217 if (S == 1) {
20218 switch (Constraint[0]) {
20219 default: break;
20220 case 'l': return C_RegisterClass;
20221 case 'w': return C_RegisterClass;
20222 case 'h': return C_RegisterClass;
20223 case 'x': return C_RegisterClass;
20224 case 't': return C_RegisterClass;
20225 case 'j': return C_Immediate; // Constant for movw.
20226 // An address with a single base register. Due to the way we
20227 // currently handle addresses it is the same as an 'r' memory constraint.
20228 case 'Q': return C_Memory;
20229 }
20230 } else if (S == 2) {
20231 switch (Constraint[0]) {
20232 default: break;
20233 case 'T': return C_RegisterClass;
20234 // All 'U+' constraints are addresses.
20235 case 'U': return C_Memory;
20236 }
20237 }
20238 return TargetLowering::getConstraintType(Constraint);
20239}
20240
20241/// Examine constraint type and operand type and determine a weight value.
20242/// This object must already have been set up with the operand type
20243/// and the current alternative constraint selected.
20244TargetLowering::ConstraintWeight
20245ARMTargetLowering::getSingleConstraintMatchWeight(
20246 AsmOperandInfo &info, const char *constraint) const {
20247 ConstraintWeight weight = CW_Invalid;
20248 Value *CallOperandVal = info.CallOperandVal;
20249 // If we don't have a value, we can't do a match,
20250 // but allow it at the lowest weight.
20251 if (!CallOperandVal)
20252 return CW_Default;
20253 Type *type = CallOperandVal->getType();
20254 // Look at the constraint type.
20255 switch (*constraint) {
20256 default:
20257 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20258 break;
20259 case 'l':
20260 if (type->isIntegerTy()) {
20261 if (Subtarget->isThumb())
20262 weight = CW_SpecificReg;
20263 else
20264 weight = CW_Register;
20265 }
20266 break;
20267 case 'w':
20268 if (type->isFloatingPointTy())
20269 weight = CW_Register;
20270 break;
20271 }
20272 return weight;
20273}
20274
20275static bool isIncompatibleReg(const MCPhysReg &PR, MVT VT) {
20276 if (PR == 0 || VT == MVT::Other)
20277 return false;
20278 if (ARM::SPRRegClass.contains(Reg: PR))
20279 return VT != MVT::f32 && VT != MVT::f16 && VT != MVT::i32;
20280 if (ARM::DPRRegClass.contains(Reg: PR))
20281 return VT != MVT::f64 && !VT.is64BitVector();
20282 return false;
20283}
20284
20285using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
20286
20287RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
20288 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
20289 switch (Constraint.size()) {
20290 case 1:
20291 // GCC ARM Constraint Letters
20292 switch (Constraint[0]) {
20293 case 'l': // Low regs or general regs.
20294 if (Subtarget->isThumb())
20295 return RCPair(0U, &ARM::tGPRRegClass);
20296 return RCPair(0U, &ARM::GPRRegClass);
20297 case 'h': // High regs or no regs.
20298 if (Subtarget->isThumb())
20299 return RCPair(0U, &ARM::hGPRRegClass);
20300 break;
20301 case 'r':
20302 if (Subtarget->isThumb1Only())
20303 return RCPair(0U, &ARM::tGPRRegClass);
20304 return RCPair(0U, &ARM::GPRRegClass);
20305 case 'w':
20306 if (VT == MVT::Other)
20307 break;
20308 if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
20309 return RCPair(0U, &ARM::SPRRegClass);
20310 if (VT.getSizeInBits() == 64)
20311 return RCPair(0U, &ARM::DPRRegClass);
20312 if (VT.getSizeInBits() == 128)
20313 return RCPair(0U, &ARM::QPRRegClass);
20314 break;
20315 case 'x':
20316 if (VT == MVT::Other)
20317 break;
20318 if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
20319 return RCPair(0U, &ARM::SPR_8RegClass);
20320 if (VT.getSizeInBits() == 64)
20321 return RCPair(0U, &ARM::DPR_8RegClass);
20322 if (VT.getSizeInBits() == 128)
20323 return RCPair(0U, &ARM::QPR_8RegClass);
20324 break;
20325 case 't':
20326 if (VT == MVT::Other)
20327 break;
20328 if (VT == MVT::f32 || VT == MVT::i32 || VT == MVT::f16 || VT == MVT::bf16)
20329 return RCPair(0U, &ARM::SPRRegClass);
20330 if (VT.getSizeInBits() == 64)
20331 return RCPair(0U, &ARM::DPR_VFP2RegClass);
20332 if (VT.getSizeInBits() == 128)
20333 return RCPair(0U, &ARM::QPR_VFP2RegClass);
20334 break;
20335 }
20336 break;
20337
20338 case 2:
20339 if (Constraint[0] == 'T') {
20340 switch (Constraint[1]) {
20341 default:
20342 break;
20343 case 'e':
20344 return RCPair(0U, &ARM::tGPREvenRegClass);
20345 case 'o':
20346 return RCPair(0U, &ARM::tGPROddRegClass);
20347 }
20348 }
20349 break;
20350
20351 default:
20352 break;
20353 }
20354
20355 if (StringRef("{cc}").equals_insensitive(RHS: Constraint))
20356 return std::make_pair(x: unsigned(ARM::CPSR), y: &ARM::CCRRegClass);
20357
20358 // r14 is an alias of lr.
20359 if (StringRef("{r14}").equals_insensitive(RHS: Constraint))
20360 return std::make_pair(x: unsigned(ARM::LR), y: getRegClassFor(VT: MVT::i32));
20361
20362 auto RCP = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20363 if (isIncompatibleReg(PR: RCP.first, VT))
20364 return {0, nullptr};
20365 return RCP;
20366}
20367
20368/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20369/// vector. If it is invalid, don't add anything to Ops.
20370void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20371 StringRef Constraint,
20372 std::vector<SDValue> &Ops,
20373 SelectionDAG &DAG) const {
20374 SDValue Result;
20375
20376 // Currently only support length 1 constraints.
20377 if (Constraint.size() != 1)
20378 return;
20379
20380 char ConstraintLetter = Constraint[0];
20381 switch (ConstraintLetter) {
20382 default: break;
20383 case 'j':
20384 case 'I': case 'J': case 'K': case 'L':
20385 case 'M': case 'N': case 'O':
20386 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: Op);
20387 if (!C)
20388 return;
20389
20390 int64_t CVal64 = C->getSExtValue();
20391 int CVal = (int) CVal64;
20392 // None of these constraints allow values larger than 32 bits. Check
20393 // that the value fits in an int.
20394 if (CVal != CVal64)
20395 return;
20396
20397 switch (ConstraintLetter) {
20398 case 'j':
20399 // Constant suitable for movw, must be between 0 and
20400 // 65535.
20401 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
20402 if (CVal >= 0 && CVal <= 65535)
20403 break;
20404 return;
20405 case 'I':
20406 if (Subtarget->isThumb1Only()) {
20407 // This must be a constant between 0 and 255, for ADD
20408 // immediates.
20409 if (CVal >= 0 && CVal <= 255)
20410 break;
20411 } else if (Subtarget->isThumb2()) {
20412 // A constant that can be used as an immediate value in a
20413 // data-processing instruction.
20414 if (ARM_AM::getT2SOImmVal(Arg: CVal) != -1)
20415 break;
20416 } else {
20417 // A constant that can be used as an immediate value in a
20418 // data-processing instruction.
20419 if (ARM_AM::getSOImmVal(Arg: CVal) != -1)
20420 break;
20421 }
20422 return;
20423
20424 case 'J':
20425 if (Subtarget->isThumb1Only()) {
20426 // This must be a constant between -255 and -1, for negated ADD
20427 // immediates. This can be used in GCC with an "n" modifier that
20428 // prints the negated value, for use with SUB instructions. It is
20429 // not useful otherwise but is implemented for compatibility.
20430 if (CVal >= -255 && CVal <= -1)
20431 break;
20432 } else {
20433 // This must be a constant between -4095 and 4095. This is suitable
20434 // for use as the immediate offset field in LDR and STR instructions
20435 // such as LDR r0,[r1,#offset].
20436 if (CVal >= -4095 && CVal <= 4095)
20437 break;
20438 }
20439 return;
20440
20441 case 'K':
20442 if (Subtarget->isThumb1Only()) {
20443 // A 32-bit value where only one byte has a nonzero value. Exclude
20444 // zero to match GCC. This constraint is used by GCC internally for
20445 // constants that can be loaded with a move/shift combination.
20446 // It is not useful otherwise but is implemented for compatibility.
20447 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(V: CVal))
20448 break;
20449 } else if (Subtarget->isThumb2()) {
20450 // A constant whose bitwise inverse can be used as an immediate
20451 // value in a data-processing instruction. This can be used in GCC
20452 // with a "B" modifier that prints the inverted value, for use with
20453 // BIC and MVN instructions. It is not useful otherwise but is
20454 // implemented for compatibility.
20455 if (ARM_AM::getT2SOImmVal(Arg: ~CVal) != -1)
20456 break;
20457 } else {
20458 // A constant whose bitwise inverse can be used as an immediate
20459 // value in a data-processing instruction. This can be used in GCC
20460 // with a "B" modifier that prints the inverted value, for use with
20461 // BIC and MVN instructions. It is not useful otherwise but is
20462 // implemented for compatibility.
20463 if (ARM_AM::getSOImmVal(Arg: ~CVal) != -1)
20464 break;
20465 }
20466 return;
20467
20468 case 'L':
20469 if (Subtarget->isThumb1Only()) {
20470 // This must be a constant between -7 and 7,
20471 // for 3-operand ADD/SUB immediate instructions.
20472 if (CVal >= -7 && CVal < 7)
20473 break;
20474 } else if (Subtarget->isThumb2()) {
20475 // A constant whose negation can be used as an immediate value in a
20476 // data-processing instruction. This can be used in GCC with an "n"
20477 // modifier that prints the negated value, for use with SUB
20478 // instructions. It is not useful otherwise but is implemented for
20479 // compatibility.
20480 if (ARM_AM::getT2SOImmVal(Arg: -CVal) != -1)
20481 break;
20482 } else {
20483 // A constant whose negation can be used as an immediate value in a
20484 // data-processing instruction. This can be used in GCC with an "n"
20485 // modifier that prints the negated value, for use with SUB
20486 // instructions. It is not useful otherwise but is implemented for
20487 // compatibility.
20488 if (ARM_AM::getSOImmVal(Arg: -CVal) != -1)
20489 break;
20490 }
20491 return;
20492
20493 case 'M':
20494 if (Subtarget->isThumb1Only()) {
20495 // This must be a multiple of 4 between 0 and 1020, for
20496 // ADD sp + immediate.
20497 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
20498 break;
20499 } else {
20500 // A power of two or a constant between 0 and 32. This is used in
20501 // GCC for the shift amount on shifted register operands, but it is
20502 // useful in general for any shift amounts.
20503 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
20504 break;
20505 }
20506 return;
20507
20508 case 'N':
20509 if (Subtarget->isThumb1Only()) {
20510 // This must be a constant between 0 and 31, for shift amounts.
20511 if (CVal >= 0 && CVal <= 31)
20512 break;
20513 }
20514 return;
20515
20516 case 'O':
20517 if (Subtarget->isThumb1Only()) {
20518 // This must be a multiple of 4 between -508 and 508, for
20519 // ADD/SUB sp = sp + immediate.
20520 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
20521 break;
20522 }
20523 return;
20524 }
20525 Result = DAG.getSignedTargetConstant(Val: CVal, DL: SDLoc(Op), VT: Op.getValueType());
20526 break;
20527 }
20528
20529 if (Result.getNode()) {
20530 Ops.push_back(x: Result);
20531 return;
20532 }
20533 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20534}
20535
20536static RTLIB::Libcall getDivRemLibcall(
20537 const SDNode *N, MVT::SimpleValueType SVT) {
20538 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
20539 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
20540 "Unhandled Opcode in getDivRemLibcall");
20541 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20542 N->getOpcode() == ISD::SREM;
20543 RTLIB::Libcall LC;
20544 switch (SVT) {
20545 default: llvm_unreachable("Unexpected request for libcall!");
20546 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
20547 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
20548 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
20549 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
20550 }
20551 return LC;
20552}
20553
20554static TargetLowering::ArgListTy getDivRemArgList(
20555 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
20556 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
20557 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
20558 "Unhandled Opcode in getDivRemArgList");
20559 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20560 N->getOpcode() == ISD::SREM;
20561 TargetLowering::ArgListTy Args;
20562 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
20563 EVT ArgVT = N->getOperand(Num: i).getValueType();
20564 Type *ArgTy = ArgVT.getTypeForEVT(Context&: *Context);
20565 TargetLowering::ArgListEntry Entry(N->getOperand(Num: i), ArgTy);
20566 Entry.IsSExt = isSigned;
20567 Entry.IsZExt = !isSigned;
20568 Args.push_back(x: Entry);
20569 }
20570 if (Subtarget->getTargetTriple().isOSWindows() && Args.size() >= 2)
20571 std::swap(a&: Args[0], b&: Args[1]);
20572 return Args;
20573}
20574
20575SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
20576 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
20577 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
20578 Subtarget->isTargetFuchsia() || Subtarget->isTargetWindows()) &&
20579 "Register-based DivRem lowering only");
20580 unsigned Opcode = Op->getOpcode();
20581 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
20582 "Invalid opcode for Div/Rem lowering");
20583 bool isSigned = (Opcode == ISD::SDIVREM);
20584 EVT VT = Op->getValueType(ResNo: 0);
20585 SDLoc dl(Op);
20586
20587 if (VT == MVT::i64 && isa<ConstantSDNode>(Val: Op.getOperand(i: 1))) {
20588 SmallVector<SDValue> Result;
20589 if (expandDIVREMByConstant(N: Op.getNode(), Result, HiLoVT: MVT::i32, DAG)) {
20590 SDValue Res0 =
20591 DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT, N1: Result[0], N2: Result[1]);
20592 SDValue Res1 =
20593 DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT, N1: Result[2], N2: Result[3]);
20594 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl, VTList: Op->getVTList(),
20595 Ops: {Res0, Res1});
20596 }
20597 }
20598
20599 Type *Ty = VT.getTypeForEVT(Context&: *DAG.getContext());
20600
20601 // If the target has hardware divide, use divide + multiply + subtract:
20602 // div = a / b
20603 // rem = a - b * div
20604 // return {div, rem}
20605 // This should be lowered into UDIV/SDIV + MLS later on.
20606 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
20607 : Subtarget->hasDivideInARMMode();
20608 if (hasDivide && Op->getValueType(ResNo: 0).isSimple() &&
20609 Op->getSimpleValueType(ResNo: 0) == MVT::i32) {
20610 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
20611 const SDValue Dividend = Op->getOperand(Num: 0);
20612 const SDValue Divisor = Op->getOperand(Num: 1);
20613 SDValue Div = DAG.getNode(Opcode: DivOpcode, DL: dl, VT, N1: Dividend, N2: Divisor);
20614 SDValue Mul = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT, N1: Div, N2: Divisor);
20615 SDValue Rem = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: Dividend, N2: Mul);
20616
20617 SDValue Values[2] = {Div, Rem};
20618 return DAG.getNode(Opcode: ISD::MERGE_VALUES, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT), Ops: Values);
20619 }
20620
20621 RTLIB::Libcall LC = getDivRemLibcall(N: Op.getNode(),
20622 SVT: VT.getSimpleVT().SimpleTy);
20623 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(Call: LC);
20624
20625 SDValue InChain = DAG.getEntryNode();
20626
20627 TargetLowering::ArgListTy Args = getDivRemArgList(N: Op.getNode(),
20628 Context: DAG.getContext(),
20629 Subtarget);
20630
20631 SDValue Callee =
20632 DAG.getExternalSymbol(LCImpl, VT: getPointerTy(DL: DAG.getDataLayout()));
20633
20634 Type *RetTy = StructType::get(elt1: Ty, elts: Ty);
20635
20636 if (getTM().getTargetTriple().isOSWindows())
20637 InChain = WinDBZCheckDenominator(DAG, N: Op.getNode(), InChain);
20638
20639 TargetLowering::CallLoweringInfo CLI(DAG);
20640 CLI.setDebugLoc(dl)
20641 .setChain(InChain)
20642 .setCallee(CC: DAG.getLibcalls().getLibcallImplCallingConv(Call: LCImpl), ResultType: RetTy,
20643 Target: Callee, ArgsList: std::move(Args))
20644 .setInRegister()
20645 .setSExtResult(isSigned)
20646 .setZExtResult(!isSigned);
20647
20648 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
20649 return CallInfo.first;
20650}
20651
20652// Lowers REM using divmod helpers
20653// see RTABI section 4.2/4.3
20654SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
20655 EVT VT = N->getValueType(ResNo: 0);
20656
20657 if (VT == MVT::i64 && isa<ConstantSDNode>(Val: N->getOperand(Num: 1))) {
20658 SmallVector<SDValue> Result;
20659 if (expandDIVREMByConstant(N, Result, HiLoVT: MVT::i32, DAG))
20660 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: SDLoc(N), VT: N->getValueType(ResNo: 0),
20661 N1: Result[0], N2: Result[1]);
20662 }
20663
20664 // Build return types (div and rem)
20665 std::vector<Type*> RetTyParams;
20666 Type *RetTyElement;
20667
20668 switch (VT.getSimpleVT().SimpleTy) {
20669 default: llvm_unreachable("Unexpected request for libcall!");
20670 case MVT::i8: RetTyElement = Type::getInt8Ty(C&: *DAG.getContext()); break;
20671 case MVT::i16: RetTyElement = Type::getInt16Ty(C&: *DAG.getContext()); break;
20672 case MVT::i32: RetTyElement = Type::getInt32Ty(C&: *DAG.getContext()); break;
20673 case MVT::i64: RetTyElement = Type::getInt64Ty(C&: *DAG.getContext()); break;
20674 }
20675
20676 RetTyParams.push_back(x: RetTyElement);
20677 RetTyParams.push_back(x: RetTyElement);
20678 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
20679 Type *RetTy = StructType::get(Context&: *DAG.getContext(), Elements: ret);
20680
20681 RTLIB::Libcall LC = getDivRemLibcall(N, SVT: N->getValueType(ResNo: 0).getSimpleVT().
20682 SimpleTy);
20683 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(Call: LC);
20684 SDValue InChain = DAG.getEntryNode();
20685 TargetLowering::ArgListTy Args = getDivRemArgList(N, Context: DAG.getContext(),
20686 Subtarget);
20687 bool isSigned = N->getOpcode() == ISD::SREM;
20688
20689 SDValue Callee =
20690 DAG.getExternalSymbol(LCImpl, VT: getPointerTy(DL: DAG.getDataLayout()));
20691
20692 if (getTM().getTargetTriple().isOSWindows())
20693 InChain = WinDBZCheckDenominator(DAG, N, InChain);
20694
20695 // Lower call
20696 CallLoweringInfo CLI(DAG);
20697 CLI.setChain(InChain)
20698 .setCallee(CC: DAG.getLibcalls().getLibcallImplCallingConv(Call: LCImpl), ResultType: RetTy,
20699 Target: Callee, ArgsList: std::move(Args))
20700 .setSExtResult(isSigned)
20701 .setZExtResult(!isSigned)
20702 .setDebugLoc(SDLoc(N));
20703 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
20704
20705 // Return second (rem) result operand (first contains div)
20706 SDNode *ResNode = CallResult.first.getNode();
20707 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
20708 return ResNode->getOperand(Num: 1);
20709}
20710
20711SDValue
20712ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
20713 assert(getTM().getTargetTriple().isOSWindows() &&
20714 "unsupported target platform");
20715 SDLoc DL(Op);
20716
20717 // Get the inputs.
20718 SDValue Chain = Op.getOperand(i: 0);
20719 SDValue Size = Op.getOperand(i: 1);
20720
20721 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
20722 Kind: "no-stack-arg-probe")) {
20723 MaybeAlign Align =
20724 cast<ConstantSDNode>(Val: Op.getOperand(i: 2))->getMaybeAlignValue();
20725 SDValue SP = DAG.getCopyFromReg(Chain, dl: DL, Reg: ARM::SP, VT: MVT::i32);
20726 Chain = SP.getValue(R: 1);
20727 SP = DAG.getNode(Opcode: ISD::SUB, DL, VT: MVT::i32, N1: SP, N2: Size);
20728 if (Align)
20729 SP = DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: SP.getValue(R: 0),
20730 N2: DAG.getSignedConstant(Val: -Align->value(), DL, VT: MVT::i32));
20731 Chain = DAG.getCopyToReg(Chain, dl: DL, Reg: ARM::SP, N: SP);
20732 SDValue Ops[2] = { SP, Chain };
20733 return DAG.getMergeValues(Ops, dl: DL);
20734 }
20735
20736 SDValue Words = DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: Size,
20737 N2: DAG.getConstant(Val: 2, DL, VT: MVT::i32));
20738
20739 SDValue Glue;
20740 Chain = DAG.getCopyToReg(Chain, dl: DL, Reg: ARM::R4, N: Words, Glue);
20741 Glue = Chain.getValue(R: 1);
20742
20743 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
20744 Chain = DAG.getNode(Opcode: ARMISD::WIN__CHKSTK, DL, VTList: NodeTys, N1: Chain, N2: Glue);
20745
20746 SDValue NewSP = DAG.getCopyFromReg(Chain, dl: DL, Reg: ARM::SP, VT: MVT::i32);
20747 Chain = NewSP.getValue(R: 1);
20748
20749 SDValue Ops[2] = { NewSP, Chain };
20750 return DAG.getMergeValues(Ops, dl: DL);
20751}
20752
20753SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
20754 bool IsStrict = Op->isStrictFPOpcode();
20755 SDValue SrcVal = Op.getOperand(i: IsStrict ? 1 : 0);
20756 const unsigned DstSz = Op.getValueType().getSizeInBits();
20757 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
20758 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
20759 "Unexpected type for custom-lowering FP_EXTEND");
20760
20761 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
20762 "With both FP DP and 16, any FP conversion is legal!");
20763
20764 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
20765 "With FP16, 16 to 32 conversion is legal!");
20766
20767 // Converting from 32 -> 64 is valid if we have FP64.
20768 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
20769 // FIXME: Remove this when we have strict fp instruction selection patterns
20770 if (IsStrict) {
20771 SDLoc Loc(Op);
20772 SDValue Result = DAG.getNode(Opcode: ISD::FP_EXTEND,
20773 DL: Loc, VT: Op.getValueType(), Operand: SrcVal);
20774 return DAG.getMergeValues(Ops: {Result, Op.getOperand(i: 0)}, dl: Loc);
20775 }
20776 return Op;
20777 }
20778
20779 // Either we are converting from 16 -> 64, without FP16 and/or
20780 // FP.double-precision or without Armv8-fp. So we must do it in two
20781 // steps.
20782 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
20783 // without FP16. So we must do a function call.
20784 SDLoc Loc(Op);
20785 RTLIB::Libcall LC;
20786 MakeLibCallOptions CallOptions;
20787 SDValue Chain = IsStrict ? Op.getOperand(i: 0) : SDValue();
20788 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
20789 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
20790 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
20791 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
20792 if (Supported) {
20793 if (IsStrict) {
20794 SrcVal = DAG.getNode(Opcode: ISD::STRICT_FP_EXTEND, DL: Loc,
20795 ResultTys: {DstVT, MVT::Other}, Ops: {Chain, SrcVal});
20796 Chain = SrcVal.getValue(R: 1);
20797 } else {
20798 SrcVal = DAG.getNode(Opcode: ISD::FP_EXTEND, DL: Loc, VT: DstVT, Operand: SrcVal);
20799 }
20800 } else {
20801 LC = RTLIB::getFPEXT(OpVT: SrcVT, RetVT: DstVT);
20802 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
20803 "Unexpected type for custom-lowering FP_EXTEND");
20804 std::tie(args&: SrcVal, args&: Chain) = makeLibCall(DAG, LC, RetVT: DstVT, Ops: SrcVal, CallOptions,
20805 dl: Loc, Chain);
20806 }
20807 }
20808
20809 return IsStrict ? DAG.getMergeValues(Ops: {SrcVal, Chain}, dl: Loc) : SrcVal;
20810}
20811
20812SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
20813 bool IsStrict = Op->isStrictFPOpcode();
20814
20815 SDValue SrcVal = Op.getOperand(i: IsStrict ? 1 : 0);
20816 EVT SrcVT = SrcVal.getValueType();
20817 EVT DstVT = Op.getValueType();
20818 const unsigned DstSz = Op.getValueType().getSizeInBits();
20819 const unsigned SrcSz = SrcVT.getSizeInBits();
20820 (void)DstSz;
20821 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
20822 "Unexpected type for custom-lowering FP_ROUND");
20823
20824 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
20825 "With both FP DP and 16, any FP conversion is legal!");
20826
20827 SDLoc Loc(Op);
20828
20829 // Instruction from 32 -> 16 if hasFP16 is valid
20830 if (SrcSz == 32 && Subtarget->hasFP16())
20831 return Op;
20832
20833 // Lib call from 32 -> 16 / 64 -> [32, 16]
20834 RTLIB::Libcall LC = RTLIB::getFPROUND(OpVT: SrcVT, RetVT: DstVT);
20835 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
20836 "Unexpected type for custom-lowering FP_ROUND");
20837 MakeLibCallOptions CallOptions;
20838 SDValue Chain = IsStrict ? Op.getOperand(i: 0) : SDValue();
20839 SDValue Result;
20840 std::tie(args&: Result, args&: Chain) = makeLibCall(DAG, LC, RetVT: DstVT, Ops: SrcVal, CallOptions,
20841 dl: Loc, Chain);
20842 return IsStrict ? DAG.getMergeValues(Ops: {Result, Chain}, dl: Loc) : Result;
20843}
20844
20845bool
20846ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
20847 // The ARM target isn't yet aware of offsets.
20848 return false;
20849}
20850
20851bool ARM::isBitFieldInvertedMask(unsigned v) {
20852 if (v == 0xffffffff)
20853 return false;
20854
20855 // there can be 1's on either or both "outsides", all the "inside"
20856 // bits must be 0's
20857 return isShiftedMask_32(Value: ~v);
20858}
20859
20860/// isFPImmLegal - Returns true if the target can instruction select the
20861/// specified FP immediate natively. If false, the legalizer will
20862/// materialize the FP immediate as a load from a constant pool.
20863bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
20864 bool ForCodeSize) const {
20865 if (!Subtarget->hasVFP3Base())
20866 return false;
20867 if (VT == MVT::f16 && Subtarget->hasFullFP16())
20868 return ARM_AM::getFP16Imm(FPImm: Imm) != -1;
20869 if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
20870 ARM_AM::getFP32FP16Imm(FPImm: Imm) != -1)
20871 return true;
20872 if (VT == MVT::f32)
20873 return ARM_AM::getFP32Imm(FPImm: Imm) != -1;
20874 if (VT == MVT::f64 && Subtarget->hasFP64())
20875 return ARM_AM::getFP64Imm(FPImm: Imm) != -1;
20876 return false;
20877}
20878
20879/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
20880/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
20881/// specified in the intrinsic calls.
20882void ARMTargetLowering::getTgtMemIntrinsic(
20883 SmallVectorImpl<IntrinsicInfo> &Infos, const CallBase &I,
20884 MachineFunction &MF, unsigned Intrinsic) const {
20885 IntrinsicInfo Info;
20886 switch (Intrinsic) {
20887 case Intrinsic::arm_neon_vld1:
20888 case Intrinsic::arm_neon_vld2:
20889 case Intrinsic::arm_neon_vld3:
20890 case Intrinsic::arm_neon_vld4:
20891 case Intrinsic::arm_neon_vld2lane:
20892 case Intrinsic::arm_neon_vld3lane:
20893 case Intrinsic::arm_neon_vld4lane:
20894 case Intrinsic::arm_neon_vld2dup:
20895 case Intrinsic::arm_neon_vld3dup:
20896 case Intrinsic::arm_neon_vld4dup: {
20897 Info.opc = ISD::INTRINSIC_W_CHAIN;
20898 // Conservatively set memVT to the entire set of vectors loaded.
20899 auto &DL = I.getDataLayout();
20900 uint64_t NumElts = DL.getTypeSizeInBits(Ty: I.getType()) / 64;
20901 Info.memVT = EVT::getVectorVT(Context&: I.getType()->getContext(), VT: MVT::i64, NumElements: NumElts);
20902 Info.ptrVal = I.getArgOperand(i: 0);
20903 Info.offset = 0;
20904 Value *AlignArg = I.getArgOperand(i: I.arg_size() - 1);
20905 Info.align = cast<ConstantInt>(Val: AlignArg)->getMaybeAlignValue();
20906 // volatile loads with NEON intrinsics not supported
20907 Info.flags = MachineMemOperand::MOLoad;
20908 Infos.push_back(Elt: Info);
20909 return;
20910 }
20911 case Intrinsic::arm_neon_vld1x2:
20912 case Intrinsic::arm_neon_vld1x3:
20913 case Intrinsic::arm_neon_vld1x4: {
20914 Info.opc = ISD::INTRINSIC_W_CHAIN;
20915 // Conservatively set memVT to the entire set of vectors loaded.
20916 auto &DL = I.getDataLayout();
20917 uint64_t NumElts = DL.getTypeSizeInBits(Ty: I.getType()) / 64;
20918 Info.memVT = EVT::getVectorVT(Context&: I.getType()->getContext(), VT: MVT::i64, NumElements: NumElts);
20919 Info.ptrVal = I.getArgOperand(i: I.arg_size() - 1);
20920 Info.offset = 0;
20921 Info.align = I.getParamAlign(ArgNo: I.arg_size() - 1).valueOrOne();
20922 // volatile loads with NEON intrinsics not supported
20923 Info.flags = MachineMemOperand::MOLoad;
20924 Infos.push_back(Elt: Info);
20925 return;
20926 }
20927 case Intrinsic::arm_neon_vst1:
20928 case Intrinsic::arm_neon_vst2:
20929 case Intrinsic::arm_neon_vst3:
20930 case Intrinsic::arm_neon_vst4:
20931 case Intrinsic::arm_neon_vst2lane:
20932 case Intrinsic::arm_neon_vst3lane:
20933 case Intrinsic::arm_neon_vst4lane: {
20934 Info.opc = ISD::INTRINSIC_VOID;
20935 // Conservatively set memVT to the entire set of vectors stored.
20936 auto &DL = I.getDataLayout();
20937 unsigned NumElts = 0;
20938 for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
20939 Type *ArgTy = I.getArgOperand(i: ArgI)->getType();
20940 if (!ArgTy->isVectorTy())
20941 break;
20942 NumElts += DL.getTypeSizeInBits(Ty: ArgTy) / 64;
20943 }
20944 Info.memVT = EVT::getVectorVT(Context&: I.getType()->getContext(), VT: MVT::i64, NumElements: NumElts);
20945 Info.ptrVal = I.getArgOperand(i: 0);
20946 Info.offset = 0;
20947 Value *AlignArg = I.getArgOperand(i: I.arg_size() - 1);
20948 Info.align = cast<ConstantInt>(Val: AlignArg)->getMaybeAlignValue();
20949 // volatile stores with NEON intrinsics not supported
20950 Info.flags = MachineMemOperand::MOStore;
20951 Infos.push_back(Elt: Info);
20952 return;
20953 }
20954 case Intrinsic::arm_neon_vst1x2:
20955 case Intrinsic::arm_neon_vst1x3:
20956 case Intrinsic::arm_neon_vst1x4: {
20957 Info.opc = ISD::INTRINSIC_VOID;
20958 // Conservatively set memVT to the entire set of vectors stored.
20959 auto &DL = I.getDataLayout();
20960 unsigned NumElts = 0;
20961 for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
20962 Type *ArgTy = I.getArgOperand(i: ArgI)->getType();
20963 if (!ArgTy->isVectorTy())
20964 break;
20965 NumElts += DL.getTypeSizeInBits(Ty: ArgTy) / 64;
20966 }
20967 Info.memVT = EVT::getVectorVT(Context&: I.getType()->getContext(), VT: MVT::i64, NumElements: NumElts);
20968 Info.ptrVal = I.getArgOperand(i: 0);
20969 Info.offset = 0;
20970 Info.align = I.getParamAlign(ArgNo: 0).valueOrOne();
20971 // volatile stores with NEON intrinsics not supported
20972 Info.flags = MachineMemOperand::MOStore;
20973 Infos.push_back(Elt: Info);
20974 return;
20975 }
20976 case Intrinsic::arm_mve_vld2q:
20977 case Intrinsic::arm_mve_vld4q: {
20978 Info.opc = ISD::INTRINSIC_W_CHAIN;
20979 // Conservatively set memVT to the entire set of vectors loaded.
20980 Type *VecTy = cast<StructType>(Val: I.getType())->getElementType(N: 1);
20981 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
20982 Info.memVT = EVT::getVectorVT(Context&: VecTy->getContext(), VT: MVT::i64, NumElements: Factor * 2);
20983 Info.ptrVal = I.getArgOperand(i: 0);
20984 Info.offset = 0;
20985 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
20986 // volatile loads with MVE intrinsics not supported
20987 Info.flags = MachineMemOperand::MOLoad;
20988 Infos.push_back(Elt: Info);
20989 return;
20990 }
20991 case Intrinsic::arm_mve_vst2q:
20992 case Intrinsic::arm_mve_vst4q: {
20993 Info.opc = ISD::INTRINSIC_VOID;
20994 // Conservatively set memVT to the entire set of vectors stored.
20995 Type *VecTy = I.getArgOperand(i: 1)->getType();
20996 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
20997 Info.memVT = EVT::getVectorVT(Context&: VecTy->getContext(), VT: MVT::i64, NumElements: Factor * 2);
20998 Info.ptrVal = I.getArgOperand(i: 0);
20999 Info.offset = 0;
21000 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
21001 // volatile stores with MVE intrinsics not supported
21002 Info.flags = MachineMemOperand::MOStore;
21003 Infos.push_back(Elt: Info);
21004 return;
21005 }
21006 case Intrinsic::arm_mve_vldr_gather_base:
21007 case Intrinsic::arm_mve_vldr_gather_base_predicated: {
21008 Info.opc = ISD::INTRINSIC_W_CHAIN;
21009 Info.ptrVal = nullptr;
21010 Info.memVT = MVT::getVT(Ty: I.getType());
21011 Info.align = Align(1);
21012 Info.flags |= MachineMemOperand::MOLoad;
21013 Infos.push_back(Elt: Info);
21014 return;
21015 }
21016 case Intrinsic::arm_mve_vldr_gather_base_wb:
21017 case Intrinsic::arm_mve_vldr_gather_base_wb_predicated: {
21018 Info.opc = ISD::INTRINSIC_W_CHAIN;
21019 Info.ptrVal = nullptr;
21020 Info.memVT = MVT::getVT(Ty: I.getType()->getContainedType(i: 0));
21021 Info.align = Align(1);
21022 Info.flags |= MachineMemOperand::MOLoad;
21023 Infos.push_back(Elt: Info);
21024 return;
21025 }
21026 case Intrinsic::arm_mve_vldr_gather_offset:
21027 case Intrinsic::arm_mve_vldr_gather_offset_predicated: {
21028 Info.opc = ISD::INTRINSIC_W_CHAIN;
21029 Info.ptrVal = nullptr;
21030 MVT DataVT = MVT::getVT(Ty: I.getType());
21031 unsigned MemSize = cast<ConstantInt>(Val: I.getArgOperand(i: 2))->getZExtValue();
21032 Info.memVT = MVT::getVectorVT(VT: MVT::getIntegerVT(BitWidth: MemSize),
21033 NumElements: DataVT.getVectorNumElements());
21034 Info.align = Align(1);
21035 Info.flags |= MachineMemOperand::MOLoad;
21036 Infos.push_back(Elt: Info);
21037 return;
21038 }
21039 case Intrinsic::arm_mve_vstr_scatter_base:
21040 case Intrinsic::arm_mve_vstr_scatter_base_predicated: {
21041 Info.opc = ISD::INTRINSIC_VOID;
21042 Info.ptrVal = nullptr;
21043 Info.memVT = MVT::getVT(Ty: I.getArgOperand(i: 2)->getType());
21044 Info.align = Align(1);
21045 Info.flags |= MachineMemOperand::MOStore;
21046 Infos.push_back(Elt: Info);
21047 return;
21048 }
21049 case Intrinsic::arm_mve_vstr_scatter_base_wb:
21050 case Intrinsic::arm_mve_vstr_scatter_base_wb_predicated: {
21051 Info.opc = ISD::INTRINSIC_W_CHAIN;
21052 Info.ptrVal = nullptr;
21053 Info.memVT = MVT::getVT(Ty: I.getArgOperand(i: 2)->getType());
21054 Info.align = Align(1);
21055 Info.flags |= MachineMemOperand::MOStore;
21056 Infos.push_back(Elt: Info);
21057 return;
21058 }
21059 case Intrinsic::arm_mve_vstr_scatter_offset:
21060 case Intrinsic::arm_mve_vstr_scatter_offset_predicated: {
21061 Info.opc = ISD::INTRINSIC_VOID;
21062 Info.ptrVal = nullptr;
21063 MVT DataVT = MVT::getVT(Ty: I.getArgOperand(i: 2)->getType());
21064 unsigned MemSize = cast<ConstantInt>(Val: I.getArgOperand(i: 3))->getZExtValue();
21065 Info.memVT = MVT::getVectorVT(VT: MVT::getIntegerVT(BitWidth: MemSize),
21066 NumElements: DataVT.getVectorNumElements());
21067 Info.align = Align(1);
21068 Info.flags |= MachineMemOperand::MOStore;
21069 Infos.push_back(Elt: Info);
21070 return;
21071 }
21072 case Intrinsic::arm_ldaex:
21073 case Intrinsic::arm_ldrex: {
21074 auto &DL = I.getDataLayout();
21075 Type *ValTy = I.getParamElementType(ArgNo: 0);
21076 Info.opc = ISD::INTRINSIC_W_CHAIN;
21077 Info.memVT = MVT::getVT(Ty: ValTy);
21078 Info.ptrVal = I.getArgOperand(i: 0);
21079 Info.offset = 0;
21080 Info.align = DL.getABITypeAlign(Ty: ValTy);
21081 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
21082 Infos.push_back(Elt: Info);
21083 return;
21084 }
21085 case Intrinsic::arm_stlex:
21086 case Intrinsic::arm_strex: {
21087 auto &DL = I.getDataLayout();
21088 Type *ValTy = I.getParamElementType(ArgNo: 1);
21089 Info.opc = ISD::INTRINSIC_W_CHAIN;
21090 Info.memVT = MVT::getVT(Ty: ValTy);
21091 Info.ptrVal = I.getArgOperand(i: 1);
21092 Info.offset = 0;
21093 Info.align = DL.getABITypeAlign(Ty: ValTy);
21094 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
21095 Infos.push_back(Elt: Info);
21096 return;
21097 }
21098 case Intrinsic::arm_stlexd:
21099 case Intrinsic::arm_strexd:
21100 Info.opc = ISD::INTRINSIC_W_CHAIN;
21101 Info.memVT = MVT::i64;
21102 Info.ptrVal = I.getArgOperand(i: 2);
21103 Info.offset = 0;
21104 Info.align = Align(8);
21105 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
21106 Infos.push_back(Elt: Info);
21107 return;
21108
21109 case Intrinsic::arm_ldaexd:
21110 case Intrinsic::arm_ldrexd:
21111 Info.opc = ISD::INTRINSIC_W_CHAIN;
21112 Info.memVT = MVT::i64;
21113 Info.ptrVal = I.getArgOperand(i: 0);
21114 Info.offset = 0;
21115 Info.align = Align(8);
21116 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
21117 Infos.push_back(Elt: Info);
21118 return;
21119
21120 default:
21121 break;
21122 }
21123}
21124
21125/// Returns true if it is beneficial to convert a load of a constant
21126/// to just the constant itself.
21127bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
21128 Type *Ty) const {
21129 assert(Ty->isIntegerTy());
21130
21131 unsigned Bits = Ty->getPrimitiveSizeInBits();
21132 if (Bits == 0 || Bits > 32)
21133 return false;
21134 return true;
21135}
21136
21137bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
21138 unsigned Index) const {
21139 if (!isOperationLegalOrCustom(Op: ISD::EXTRACT_SUBVECTOR, VT: ResVT))
21140 return false;
21141
21142 return (Index == 0 || Index == ResVT.getVectorNumElements());
21143}
21144
21145Instruction *ARMTargetLowering::makeDMB(IRBuilderBase &Builder,
21146 ARM_MB::MemBOpt Domain) const {
21147 // First, if the target has no DMB, see what fallback we can use.
21148 if (!Subtarget->hasDataBarrier()) {
21149 // Some ARMv6 cpus can support data barriers with an mcr instruction.
21150 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
21151 // here.
21152 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
21153 Value* args[6] = {Builder.getInt32(C: 15), Builder.getInt32(C: 0),
21154 Builder.getInt32(C: 0), Builder.getInt32(C: 7),
21155 Builder.getInt32(C: 10), Builder.getInt32(C: 5)};
21156 return Builder.CreateIntrinsic(ID: Intrinsic::arm_mcr, Args: args);
21157 } else {
21158 // Instead of using barriers, atomic accesses on these subtargets use
21159 // libcalls.
21160 llvm_unreachable("makeDMB on a target so old that it has no barriers");
21161 }
21162 } else {
21163 // Only a full system barrier exists in the M-class architectures.
21164 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
21165 Constant *CDomain = Builder.getInt32(C: Domain);
21166 return Builder.CreateIntrinsic(ID: Intrinsic::arm_dmb, Args: CDomain);
21167 }
21168}
21169
21170// Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
21171Instruction *ARMTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
21172 Instruction *Inst,
21173 AtomicOrdering Ord) const {
21174 switch (Ord) {
21175 case AtomicOrdering::NotAtomic:
21176 case AtomicOrdering::Unordered:
21177 llvm_unreachable("Invalid fence: unordered/non-atomic");
21178 case AtomicOrdering::Monotonic:
21179 case AtomicOrdering::Acquire:
21180 return nullptr; // Nothing to do
21181 case AtomicOrdering::SequentiallyConsistent:
21182 if (!Inst->hasAtomicStore())
21183 return nullptr; // Nothing to do
21184 [[fallthrough]];
21185 case AtomicOrdering::Release:
21186 case AtomicOrdering::AcquireRelease:
21187 if (Subtarget->preferISHSTBarriers())
21188 return makeDMB(Builder, Domain: ARM_MB::ISHST);
21189 // FIXME: add a comment with a link to documentation justifying this.
21190 else
21191 return makeDMB(Builder, Domain: ARM_MB::ISH);
21192 }
21193 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
21194}
21195
21196Instruction *ARMTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
21197 Instruction *Inst,
21198 AtomicOrdering Ord) const {
21199 switch (Ord) {
21200 case AtomicOrdering::NotAtomic:
21201 case AtomicOrdering::Unordered:
21202 llvm_unreachable("Invalid fence: unordered/not-atomic");
21203 case AtomicOrdering::Monotonic:
21204 case AtomicOrdering::Release:
21205 return nullptr; // Nothing to do
21206 case AtomicOrdering::Acquire:
21207 case AtomicOrdering::AcquireRelease:
21208 case AtomicOrdering::SequentiallyConsistent:
21209 return makeDMB(Builder, Domain: ARM_MB::ISH);
21210 }
21211 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
21212}
21213
21214// Loads and stores less than 64-bits are already atomic; ones above that
21215// are doomed anyway, so defer to the default libcall and blame the OS when
21216// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21217// anything for those.
21218TargetLoweringBase::AtomicExpansionKind
21219ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
21220 bool has64BitAtomicStore;
21221 if (Subtarget->isMClass())
21222 has64BitAtomicStore = false;
21223 else if (Subtarget->isThumb())
21224 has64BitAtomicStore = Subtarget->hasV7Ops();
21225 else
21226 has64BitAtomicStore = Subtarget->hasV6Ops();
21227
21228 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
21229 return Size == 64 && has64BitAtomicStore ? AtomicExpansionKind::Expand
21230 : AtomicExpansionKind::None;
21231}
21232
21233// Loads and stores less than 64-bits are already atomic; ones above that
21234// are doomed anyway, so defer to the default libcall and blame the OS when
21235// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21236// anything for those.
21237// FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
21238// guarantee, see DDI0406C ARM architecture reference manual,
21239// sections A8.8.72-74 LDRD)
21240TargetLowering::AtomicExpansionKind
21241ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
21242 bool has64BitAtomicLoad;
21243 if (Subtarget->isMClass())
21244 has64BitAtomicLoad = false;
21245 else if (Subtarget->isThumb())
21246 has64BitAtomicLoad = Subtarget->hasV7Ops();
21247 else
21248 has64BitAtomicLoad = Subtarget->hasV6Ops();
21249
21250 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
21251 return (Size == 64 && has64BitAtomicLoad) ? AtomicExpansionKind::LLOnly
21252 : AtomicExpansionKind::None;
21253}
21254
21255// For the real atomic operations, we have ldrex/strex up to 32 bits,
21256// and up to 64 bits on the non-M profiles
21257TargetLowering::AtomicExpansionKind
21258ARMTargetLowering::shouldExpandAtomicRMWInIR(const AtomicRMWInst *AI) const {
21259 if (AI->isFloatingPointOperation())
21260 return AtomicExpansionKind::CmpXChg;
21261
21262 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
21263 bool hasAtomicRMW;
21264 if (Subtarget->isMClass())
21265 hasAtomicRMW = Subtarget->hasV8MBaselineOps();
21266 else if (Subtarget->isThumb())
21267 hasAtomicRMW = Subtarget->hasV7Ops();
21268 else
21269 hasAtomicRMW = Subtarget->hasV6Ops();
21270 if (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) {
21271 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
21272 // implement atomicrmw without spilling. If the target address is also on
21273 // the stack and close enough to the spill slot, this can lead to a
21274 // situation where the monitor always gets cleared and the atomic operation
21275 // can never succeed. So at -O0 lower this operation to a CAS loop.
21276 if (getTargetMachine().getOptLevel() == CodeGenOptLevel::None)
21277 return AtomicExpansionKind::CmpXChg;
21278 return AtomicExpansionKind::LLSC;
21279 }
21280 return AtomicExpansionKind::None;
21281}
21282
21283// Similar to shouldExpandAtomicRMWInIR, ldrex/strex can be used up to 32
21284// bits, and up to 64 bits on the non-M profiles.
21285TargetLowering::AtomicExpansionKind
21286ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
21287 const AtomicCmpXchgInst *AI) const {
21288 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
21289 // implement cmpxchg without spilling. If the address being exchanged is also
21290 // on the stack and close enough to the spill slot, this can lead to a
21291 // situation where the monitor always gets cleared and the atomic operation
21292 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
21293 unsigned Size = AI->getOperand(i_nocapture: 1)->getType()->getPrimitiveSizeInBits();
21294 bool HasAtomicCmpXchg;
21295 if (Subtarget->isMClass())
21296 HasAtomicCmpXchg = Subtarget->hasV8MBaselineOps();
21297 else if (Subtarget->isThumb())
21298 HasAtomicCmpXchg = Subtarget->hasV7Ops();
21299 else
21300 HasAtomicCmpXchg = Subtarget->hasV6Ops();
21301 if (getTargetMachine().getOptLevel() != CodeGenOptLevel::None &&
21302 HasAtomicCmpXchg && Size <= (Subtarget->isMClass() ? 32U : 64U))
21303 return AtomicExpansionKind::LLSC;
21304 return AtomicExpansionKind::None;
21305}
21306
21307bool ARMTargetLowering::shouldInsertFencesForAtomic(
21308 const Instruction *I) const {
21309 return InsertFencesForAtomic;
21310}
21311
21312bool ARMTargetLowering::useLoadStackGuardNode(const Module &M) const {
21313 // ROPI/RWPI are not supported currently.
21314 return !Subtarget->isROPI() && !Subtarget->isRWPI();
21315}
21316
21317void ARMTargetLowering::insertSSPDeclarations(
21318 Module &M, const LibcallLoweringInfo &Libcalls) const {
21319 // MSVC CRT provides functionalities for stack protection.
21320 RTLIB::LibcallImpl SecurityCheckCookieLibcall =
21321 Libcalls.getLibcallImpl(Call: RTLIB::SECURITY_CHECK_COOKIE);
21322
21323 RTLIB::LibcallImpl SecurityCookieVar =
21324 Libcalls.getLibcallImpl(Call: RTLIB::STACK_CHECK_GUARD);
21325 if (SecurityCheckCookieLibcall != RTLIB::Unsupported &&
21326 SecurityCookieVar != RTLIB::Unsupported) {
21327 // MSVC CRT has a global variable holding security cookie.
21328 M.getOrInsertGlobal(Name: getLibcallImplName(Call: SecurityCookieVar),
21329 Ty: PointerType::getUnqual(C&: M.getContext()));
21330
21331 // MSVC CRT has a function to validate security cookie.
21332 FunctionCallee SecurityCheckCookie =
21333 M.getOrInsertFunction(Name: getLibcallImplName(Call: SecurityCheckCookieLibcall),
21334 RetTy: Type::getVoidTy(C&: M.getContext()),
21335 Args: PointerType::getUnqual(C&: M.getContext()));
21336 if (Function *F = dyn_cast<Function>(Val: SecurityCheckCookie.getCallee()))
21337 F->addParamAttr(ArgNo: 0, Kind: Attribute::AttrKind::InReg);
21338 }
21339
21340 TargetLowering::insertSSPDeclarations(M, Libcalls);
21341}
21342
21343bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
21344 unsigned &Cost) const {
21345 // If we do not have NEON, vector types are not natively supported.
21346 if (!Subtarget->hasNEON())
21347 return false;
21348
21349 // Floating point values and vector values map to the same register file.
21350 // Therefore, although we could do a store extract of a vector type, this is
21351 // better to leave at float as we have more freedom in the addressing mode for
21352 // those.
21353 if (VectorTy->isFPOrFPVectorTy())
21354 return false;
21355
21356 // If the index is unknown at compile time, this is very expensive to lower
21357 // and it is not possible to combine the store with the extract.
21358 if (!isa<ConstantInt>(Val: Idx))
21359 return false;
21360
21361 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
21362 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedValue();
21363 // We can do a store + vector extract on any vector that fits perfectly in a D
21364 // or Q register.
21365 if (BitWidth == 64 || BitWidth == 128) {
21366 Cost = 0;
21367 return true;
21368 }
21369 return false;
21370}
21371
21372bool ARMTargetLowering::canCreateUndefOrPoisonForTargetNode(
21373 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
21374 bool PoisonOnly, bool ConsiderFlags, unsigned Depth) const {
21375 unsigned Opcode = Op.getOpcode();
21376 switch (Opcode) {
21377 case ARMISD::VORRIMM:
21378 case ARMISD::VBICIMM:
21379 return false;
21380 }
21381 return TargetLowering::canCreateUndefOrPoisonForTargetNode(
21382 Op, DemandedElts, DAG, PoisonOnly, ConsiderFlags, Depth);
21383}
21384
21385bool ARMTargetLowering::isCheapToSpeculateCttz(Type *Ty) const {
21386 return Subtarget->hasV5TOps() && !Subtarget->isThumb1Only();
21387}
21388
21389bool ARMTargetLowering::isCheapToSpeculateCtlz(Type *Ty) const {
21390 return Subtarget->hasV5TOps() && !Subtarget->isThumb1Only();
21391}
21392
21393bool ARMTargetLowering::isMaskAndCmp0FoldingBeneficial(
21394 const Instruction &AndI) const {
21395 if (!Subtarget->hasV7Ops())
21396 return false;
21397
21398 // Sink the `and` instruction only if the mask would fit into a modified
21399 // immediate operand.
21400 ConstantInt *Mask = dyn_cast<ConstantInt>(Val: AndI.getOperand(i: 1));
21401 if (!Mask || Mask->getValue().getBitWidth() > 32u)
21402 return false;
21403 auto MaskVal = unsigned(Mask->getValue().getZExtValue());
21404 return (Subtarget->isThumb2() ? ARM_AM::getT2SOImmVal(Arg: MaskVal)
21405 : ARM_AM::getSOImmVal(Arg: MaskVal)) != -1;
21406}
21407
21408TargetLowering::ShiftLegalizationStrategy
21409ARMTargetLowering::preferredShiftLegalizationStrategy(
21410 SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
21411 if (Subtarget->hasMinSize() && !getTM().getTargetTriple().isOSWindows())
21412 return ShiftLegalizationStrategy::LowerToLibcall;
21413 return TargetLowering::preferredShiftLegalizationStrategy(DAG, N,
21414 ExpansionFactor);
21415}
21416
21417Value *ARMTargetLowering::emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
21418 Value *Addr,
21419 AtomicOrdering Ord) const {
21420 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21421 bool IsAcquire = isAcquireOrStronger(AO: Ord);
21422
21423 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
21424 // intrinsic must return {i32, i32} and we have to recombine them into a
21425 // single i64 here.
21426 if (ValueTy->getPrimitiveSizeInBits() == 64) {
21427 Intrinsic::ID Int =
21428 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
21429
21430 Value *LoHi =
21431 Builder.CreateIntrinsic(ID: Int, Args: Addr, /*FMFSource=*/nullptr, Name: "lohi");
21432
21433 Value *Lo = Builder.CreateExtractValue(Agg: LoHi, Idxs: 0, Name: "lo");
21434 Value *Hi = Builder.CreateExtractValue(Agg: LoHi, Idxs: 1, Name: "hi");
21435 if (!Subtarget->isLittle())
21436 std::swap (a&: Lo, b&: Hi);
21437 Lo = Builder.CreateZExt(V: Lo, DestTy: ValueTy, Name: "lo64");
21438 Hi = Builder.CreateZExt(V: Hi, DestTy: ValueTy, Name: "hi64");
21439 return Builder.CreateOr(
21440 LHS: Lo, RHS: Builder.CreateShl(LHS: Hi, RHS: ConstantInt::get(Ty: ValueTy, V: 32)), Name: "val64");
21441 }
21442
21443 Type *Tys[] = { Addr->getType() };
21444 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
21445 CallInst *CI = Builder.CreateIntrinsic(ID: Int, Types: Tys, Args: Addr);
21446
21447 CI->addParamAttr(
21448 ArgNo: 0, Attr: Attribute::get(Context&: M->getContext(), Kind: Attribute::ElementType, Ty: ValueTy));
21449 return Builder.CreateTruncOrBitCast(V: CI, DestTy: ValueTy);
21450}
21451
21452void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
21453 IRBuilderBase &Builder) const {
21454 if (!Subtarget->hasV7Ops())
21455 return;
21456 Builder.CreateIntrinsic(ID: Intrinsic::arm_clrex, Args: {});
21457}
21458
21459Value *ARMTargetLowering::emitStoreConditional(IRBuilderBase &Builder,
21460 Value *Val, Value *Addr,
21461 AtomicOrdering Ord) const {
21462 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21463 bool IsRelease = isReleaseOrStronger(AO: Ord);
21464
21465 // Since the intrinsics must have legal type, the i64 intrinsics take two
21466 // parameters: "i32, i32". We must marshal Val into the appropriate form
21467 // before the call.
21468 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
21469 Intrinsic::ID Int =
21470 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
21471 Type *Int32Ty = Type::getInt32Ty(C&: M->getContext());
21472
21473 Value *Lo = Builder.CreateTrunc(V: Val, DestTy: Int32Ty, Name: "lo");
21474 Value *Hi = Builder.CreateTrunc(V: Builder.CreateLShr(LHS: Val, RHS: 32), DestTy: Int32Ty, Name: "hi");
21475 if (!Subtarget->isLittle())
21476 std::swap(a&: Lo, b&: Hi);
21477 return Builder.CreateIntrinsic(ID: Int, Args: {Lo, Hi, Addr});
21478 }
21479
21480 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
21481 Type *Tys[] = { Addr->getType() };
21482 Function *Strex = Intrinsic::getOrInsertDeclaration(M, id: Int, Tys);
21483
21484 CallInst *CI = Builder.CreateCall(
21485 Callee: Strex, Args: {Builder.CreateZExtOrBitCast(
21486 V: Val, DestTy: Strex->getFunctionType()->getParamType(i: 0)),
21487 Addr});
21488 CI->addParamAttr(ArgNo: 1, Attr: Attribute::get(Context&: M->getContext(), Kind: Attribute::ElementType,
21489 Ty: Val->getType()));
21490 return CI;
21491}
21492
21493
21494bool ARMTargetLowering::alignLoopsWithOptSize() const {
21495 return Subtarget->isMClass();
21496}
21497
21498/// A helper function for determining the number of interleaved accesses we
21499/// will generate when lowering accesses of the given type.
21500unsigned
21501ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
21502 const DataLayout &DL) const {
21503 return (DL.getTypeSizeInBits(Ty: VecTy) + 127) / 128;
21504}
21505
21506bool ARMTargetLowering::isLegalInterleavedAccessType(
21507 unsigned Factor, FixedVectorType *VecTy, Align Alignment,
21508 const DataLayout &DL) const {
21509
21510 unsigned VecSize = DL.getTypeSizeInBits(Ty: VecTy);
21511 unsigned ElSize = DL.getTypeSizeInBits(Ty: VecTy->getElementType());
21512
21513 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
21514 return false;
21515
21516 // Ensure the vector doesn't have f16 elements. Even though we could do an
21517 // i16 vldN, we can't hold the f16 vectors and will end up converting via
21518 // f32.
21519 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
21520 return false;
21521 if (Subtarget->hasMVEIntegerOps() && Factor == 3)
21522 return false;
21523
21524 // Ensure the number of vector elements is greater than 1.
21525 if (VecTy->getNumElements() < 2)
21526 return false;
21527
21528 // Ensure the element type is legal.
21529 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
21530 return false;
21531 // And the alignment if high enough under MVE.
21532 if (Subtarget->hasMVEIntegerOps() && Alignment < ElSize / 8)
21533 return false;
21534
21535 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
21536 // 128 will be split into multiple interleaved accesses.
21537 if (Subtarget->hasNEON() && VecSize == 64)
21538 return true;
21539 return VecSize % 128 == 0;
21540}
21541
21542unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
21543 if (Subtarget->hasNEON())
21544 return 4;
21545 if (Subtarget->hasMVEIntegerOps())
21546 return MVEMaxSupportedInterleaveFactor;
21547 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
21548}
21549
21550/// Lower an interleaved load into a vldN intrinsic.
21551///
21552/// E.g. Lower an interleaved load (Factor = 2):
21553/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
21554/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
21555/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
21556///
21557/// Into:
21558/// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
21559/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
21560/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
21561bool ARMTargetLowering::lowerInterleavedLoad(
21562 Instruction *Load, Value *Mask, ArrayRef<ShuffleVectorInst *> Shuffles,
21563 ArrayRef<unsigned> Indices, unsigned Factor, const APInt &GapMask) const {
21564 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
21565 "Invalid interleave factor");
21566 assert(!Shuffles.empty() && "Empty shufflevector input");
21567 assert(Shuffles.size() == Indices.size() &&
21568 "Unmatched number of shufflevectors and indices");
21569
21570 auto *LI = dyn_cast<LoadInst>(Val: Load);
21571 if (!LI)
21572 return false;
21573 assert(!Mask && GapMask.popcount() == Factor && "Unexpected mask on a load");
21574
21575 auto *VecTy = cast<FixedVectorType>(Val: Shuffles[0]->getType());
21576 Type *EltTy = VecTy->getElementType();
21577
21578 const DataLayout &DL = LI->getDataLayout();
21579 Align Alignment = LI->getAlign();
21580
21581 // Skip if we do not have NEON and skip illegal vector types. We can
21582 // "legalize" wide vector types into multiple interleaved accesses as long as
21583 // the vector types are divisible by 128.
21584 if (!isLegalInterleavedAccessType(Factor, VecTy, Alignment, DL))
21585 return false;
21586
21587 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
21588
21589 // A pointer vector can not be the return type of the ldN intrinsics. Need to
21590 // load integer vectors first and then convert to pointer vectors.
21591 if (EltTy->isPointerTy())
21592 VecTy = FixedVectorType::get(ElementType: DL.getIntPtrType(EltTy), FVTy: VecTy);
21593
21594 IRBuilder<> Builder(LI);
21595
21596 // The base address of the load.
21597 Value *BaseAddr = LI->getPointerOperand();
21598
21599 if (NumLoads > 1) {
21600 // If we're going to generate more than one load, reset the sub-vector type
21601 // to something legal.
21602 VecTy = FixedVectorType::get(ElementType: VecTy->getElementType(),
21603 NumElts: VecTy->getNumElements() / NumLoads);
21604 }
21605
21606 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
21607
21608 auto createLoadIntrinsic = [&](Value *BaseAddr) {
21609 if (Subtarget->hasNEON()) {
21610 Type *PtrTy = Builder.getPtrTy(AddrSpace: LI->getPointerAddressSpace());
21611 Type *Tys[] = {VecTy, PtrTy};
21612 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
21613 Intrinsic::arm_neon_vld3,
21614 Intrinsic::arm_neon_vld4};
21615
21616 SmallVector<Value *, 2> Ops;
21617 Ops.push_back(Elt: BaseAddr);
21618 Ops.push_back(Elt: Builder.getInt32(C: LI->getAlign().value()));
21619
21620 return Builder.CreateIntrinsic(ID: LoadInts[Factor - 2], Types: Tys, Args: Ops,
21621 /*FMFSource=*/nullptr, Name: "vldN");
21622 } else {
21623 assert((Factor == 2 || Factor == 4) &&
21624 "expected interleave factor of 2 or 4 for MVE");
21625 Intrinsic::ID LoadInts =
21626 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
21627 Type *PtrTy = Builder.getPtrTy(AddrSpace: LI->getPointerAddressSpace());
21628 Type *Tys[] = {VecTy, PtrTy};
21629
21630 SmallVector<Value *, 2> Ops;
21631 Ops.push_back(Elt: BaseAddr);
21632 return Builder.CreateIntrinsic(ID: LoadInts, Types: Tys, Args: Ops, /*FMFSource=*/nullptr,
21633 Name: "vldN");
21634 }
21635 };
21636
21637 // Holds sub-vectors extracted from the load intrinsic return values. The
21638 // sub-vectors are associated with the shufflevector instructions they will
21639 // replace.
21640 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
21641
21642 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
21643 // If we're generating more than one load, compute the base address of
21644 // subsequent loads as an offset from the previous.
21645 if (LoadCount > 0)
21646 BaseAddr = Builder.CreateConstGEP1_32(Ty: VecTy->getElementType(), Ptr: BaseAddr,
21647 Idx0: VecTy->getNumElements() * Factor);
21648
21649 CallInst *VldN = createLoadIntrinsic(BaseAddr);
21650
21651 // Replace uses of each shufflevector with the corresponding vector loaded
21652 // by ldN.
21653 for (unsigned i = 0; i < Shuffles.size(); i++) {
21654 ShuffleVectorInst *SV = Shuffles[i];
21655 unsigned Index = Indices[i];
21656
21657 Value *SubVec = Builder.CreateExtractValue(Agg: VldN, Idxs: Index);
21658
21659 // Convert the integer vector to pointer vector if the element is pointer.
21660 if (EltTy->isPointerTy())
21661 SubVec = Builder.CreateIntToPtr(
21662 V: SubVec,
21663 DestTy: FixedVectorType::get(ElementType: SV->getType()->getElementType(), FVTy: VecTy));
21664
21665 SubVecs[SV].push_back(Elt: SubVec);
21666 }
21667 }
21668
21669 // Replace uses of the shufflevector instructions with the sub-vectors
21670 // returned by the load intrinsic. If a shufflevector instruction is
21671 // associated with more than one sub-vector, those sub-vectors will be
21672 // concatenated into a single wide vector.
21673 for (ShuffleVectorInst *SVI : Shuffles) {
21674 auto &SubVec = SubVecs[SVI];
21675 auto *WideVec =
21676 SubVec.size() > 1 ? concatenateVectors(Builder, Vecs: SubVec) : SubVec[0];
21677 SVI->replaceAllUsesWith(V: WideVec);
21678 }
21679
21680 return true;
21681}
21682
21683/// Lower an interleaved store into a vstN intrinsic.
21684///
21685/// E.g. Lower an interleaved store (Factor = 3):
21686/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
21687/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
21688/// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
21689///
21690/// Into:
21691/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
21692/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
21693/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
21694/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
21695///
21696/// Note that the new shufflevectors will be removed and we'll only generate one
21697/// vst3 instruction in CodeGen.
21698///
21699/// Example for a more general valid mask (Factor 3). Lower:
21700/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
21701/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
21702/// store <12 x i32> %i.vec, <12 x i32>* %ptr
21703///
21704/// Into:
21705/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
21706/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
21707/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
21708/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
21709bool ARMTargetLowering::lowerInterleavedStore(Instruction *Store,
21710 Value *LaneMask,
21711 ShuffleVectorInst *SVI,
21712 unsigned Factor,
21713 const APInt &GapMask) const {
21714 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
21715 "Invalid interleave factor");
21716 auto *SI = dyn_cast<StoreInst>(Val: Store);
21717 if (!SI)
21718 return false;
21719 assert(!LaneMask && GapMask.popcount() == Factor &&
21720 "Unexpected mask on store");
21721
21722 auto *VecTy = cast<FixedVectorType>(Val: SVI->getType());
21723 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
21724
21725 unsigned LaneLen = VecTy->getNumElements() / Factor;
21726 Type *EltTy = VecTy->getElementType();
21727 auto *SubVecTy = FixedVectorType::get(ElementType: EltTy, NumElts: LaneLen);
21728
21729 const DataLayout &DL = SI->getDataLayout();
21730 Align Alignment = SI->getAlign();
21731
21732 // Skip if we do not have NEON and skip illegal vector types. We can
21733 // "legalize" wide vector types into multiple interleaved accesses as long as
21734 // the vector types are divisible by 128.
21735 if (!isLegalInterleavedAccessType(Factor, VecTy: SubVecTy, Alignment, DL))
21736 return false;
21737
21738 unsigned NumStores = getNumInterleavedAccesses(VecTy: SubVecTy, DL);
21739
21740 Value *Op0 = SVI->getOperand(i_nocapture: 0);
21741 Value *Op1 = SVI->getOperand(i_nocapture: 1);
21742 IRBuilder<> Builder(SI);
21743
21744 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
21745 // vectors to integer vectors.
21746 if (EltTy->isPointerTy()) {
21747 Type *IntTy = DL.getIntPtrType(EltTy);
21748
21749 // Convert to the corresponding integer vector.
21750 auto *IntVecTy =
21751 FixedVectorType::get(ElementType: IntTy, FVTy: cast<FixedVectorType>(Val: Op0->getType()));
21752 Op0 = Builder.CreatePtrToInt(V: Op0, DestTy: IntVecTy);
21753 Op1 = Builder.CreatePtrToInt(V: Op1, DestTy: IntVecTy);
21754
21755 SubVecTy = FixedVectorType::get(ElementType: IntTy, NumElts: LaneLen);
21756 }
21757
21758 // The base address of the store.
21759 Value *BaseAddr = SI->getPointerOperand();
21760
21761 if (NumStores > 1) {
21762 // If we're going to generate more than one store, reset the lane length
21763 // and sub-vector type to something legal.
21764 LaneLen /= NumStores;
21765 SubVecTy = FixedVectorType::get(ElementType: SubVecTy->getElementType(), NumElts: LaneLen);
21766 }
21767
21768 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
21769
21770 auto Mask = SVI->getShuffleMask();
21771
21772 auto createStoreIntrinsic = [&](Value *BaseAddr,
21773 SmallVectorImpl<Value *> &Shuffles) {
21774 if (Subtarget->hasNEON()) {
21775 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
21776 Intrinsic::arm_neon_vst3,
21777 Intrinsic::arm_neon_vst4};
21778 Type *PtrTy = Builder.getPtrTy(AddrSpace: SI->getPointerAddressSpace());
21779 Type *Tys[] = {PtrTy, SubVecTy};
21780
21781 SmallVector<Value *, 6> Ops;
21782 Ops.push_back(Elt: BaseAddr);
21783 append_range(C&: Ops, R&: Shuffles);
21784 Ops.push_back(Elt: Builder.getInt32(C: SI->getAlign().value()));
21785 Builder.CreateIntrinsic(ID: StoreInts[Factor - 2], Types: Tys, Args: Ops);
21786 } else {
21787 assert((Factor == 2 || Factor == 4) &&
21788 "expected interleave factor of 2 or 4 for MVE");
21789 Intrinsic::ID StoreInts =
21790 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
21791 Type *PtrTy = Builder.getPtrTy(AddrSpace: SI->getPointerAddressSpace());
21792 Type *Tys[] = {PtrTy, SubVecTy};
21793
21794 SmallVector<Value *, 6> Ops;
21795 Ops.push_back(Elt: BaseAddr);
21796 append_range(C&: Ops, R&: Shuffles);
21797 for (unsigned F = 0; F < Factor; F++) {
21798 Ops.push_back(Elt: Builder.getInt32(C: F));
21799 Builder.CreateIntrinsic(ID: StoreInts, Types: Tys, Args: Ops);
21800 Ops.pop_back();
21801 }
21802 }
21803 };
21804
21805 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
21806 // If we generating more than one store, we compute the base address of
21807 // subsequent stores as an offset from the previous.
21808 if (StoreCount > 0)
21809 BaseAddr = Builder.CreateConstGEP1_32(Ty: SubVecTy->getElementType(),
21810 Ptr: BaseAddr, Idx0: LaneLen * Factor);
21811
21812 SmallVector<Value *, 4> Shuffles;
21813
21814 // Split the shufflevector operands into sub vectors for the new vstN call.
21815 for (unsigned i = 0; i < Factor; i++) {
21816 unsigned IdxI = StoreCount * LaneLen * Factor + i;
21817 if (Mask[IdxI] >= 0) {
21818 Shuffles.push_back(Elt: Builder.CreateShuffleVector(
21819 V1: Op0, V2: Op1, Mask: createSequentialMask(Start: Mask[IdxI], NumInts: LaneLen, NumUndefs: 0)));
21820 } else {
21821 unsigned StartMask = 0;
21822 for (unsigned j = 1; j < LaneLen; j++) {
21823 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
21824 if (Mask[IdxJ * Factor + IdxI] >= 0) {
21825 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
21826 break;
21827 }
21828 }
21829 // Note: If all elements in a chunk are undefs, StartMask=0!
21830 // Note: Filling undef gaps with random elements is ok, since
21831 // those elements were being written anyway (with undefs).
21832 // In the case of all undefs we're defaulting to using elems from 0
21833 // Note: StartMask cannot be negative, it's checked in
21834 // isReInterleaveMask
21835 Shuffles.push_back(Elt: Builder.CreateShuffleVector(
21836 V1: Op0, V2: Op1, Mask: createSequentialMask(Start: StartMask, NumInts: LaneLen, NumUndefs: 0)));
21837 }
21838 }
21839
21840 createStoreIntrinsic(BaseAddr, Shuffles);
21841 }
21842 return true;
21843}
21844
21845enum HABaseType {
21846 HA_UNKNOWN = 0,
21847 HA_FLOAT,
21848 HA_DOUBLE,
21849 HA_VECT64,
21850 HA_VECT128
21851};
21852
21853static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
21854 uint64_t &Members) {
21855 if (auto *ST = dyn_cast<StructType>(Val: Ty)) {
21856 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
21857 uint64_t SubMembers = 0;
21858 if (!isHomogeneousAggregate(Ty: ST->getElementType(N: i), Base, Members&: SubMembers))
21859 return false;
21860 Members += SubMembers;
21861 }
21862 } else if (auto *AT = dyn_cast<ArrayType>(Val: Ty)) {
21863 uint64_t SubMembers = 0;
21864 if (!isHomogeneousAggregate(Ty: AT->getElementType(), Base, Members&: SubMembers))
21865 return false;
21866 Members += SubMembers * AT->getNumElements();
21867 } else if (Ty->isFloatTy()) {
21868 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
21869 return false;
21870 Members = 1;
21871 Base = HA_FLOAT;
21872 } else if (Ty->isDoubleTy()) {
21873 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
21874 return false;
21875 Members = 1;
21876 Base = HA_DOUBLE;
21877 } else if (auto *VT = dyn_cast<VectorType>(Val: Ty)) {
21878 Members = 1;
21879 switch (Base) {
21880 case HA_FLOAT:
21881 case HA_DOUBLE:
21882 return false;
21883 case HA_VECT64:
21884 return VT->getPrimitiveSizeInBits().getFixedValue() == 64;
21885 case HA_VECT128:
21886 return VT->getPrimitiveSizeInBits().getFixedValue() == 128;
21887 case HA_UNKNOWN:
21888 switch (VT->getPrimitiveSizeInBits().getFixedValue()) {
21889 case 64:
21890 Base = HA_VECT64;
21891 return true;
21892 case 128:
21893 Base = HA_VECT128;
21894 return true;
21895 default:
21896 return false;
21897 }
21898 }
21899 }
21900
21901 return (Members > 0 && Members <= 4);
21902}
21903
21904/// Return the correct alignment for the current calling convention.
21905Align ARMTargetLowering::getABIAlignmentForCallingConv(
21906 Type *ArgTy, const DataLayout &DL) const {
21907 const Align ABITypeAlign = DL.getABITypeAlign(Ty: ArgTy);
21908 if (!ArgTy->isVectorTy())
21909 return ABITypeAlign;
21910
21911 // Avoid over-aligning vector parameters. It would require realigning the
21912 // stack and waste space for no real benefit.
21913 MaybeAlign StackAlign = DL.getStackAlignment();
21914 assert(StackAlign && "data layout string is missing stack alignment");
21915 return std::min(a: ABITypeAlign, b: *StackAlign);
21916}
21917
21918/// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
21919/// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
21920/// passing according to AAPCS rules.
21921bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
21922 Type *Ty, CallingConv::ID CallConv, bool isVarArg,
21923 const DataLayout &DL) const {
21924 if (getEffectiveCallingConv(CC: CallConv, isVarArg) !=
21925 CallingConv::ARM_AAPCS_VFP)
21926 return false;
21927
21928 HABaseType Base = HA_UNKNOWN;
21929 uint64_t Members = 0;
21930 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
21931 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
21932
21933 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
21934 return IsHA || IsIntArray;
21935}
21936
21937Register ARMTargetLowering::getExceptionPointerRegister(
21938 const Constant *PersonalityFn) const {
21939 // Platforms which do not use SjLj EH may return values in these registers
21940 // via the personality function.
21941 ExceptionHandling EM = getTargetMachine().getExceptionModel();
21942 return EM == ExceptionHandling::SjLj ? Register() : ARM::R0;
21943}
21944
21945Register ARMTargetLowering::getExceptionSelectorRegister(
21946 const Constant *PersonalityFn) const {
21947 // Platforms which do not use SjLj EH may return values in these registers
21948 // via the personality function.
21949 ExceptionHandling EM = getTargetMachine().getExceptionModel();
21950 return EM == ExceptionHandling::SjLj ? Register() : ARM::R1;
21951}
21952
21953void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
21954 // Update IsSplitCSR in ARMFunctionInfo.
21955 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
21956 AFI->setIsSplitCSR(true);
21957}
21958
21959void ARMTargetLowering::insertCopiesSplitCSR(
21960 MachineBasicBlock *Entry,
21961 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
21962 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
21963 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(MF: Entry->getParent());
21964 if (!IStart)
21965 return;
21966
21967 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21968 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
21969 MachineBasicBlock::iterator MBBI = Entry->begin();
21970 for (const MCPhysReg *I = IStart; *I; ++I) {
21971 const TargetRegisterClass *RC = nullptr;
21972 if (ARM::GPRRegClass.contains(Reg: *I))
21973 RC = &ARM::GPRRegClass;
21974 else if (ARM::DPRRegClass.contains(Reg: *I))
21975 RC = &ARM::DPRRegClass;
21976 else
21977 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
21978
21979 Register NewVR = MRI->createVirtualRegister(RegClass: RC);
21980 // Create copy from CSR to a virtual register.
21981 // FIXME: this currently does not emit CFI pseudo-instructions, it works
21982 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
21983 // nounwind. If we want to generalize this later, we may need to emit
21984 // CFI pseudo-instructions.
21985 assert(Entry->getParent()->getFunction().hasFnAttribute(
21986 Attribute::NoUnwind) &&
21987 "Function should be nounwind in insertCopiesSplitCSR!");
21988 Entry->addLiveIn(PhysReg: *I);
21989 BuildMI(BB&: *Entry, I: MBBI, MIMD: DebugLoc(), MCID: TII->get(Opcode: TargetOpcode::COPY), DestReg: NewVR)
21990 .addReg(RegNo: *I);
21991
21992 // Insert the copy-back instructions right before the terminator.
21993 for (auto *Exit : Exits)
21994 BuildMI(BB&: *Exit, I: Exit->getFirstTerminator(), MIMD: DebugLoc(),
21995 MCID: TII->get(Opcode: TargetOpcode::COPY), DestReg: *I)
21996 .addReg(RegNo: NewVR);
21997 }
21998}
21999
22000void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
22001 MF.getFrameInfo().computeMaxCallFrameSize(MF);
22002 TargetLoweringBase::finalizeLowering(MF);
22003}
22004
22005bool ARMTargetLowering::isComplexDeinterleavingSupported() const {
22006 return Subtarget->hasMVEIntegerOps();
22007}
22008
22009bool ARMTargetLowering::isComplexDeinterleavingOperationSupported(
22010 ComplexDeinterleavingOperation Operation, Type *Ty) const {
22011 auto *VTy = dyn_cast<FixedVectorType>(Val: Ty);
22012 if (!VTy)
22013 return false;
22014
22015 auto *ScalarTy = VTy->getScalarType();
22016 unsigned NumElements = VTy->getNumElements();
22017
22018 unsigned VTyWidth = VTy->getScalarSizeInBits() * NumElements;
22019 if (VTyWidth < 128 || !llvm::isPowerOf2_32(Value: VTyWidth))
22020 return false;
22021
22022 // Both VCADD and VCMUL/VCMLA support the same types, F16 and F32
22023 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy())
22024 return Subtarget->hasMVEFloatOps();
22025
22026 if (Operation != ComplexDeinterleavingOperation::CAdd)
22027 return false;
22028
22029 return Subtarget->hasMVEIntegerOps() &&
22030 (ScalarTy->isIntegerTy(Bitwidth: 8) || ScalarTy->isIntegerTy(Bitwidth: 16) ||
22031 ScalarTy->isIntegerTy(Bitwidth: 32));
22032}
22033
22034ArrayRef<MCPhysReg> ARMTargetLowering::getRoundingControlRegisters() const {
22035 static const MCPhysReg RCRegs[] = {ARM::FPSCR_RM};
22036 return RCRegs;
22037}
22038
22039Value *ARMTargetLowering::createComplexDeinterleavingIR(
22040 IRBuilderBase &B, ComplexDeinterleavingOperation OperationType,
22041 ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
22042 Value *Accumulator) const {
22043
22044 FixedVectorType *Ty = cast<FixedVectorType>(Val: InputA->getType());
22045
22046 unsigned TyWidth = Ty->getScalarSizeInBits() * Ty->getNumElements();
22047
22048 assert(TyWidth >= 128 && "Width of vector type must be at least 128 bits");
22049
22050 if (TyWidth > 128) {
22051 int Stride = Ty->getNumElements() / 2;
22052 auto SplitSeq = llvm::seq<int>(Begin: 0, End: Ty->getNumElements());
22053 auto SplitSeqVec = llvm::to_vector(Range&: SplitSeq);
22054 ArrayRef<int> LowerSplitMask(&SplitSeqVec[0], Stride);
22055 ArrayRef<int> UpperSplitMask(&SplitSeqVec[Stride], Stride);
22056
22057 auto *LowerSplitA = B.CreateShuffleVector(V: InputA, Mask: LowerSplitMask);
22058 auto *LowerSplitB = B.CreateShuffleVector(V: InputB, Mask: LowerSplitMask);
22059 auto *UpperSplitA = B.CreateShuffleVector(V: InputA, Mask: UpperSplitMask);
22060 auto *UpperSplitB = B.CreateShuffleVector(V: InputB, Mask: UpperSplitMask);
22061 Value *LowerSplitAcc = nullptr;
22062 Value *UpperSplitAcc = nullptr;
22063
22064 if (Accumulator) {
22065 LowerSplitAcc = B.CreateShuffleVector(V: Accumulator, Mask: LowerSplitMask);
22066 UpperSplitAcc = B.CreateShuffleVector(V: Accumulator, Mask: UpperSplitMask);
22067 }
22068
22069 auto *LowerSplitInt = createComplexDeinterleavingIR(
22070 B, OperationType, Rotation, InputA: LowerSplitA, InputB: LowerSplitB, Accumulator: LowerSplitAcc);
22071 auto *UpperSplitInt = createComplexDeinterleavingIR(
22072 B, OperationType, Rotation, InputA: UpperSplitA, InputB: UpperSplitB, Accumulator: UpperSplitAcc);
22073
22074 ArrayRef<int> JoinMask(&SplitSeqVec[0], Ty->getNumElements());
22075 return B.CreateShuffleVector(V1: LowerSplitInt, V2: UpperSplitInt, Mask: JoinMask);
22076 }
22077
22078 auto *IntTy = Type::getInt32Ty(C&: B.getContext());
22079
22080 ConstantInt *ConstRotation = nullptr;
22081 if (OperationType == ComplexDeinterleavingOperation::CMulPartial) {
22082 ConstRotation = ConstantInt::get(Ty: IntTy, V: (int)Rotation);
22083
22084 if (Accumulator)
22085 return B.CreateIntrinsic(ID: Intrinsic::arm_mve_vcmlaq, Types: Ty,
22086 Args: {ConstRotation, Accumulator, InputB, InputA});
22087 return B.CreateIntrinsic(ID: Intrinsic::arm_mve_vcmulq, Types: Ty,
22088 Args: {ConstRotation, InputB, InputA});
22089 }
22090
22091 if (OperationType == ComplexDeinterleavingOperation::CAdd) {
22092 // 1 means the value is not halved.
22093 auto *ConstHalving = ConstantInt::get(Ty: IntTy, V: 1);
22094
22095 if (Rotation == ComplexDeinterleavingRotation::Rotation_90)
22096 ConstRotation = ConstantInt::get(Ty: IntTy, V: 0);
22097 else if (Rotation == ComplexDeinterleavingRotation::Rotation_270)
22098 ConstRotation = ConstantInt::get(Ty: IntTy, V: 1);
22099
22100 if (!ConstRotation)
22101 return nullptr; // Invalid rotation for arm_mve_vcaddq
22102
22103 return B.CreateIntrinsic(ID: Intrinsic::arm_mve_vcaddq, Types: Ty,
22104 Args: {ConstHalving, ConstRotation, InputA, InputB});
22105 }
22106
22107 return nullptr;
22108}
22109