LLVM 24.0.0git
AArch64TargetTransformInfo.cpp
Go to the documentation of this file.
1//===-- AArch64TargetTransformInfo.cpp - AArch64 specific TTI -------------===//
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
10#include "AArch64ExpandImm.h"
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/bit.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/IntrinsicsAArch64.h"
27#include "llvm/Support/Debug.h"
32#include <algorithm>
33#include <optional>
34using namespace llvm;
35using namespace llvm::PatternMatch;
36
37#define DEBUG_TYPE "aarch64tti"
38
39namespace {
40class TailFoldingOption {
41 // These bitfields will only ever be set to something non-zero in operator=,
42 // when setting the -sve-tail-folding option. This option should always be of
43 // the form (default|simple|all|disable)[+(Flag1|Flag2|etc)], where here
44 // InitialBits is one of (disabled|all|simple). EnableBits represents
45 // additional flags we're enabling, and DisableBits for those flags we're
46 // disabling. The default flag is tracked in the variable NeedsDefault, since
47 // at the time of setting the option we may not know what the default value
48 // for the CPU is.
52
53 // This value needs to be initialised to true in case the user does not
54 // explicitly set the -sve-tail-folding option.
55 bool NeedsDefault = true;
56
57 void setInitialBits(TailFoldingOpts Bits) { InitialBits = Bits; }
58
59 void setNeedsDefault(bool V) { NeedsDefault = V; }
60
61 void setEnableBit(TailFoldingOpts Bit) {
62 EnableBits |= Bit;
63 DisableBits &= ~Bit;
64 }
65
66 void setDisableBit(TailFoldingOpts Bit) {
67 EnableBits &= ~Bit;
68 DisableBits |= Bit;
69 }
70
71 TailFoldingOpts getBits(TailFoldingOpts DefaultBits) const {
73
74 assert((InitialBits == TailFoldingOpts::Disabled || !NeedsDefault) &&
75 "Initial bits should only include one of "
76 "(disabled|all|simple|default)");
77 Bits = NeedsDefault ? DefaultBits : InitialBits;
78 Bits |= EnableBits;
79 Bits &= ~DisableBits;
80
81 return Bits;
82 }
83
84 void reportError(std::string Opt) {
85 errs() << "invalid argument '" << Opt
86 << "' to -sve-tail-folding=; the option should be of the form\n"
87 " (disabled|all|default|simple)[+(reductions|recurrences"
88 "|reverse|noreductions|norecurrences|noreverse)]\n";
89 report_fatal_error("Unrecognised tail-folding option");
90 }
91
92public:
93
94 void operator=(const std::string &Val) {
95 // If the user explicitly sets -sve-tail-folding= then treat as an error.
96 if (Val.empty()) {
97 reportError("");
98 return;
99 }
100
101 // Since the user is explicitly setting the option we don't automatically
102 // need the default unless they require it.
103 setNeedsDefault(false);
104
105 SmallVector<StringRef, 4> TailFoldTypes;
106 StringRef(Val).split(TailFoldTypes, '+', -1, false);
107
108 unsigned StartIdx = 1;
109 if (TailFoldTypes[0] == "disabled")
110 setInitialBits(TailFoldingOpts::Disabled);
111 else if (TailFoldTypes[0] == "all")
112 setInitialBits(TailFoldingOpts::All);
113 else if (TailFoldTypes[0] == "default")
114 setNeedsDefault(true);
115 else if (TailFoldTypes[0] == "simple")
116 setInitialBits(TailFoldingOpts::Simple);
117 else {
118 StartIdx = 0;
119 setInitialBits(TailFoldingOpts::Disabled);
120 }
121
122 for (unsigned I = StartIdx; I < TailFoldTypes.size(); I++) {
123 if (TailFoldTypes[I] == "reductions")
124 setEnableBit(TailFoldingOpts::Reductions);
125 else if (TailFoldTypes[I] == "recurrences")
126 setEnableBit(TailFoldingOpts::Recurrences);
127 else if (TailFoldTypes[I] == "reverse")
128 setEnableBit(TailFoldingOpts::Reverse);
129 else if (TailFoldTypes[I] == "noreductions")
130 setDisableBit(TailFoldingOpts::Reductions);
131 else if (TailFoldTypes[I] == "norecurrences")
132 setDisableBit(TailFoldingOpts::Recurrences);
133 else if (TailFoldTypes[I] == "noreverse")
134 setDisableBit(TailFoldingOpts::Reverse);
135 else
136 reportError(Val);
137 }
138 }
139
140 bool isDisabled(TailFoldingOpts DefaultBits) const {
141 return getBits(DefaultBits) == TailFoldingOpts::Disabled;
142 }
143
144 bool satisfies(TailFoldingOpts DefaultBits, TailFoldingOpts Required) const {
145 return (getBits(DefaultBits) & Required) == Required;
146 }
147};
148} // namespace
149
150TailFoldingOption TailFoldingOptionLoc;
151
153 "sve-tail-folding",
154 cl::desc(
155 "Control the use of vectorisation using tail-folding for SVE where the"
156 " option is specified in the form (Initial)[+(Flag1|Flag2|...)]:"
157 "\ndisabled (Initial) No loop types will vectorize using "
158 "tail-folding"
159 "\ndefault (Initial) Uses the default tail-folding settings for "
160 "the target CPU"
161 "\nall (Initial) All legal loop types will vectorize using "
162 "tail-folding"
163 "\nsimple (Initial) Use tail-folding for simple loops (not "
164 "reductions or recurrences)"
165 "\nreductions Use tail-folding for loops containing reductions"
166 "\nnoreductions Inverse of above"
167 "\nrecurrences Use tail-folding for loops containing fixed order "
168 "recurrences"
169 "\nnorecurrences Inverse of above"
170 "\nreverse Use tail-folding for loops requiring reversed "
171 "predicates"
172 "\nnoreverse Inverse of above"),
174
175/// Returns true if the function has explicit operations that can only be
176/// lowered using incompatible instructions for the selected mode. This also
177/// returns true if the function F may use or modify ZA state.
179 bool ConsiderZA,
180 bool ConsiderZT,
181 bool ConsiderSM) const {
182 if (!ConsiderZA && !ConsiderZT && !ConsiderSM)
183 return false;
184
185 bool IsAlwaysInline = F->hasFnAttribute(Attribute::AlwaysInline);
186 // If the interface has vscale-dependent arguments/return value, then the ACLE
187 // describes that the function can only have defined behaviour if vscale is
188 // the same for both streaming/non-streaming mode, meaning that we can assume
189 // vscale is equivalent.
190 // FIXME: Handle the case where vscale_range is known and equivalent for
191 // caller and callee.
192 bool AssumeVScaleIsEquivalent =
193 F->getReturnType()->isScalableTy() ||
194 any_of(F->getFunctionType()->params(),
195 [](const Type *T) { return T->isScalableTy(); });
196
197 for (const BasicBlock &BB : *F) {
198 for (const Instruction &I : BB) {
199 if (auto *CB = dyn_cast<CallBase>(&I)) {
200 SMECallAttrs CallAttrs(*CB, &TLI->getRuntimeLibcallsInfo());
201
202 // Inline asm must be rejected as it could use SME state.
203 if (CB->isInlineAsm())
204 return true;
205
206 if (CallAttrs.callee().isSMEABIRoutine())
207 return true;
208
209 // If the callee has calls to streaming compatible functions, then those
210 // may have statements which depend on SME state (e.g. vscale or
211 // explicit reads of PSTATE.SM). If we were to inline those calls,
212 // behaviour may change after inlining because the streaming-compatible
213 // function would be executed in a different streaming mode.
214 // Conservatively avoid inlining for now.
215 if (ConsiderSM && CallAttrs.callee().hasStreamingCompatibleInterface())
216 return true;
217 }
218
219 if (!ConsiderSM)
220 continue;
221
222 auto *II = dyn_cast<IntrinsicInst>(&I);
223
224 // FIXME: Be less conservative about target intrinsics.
225 if (II && II->getCalledFunction()->isTargetIntrinsic())
226 return true;
227
228 // Determine if the operation is vscale dependent by looking at it's
229 // operand/result types.
230 if (!AssumeVScaleIsEquivalent &&
231 ((II && II->getIntrinsicID() == Intrinsic::vscale) ||
232 I.getType()->isScalableTy() ||
233 any_of(
234 I.operand_values(),
235 [](const Value *V) { return V->getType()->isScalableTy(); }) ||
237 .getSourceElementType()
238 ->isScalableTy()) ||
239 (isa<AllocaInst>(I) && cast<AllocaInst>(I).isScalable())))
240 return true;
241
242 // Inlining operations on fixed-length vectors when the streaming
243 // mode does not match is rejected because performance may be impacted.
244 // This decision should eventually be moved to the cost-model.
245 if (!IsAlwaysInline && (isa<FixedVectorType>(I.getType()) ||
246 any_of(I.operand_values(), [](const Value *V) {
247 return isa<FixedVectorType>(V->getType());
248 })))
249 return true;
250
251 // If the operation is invalid in the current mode, it should not be
252 // inlined.
253 SmallVector<Value *> Opnds(I.op_begin(), I.op_end());
255 return true;
256 }
257 }
258
259 return false;
260}
261
263 SmallVectorImpl<StringRef> &Features) {
264 StringRef AttributeStr =
265 TTI->isMultiversionedFunction(F) ? "fmv-features" : "target-features";
266 StringRef FeatureStr = F.getFnAttribute(AttributeStr).getValueAsString();
267 FeatureStr.split(Features, ",");
268}
269
272 extractAttrFeatures(F, this, Features);
273 return AArch64::getCpuSupportsMask(Features);
274}
275
278 extractAttrFeatures(F, this, Features);
279 return AArch64::getFMVPriority(Features);
280}
281
283 return F.hasFnAttribute("fmv-features");
284}
285
286/// The compiler must not inline when that may alter the behavior of the
287/// program. This is especially relevant around SME which implements different
288/// runtime modes and maintains external state through attributes.
289///
290/// The compiler must not inline when:
291//
292/// * The module is compiled with 'strict-fp' and the called function
293/// implements a different FP environment than the caller.
294///
295/// * The called function has operations that are incompatible in the mode
296/// of the caller, e.g.:
297/// * inlining non-streaming-only instructions into a streaming function.
298/// * inlining streaming-only instructions into a non-streaming function.
299///
300/// Inline asm blocks must be entered and exited in the [streaming] mode of
301/// the parent function. There is no language-level mechanism to inform the
302/// compiler that a particular inline asm block is streaming compatible, so
303/// the compiler must reject this as a candidate for inlining.
304///
305/// * The called function contains vscale-dependent operations but otherwise
306/// does not take/return VL-dependent arguments (see definition in the
307/// ACLE (Arm C/C++ Language Extensions)).
308///
309/// * The called function sets up new ZA/ZT state into a function that already
310/// has ZA or ZT state, as that is not valid as per the ACLE.
311///
312/// The compiler should not inline when:
313//
314/// * The called function has fixed-length vectors and the caller is in
315/// streaming mode, as this may cause performance regressions. This should
316/// never result in an error to be reported.
317///
318/// * The called function sets up new ZA/ZT state into a function that has no
319/// ZA and no ZT state, as the compiler currently cannot transfer the
320/// attribute to the caller. It may also impact performance, but that should
321/// be covered by AArch64TTIImpl::getInlineCallPenalty().
322///
323/// If a callee is incompatible with its caller, then the inliner should prevent
324/// inlining. LLVM's `alwaysinline` attribute has no impact on whether a callee
325/// is inline compatible. This is especially relevant with streaming-mode
326/// attributes, where `alwaysinline`ing a function into a function with a
327/// different streaming mode may otherwise impact runtime behaviour.
329 const Function *Callee) const {
330 SMECallAttrs CallAttrs(*Caller, *Callee);
331
332 // Never inline a function explicitly marked as being streaming,
333 // into a non-streaming function. Assume it was marked as streaming
334 // for a reason.
335 if (CallAttrs.caller().hasNonStreamingInterfaceAndBody() &&
336 CallAttrs.callee().hasStreamingInterfaceOrBody())
337 return false;
338
339 if (CallAttrs.callee().isNewZA() || CallAttrs.callee().isNewZT0())
340 return false;
341
342 // When inlining, we should consider the body of the function, not the
343 // interface.
344 if (CallAttrs.callee().hasStreamingBody()) {
345 CallAttrs.callee().set(SMEAttrs::SM_Compatible, false);
346 CallAttrs.callee().set(SMEAttrs::SM_Enabled, true);
347 }
348
349 bool ConsiderZA = CallAttrs.requiresZASave();
350 bool ConsiderZT = CallAttrs.requiresPreservingZT0() ||
351 CallAttrs.requiresPreservingAllZAState();
352 bool ConsiderSM = CallAttrs.requiresSMChange();
353
354 // FP environment is interpreted differently between streaming mode and
355 // non-streaming mode, so are not inline-compatible.
356 // FIXME: Analyze whether the callee actually has any FP operations.
357 if (ConsiderSM && (Caller->isStrictFP() || Callee->isStrictFP()))
358 return false;
359
360 if (hasPossibleIncompatibleOps(Callee, ConsiderZA, ConsiderZT, ConsiderSM))
361 return false;
362
363 return BaseT::areInlineCompatible(Caller, Callee);
364}
365
367 const Function *Callee,
368 ArrayRef<Type *> Types) const {
369 if (!BaseT::areTypesABICompatible(Caller, Callee, Types))
370 return false;
371
372 // We need to ensure that argument promotion does not attempt to promote
373 // pointers to fixed-length vector types larger than 128 bits like
374 // <8 x float> (and pointers to aggregate types which have such fixed-length
375 // vector type members) into the values of the pointees. Such vector types
376 // are used for SVE VLS but there is no ABI for SVE VLS arguments and the
377 // backend cannot lower such value arguments. The 128-bit fixed-length SVE
378 // types can be safely treated as 128-bit NEON types and they cannot be
379 // distinguished in IR.
380 if (ST->useSVEForFixedLengthVectors() && llvm::any_of(Types, [](Type *Ty) {
381 auto FVTy = dyn_cast<FixedVectorType>(Ty);
382 return FVTy &&
383 FVTy->getScalarSizeInBits() * FVTy->getNumElements() > 128;
384 }))
385 return false;
386
387 return true;
388}
389
390unsigned
392 unsigned DefaultCallPenalty) const {
393 // This function calculates a penalty for executing Call in F.
394 //
395 // There are two ways this function can be called:
396 // (1) F:
397 // call from F -> G (the call here is Call)
398 //
399 // For (1), Call.getCaller() == F, so it will always return a high cost if
400 // a streaming-mode change is required (thus promoting the need to inline the
401 // function)
402 //
403 // (2) F:
404 // call from F -> G (the call here is not Call)
405 // G:
406 // call from G -> H (the call here is Call)
407 //
408 // For (2), if after inlining the body of G into F the call to H requires a
409 // streaming-mode change, and the call to G from F would also require a
410 // streaming-mode change, then there is benefit to do the streaming-mode
411 // change only once and avoid inlining of G into F.
412
413 SMEAttrs FAttrs(*F);
414 SMECallAttrs CallAttrs(Call, &getTLI()->getRuntimeLibcallsInfo());
415
416 if (SMECallAttrs(FAttrs, CallAttrs.callee()).requiresSMChange()) {
417 if (F == Call.getCaller()) // (1)
418 return ST->getCLOpts().call_penalty_sm_change * DefaultCallPenalty;
419 if (SMECallAttrs(FAttrs, CallAttrs.caller()).requiresSMChange()) // (2)
420 return ST->getCLOpts().inline_call_penalty_sm_change * DefaultCallPenalty;
421 }
422
423 return DefaultCallPenalty;
424}
425
427 TargetTransformInfo::VectorKind K, Type *ElementTy) const {
428 // Don't maximize bandwidth for i1s. The legal width of predicates is derived
429 // from the data vectors they are used with. Maximizing the predicate width
430 // will just result in excessive VFs with a lot of unpacking.
431 if (ElementTy && ElementTy->isIntegerTy(1))
432 return false;
433
434 // If we don't know the specific class of vector just return true. Later VF
435 // selection will ask us about fixed or scalable vectors.
437 return true;
438
439 if (K == TargetTransformInfo::VectorKind::FixedWidth && ST->isNeonAvailable())
440 return true;
441
443 ST->isSVEorStreamingSVEAvailable() &&
444 !ST->disableMaximizeScalableBandwidth();
445}
446
447/// Calculate the cost of materializing a 64-bit value. This helper
448/// method might only calculate a fraction of a larger immediate. Therefore it
449/// is valid to return a cost of ZERO.
451 // Check if the immediate can be encoded within an instruction.
452 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, 64))
453 return 0;
454
455 if (Val < 0)
456 Val = ~Val;
457
458 // Calculate how many moves we will need to materialize this constant.
460 AArch64_IMM::expandMOVImm(Val, 64, Insn);
461 return Insn.size();
462}
463
464/// Calculate the cost of materializing the given constant.
467 TTI::TargetCostKind CostKind) const {
468 assert(Ty->isIntegerTy());
469
470 unsigned BitSize = Ty->getPrimitiveSizeInBits();
471 if (BitSize == 0)
472 return ~0U;
473
474 // Sign-extend all constants to a multiple of 64-bit.
475 APInt ImmVal = Imm;
476 if (BitSize & 0x3f)
477 ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
478
479 // Split the constant into 64-bit chunks and calculate the cost for each
480 // chunk.
482 for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
483 APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
484 int64_t Val = Tmp.getSExtValue();
485 Cost += getIntImmCost(Val);
486 }
487 // We need at least one instruction to materialze the constant.
488 return std::max<InstructionCost>(1, Cost);
489}
490
492 const APInt &Imm, Type *Ty,
493 TTI::TargetCostKind CostKind,
494 Instruction *Inst) const {
495 assert(Ty->isIntegerTy());
496
497 unsigned BitSize = Ty->getPrimitiveSizeInBits();
498 // There is no cost model for constants with a bit size of 0. Return TCC_Free
499 // here, so that constant hoisting will ignore this constant.
500 if (BitSize == 0)
501 return TTI::TCC_Free;
502
503 unsigned ImmIdx = ~0U;
504 switch (Opcode) {
505 default:
506 return TTI::TCC_Free;
507 case Instruction::GetElementPtr:
508 // Always hoist the base address of a GetElementPtr.
509 if (Idx == 0)
510 return 2 * TTI::TCC_Basic;
511 return TTI::TCC_Free;
512 case Instruction::Store:
513 ImmIdx = 0;
514 break;
515 case Instruction::Add:
516 case Instruction::Sub:
517 case Instruction::Mul:
518 case Instruction::UDiv:
519 case Instruction::SDiv:
520 case Instruction::URem:
521 case Instruction::SRem:
522 case Instruction::And:
523 case Instruction::Or:
524 case Instruction::Xor:
525 case Instruction::ICmp:
526 ImmIdx = 1;
527 break;
528 // Always return TCC_Free for the shift value of a shift instruction.
529 case Instruction::Shl:
530 case Instruction::LShr:
531 case Instruction::AShr:
532 if (Idx == 1)
533 return TTI::TCC_Free;
534 break;
535 case Instruction::Trunc:
536 case Instruction::ZExt:
537 case Instruction::SExt:
538 case Instruction::IntToPtr:
539 case Instruction::PtrToInt:
540 case Instruction::BitCast:
541 case Instruction::PHI:
542 case Instruction::Call:
543 case Instruction::Select:
544 case Instruction::Ret:
545 case Instruction::Load:
546 break;
547 }
548
549 if (Idx == ImmIdx) {
550 int NumConstants = (BitSize + 63) / 64;
552 return (Cost <= NumConstants * TTI::TCC_Basic)
553 ? static_cast<int>(TTI::TCC_Free)
554 : Cost;
555 }
556 return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
557}
558
561 const APInt &Imm, Type *Ty,
562 TTI::TargetCostKind CostKind) const {
563 assert(Ty->isIntegerTy());
564
565 unsigned BitSize = Ty->getPrimitiveSizeInBits();
566 // There is no cost model for constants with a bit size of 0. Return TCC_Free
567 // here, so that constant hoisting will ignore this constant.
568 if (BitSize == 0)
569 return TTI::TCC_Free;
570
571 // Most (all?) AArch64 intrinsics do not support folding immediates into the
572 // selected instruction, so we compute the materialization cost for the
573 // immediate directly.
574 if (IID >= Intrinsic::aarch64_addg && IID <= Intrinsic::aarch64_udiv)
575 return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
576
577 switch (IID) {
578 default:
579 return TTI::TCC_Free;
580 case Intrinsic::sadd_with_overflow:
581 case Intrinsic::uadd_with_overflow:
582 case Intrinsic::ssub_with_overflow:
583 case Intrinsic::usub_with_overflow:
584 case Intrinsic::smul_with_overflow:
585 case Intrinsic::umul_with_overflow:
586 if (Idx == 1) {
587 int NumConstants = (BitSize + 63) / 64;
589 return (Cost <= NumConstants * TTI::TCC_Basic)
590 ? static_cast<int>(TTI::TCC_Free)
591 : Cost;
592 }
593 break;
594 case Intrinsic::experimental_stackmap:
595 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
596 return TTI::TCC_Free;
597 break;
598 case Intrinsic::experimental_patchpoint_void:
599 case Intrinsic::experimental_patchpoint:
600 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
601 return TTI::TCC_Free;
602 break;
603 case Intrinsic::experimental_gc_statepoint:
604 if ((Idx < 5) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
605 return TTI::TCC_Free;
606 break;
607 }
608 return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
609}
610
612 // MispredictPenalty is defined per-CPU in AArch64Sched*.td (e.g.,
613 // AArch64SchedNeoverseV2.td).
614 return ST->getMispredictionPenalty();
615}
616
617static bool isUnpackedVectorVT(EVT VecVT) {
618 return VecVT.isScalableVector() &&
620}
621
624 const IntrinsicCostAttributes &ICA,
625 TTI::TargetCostKind CostKind) const {
626 // We need to know at least the number of elements in the vector of buckets
627 // and the size of each element to update.
628 if (ICA.getArgTypes().size() < 2)
630
631 // Only interested in costing for the hardware instruction from SVE2.
632 if (!ST->isSVEAvailable() || !ST->hasSVE2())
634
635 // FIXME: We should be able to generate histcnt for fixed-length vectors
636 // using ptrue with a specific VL.
637 auto *BucketPtrsTy = cast<VectorType>(ICA.getArgTypes()[0]);
638 unsigned MinEC = BucketPtrsTy->getElementCount().getKnownMinValue();
639 if (!isPowerOf2_64(MinEC) || !BucketPtrsTy->isScalableTy() || MinEC == 1)
641
642 Type *EltTy = ICA.getArgTypes()[1];
643 unsigned EltSize = EltTy->getScalarSizeInBits();
644 // Only allow (up to 64b) integers or pointers for bucket elements.
645 if ((!EltTy->isIntegerTy() && !EltTy->isPointerTy()) || EltSize > 64)
647
649 /// Get gather/scatter costs.
650 /// TODO: Find a way to get more info about the pointers, so we can determine
651 /// whether we can use 32b indices or require full 64b pointers.
652 Type *DataTy = VectorType::get(EltTy, BucketPtrsTy->getElementCount());
653 MemIntrinsicCostAttributes GMICA(Intrinsic::masked_gather, DataTy, Align(1));
654 Cost += getGatherScatterOpCost(GMICA, CostKind);
655 MemIntrinsicCostAttributes SMICA(Intrinsic::masked_scatter, DataTy, Align(1));
656 Cost += getGatherScatterOpCost(SMICA, CostKind);
657
658 // HistCnt only supports 32b and 64b element types. If the element size
659 // is smaller we may need multiple histcnts, even if the vector would
660 // otherwise be legal.
661 unsigned LegalEltSize = EltSize <= 32 ? 32 : 64;
662
663 // HistCnt is the same cost as a vector integer add on 128b implementations,
664 // but will likely increase on wider vector types. Multiply by vscale as
665 // a quick estimate.
666 unsigned VScale = ST->getVScaleForTuning();
667 unsigned NaturalMinEC = AArch64::SVEBitsPerBlock / LegalEltSize;
668 unsigned TotalHistCnts = MinEC / NaturalMinEC;
669 Cost += VScale * TotalHistCnts;
670
671 return Cost;
672}
673
676 TTI::TargetCostKind CostKind) const {
677 // The code-generator is currently not able to handle scalable vectors
678 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
679 // it. This change will be removed when code-generation for these types is
680 // sufficiently reliable.
681 // Only allow masked ld/st to pass through to getMemIntrinsicInstrCost().
682 auto *RetTy = ICA.getReturnType();
683 if (auto *VTy = dyn_cast<ScalableVectorType>(RetTy))
684 if (VTy->getElementCount() == ElementCount::getScalable(1) &&
685 !is_contained({Intrinsic::masked_load, Intrinsic::masked_store},
686 ICA.getID()))
688
689 switch (ICA.getID()) {
690 case Intrinsic::experimental_vector_histogram_add: {
691 InstructionCost HistCost = getHistogramCost(ST, ICA, CostKind);
692 // If the cost isn't valid, we may still be able to scalarize
693 if (HistCost.isValid())
694 return HistCost;
695 break;
696 }
697 case Intrinsic::experimental_vector_histogram_uadd_sat:
698 case Intrinsic::experimental_vector_histogram_umax:
699 case Intrinsic::experimental_vector_histogram_umin:
700 // No hardware support for these histogram variants on AArch64.
702 case Intrinsic::clmul: {
703 auto LT = getTypeLegalizationCost(RetTy);
704
705 // PMUL v8i8/v16i8 is always available on AArch64
706 if (ST->hasNEON()) {
707 if (LT.second == MVT::v8i8 || LT.second == MVT::v16i8)
708 return LT.first;
709
710 // Scalar i8 lowers through scalar/vector moves around PMUL.
711 if (TLI->getValueType(DL, RetTy, true) == MVT::i8) {
712 auto *VecTy =
713 FixedVectorType::get(Type::getInt8Ty(RetTy->getContext()), 8);
714 return 1 +
715 getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind,
716 -1, nullptr, nullptr) *
717 2 +
718 getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind,
719 -1, nullptr, nullptr);
720 }
721 }
722
723 if (LT.second.SimpleTy == MVT::nxv2i64)
724 if (ST->hasSVEAES() && (ST->isSVEAvailable() || ST->hasSSVE_AES()))
725 return LT.first * 3;
726
727 if (ST->hasSVE2() || ST->hasSME()) {
728 switch (LT.second.SimpleTy) {
729 case MVT::nxv16i8:
730 return LT.first;
731 case MVT::nxv8i16:
732 return LT.first * 6;
733 case MVT::nxv4i32:
734 return LT.first * 3;
735 case MVT::nxv2i64:
736 return LT.first * 8;
737 default:
738 break;
739 }
740 }
741
742 // Avoid +sve giving this cost 2 due to custom lowering: It's very slow
743 if (LT.second.SimpleTy == MVT::nxv2i64)
744 return 192;
745
746 if (ST->hasAES()) {
747 switch (LT.second.SimpleTy) {
748 case MVT::i16:
749 case MVT::i32:
750 case MVT::i64:
751 case MVT::i128: {
752 auto *VecTy =
753 FixedVectorType::get(Type::getInt64Ty(RetTy->getContext()), 1);
754 return LT.first *
755 (1 +
756 getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind,
757 -1, nullptr, nullptr) *
758 2 +
759 getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind,
760 -1, nullptr, nullptr));
761 }
762 case MVT::v1i64:
763 return LT.first;
764 case MVT::v2i64:
765 return LT.first * 3;
766 case MVT::v2i32:
767 return LT.first * 6;
768 case MVT::v4i32:
769 return LT.first * 11;
770 case MVT::v4i16:
771 return LT.first * 14;
772 default:
773 break;
774 }
775 }
776 break;
777 }
778 case Intrinsic::smulh:
779 case Intrinsic::umulh: {
780 InstructionCost MulCost =
781 getArithmeticInstrCost(Instruction::Mul, RetTy, CostKind);
782
783 // Wide types like i128 need every partial product of a wide multiply
784 // and the carry chain between them. This is a crude cost approximation.
785 if (RetTy->getScalarSizeInBits() > 64)
786 return 2 * MulCost;
787
788 auto LT = getTypeLegalizationCost(RetTy);
789 MVT MTy = LT.second;
790
791 // Per-register cost to extend the operands.
792 InstructionCost ExtraCost =
793 LT.first *
794 (MTy.getScalarSizeInBits() != RetTy->getScalarSizeInBits() ? 2 : 0);
795
796 // MULH and MUL lower similarly for 64-bit products. For vectors, they
797 // also share the reduced vector multiply bandwidth seen on some cores.
798 if (MTy.getScalarSizeInBits() == 64)
799 return MulCost + ExtraCost;
800
801 // Scalable vectors (and fixed-length vectors, when possible) use SVE.
802 if (MTy.isScalableVector() ||
803 (MTy.isFixedLengthVector() && ST->isSVEorStreamingSVEAvailable()))
804 return LT.first + ExtraCost;
805
806 static const CostTblEntry MulHighCostTbl[] = {
807 {ISD::MULHU, MVT::i32, 2}, // [su]mull + lsr
808
809 {ISD::MULHU, MVT::v8i8, 2}, // [su]mull + shrn
810 {ISD::MULHU, MVT::v4i16, 2}, // "
811 {ISD::MULHU, MVT::v2i32, 2}, // "
812
813 {ISD::MULHU, MVT::v16i8, 3}, // [su]mull + [su]mull2 + uzp2
814 {ISD::MULHU, MVT::v8i16, 3}, // "
815 {ISD::MULHU, MVT::v4i32, 3}, // "
816 };
817
818 // Currently we assume SMULH has the same cost as UMULH.
819 if (const auto *Entry = CostTableLookup(MulHighCostTbl, ISD::MULHU, MTy))
820 return LT.first * Entry->Cost + ExtraCost;
821
822 break;
823 }
824 case Intrinsic::umin:
825 case Intrinsic::umax:
826 case Intrinsic::smin:
827 case Intrinsic::smax: {
828 static const auto ValidMinMaxTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16,
829 MVT::v8i16, MVT::v2i32, MVT::v4i32,
830 MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32,
831 MVT::nxv2i64};
832 auto LT = getTypeLegalizationCost(RetTy);
833 // Type promotion for v2i8 and v2i16 types have a heavy cost when
834 // vectorising. Account for this cost to avoid vectorising unprofitable
835 // examples when vectorising loops with low trip counts.
836 bool IsSigned =
837 ICA.getID() == Intrinsic::smin || ICA.getID() == Intrinsic::smax;
838 EVT VT = TLI->getValueType(DL, RetTy, /*AllowUnknown=*/true);
839 if (VT == MVT::v2i8 || VT == MVT::v2i16 || VT == MVT::v4i8)
840 return LT.first * (IsSigned ? 5 : 3);
841 // v2i64 types get converted to cmp+bif hence the cost of 2
842 if (LT.second == MVT::v2i64)
843 return LT.first * 2;
844 if (any_of(ValidMinMaxTys, equal_to(LT.second)))
845 return LT.first;
846 break;
847 }
848 case Intrinsic::scmp:
849 case Intrinsic::ucmp: {
850 static const CostTblEntry BitreverseTbl[] = {
851 {Intrinsic::scmp, MVT::i32, 3}, // cmp+cset+csinv
852 {Intrinsic::scmp, MVT::i64, 3}, // cmp+cset+csinv
853 {Intrinsic::scmp, MVT::v8i8, 3}, // cmgt+cmgt+sub
854 {Intrinsic::scmp, MVT::v16i8, 3}, // cmgt+cmgt+sub
855 {Intrinsic::scmp, MVT::v4i16, 3}, // cmgt+cmgt+sub
856 {Intrinsic::scmp, MVT::v8i16, 3}, // cmgt+cmgt+sub
857 {Intrinsic::scmp, MVT::v2i32, 3}, // cmgt+cmgt+sub
858 {Intrinsic::scmp, MVT::v4i32, 3}, // cmgt+cmgt+sub
859 {Intrinsic::scmp, MVT::v1i64, 3}, // cmgt+cmgt+sub
860 {Intrinsic::scmp, MVT::v2i64, 3}, // cmgt+cmgt+sub
861 };
862 const auto LT = getTypeLegalizationCost(RetTy);
863 const auto *Entry =
864 CostTableLookup(BitreverseTbl, Intrinsic::scmp, LT.second);
865 if (Entry)
866 return Entry->Cost * LT.first;
867 break;
868 }
869 case Intrinsic::sadd_sat:
870 case Intrinsic::ssub_sat:
871 case Intrinsic::uadd_sat:
872 case Intrinsic::usub_sat: {
873 static const auto ValidSatTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16,
874 MVT::v8i16, MVT::v2i32, MVT::v4i32,
875 MVT::v2i64};
876 auto LT = getTypeLegalizationCost(RetTy);
877 // This is a base cost of 1 for the vadd, plus 3 extract shifts if we
878 // need to extend the type, as it uses shr(qadd(shl, shl)).
879 unsigned Instrs =
880 LT.second.getScalarSizeInBits() == RetTy->getScalarSizeInBits() ? 1 : 4;
881 if (any_of(ValidSatTys, equal_to(LT.second)))
882 return LT.first * Instrs;
883
885 uint64_t VectorSize = TS.getKnownMinValue();
886
887 if (ST->isSVEAvailable() && VectorSize >= 128 && isPowerOf2_64(VectorSize))
888 return LT.first * Instrs;
889
890 break;
891 }
892 case Intrinsic::abs: {
893 static const auto ValidAbsTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16,
894 MVT::v8i16, MVT::v2i32, MVT::v4i32,
895 MVT::v2i64, MVT::nxv16i8, MVT::nxv8i16,
896 MVT::nxv4i32, MVT::nxv2i64};
897 auto LT = getTypeLegalizationCost(RetTy);
898 if (any_of(ValidAbsTys, equal_to(LT.second)))
899 return LT.first;
900 break;
901 }
902 case Intrinsic::bswap: {
903 static const auto ValidAbsTys = {MVT::v4i16, MVT::v8i16, MVT::v2i32,
904 MVT::v4i32, MVT::v2i64};
905 auto LT = getTypeLegalizationCost(RetTy);
906 if (any_of(ValidAbsTys, equal_to(LT.second)) &&
907 LT.second.getScalarSizeInBits() == RetTy->getScalarSizeInBits())
908 return LT.first;
909 break;
910 }
911 case Intrinsic::fma:
912 case Intrinsic::fmuladd: {
913 // Given a fma or fmuladd, cost it the same as a fmul instruction which are
914 // usually the same for costs. TODO: Add fp16 and bf16 expansion costs.
915 Type *EltTy = RetTy->getScalarType();
916 if (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
917 (EltTy->isHalfTy() && ST->hasFullFP16()))
918 return getArithmeticInstrCost(Instruction::FMul, RetTy, CostKind);
919 break;
920 }
921 case Intrinsic::stepvector: {
922 InstructionCost Cost = 1; // Cost of the `index' instruction
923 auto LT = getTypeLegalizationCost(RetTy);
924 // Legalisation of illegal vectors involves an `index' instruction plus
925 // (LT.first - 1) vector adds.
926 if (LT.first > 1) {
927 Type *LegalVTy = EVT(LT.second).getTypeForEVT(RetTy->getContext());
928 InstructionCost AddCost =
929 getArithmeticInstrCost(Instruction::Add, LegalVTy, CostKind);
930 Cost += AddCost * (LT.first - 1);
931 }
932 return Cost;
933 }
934 case Intrinsic::vector_extract:
935 case Intrinsic::vector_insert: {
936 // If both the vector and subvector types are legal types and the index
937 // is 0, then this should be a no-op or simple operation; return a
938 // relatively low cost.
939
940 // If arguments aren't actually supplied, then we cannot determine the
941 // value of the index. We also want to skip predicate types.
942 if (ICA.getArgs().size() != ICA.getArgTypes().size() ||
944 break;
945
946 LLVMContext &C = RetTy->getContext();
947 EVT VecVT = getTLI()->getValueType(DL, ICA.getArgTypes()[0]);
948 bool IsExtract = ICA.getID() == Intrinsic::vector_extract;
949 EVT SubVecVT = IsExtract ? getTLI()->getValueType(DL, RetTy)
950 : getTLI()->getValueType(DL, ICA.getArgTypes()[1]);
951 // Skip this if either the vector or subvector types are unpacked
952 // SVE types; they may get lowered to stack stores and loads.
953 if (isUnpackedVectorVT(VecVT) || isUnpackedVectorVT(SubVecVT))
954 break;
955
957 getTLI()->getTypeConversion(C, SubVecVT);
959 getTLI()->getTypeConversion(C, VecVT);
960 const Value *Idx = IsExtract ? ICA.getArgs()[1] : ICA.getArgs()[2];
961 const ConstantInt *CIdx = cast<ConstantInt>(Idx);
962 if (SubVecLK.first == TargetLoweringBase::TypeLegal &&
963 VecLK.first == TargetLoweringBase::TypeLegal && CIdx->isZero())
964 return TTI::TCC_Free;
965 break;
966 }
967 case Intrinsic::bitreverse: {
968 static const CostTblEntry BitreverseTbl[] = {
969 {Intrinsic::bitreverse, MVT::i32, 1},
970 {Intrinsic::bitreverse, MVT::i64, 1},
971 {Intrinsic::bitreverse, MVT::v8i8, 1},
972 {Intrinsic::bitreverse, MVT::v16i8, 1},
973 {Intrinsic::bitreverse, MVT::v4i16, 2},
974 {Intrinsic::bitreverse, MVT::v8i16, 2},
975 {Intrinsic::bitreverse, MVT::v2i32, 2},
976 {Intrinsic::bitreverse, MVT::v4i32, 2},
977 {Intrinsic::bitreverse, MVT::v1i64, 2},
978 {Intrinsic::bitreverse, MVT::v2i64, 2},
979 };
980 const auto LegalisationCost = getTypeLegalizationCost(RetTy);
981 const auto *Entry =
982 CostTableLookup(BitreverseTbl, ICA.getID(), LegalisationCost.second);
983 if (Entry) {
984 // Cost Model is using the legal type(i32) that i8 and i16 will be
985 // converted to +1 so that we match the actual lowering cost
986 if (TLI->getValueType(DL, RetTy, true) == MVT::i8 ||
987 TLI->getValueType(DL, RetTy, true) == MVT::i16)
988 return LegalisationCost.first * Entry->Cost + 1;
989
990 return LegalisationCost.first * Entry->Cost;
991 }
992 break;
993 }
994 case Intrinsic::pdep:
995 case Intrinsic::pext: {
996 unsigned BW = RetTy->getScalarSizeInBits();
997 if (!RetTy->isVectorTy() && ST->isSVEBitPermAvailable() && BW <= 64) {
998 Type *VecTy = VectorType::get(RetTy, 64 / BW, false);
1000 getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind, 0,
1001 nullptr, nullptr) +
1002 getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind, 0,
1003 nullptr, nullptr) +
1004 1 +
1005 getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind, 0,
1006 nullptr, nullptr);
1007 return Cost;
1008 }
1009 break;
1010 }
1011 case Intrinsic::ctpop: {
1012 auto LT = getTypeLegalizationCost(RetTy);
1013 MVT MTy = LT.second;
1014
1015 if (ST->hasCSSC() && !RetTy->isVectorTy()) {
1016 int ExtraCost =
1017 MTy.getScalarSizeInBits() != RetTy->getScalarSizeInBits() ? 1 : 0;
1018 return LT.first + ExtraCost;
1019 }
1020 if (!ST->hasNEON()) {
1021 // 32-bit or 64-bit ctpop without NEON is 12 instructions.
1022 return getTypeLegalizationCost(RetTy).first * 12;
1023 }
1024 static const CostTblEntry CtpopCostTbl[] = {
1025 {ISD::CTPOP, MVT::v2i64, 4},
1026 {ISD::CTPOP, MVT::v4i32, 3},
1027 {ISD::CTPOP, MVT::v8i16, 2},
1028 {ISD::CTPOP, MVT::v16i8, 1},
1029 {ISD::CTPOP, MVT::i64, 4},
1030 {ISD::CTPOP, MVT::v2i32, 3},
1031 {ISD::CTPOP, MVT::v4i16, 2},
1032 {ISD::CTPOP, MVT::v8i8, 1},
1033 {ISD::CTPOP, MVT::i32, 5},
1034 // SVE types (For targets that override NEON for fixed length vectors)
1035 {ISD::CTPOP, MVT::nxv2i64, 1},
1036 {ISD::CTPOP, MVT::nxv4i32, 1},
1037 {ISD::CTPOP, MVT::nxv8i16, 1},
1038 {ISD::CTPOP, MVT::nxv16i8, 1},
1039 };
1040
1041 // When SVE is available CNT will be used for fixed and scalable vectors.
1042 if (ST->isSVEorStreamingSVEAvailable() && MTy.isFixedLengthVector())
1044 128 / MTy.getScalarSizeInBits());
1045
1046 if (const auto *Entry = CostTableLookup(CtpopCostTbl, ISD::CTPOP, MTy)) {
1047 // Extra cost of +1 when illegal vector types are legalized by promoting
1048 // the integer type.
1049 int ExtraCost = MTy.isVector() && MTy.getScalarSizeInBits() !=
1050 RetTy->getScalarSizeInBits()
1051 ? 1
1052 : 0;
1053 return LT.first * Entry->Cost + ExtraCost;
1054 }
1055 break;
1056 }
1057 case Intrinsic::sadd_with_overflow:
1058 case Intrinsic::uadd_with_overflow:
1059 case Intrinsic::ssub_with_overflow:
1060 case Intrinsic::usub_with_overflow:
1061 case Intrinsic::smul_with_overflow:
1062 case Intrinsic::umul_with_overflow: {
1063 static const CostTblEntry WithOverflowCostTbl[] = {
1064 {Intrinsic::sadd_with_overflow, MVT::i8, 3},
1065 {Intrinsic::uadd_with_overflow, MVT::i8, 3},
1066 {Intrinsic::sadd_with_overflow, MVT::i16, 3},
1067 {Intrinsic::uadd_with_overflow, MVT::i16, 3},
1068 {Intrinsic::sadd_with_overflow, MVT::i32, 1},
1069 {Intrinsic::uadd_with_overflow, MVT::i32, 1},
1070 {Intrinsic::sadd_with_overflow, MVT::i64, 1},
1071 {Intrinsic::uadd_with_overflow, MVT::i64, 1},
1072 {Intrinsic::ssub_with_overflow, MVT::i8, 3},
1073 {Intrinsic::usub_with_overflow, MVT::i8, 3},
1074 {Intrinsic::ssub_with_overflow, MVT::i16, 3},
1075 {Intrinsic::usub_with_overflow, MVT::i16, 3},
1076 {Intrinsic::ssub_with_overflow, MVT::i32, 1},
1077 {Intrinsic::usub_with_overflow, MVT::i32, 1},
1078 {Intrinsic::ssub_with_overflow, MVT::i64, 1},
1079 {Intrinsic::usub_with_overflow, MVT::i64, 1},
1080 {Intrinsic::smul_with_overflow, MVT::i8, 5},
1081 {Intrinsic::umul_with_overflow, MVT::i8, 4},
1082 {Intrinsic::smul_with_overflow, MVT::i16, 5},
1083 {Intrinsic::umul_with_overflow, MVT::i16, 4},
1084 {Intrinsic::smul_with_overflow, MVT::i32, 2}, // eg umull;tst
1085 {Intrinsic::umul_with_overflow, MVT::i32, 2}, // eg umull;cmp sxtw
1086 {Intrinsic::smul_with_overflow, MVT::i64, 3}, // eg mul;smulh;cmp
1087 {Intrinsic::umul_with_overflow, MVT::i64, 3}, // eg mul;umulh;cmp asr
1088 };
1089 EVT MTy = TLI->getValueType(DL, RetTy->getContainedType(0), true);
1090 if (MTy.isSimple())
1091 if (const auto *Entry = CostTableLookup(WithOverflowCostTbl, ICA.getID(),
1092 MTy.getSimpleVT()))
1093 return Entry->Cost;
1094 break;
1095 }
1096 case Intrinsic::fptosi_sat:
1097 case Intrinsic::fptoui_sat: {
1098 if (ICA.getArgTypes().empty())
1099 break;
1100 bool IsSigned = ICA.getID() == Intrinsic::fptosi_sat;
1101 auto LT = getTypeLegalizationCost(ICA.getArgTypes()[0]);
1102 EVT MTy = TLI->getValueType(DL, RetTy);
1103 // Check for the legal types, which are where the size of the input and the
1104 // output are the same, or we are using cvt f64->i32 or f32->i64.
1105 if ((LT.second == MVT::f32 || LT.second == MVT::f64 ||
1106 LT.second == MVT::v2f32 || LT.second == MVT::v4f32 ||
1107 LT.second == MVT::v2f64)) {
1108 if ((LT.second.getScalarSizeInBits() == MTy.getScalarSizeInBits() ||
1109 (LT.second == MVT::f64 && MTy == MVT::i32) ||
1110 (LT.second == MVT::f32 && MTy == MVT::i64)))
1111 return LT.first;
1112 // Extending vector types v2f32->v2i64, fcvtl*2 + fcvt*2
1113 if (LT.second.getScalarType() == MVT::f32 && MTy.isFixedLengthVector() &&
1114 MTy.getScalarSizeInBits() == 64)
1115 return LT.first * (MTy.getVectorNumElements() > 2 ? 4 : 2);
1116 }
1117 // Similarly for fp16 sizes. Without FullFP16 we generally need to fcvt to
1118 // f32.
1119 if (LT.second.getScalarType() == MVT::f16 && !ST->hasFullFP16())
1120 return LT.first + getIntrinsicInstrCost(
1121 {ICA.getID(),
1122 RetTy,
1123 {ICA.getArgTypes()[0]->getWithNewType(
1124 Type::getFloatTy(RetTy->getContext()))}},
1125 CostKind);
1126 if ((LT.second == MVT::f16 && MTy == MVT::i32) ||
1127 (LT.second == MVT::f16 && MTy == MVT::i64) ||
1128 ((LT.second == MVT::v4f16 || LT.second == MVT::v8f16) &&
1129 (LT.second.getScalarSizeInBits() == MTy.getScalarSizeInBits())))
1130 return LT.first;
1131 // Extending vector types v8f16->v8i32, fcvtl*2 + fcvt*2
1132 if (LT.second.getScalarType() == MVT::f16 && MTy.isFixedLengthVector() &&
1133 MTy.getScalarSizeInBits() == 32)
1134 return LT.first * (MTy.getVectorNumElements() > 4 ? 4 : 2);
1135 // Extending vector types v8f16->v8i32. These current scalarize but the
1136 // codegen could be better.
1137 if (LT.second.getScalarType() == MVT::f16 && MTy.isFixedLengthVector() &&
1138 MTy.getScalarSizeInBits() == 64)
1139 return MTy.getVectorNumElements() * 3;
1140
1141 // If we can we use a legal convert followed by a min+max
1142 if ((LT.second.getScalarType() == MVT::f32 ||
1143 LT.second.getScalarType() == MVT::f64 ||
1144 LT.second.getScalarType() == MVT::f16) &&
1145 LT.second.getScalarSizeInBits() >= MTy.getScalarSizeInBits()) {
1146 Type *LegalTy =
1147 Type::getIntNTy(RetTy->getContext(), LT.second.getScalarSizeInBits());
1148 if (LT.second.isVector())
1149 LegalTy = VectorType::get(LegalTy, LT.second.getVectorElementCount());
1151 IntrinsicCostAttributes Attrs1(IsSigned ? Intrinsic::smin
1152 : Intrinsic::umin,
1153 LegalTy, {LegalTy, LegalTy});
1154 Cost += getIntrinsicInstrCost(Attrs1, CostKind);
1155 IntrinsicCostAttributes Attrs2(IsSigned ? Intrinsic::smax
1156 : Intrinsic::umax,
1157 LegalTy, {LegalTy, LegalTy});
1158 Cost += getIntrinsicInstrCost(Attrs2, CostKind);
1159 return LT.first * Cost +
1160 ((LT.second.getScalarType() != MVT::f16 || ST->hasFullFP16()) ? 0
1161 : 1);
1162 }
1163 // Otherwise we need to follow the default expansion that clamps the value
1164 // using a float min/max with a fcmp+sel for nan handling when signed.
1165 Type *FPTy = ICA.getArgTypes()[0]->getScalarType();
1166 RetTy = RetTy->getScalarType();
1167 if (LT.second.isVector()) {
1168 FPTy = VectorType::get(FPTy, LT.second.getVectorElementCount());
1169 RetTy = VectorType::get(RetTy, LT.second.getVectorElementCount());
1170 }
1171 IntrinsicCostAttributes Attrs1(Intrinsic::minnum, FPTy, {FPTy, FPTy});
1172 InstructionCost Cost = getIntrinsicInstrCost(Attrs1, CostKind);
1173 IntrinsicCostAttributes Attrs2(Intrinsic::maxnum, FPTy, {FPTy, FPTy});
1174 Cost += getIntrinsicInstrCost(Attrs2, CostKind);
1175 Cost +=
1176 getCastInstrCost(IsSigned ? Instruction::FPToSI : Instruction::FPToUI,
1177 RetTy, FPTy, TTI::CastContextHint::None, CostKind);
1178 if (IsSigned) {
1179 Type *CondTy = RetTy->getWithNewBitWidth(1);
1180 Cost += getCmpSelInstrCost(BinaryOperator::FCmp, FPTy, CondTy,
1181 CmpInst::FCMP_UNO, CostKind);
1182 Cost += getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
1183 CmpInst::FCMP_UNO, CostKind);
1184 }
1185 return LT.first * Cost;
1186 }
1187 case Intrinsic::fshl:
1188 case Intrinsic::fshr: {
1189 if (ICA.getArgs().empty())
1190 break;
1191
1192 const TTI::OperandValueInfo OpInfoZ = TTI::getOperandInfo(ICA.getArgs()[2]);
1193
1194 // ROTR / ROTL is a funnel shift with equal first and second operand. For
1195 // ROTR on integer registers (i32/i64) this can be done in a single ror
1196 // instruction. A fshl with a non-constant shift uses a neg + ror.
1197 if (RetTy->isIntegerTy() && ICA.getArgs()[0] == ICA.getArgs()[1] &&
1198 (RetTy->getPrimitiveSizeInBits() == 32 ||
1199 RetTy->getPrimitiveSizeInBits() == 64)) {
1200 InstructionCost NegCost =
1201 (ICA.getID() == Intrinsic::fshl && !OpInfoZ.isConstant()) ? 1 : 0;
1202 return 1 + NegCost;
1203 }
1204
1205 // TODO: Add handling for fshl where third argument is not a constant.
1206 if (!OpInfoZ.isConstant())
1207 break;
1208
1209 const auto LegalisationCost = getTypeLegalizationCost(RetTy);
1210 if (OpInfoZ.isUniform()) {
1211 static const CostTblEntry FshlTbl[] = {
1212 {Intrinsic::fshl, MVT::v4i32, 2}, // shl + usra
1213 {Intrinsic::fshl, MVT::v2i64, 2}, {Intrinsic::fshl, MVT::v16i8, 2},
1214 {Intrinsic::fshl, MVT::v8i16, 2}, {Intrinsic::fshl, MVT::v2i32, 2},
1215 {Intrinsic::fshl, MVT::v8i8, 2}, {Intrinsic::fshl, MVT::v4i16, 2}};
1216 // Costs for both fshl & fshr are the same, so just pass Intrinsic::fshl
1217 // to avoid having to duplicate the costs.
1218 const auto *Entry =
1219 CostTableLookup(FshlTbl, Intrinsic::fshl, LegalisationCost.second);
1220 if (Entry)
1221 return LegalisationCost.first * Entry->Cost;
1222 }
1223
1224 auto TyL = getTypeLegalizationCost(RetTy);
1225 if (!RetTy->isIntegerTy())
1226 break;
1227
1228 // Estimate cost manually, as types like i8 and i16 will get promoted to
1229 // i32 and CostTableLookup will ignore the extra conversion cost.
1230 bool HigherCost = (RetTy->getScalarSizeInBits() != 32 &&
1231 RetTy->getScalarSizeInBits() < 64) ||
1232 (RetTy->getScalarSizeInBits() % 64 != 0);
1233 unsigned ExtraCost = HigherCost ? 1 : 0;
1234 if (RetTy->getScalarSizeInBits() == 32 ||
1235 RetTy->getScalarSizeInBits() == 64)
1236 ExtraCost = 0; // fhsl/fshr for i32 and i64 can be lowered to a single
1237 // extr instruction.
1238 else if (HigherCost)
1239 ExtraCost = 1;
1240 else
1241 break;
1242 return TyL.first + ExtraCost;
1243 }
1244 case Intrinsic::get_active_lane_mask: {
1245 auto RetTy = cast<VectorType>(ICA.getReturnType());
1246 EVT RetVT = getTLI()->getValueType(DL, RetTy);
1247 EVT OpVT = getTLI()->getValueType(DL, ICA.getArgTypes()[0]);
1248 if (getTLI()->shouldExpandGetActiveLaneMask(RetVT, OpVT))
1249 break;
1250
1251 if (RetTy->isScalableTy()) {
1252 if (TLI->getTypeAction(RetTy->getContext(), RetVT) !=
1254 break;
1255
1256 auto LT = getTypeLegalizationCost(RetTy);
1257 InstructionCost Cost = LT.first;
1258 // When SVE2p1 or SME2 is available, we can halve getTypeLegalizationCost
1259 // as get_active_lane_mask may lower to the sve_whilelo_x2 intrinsic, e.g.
1260 // nxv32i1 = get_active_lane_mask(base, idx) ->
1261 // {nxv16i1, nxv16i1} = sve_whilelo_x2(base, idx)
1262 if (ST->hasSVE2p1() || ST->hasSME2()) {
1263 Cost /= 2;
1264 if (Cost == 1)
1265 return Cost;
1266 }
1267
1268 // If more than one whilelo intrinsic is required, include the extra cost
1269 // required by the saturating add & select required to increment the
1270 // start value after the first intrinsic call.
1271 Type *OpTy = ICA.getArgTypes()[0];
1272 IntrinsicCostAttributes AddAttrs(Intrinsic::uadd_sat, OpTy, {OpTy, OpTy});
1273 InstructionCost SplitCost = getIntrinsicInstrCost(AddAttrs, CostKind);
1274 Type *CondTy = OpTy->getWithNewBitWidth(1);
1275 SplitCost += getCmpSelInstrCost(Instruction::Select, OpTy, CondTy,
1276 CmpInst::ICMP_UGT, CostKind);
1277 return Cost + (SplitCost * (Cost - 1));
1278 } else if (!getTLI()->isTypeLegal(RetVT)) {
1279 // We don't have enough context at this point to determine if the mask
1280 // is going to be kept live after the block, which will force the vXi1
1281 // type to be expanded to legal vectors of integers, e.g. v4i1->v4i32.
1282 // For now, we just assume the vectorizer created this intrinsic and
1283 // the result will be the input for a PHI. In this case the cost will
1284 // be extremely high for fixed-width vectors.
1285 // NOTE: getScalarizationOverhead returns a cost that's far too
1286 // pessimistic for the actual generated codegen. In reality there are
1287 // two instructions generated per lane.
1288 return cast<FixedVectorType>(RetTy)->getNumElements() * 2;
1289 }
1290 break;
1291 }
1292 case Intrinsic::experimental_vector_match: {
1293 if (!ST->hasSVE2() || !ST->isSVEAvailable())
1294 break;
1295
1296 auto *NeedleTy = cast<FixedVectorType>(ICA.getArgTypes()[1]);
1297
1298 // We expand vector.matches with <= 2 elements to a chain of compares.
1299 unsigned SearchSize = NeedleTy->getNumElements();
1300 if (SearchSize <= 2)
1301 break;
1302
1303 auto [LegalParts, SearchVT] = getTypeLegalizationCost(ICA.getArgTypes()[0]);
1304 if (!is_contained(
1305 {MVT::nxv8i16, MVT::nxv16i8, MVT::v8i16, MVT::v16i8, MVT::v8i8},
1306 SearchVT.SimpleTy))
1307 break;
1308
1309 unsigned ElementSizeInBits = SearchVT.getScalarSizeInBits();
1310
1311 // Number of needle elements we can compare per `match` instruction.
1312 unsigned NeedleEltsPerMatch = AArch64::SVEBitsPerBlock / ElementSizeInBits;
1313
1314 // How many `match` instructions we need to match `SearchSize` elements.
1315 unsigned MatchesRequiredForNeedle =
1316 llvm::divideCeil(SearchSize, NeedleEltsPerMatch);
1317
1318 // Base cost for MATCH instructions. At least on the Neoverse V2 and
1319 // Neoverse V3, these are cheap operations with the same latency as a
1320 // vector ADD. In most cases, however, we also need to do an extra DUP.
1321 // For fixed-length vectors we currently need an extra five--six
1322 // instructions besides the MATCH.
1324 if (isa<FixedVectorType>(RetTy))
1325 Cost += 10;
1326
1327 return Cost * LegalParts * MatchesRequiredForNeedle;
1328 }
1329 case Intrinsic::cttz: {
1330 auto LT = getTypeLegalizationCost(ICA.getArgTypes()[0]);
1331 if (LT.second == MVT::v8i8 || LT.second == MVT::v16i8)
1332 return LT.first * 2;
1333 if (LT.second == MVT::v4i16 || LT.second == MVT::v8i16 ||
1334 LT.second == MVT::v2i32 || LT.second == MVT::v4i32)
1335 return LT.first * 3;
1336 break;
1337 }
1338 case Intrinsic::experimental_cttz_elts: {
1339 EVT ArgVT = getTLI()->getValueType(DL, ICA.getArgTypes()[0]);
1340 if (getTLI()->isOperationCustom(ISD::CTTZ_ELTS, ArgVT)) {
1341 // This will consist of a SVE brkb and a cntp instruction. These
1342 // typically have the same latency and half the throughput as a vector
1343 // add instruction.
1344 return 4;
1345 }
1346 break;
1347 }
1348 case Intrinsic::mask_beforefirst: {
1349 if (!ST->isSVEorStreamingSVEAvailable() ||
1350 !isa<ScalableVectorType>(RetTy) ||
1351 !TLI->isTypeLegal(getTLI()->getValueType(DL, RetTy)))
1352 break;
1353
1354 // mask_beforefirst(mask) -> brkb_z(ptrue, mask) but we ignore ptrue
1355 // because it's typically used by other instructions in the function.
1356 return 1;
1357 }
1358 case Intrinsic::loop_dependence_raw_mask:
1359 case Intrinsic::loop_dependence_war_mask: {
1360 // The whilewr/rw instructions require SVE2 or SME.
1361 if (ST->hasSVE2() || ST->hasSME()) {
1362 EVT VecVT = getTLI()->getValueType(DL, RetTy);
1363 unsigned EltSizeInBytes =
1364 cast<ConstantInt>(ICA.getArgs()[2])->getZExtValue();
1365 if (!is_contained({1u, 2u, 4u, 8u}, EltSizeInBytes) ||
1366 VecVT.getVectorMinNumElements() != (16 / EltSizeInBytes))
1367 break;
1368 // For fixed-vector types we need to AND the mask with a ptrue vl<N>.
1369 return isa<FixedVectorType>(RetTy) ? 2 : 1;
1370 }
1371 break;
1372 }
1373 case Intrinsic::experimental_vector_extract_last_active:
1374 if (ST->isSVEorStreamingSVEAvailable()) {
1375 auto [LegalCost, _] = getTypeLegalizationCost(ICA.getArgTypes()[0]);
1376 // This should turn into chained clastb instructions.
1377 return LegalCost;
1378 }
1379 break;
1380 case Intrinsic::pow: {
1381 // For scalar calls we know the target has the libcall, and for fixed-width
1382 // vectors we know for the worst case it can be scalarised.
1383 EVT VT = getTLI()->getValueType(DL, RetTy);
1384 RTLIB::Libcall LC = RTLIB::getPOW(VT);
1385 bool HasLibcall =
1386 getTLI()->getLibcallLoweringInfo().getVectorLibcallImplOrMasked(LC) !=
1387 RTLIB::Unsupported;
1388 bool CanLowerWithLibcalls = !isa<ScalableVectorType>(RetTy) || HasLibcall;
1389
1390 // If we know that the call can be lowered with libcalls then it's safe to
1391 // reduce the costs in some cases. This is important for scalable vectors,
1392 // since we cannot scalarize the call in the absence of a vector math
1393 // library.
1394 if (CanLowerWithLibcalls && ICA.getInst() && !ICA.getArgs().empty()) {
1395 // If we know the fast math flags and the exponent is a constant then the
1396 // cost may be less for some exponents like 0.25 and 0.75.
1397 const Constant *ExpC = dyn_cast<Constant>(ICA.getArgs()[1]);
1398 if (ExpC && isa<VectorType>(ExpC->getType()))
1399 ExpC = ExpC->getSplatValue();
1400 if (auto *ExpF = dyn_cast_or_null<ConstantFP>(ExpC)) {
1401 // The argument must be a FP constant.
1402 bool Is025 = ExpF->getValueAPF().isExactlyValue(0.25);
1403 bool Is075 = ExpF->getValueAPF().isExactlyValue(0.75);
1404 FastMathFlags FMF = ICA.getInst()->getFastMathFlags();
1405 if ((Is025 || Is075) && FMF.noInfs() && FMF.approxFunc() &&
1406 (!Is025 || FMF.noSignedZeros())) {
1407 IntrinsicCostAttributes Attrs(Intrinsic::sqrt, RetTy, {RetTy}, FMF);
1408 InstructionCost Sqrt = getIntrinsicInstrCost(Attrs, CostKind);
1409 if (Is025)
1410 return 2 * Sqrt;
1412 getArithmeticInstrCost(Instruction::FMul, RetTy, CostKind);
1413 return (Sqrt * 2) + FMul;
1414 }
1415 // TODO: For 1/3 exponents we expect the cbrt call to be slightly
1416 // cheaper than pow.
1417 }
1418 }
1419
1420 if (HasLibcall)
1421 return getCallInstrCost(nullptr, RetTy, ICA.getArgTypes(), CostKind);
1422 break;
1423 }
1424 case Intrinsic::sqrt:
1425 case Intrinsic::fabs:
1426 case Intrinsic::ceil:
1427 case Intrinsic::floor:
1428 case Intrinsic::nearbyint:
1429 case Intrinsic::round:
1430 case Intrinsic::rint:
1431 case Intrinsic::roundeven:
1432 case Intrinsic::trunc:
1433 case Intrinsic::minnum:
1434 case Intrinsic::maxnum:
1435 case Intrinsic::minimum:
1436 case Intrinsic::maximum: {
1437 if (isa<ScalableVectorType>(RetTy) && ST->isSVEorStreamingSVEAvailable()) {
1438 auto LT = getTypeLegalizationCost(RetTy);
1439 return LT.first;
1440 }
1441 break;
1442 }
1443 default:
1444 break;
1445 }
1446 return BaseT::getIntrinsicInstrCost(ICA, CostKind);
1447}
1448
1449/// The function will remove redundant reinterprets casting in the presence
1450/// of the control flow
1451static std::optional<Instruction *> processPhiNode(InstCombiner &IC,
1452 IntrinsicInst &II) {
1454 auto RequiredType = II.getType();
1455
1456 auto *PN = dyn_cast<PHINode>(II.getArgOperand(0));
1457 assert(PN && "Expected Phi Node!");
1458
1459 // Don't create a new Phi unless we can remove the old one.
1460 if (!PN->hasOneUse())
1461 return std::nullopt;
1462
1463 for (Value *IncValPhi : PN->incoming_values()) {
1464 auto *Reinterpret = dyn_cast<IntrinsicInst>(IncValPhi);
1465 if (!Reinterpret ||
1466 Reinterpret->getIntrinsicID() !=
1467 Intrinsic::aarch64_sve_convert_to_svbool ||
1468 RequiredType != Reinterpret->getArgOperand(0)->getType())
1469 return std::nullopt;
1470 }
1471
1472 // Create the new Phi
1473 IC.Builder.SetInsertPoint(PN);
1474 PHINode *NPN = IC.Builder.CreatePHI(RequiredType, PN->getNumIncomingValues());
1475 Worklist.push_back(PN);
1476
1477 for (unsigned I = 0; I < PN->getNumIncomingValues(); I++) {
1478 auto *Reinterpret = cast<Instruction>(PN->getIncomingValue(I));
1479 NPN->addIncoming(Reinterpret->getOperand(0), PN->getIncomingBlock(I));
1480 Worklist.push_back(Reinterpret);
1481 }
1482
1483 // Cleanup Phi Node and reinterprets
1484 return IC.replaceInstUsesWith(II, NPN);
1485}
1486
1487// A collection of properties common to SVE intrinsics that allow for combines
1488// to be written without needing to know the specific intrinsic.
1490 //
1491 // Helper routines for common intrinsic definitions.
1492 //
1493
1494 // e.g. llvm.aarch64.sve.add pg, op1, op2
1495 // with IID ==> llvm.aarch64.sve.add_u
1496 static SVEIntrinsicInfo
1503
1504 // e.g. llvm.aarch64.sve.neg inactive, pg, op
1511
1512 // e.g. llvm.aarch64.sve.fcvtnt inactive, pg, op
1518
1519 // e.g. llvm.aarch64.sve.add_u pg, op1, op2
1525
1526 // e.g. llvm.aarch64.sve.prf pg, ptr (GPIndex = 0)
1527 // llvm.aarch64.sve.st1 data, pg, ptr (GPIndex = 1)
1528 static SVEIntrinsicInfo defaultVoidOp(unsigned GPIndex) {
1529 return SVEIntrinsicInfo()
1532 }
1533
1534 // e.g. llvm.aarch64.sve.cmpeq pg, op1, op2
1535 // llvm.aarch64.sve.ld1 pg, ptr
1542
1543 // All properties relate to predication and thus having a general predicate
1544 // is the minimum requirement to say there is intrinsic info to act on.
1545 explicit operator bool() const { return hasGoverningPredicate(); }
1546
1547 //
1548 // Properties relating to the governing predicate.
1549 //
1550
1552 return GoverningPredicateIdx != std::numeric_limits<unsigned>::max();
1553 }
1554
1556 assert(hasGoverningPredicate() && "Property not set!");
1557 return GoverningPredicateIdx;
1558 }
1559
1561 assert(!hasGoverningPredicate() && "Cannot set property twice!");
1562 GoverningPredicateIdx = Index;
1563 return *this;
1564 }
1565
1566 //
1567 // Properties relating to operations the intrinsic could be transformed into.
1568 // NOTE: This does not mean such a transformation is always possible, but the
1569 // knowledge makes it possible to reuse existing optimisations without needing
1570 // to embed specific handling for each intrinsic. For example, instruction
1571 // simplification can be used to optimise an intrinsic's active lanes.
1572 //
1573
1574 //
1575 // Intrinsic that produces the same result for active lanes.
1576 //
1577
1579 return UndefIntrinsic != Intrinsic::not_intrinsic;
1580 }
1581
1583 assert(hasMatchingUndefIntrinsic() && "Property not set!");
1584 return UndefIntrinsic;
1585 }
1586
1588 assert(!hasMatchingUndefIntrinsic() && "Cannot set property twice!");
1589 UndefIntrinsic = IID;
1590 return *this;
1591 }
1592
1593 //
1594 // Instruction where active lanes produce the same result.
1595 //
1596
1597 bool hasMatchingIROpode() const { return IROpcode != 0; }
1598
1599 unsigned getMatchingIROpode() const {
1600 assert(hasMatchingIROpode() && "Property not set!");
1601 return IROpcode;
1602 }
1603
1605 assert(!hasMatchingIROpode() && "Cannot set property twice!");
1606 IROpcode = Opcode;
1607 return *this;
1608 }
1609
1610 bool hasCmpPredicate() const {
1611 return CmpPredicate != CmpInst::BAD_ICMP_PREDICATE;
1612 }
1613
1615 assert(hasCmpPredicate() && "Property not set!");
1616 return CmpPredicate;
1617 }
1618
1620 assert(!hasCmpPredicate() && "Cannot set property twice!");
1621 CmpPredicate = Pred;
1622
1623 if (CmpInst::isFPPredicate(Pred))
1624 return setMatchingIROpcode(Instruction::FCmp);
1625
1626 if (CmpInst::isIntPredicate(Pred))
1627 return setMatchingIROpcode(Instruction::ICmp);
1628
1629 llvm_unreachable("Unsupported compare predicate!");
1630 }
1631
1632 //
1633 // Properties relating to the result of inactive lanes.
1634 //
1635
1637 return ResultLanes == InactiveLanesTakenFromOperand;
1638 }
1639
1641 assert(inactiveLanesTakenFromOperand() && "Property not set!");
1642 return OperandIdxForInactiveLanes;
1643 }
1644
1646 assert(ResultLanes == Uninitialized && "Cannot set property twice!");
1647 ResultLanes = InactiveLanesTakenFromOperand;
1648 OperandIdxForInactiveLanes = Index;
1649 return *this;
1650 }
1651
1653 return ResultLanes == InactiveLanesAreNotDefined;
1654 }
1655
1657 assert(ResultLanes == Uninitialized && "Cannot set property twice!");
1658 ResultLanes = InactiveLanesAreNotDefined;
1659 return *this;
1660 }
1661
1663 return ResultLanes == InactiveLanesAreUnused;
1664 }
1665
1667 assert(ResultLanes == Uninitialized && "Cannot set property twice!");
1668 ResultLanes = InactiveLanesAreUnused;
1669 return *this;
1670 }
1671
1672 // NOTE: Whilst not limited to only inactive lanes, the common use case is:
1673 // inactiveLanesAreZeroed =
1674 // resultIsZeroInitialized() && inactiveLanesAreUnused()
1675 bool resultIsZeroInitialized() const { return ResultIsZeroInitialized; }
1676
1678 ResultIsZeroInitialized = true;
1679 return *this;
1680 }
1681
1682 //
1683 // The first operand of unary merging operations is typically only used to
1684 // set the result for inactive lanes. Knowing this allows us to deadcode the
1685 // operand when we can prove there are no inactive lanes.
1686 //
1687
1689 return OperandIdxWithNoActiveLanes != std::numeric_limits<unsigned>::max();
1690 }
1691
1693 assert(hasOperandWithNoActiveLanes() && "Property not set!");
1694 return OperandIdxWithNoActiveLanes;
1695 }
1696
1698 assert(!hasOperandWithNoActiveLanes() && "Cannot set property twice!");
1699 OperandIdxWithNoActiveLanes = Index;
1700 return *this;
1701 }
1702
1703private:
1704 unsigned GoverningPredicateIdx = std::numeric_limits<unsigned>::max();
1705
1706 Intrinsic::ID UndefIntrinsic = Intrinsic::not_intrinsic;
1707 unsigned IROpcode = 0;
1709
1710 enum PredicationStyle {
1712 InactiveLanesTakenFromOperand,
1713 InactiveLanesAreNotDefined,
1714 InactiveLanesAreUnused
1715 } ResultLanes = Uninitialized;
1716
1717 bool ResultIsZeroInitialized = false;
1718 unsigned OperandIdxForInactiveLanes = std::numeric_limits<unsigned>::max();
1719 unsigned OperandIdxWithNoActiveLanes = std::numeric_limits<unsigned>::max();
1720};
1721
1723 // Some SVE intrinsics do not use scalable vector types, but since they are
1724 // not relevant from an SVEIntrinsicInfo perspective, they are also ignored.
1725 if (!isa<ScalableVectorType>(II.getType()) &&
1726 all_of(II.args(), [&](const Value *V) {
1727 return !isa<ScalableVectorType>(V->getType());
1728 }))
1729 return SVEIntrinsicInfo();
1730
1731 Intrinsic::ID IID = II.getIntrinsicID();
1732 switch (IID) {
1733 default:
1734 break;
1735 case Intrinsic::aarch64_sve_fcvt_bf16f32_v2:
1736 case Intrinsic::aarch64_sve_fcvt_f16f32:
1737 case Intrinsic::aarch64_sve_fcvt_f16f64:
1738 case Intrinsic::aarch64_sve_fcvt_f32f16:
1739 case Intrinsic::aarch64_sve_fcvt_f32f64:
1740 case Intrinsic::aarch64_sve_fcvt_f64f16:
1741 case Intrinsic::aarch64_sve_fcvt_f64f32:
1742 case Intrinsic::aarch64_sve_fcvtlt_f32f16:
1743 case Intrinsic::aarch64_sve_fcvtlt_f64f32:
1744 case Intrinsic::aarch64_sve_fcvtx_f32f64:
1745 case Intrinsic::aarch64_sve_fcvtzs:
1746 case Intrinsic::aarch64_sve_fcvtzs_i32f16:
1747 case Intrinsic::aarch64_sve_fcvtzs_i32f64:
1748 case Intrinsic::aarch64_sve_fcvtzs_i64f16:
1749 case Intrinsic::aarch64_sve_fcvtzs_i64f32:
1750 case Intrinsic::aarch64_sve_fcvtzu:
1751 case Intrinsic::aarch64_sve_fcvtzu_i32f16:
1752 case Intrinsic::aarch64_sve_fcvtzu_i32f64:
1753 case Intrinsic::aarch64_sve_fcvtzu_i64f16:
1754 case Intrinsic::aarch64_sve_fcvtzu_i64f32:
1755 case Intrinsic::aarch64_sve_revb:
1756 case Intrinsic::aarch64_sve_revh:
1757 case Intrinsic::aarch64_sve_revw:
1758 case Intrinsic::aarch64_sve_revd:
1759 case Intrinsic::aarch64_sve_scvtf:
1760 case Intrinsic::aarch64_sve_scvtf_f16i32:
1761 case Intrinsic::aarch64_sve_scvtf_f16i64:
1762 case Intrinsic::aarch64_sve_scvtf_f32i64:
1763 case Intrinsic::aarch64_sve_scvtf_f64i32:
1764 case Intrinsic::aarch64_sve_ucvtf:
1765 case Intrinsic::aarch64_sve_ucvtf_f16i32:
1766 case Intrinsic::aarch64_sve_ucvtf_f16i64:
1767 case Intrinsic::aarch64_sve_ucvtf_f32i64:
1768 case Intrinsic::aarch64_sve_ucvtf_f64i32:
1770
1771 case Intrinsic::aarch64_sve_fcvtnt_bf16f32_v2:
1772 case Intrinsic::aarch64_sve_fcvtnt_f16f32:
1773 case Intrinsic::aarch64_sve_fcvtnt_f32f64:
1774 case Intrinsic::aarch64_sve_fcvtxnt_f32f64:
1776
1777 case Intrinsic::aarch64_sve_fabd:
1778 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fabd_u);
1779 case Intrinsic::aarch64_sve_fadd:
1780 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fadd_u)
1781 .setMatchingIROpcode(Instruction::FAdd);
1782 case Intrinsic::aarch64_sve_fdiv:
1783 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fdiv_u)
1784 .setMatchingIROpcode(Instruction::FDiv);
1785 case Intrinsic::aarch64_sve_fmax:
1786 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmax_u);
1787 case Intrinsic::aarch64_sve_fmaxnm:
1788 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmaxnm_u);
1789 case Intrinsic::aarch64_sve_fmin:
1790 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmin_u);
1791 case Intrinsic::aarch64_sve_fminnm:
1792 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fminnm_u);
1793 case Intrinsic::aarch64_sve_fmla:
1794 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmla_u);
1795 case Intrinsic::aarch64_sve_fmls:
1796 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmls_u);
1797 case Intrinsic::aarch64_sve_fmul:
1798 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmul_u)
1799 .setMatchingIROpcode(Instruction::FMul);
1800 case Intrinsic::aarch64_sve_fmulx:
1801 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmulx_u);
1802 case Intrinsic::aarch64_sve_fnmla:
1803 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fnmla_u);
1804 case Intrinsic::aarch64_sve_fnmls:
1805 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fnmls_u);
1806 case Intrinsic::aarch64_sve_fsub:
1807 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fsub_u)
1808 .setMatchingIROpcode(Instruction::FSub);
1809 case Intrinsic::aarch64_sve_add:
1810 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_add_u)
1811 .setMatchingIROpcode(Instruction::Add);
1812 case Intrinsic::aarch64_sve_mla:
1813 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_mla_u);
1814 case Intrinsic::aarch64_sve_mls:
1815 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_mls_u);
1816 case Intrinsic::aarch64_sve_mul:
1817 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_mul_u)
1818 .setMatchingIROpcode(Instruction::Mul);
1819 case Intrinsic::aarch64_sve_sabd:
1820 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sabd_u);
1821 case Intrinsic::aarch64_sve_sdiv:
1822 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sdiv_u)
1823 .setMatchingIROpcode(Instruction::SDiv);
1824 case Intrinsic::aarch64_sve_smax:
1825 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_smax_u);
1826 case Intrinsic::aarch64_sve_smin:
1827 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_smin_u);
1828 case Intrinsic::aarch64_sve_smulh:
1829 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_smulh_u);
1830 case Intrinsic::aarch64_sve_sub:
1831 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sub_u)
1832 .setMatchingIROpcode(Instruction::Sub);
1833 case Intrinsic::aarch64_sve_uabd:
1834 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_uabd_u);
1835 case Intrinsic::aarch64_sve_udiv:
1836 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_udiv_u)
1837 .setMatchingIROpcode(Instruction::UDiv);
1838 case Intrinsic::aarch64_sve_umax:
1839 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_umax_u);
1840 case Intrinsic::aarch64_sve_umin:
1841 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_umin_u);
1842 case Intrinsic::aarch64_sve_umulh:
1843 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_umulh_u);
1844 case Intrinsic::aarch64_sve_asr:
1845 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_asr_u)
1846 .setMatchingIROpcode(Instruction::AShr);
1847 case Intrinsic::aarch64_sve_lsl:
1848 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_lsl_u)
1849 .setMatchingIROpcode(Instruction::Shl);
1850 case Intrinsic::aarch64_sve_lsr:
1851 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_lsr_u)
1852 .setMatchingIROpcode(Instruction::LShr);
1853 case Intrinsic::aarch64_sve_and:
1854 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_and_u)
1855 .setMatchingIROpcode(Instruction::And);
1856 case Intrinsic::aarch64_sve_bic:
1857 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_bic_u);
1858 case Intrinsic::aarch64_sve_eor:
1859 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_eor_u)
1860 .setMatchingIROpcode(Instruction::Xor);
1861 case Intrinsic::aarch64_sve_orr:
1862 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_orr_u)
1863 .setMatchingIROpcode(Instruction::Or);
1864 case Intrinsic::aarch64_sve_shsub:
1865 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_shsub_u);
1866 case Intrinsic::aarch64_sve_shsubr:
1868 case Intrinsic::aarch64_sve_sqrshl:
1869 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sqrshl_u);
1870 case Intrinsic::aarch64_sve_sqshl:
1871 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sqshl_u);
1872 case Intrinsic::aarch64_sve_sqsub:
1873 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sqsub_u);
1874 case Intrinsic::aarch64_sve_srshl:
1875 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_srshl_u);
1876 case Intrinsic::aarch64_sve_uhsub:
1877 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_uhsub_u);
1878 case Intrinsic::aarch64_sve_uhsubr:
1880 case Intrinsic::aarch64_sve_uqrshl:
1881 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_uqrshl_u);
1882 case Intrinsic::aarch64_sve_uqshl:
1883 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_uqshl_u);
1884 case Intrinsic::aarch64_sve_uqsub:
1885 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_uqsub_u);
1886 case Intrinsic::aarch64_sve_urshl:
1887 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_urshl_u);
1888
1889 case Intrinsic::aarch64_sve_add_u:
1891 Instruction::Add);
1892 case Intrinsic::aarch64_sve_and_u:
1894 Instruction::And);
1895 case Intrinsic::aarch64_sve_asr_u:
1897 Instruction::AShr);
1898 case Intrinsic::aarch64_sve_eor_u:
1900 Instruction::Xor);
1901 case Intrinsic::aarch64_sve_fadd_u:
1903 Instruction::FAdd);
1904 case Intrinsic::aarch64_sve_fdiv_u:
1906 Instruction::FDiv);
1907 case Intrinsic::aarch64_sve_fmul_u:
1909 Instruction::FMul);
1910 case Intrinsic::aarch64_sve_fsub_u:
1912 Instruction::FSub);
1913 case Intrinsic::aarch64_sve_lsl_u:
1915 Instruction::Shl);
1916 case Intrinsic::aarch64_sve_lsr_u:
1918 Instruction::LShr);
1919 case Intrinsic::aarch64_sve_mul_u:
1921 Instruction::Mul);
1922 case Intrinsic::aarch64_sve_orr_u:
1924 Instruction::Or);
1925 case Intrinsic::aarch64_sve_sdiv_u:
1927 Instruction::SDiv);
1928 case Intrinsic::aarch64_sve_sub_u:
1930 Instruction::Sub);
1931 case Intrinsic::aarch64_sve_udiv_u:
1933 Instruction::UDiv);
1934
1935 case Intrinsic::aarch64_sve_addqv:
1936 case Intrinsic::aarch64_sve_bic_z:
1937 case Intrinsic::aarch64_sve_brka_z:
1938 case Intrinsic::aarch64_sve_brkb_z:
1939 case Intrinsic::aarch64_sve_brkn_z:
1940 case Intrinsic::aarch64_sve_brkpa_z:
1941 case Intrinsic::aarch64_sve_brkpb_z:
1942 case Intrinsic::aarch64_sve_cntp:
1943 case Intrinsic::aarch64_sve_compact:
1944 case Intrinsic::aarch64_sve_eorv:
1945 case Intrinsic::aarch64_sve_eorqv:
1946 case Intrinsic::aarch64_sve_nand_z:
1947 case Intrinsic::aarch64_sve_nor_z:
1948 case Intrinsic::aarch64_sve_orn_z:
1949 case Intrinsic::aarch64_sve_orv:
1950 case Intrinsic::aarch64_sve_orqv:
1951 case Intrinsic::aarch64_sve_pnext:
1952 case Intrinsic::aarch64_sve_rdffr_z:
1953 case Intrinsic::aarch64_sve_saddv:
1954 case Intrinsic::aarch64_sve_uaddv:
1955 case Intrinsic::aarch64_sve_umaxv:
1956 case Intrinsic::aarch64_sve_umaxqv:
1957 case Intrinsic::aarch64_sve_facge:
1958 case Intrinsic::aarch64_sve_facgt:
1959 case Intrinsic::aarch64_sve_ld1:
1960 case Intrinsic::aarch64_sve_ld1_gather:
1961 case Intrinsic::aarch64_sve_ld1_gather_index:
1962 case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
1963 case Intrinsic::aarch64_sve_ld1_gather_sxtw:
1964 case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
1965 case Intrinsic::aarch64_sve_ld1_gather_uxtw:
1966 case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
1967 case Intrinsic::aarch64_sve_ld1q_gather_index:
1968 case Intrinsic::aarch64_sve_ld1q_gather_scalar_offset:
1969 case Intrinsic::aarch64_sve_ld1q_gather_vector_offset:
1970 case Intrinsic::aarch64_sve_ld1ro:
1971 case Intrinsic::aarch64_sve_ld1rq:
1972 case Intrinsic::aarch64_sve_ld1udq:
1973 case Intrinsic::aarch64_sve_ld1uwq:
1974 case Intrinsic::aarch64_sve_ld2_sret:
1975 case Intrinsic::aarch64_sve_ld2q_sret:
1976 case Intrinsic::aarch64_sve_ld3_sret:
1977 case Intrinsic::aarch64_sve_ld3q_sret:
1978 case Intrinsic::aarch64_sve_ld4_sret:
1979 case Intrinsic::aarch64_sve_ld4q_sret:
1980 case Intrinsic::aarch64_sve_ldff1:
1981 case Intrinsic::aarch64_sve_ldff1_gather:
1982 case Intrinsic::aarch64_sve_ldff1_gather_index:
1983 case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
1984 case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
1985 case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
1986 case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
1987 case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
1988 case Intrinsic::aarch64_sve_ldnf1:
1989 case Intrinsic::aarch64_sve_ldnt1:
1990 case Intrinsic::aarch64_sve_ldnt1_gather:
1991 case Intrinsic::aarch64_sve_ldnt1_gather_index:
1992 case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
1993 case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
1995
1996 case Intrinsic::aarch64_sve_and_z:
1998 Instruction::And);
1999 case Intrinsic::aarch64_sve_orr_z:
2001 Instruction::Or);
2002 case Intrinsic::aarch64_sve_eor_z:
2004 Instruction::Xor);
2005
2006 case Intrinsic::aarch64_sve_cmpeq:
2007 case Intrinsic::aarch64_sve_cmpeq_wide:
2010 case Intrinsic::aarch64_sve_cmpge:
2011 case Intrinsic::aarch64_sve_cmpge_wide:
2014 case Intrinsic::aarch64_sve_cmpgt:
2015 case Intrinsic::aarch64_sve_cmpgt_wide:
2018 case Intrinsic::aarch64_sve_cmphi:
2019 case Intrinsic::aarch64_sve_cmphi_wide:
2022 case Intrinsic::aarch64_sve_cmphs:
2023 case Intrinsic::aarch64_sve_cmphs_wide:
2026 case Intrinsic::aarch64_sve_cmple_wide:
2029 case Intrinsic::aarch64_sve_cmplo_wide:
2032 case Intrinsic::aarch64_sve_cmpls_wide:
2035 case Intrinsic::aarch64_sve_cmplt_wide:
2038 case Intrinsic::aarch64_sve_cmpne:
2039 case Intrinsic::aarch64_sve_cmpne_wide:
2042 case Intrinsic::aarch64_sve_fcmpeq:
2045 case Intrinsic::aarch64_sve_fcmpge:
2048 case Intrinsic::aarch64_sve_fcmpgt:
2051 case Intrinsic::aarch64_sve_fcmpne:
2054 case Intrinsic::aarch64_sve_fcmpuo:
2057
2058 case Intrinsic::aarch64_sve_prf:
2059 case Intrinsic::aarch64_sve_prfb_gather_index:
2060 case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
2061 case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
2062 case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
2063 case Intrinsic::aarch64_sve_prfd_gather_index:
2064 case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
2065 case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
2066 case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
2067 case Intrinsic::aarch64_sve_prfh_gather_index:
2068 case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
2069 case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
2070 case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
2071 case Intrinsic::aarch64_sve_prfw_gather_index:
2072 case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
2073 case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
2074 case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
2076
2077 case Intrinsic::aarch64_sve_st1_scatter:
2078 case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
2079 case Intrinsic::aarch64_sve_st1_scatter_sxtw:
2080 case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
2081 case Intrinsic::aarch64_sve_st1_scatter_uxtw:
2082 case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
2083 case Intrinsic::aarch64_sve_st1dq:
2084 case Intrinsic::aarch64_sve_st1q_scatter_index:
2085 case Intrinsic::aarch64_sve_st1q_scatter_scalar_offset:
2086 case Intrinsic::aarch64_sve_st1q_scatter_vector_offset:
2087 case Intrinsic::aarch64_sve_st1wq:
2088 case Intrinsic::aarch64_sve_stnt1:
2089 case Intrinsic::aarch64_sve_stnt1_scatter:
2090 case Intrinsic::aarch64_sve_stnt1_scatter_index:
2091 case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
2092 case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
2094 case Intrinsic::aarch64_sve_st2:
2095 case Intrinsic::aarch64_sve_st2q:
2097 case Intrinsic::aarch64_sve_st3:
2098 case Intrinsic::aarch64_sve_st3q:
2100 case Intrinsic::aarch64_sve_st4:
2101 case Intrinsic::aarch64_sve_st4q:
2103 }
2104
2105 return SVEIntrinsicInfo();
2106}
2107
2109 Value *UncastedPred;
2110
2111 // Look through predicate casts that only remove lanes.
2113 m_Value(UncastedPred)))) {
2114 auto *OrigPredTy = cast<ScalableVectorType>(Pred->getType());
2115 Pred = UncastedPred;
2116
2118 m_Value(UncastedPred))))
2119 // If the predicate has the same or less lanes than the uncasted predicate
2120 // then we know the casting has no effect.
2121 if (OrigPredTy->getMinNumElements() <=
2122 cast<ScalableVectorType>(UncastedPred->getType())
2123 ->getMinNumElements())
2124 Pred = UncastedPred;
2125 }
2126
2127 auto *C = dyn_cast<Constant>(Pred);
2128 return C && C->isAllOnesValue();
2129}
2130
2131// Simplify `V` by only considering the operations that affect active lanes.
2132// This function should only return existing Values or newly created Constants.
2133static Value *stripInactiveLanes(Value *V, const Value *Pg) {
2134 auto *Dup = dyn_cast<IntrinsicInst>(V);
2135 if (Dup && Dup->getIntrinsicID() == Intrinsic::aarch64_sve_dup &&
2136 Dup->getOperand(1) == Pg && isa<Constant>(Dup->getOperand(2)))
2138 cast<VectorType>(V->getType())->getElementCount(),
2139 cast<Constant>(Dup->getOperand(2)));
2140
2141 return V;
2142}
2143
2144static std::optional<Instruction *>
2146 const SVEIntrinsicInfo &IInfo) {
2147 const unsigned Opc = IInfo.getMatchingIROpode();
2148 assert(Instruction::isBinaryOp(Opc) && "Expected a binary operation!");
2149
2150 Value *Pg = II.getOperand(0);
2151 Value *Op1 = II.getOperand(1);
2152 Value *Op2 = II.getOperand(2);
2153 const DataLayout &DL = II.getDataLayout();
2154
2155 // Canonicalise constants to the RHS.
2157 isa<Constant>(Op1) && !isa<Constant>(Op2)) {
2158 IC.replaceOperand(II, 1, Op2);
2159 IC.replaceOperand(II, 2, Op1);
2160 return &II;
2161 }
2162
2163 // Only active lanes matter when simplifying the operation.
2164 Op1 = stripInactiveLanes(Op1, Pg);
2165 Op2 = stripInactiveLanes(Op2, Pg);
2166
2167 Value *SimpleII;
2168 if (auto FII = dyn_cast<FPMathOperator>(&II))
2169 SimpleII = simplifyBinOp(Opc, Op1, Op2, FII->getFastMathFlags(), DL);
2170 else
2171 SimpleII = simplifyBinOp(Opc, Op1, Op2, DL);
2172
2173 // If both operands are convert.to.svbool from the same narrower predicate
2174 // type, try to simplify the operation at that narrower type. This is valid
2175 // because the conversions zero the lanes not represented by the narrower
2176 // type, so those lanes of the result are zero either way.
2177 Value *NarrowOp1, *NarrowOp2;
2178 if (!SimpleII &&
2180 m_Value(NarrowOp1))) &&
2182 m_Value(NarrowOp2))) &&
2183 NarrowOp1->getType() == NarrowOp2->getType()) {
2184 Value *SimpleNarrow = simplifyBinOp(Opc, NarrowOp1, NarrowOp2, DL);
2185 if (SimpleNarrow && !isa<UndefValue>(SimpleNarrow)) {
2186 if (match(SimpleNarrow, m_ZeroInt()))
2187 SimpleII = Constant::getNullValue(II.getType());
2188 else if (SimpleNarrow == NarrowOp1)
2189 SimpleII = Op1;
2190 else if (SimpleNarrow == NarrowOp2)
2191 SimpleII = Op2;
2192 else
2193 SimpleII =
2194 IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_convert_to_svbool,
2195 SimpleNarrow->getType(), SimpleNarrow);
2196 }
2197 }
2198
2199 // An SVE intrinsic's result is always defined. However, this is not the case
2200 // for its equivalent IR instruction (e.g. when shifting by an amount more
2201 // than the data's bitwidth). Simplifications to an undefined result must be
2202 // ignored to preserve the intrinsic's expected behaviour.
2203 if (!SimpleII || isa<UndefValue>(SimpleII))
2204 return std::nullopt;
2205
2206 if (IInfo.inactiveLanesAreNotDefined())
2207 return IC.replaceInstUsesWith(II, SimpleII);
2208
2209 Value *Inactive =
2211 ? Constant::getNullValue(II.getType())
2212 : II.getOperand(IInfo.getOperandIdxInactiveLanesTakenFrom());
2213
2214 // The intrinsic does nothing (e.g. sve.mul(pg, A, 1.0)).
2215 if (SimpleII == Inactive)
2216 return IC.replaceInstUsesWith(II, SimpleII);
2217
2218 // Inactive lanes must be preserved.
2219 SimpleII = IC.Builder.CreateSelect(Pg, SimpleII, Inactive);
2220 return IC.replaceInstUsesWith(II, SimpleII);
2221}
2222
2223static std::optional<Instruction *>
2225 const SVEIntrinsicInfo &IInfo) {
2226 const unsigned Opc = IInfo.getMatchingIROpode();
2227 assert((Opc == Instruction::ICmp || Opc == Instruction::FCmp) &&
2228 "Expected a compare operation!");
2229
2230 Value *Pg = II.getOperand(0);
2231 Value *LHS = II.getOperand(1);
2232 Value *RHS = II.getOperand(2);
2233 CmpInst::Predicate CmpPred = IInfo.getCmpPredicate();
2234 bool IsWideICmp =
2235 Opc == Instruction::ICmp && LHS->getType() != RHS->getType();
2236 assert((IsWideICmp || LHS->getType() == RHS->getType()) &&
2237 "Unexpected wide compare!");
2238
2239 // Canonicalise constants to the RHS.
2240 if ((ICmpInst::isCommutative(CmpPred) || FCmpInst::isCommutative(CmpPred)) &&
2241 isa<Constant>(LHS) && !isa<Constant>(RHS) && !IsWideICmp) {
2242 IC.replaceOperand(II, 1, RHS);
2243 IC.replaceOperand(II, 2, LHS);
2244 return &II;
2245 }
2246
2247 // Only active lanes matter when simplifying the operation.
2248 LHS = stripInactiveLanes(LHS, Pg);
2249 RHS = stripInactiveLanes(RHS, Pg);
2250
2251 if (IsWideICmp) {
2252 // We can do more for wide compares, but not using simplifyCmpInst.
2253 const APInt *LHSVal, *RHSVal;
2254 if (!match(LHS, m_APInt(LHSVal)) || !match(RHS, m_APInt(RHSVal)))
2255 return std::nullopt;
2256
2257 // Consider cmpge.wide(..., <vscale x 4 x i32> LHS, <vscale x 2 x i64> RHS),
2258 // we must reconstruct the constants because LHS has the wrong element type,
2259 // and RHS the wrong element count.
2260 Type *WideVT = VectorType::get(RHS->getType()->getScalarType(),
2261 cast<VectorType>(LHS->getType()));
2262 // NOTE: Wide equality comparisons are signed.
2263 if (ICmpInst::isUnsigned(CmpPred)) {
2264 LHS = ConstantInt::get(WideVT, LHSVal->getZExtValue());
2265 RHS = ConstantInt::get(WideVT, RHSVal->getZExtValue());
2266 } else {
2267 LHS = ConstantInt::get(WideVT, LHSVal->getSExtValue());
2268 RHS = ConstantInt::get(WideVT, RHSVal->getSExtValue());
2269 }
2270 }
2271
2272 // TODO: Allow fast-math flags for calls to compare intrinsics.
2273 const DataLayout &DL = II.getDataLayout();
2274 Value *SimpleII = simplifyCmpInst(CmpPred, LHS, RHS, DL);
2275
2276 // No simplification happened.
2277 if (!SimpleII)
2278 return std::nullopt;
2279
2280 assert(IInfo.resultIsZeroInitialized() && "Expected a zeroing operation!");
2281
2282 if (match(SimpleII, m_ZeroInt()))
2283 return IC.replaceInstUsesWith(II, SimpleII);
2284
2285 // Inactive lanes must be zeroed.
2286 SimpleII = IC.Builder.CreateLogicalAnd(Pg, SimpleII);
2287 return IC.replaceInstUsesWith(II, SimpleII);
2288}
2289
2290// Use SVE intrinsic info to eliminate redundant operands and/or canonicalise
2291// to operations with less strict inactive lane requirements.
2292static std::optional<Instruction *>
2294 const SVEIntrinsicInfo &IInfo) {
2295 if (!IInfo.hasGoverningPredicate())
2296 return std::nullopt;
2297
2298 auto *OpPredicate = II.getOperand(IInfo.getGoverningPredicateOperandIdx());
2299
2300 // If there are no active lanes.
2301 if (match(OpPredicate, m_ZeroInt())) {
2303 return IC.replaceInstUsesWith(
2304 II, II.getOperand(IInfo.getOperandIdxInactiveLanesTakenFrom()));
2305
2306 if (IInfo.inactiveLanesAreUnused()) {
2307 if (IInfo.resultIsZeroInitialized())
2309
2310 return IC.eraseInstFromFunction(II);
2311 }
2312 }
2313
2314 // If there are no inactive lanes.
2315 if (isAllActivePredicate(OpPredicate)) {
2316 if (IInfo.hasOperandWithNoActiveLanes()) {
2317 unsigned OpIdx = IInfo.getOperandIdxWithNoActiveLanes();
2318 if (!isa<UndefValue>(II.getOperand(OpIdx)))
2319 return IC.replaceOperand(II, OpIdx, UndefValue::get(II.getType()));
2320 }
2321
2322 if (IInfo.hasMatchingUndefIntrinsic()) {
2323 auto *NewDecl = Intrinsic::getOrInsertDeclaration(
2324 II.getModule(), IInfo.getMatchingUndefIntrinsic(), {II.getType()});
2325 II.setCalledFunction(NewDecl);
2326 return &II;
2327 }
2328 }
2329
2330 if (!IInfo.hasMatchingIROpode())
2331 return std::nullopt;
2332
2333 //
2334 // Operation specific simplifications.
2335 //
2336
2337 unsigned Opc = IInfo.getMatchingIROpode();
2338
2340 return simplifySVEIntrinsicBinOp(IC, II, IInfo);
2341
2342 if (Opc == Instruction::FCmp || Opc == Instruction::ICmp)
2343 return simplifySVEIntrinsicCompare(IC, II, IInfo);
2344
2345 return std::nullopt;
2346}
2347
2348// (from_svbool (binop (to_svbool pred) (svbool_t _) (svbool_t _))))
2349// => (binop (pred) (from_svbool _) (from_svbool _))
2350//
2351// The above transformation eliminates a `to_svbool` in the predicate
2352// operand of bitwise operation `binop` by narrowing the vector width of
2353// the operation. For example, it would convert a `<vscale x 16 x i1>
2354// and` into a `<vscale x 4 x i1> and`. This is profitable because
2355// to_svbool must zero the new lanes during widening, whereas
2356// from_svbool is free.
2357static std::optional<Instruction *>
2359 auto m_ConvertToSVBool = [](auto P) {
2361 };
2362 constexpr Intrinsic::ID ConvertFromSVBool =
2363 Intrinsic::aarch64_sve_convert_from_svbool;
2364
2365 Type *Ty = II.getType();
2366 Value *LHS, *RHS, *NarrowLHS, *NarrowRHS;
2367
2368 if (match(II.getOperand(0),
2370 m_ConvertToSVBool(m_SpecificType(Ty, NarrowRHS))))) {
2371 NarrowLHS = IC.Builder.CreateIntrinsic(ConvertFromSVBool, Ty, LHS);
2372 Value *NarrowAnd = IC.Builder.CreateLogicalAnd(NarrowLHS, NarrowRHS);
2373 return IC.replaceInstUsesWith(II, NarrowAnd);
2374 }
2375
2376 if (match(II.getOperand(0),
2377 m_LogicalAnd(m_ConvertToSVBool(m_SpecificType(Ty, NarrowLHS)),
2378 m_Value(RHS)))) {
2379 NarrowRHS = IC.Builder.CreateIntrinsic(ConvertFromSVBool, Ty, RHS);
2380 Value *NarrowAnd = IC.Builder.CreateLogicalAnd(NarrowLHS, NarrowRHS);
2381 return IC.replaceInstUsesWith(II, NarrowAnd);
2382 }
2383
2384 auto BinOp = dyn_cast<IntrinsicInst>(II.getOperand(0));
2385 if (!BinOp)
2386 return std::nullopt;
2387
2388 Intrinsic::ID BinOpIID = BinOp->getIntrinsicID();
2389 switch (BinOpIID) {
2390 case Intrinsic::aarch64_sve_and_z:
2391 case Intrinsic::aarch64_sve_bic_z:
2392 case Intrinsic::aarch64_sve_eor_z:
2393 case Intrinsic::aarch64_sve_nand_z:
2394 case Intrinsic::aarch64_sve_nor_z:
2395 case Intrinsic::aarch64_sve_orn_z:
2396 case Intrinsic::aarch64_sve_orr_z:
2397 break;
2398 default:
2399 return std::nullopt;
2400 }
2401
2402 Value *BinOpPred = BinOp->getOperand(0);
2403 Value *BinOpOp1 = BinOp->getOperand(1);
2404 Value *BinOpOp2 = BinOp->getOperand(2);
2405
2406 Value *NarrowBinOpPred;
2407 if (!match(BinOpPred, m_ConvertToSVBool(m_SpecificType(Ty, NarrowBinOpPred))))
2408 return std::nullopt;
2409
2410 Value *NarrowBinOpOp1 =
2411 IC.Builder.CreateIntrinsic(ConvertFromSVBool, Ty, BinOpOp1);
2412 Value *NarrowBinOpOp2 = NarrowBinOpOp1;
2413 if (BinOpOp1 != BinOpOp2)
2414 NarrowBinOpOp2 =
2415 IC.Builder.CreateIntrinsic(ConvertFromSVBool, Ty, BinOpOp2);
2416 Value *NarrowedBinOp = IC.Builder.CreateIntrinsic(
2417 BinOpIID, Ty, {NarrowBinOpPred, NarrowBinOpOp1, NarrowBinOpOp2});
2418 return IC.replaceInstUsesWith(II, NarrowedBinOp);
2419}
2420
2421static std::optional<Instruction *>
2423 // If the reinterpret instruction operand is a PHI Node
2424 if (isa<PHINode>(II.getArgOperand(0)))
2425 return processPhiNode(IC, II);
2426
2427 if (auto BinOpCombine = tryCombineFromSVBoolBinOp(IC, II))
2428 return BinOpCombine;
2429
2430 // Ignore converts to/from svcount_t.
2431 if (isa<TargetExtType>(II.getArgOperand(0)->getType()) ||
2432 isa<TargetExtType>(II.getType()))
2433 return std::nullopt;
2434
2435 SmallVector<Instruction *, 32> CandidatesForRemoval;
2436 Value *Cursor = II.getOperand(0), *EarliestReplacement = nullptr;
2437
2438 const auto *IVTy = cast<VectorType>(II.getType());
2439
2440 // Walk the chain of conversions.
2441 while (Cursor) {
2442 // If the type of the cursor has fewer lanes than the final result, zeroing
2443 // must take place, which breaks the equivalence chain.
2444 const auto *CursorVTy = cast<VectorType>(Cursor->getType());
2445 if (CursorVTy->getElementCount().getKnownMinValue() <
2446 IVTy->getElementCount().getKnownMinValue())
2447 break;
2448
2449 // If the cursor has the same type as I, it is a viable replacement.
2450 if (Cursor->getType() == IVTy)
2451 EarliestReplacement = Cursor;
2452
2453 auto *IntrinsicCursor = dyn_cast<IntrinsicInst>(Cursor);
2454
2455 // If this is not an SVE conversion intrinsic, this is the end of the chain.
2456 if (!IntrinsicCursor || !(IntrinsicCursor->getIntrinsicID() ==
2457 Intrinsic::aarch64_sve_convert_to_svbool ||
2458 IntrinsicCursor->getIntrinsicID() ==
2459 Intrinsic::aarch64_sve_convert_from_svbool))
2460 break;
2461
2462 CandidatesForRemoval.insert(CandidatesForRemoval.begin(), IntrinsicCursor);
2463 Cursor = IntrinsicCursor->getOperand(0);
2464 }
2465
2466 // If no viable replacement in the conversion chain was found, there is
2467 // nothing to do.
2468 if (!EarliestReplacement)
2469 return std::nullopt;
2470
2471 return IC.replaceInstUsesWith(II, EarliestReplacement);
2472}
2473
2474static std::optional<Instruction *> instCombineSVESel(InstCombiner &IC,
2475 IntrinsicInst &II) {
2476 // svsel(ptrue, x, y) => x
2477 auto *OpPredicate = II.getOperand(0);
2478 if (isAllActivePredicate(OpPredicate))
2479 return IC.replaceInstUsesWith(II, II.getOperand(1));
2480
2481 auto Select =
2482 IC.Builder.CreateSelect(OpPredicate, II.getOperand(1), II.getOperand(2));
2483 return IC.replaceInstUsesWith(II, Select);
2484}
2485
2486static std::optional<Instruction *> instCombineSVEDup(InstCombiner &IC,
2487 IntrinsicInst &II) {
2488 Value *Pg = II.getOperand(1);
2489
2490 // sve.dup(V, all_active, X) ==> splat(X)
2491 if (isAllActivePredicate(Pg)) {
2492 auto *RetTy = cast<ScalableVectorType>(II.getType());
2493 Value *Splat = IC.Builder.CreateVectorSplat(RetTy->getElementCount(),
2494 II.getArgOperand(2));
2495 return IC.replaceInstUsesWith(II, Splat);
2496 }
2497
2499 m_SpecificInt(AArch64SVEPredPattern::vl1))))
2500 return std::nullopt;
2501
2502 // sve.dup(V, sve.ptrue(vl1), X) ==> insertelement V, X, 0
2503 Value *Insert = IC.Builder.CreateInsertElement(
2504 II.getArgOperand(0), II.getArgOperand(2), uint64_t(0));
2505 return IC.replaceInstUsesWith(II, Insert);
2506}
2507
2508static std::optional<Instruction *> instCombineSVEDupX(InstCombiner &IC,
2509 IntrinsicInst &II) {
2510 // Replace DupX with a regular IR splat.
2511 auto *RetTy = cast<ScalableVectorType>(II.getType());
2512 Value *Splat = IC.Builder.CreateVectorSplat(RetTy->getElementCount(),
2513 II.getArgOperand(0));
2514 Splat->takeName(&II);
2515 return IC.replaceInstUsesWith(II, Splat);
2516}
2517
2518// xor(cmpne(%pg, %lhs, %rhs), %pg)
2519// -> cmpeq(%pg, %lhs, %rhs)
2520static std::optional<Instruction *> instCombineXorSVECmpCC(InstCombiner &IC,
2521 IntrinsicInst &II) {
2522 if (!II.hasOneUse())
2523 return std::nullopt;
2524 auto *User = *II.user_begin();
2525 if (!match(User, m_c_Xor(m_Specific(&II), m_Specific(II.getOperand(0)))))
2526 return std::nullopt;
2527
2528 Intrinsic::ID IID;
2529 switch (II.getIntrinsicID()) {
2530 case Intrinsic::aarch64_sve_cmpne:
2531 IID = Intrinsic::aarch64_sve_cmpeq;
2532 break;
2533 case Intrinsic::aarch64_sve_cmpne_wide:
2534 IID = Intrinsic::aarch64_sve_cmpeq_wide;
2535 break;
2536 case Intrinsic::aarch64_sve_cmpeq:
2537 IID = Intrinsic::aarch64_sve_cmpne;
2538 break;
2539 case Intrinsic::aarch64_sve_cmpeq_wide:
2540 IID = Intrinsic::aarch64_sve_cmpne_wide;
2541 break;
2542 default:
2543 return std::nullopt;
2544 }
2545
2547 Value *CMPCC = IC.Builder.CreateIntrinsic(
2548 IID, II.getOperand(1)->getType(),
2549 {II.getOperand(0), II.getOperand(1), II.getOperand(2)});
2550 IC.replaceInstUsesWith(*User, CMPCC);
2552 return &II;
2553}
2554
2555// zext(cmpne(ptrue, %v, 0))
2556// -> umin(%pg, %v, 1)
2557static std::optional<Instruction *> instCombineZExtSVECmpNE(InstCombiner &IC,
2558 IntrinsicInst &II) {
2559 if (!isAllActivePredicate(II.getOperand(0)) ||
2560 !match(II.getOperand(2), m_Zero()))
2561 return std::nullopt;
2562
2563 for (Instruction *User : II.users()) {
2564 if (match(User, m_ZExt(m_Specific(&II)))) {
2565 Type *Ty = II.getOperand(1)->getType();
2566 if (User->getType() != Ty)
2567 continue;
2570 Intrinsic::aarch64_sve_umin, Ty,
2571 {II.getOperand(0), II.getOperand(1), ConstantInt::get(Ty, 1)});
2574 return &II;
2575 }
2576 }
2577 return std::nullopt;
2578}
2579
2580static std::optional<Instruction *> instCombineSVECmpNE(InstCombiner &IC,
2581 IntrinsicInst &II) {
2582 LLVMContext &Ctx = II.getContext();
2583
2584 if (auto Res = instCombineXorSVECmpCC(IC, II))
2585 return Res;
2586
2587 if (auto Res = instCombineZExtSVECmpNE(IC, II))
2588 return Res;
2589
2590 if (!isAllActivePredicate(II.getArgOperand(0)))
2591 return std::nullopt;
2592
2593 // Check that we have a compare of zero..
2594 auto *SplatValue =
2596 if (!SplatValue || !SplatValue->isZero())
2597 return std::nullopt;
2598
2599 // ..against a dupq
2600 auto *DupQLane = dyn_cast<IntrinsicInst>(II.getArgOperand(1));
2601 if (!DupQLane ||
2602 DupQLane->getIntrinsicID() != Intrinsic::aarch64_sve_dupq_lane)
2603 return std::nullopt;
2604
2605 // Where the dupq is a lane 0 replicate of a vector insert
2606 auto *DupQLaneIdx = dyn_cast<ConstantInt>(DupQLane->getArgOperand(1));
2607 if (!DupQLaneIdx || !DupQLaneIdx->isZero())
2608 return std::nullopt;
2609
2610 auto *VecIns = dyn_cast<IntrinsicInst>(DupQLane->getArgOperand(0));
2611 if (!VecIns || VecIns->getIntrinsicID() != Intrinsic::vector_insert)
2612 return std::nullopt;
2613
2614 // Where the vector insert is a fixed constant vector insert into undef at
2615 // index zero
2616 if (!isa<UndefValue>(VecIns->getArgOperand(0)))
2617 return std::nullopt;
2618
2619 if (!cast<ConstantInt>(VecIns->getArgOperand(2))->isZero())
2620 return std::nullopt;
2621
2622 auto *ConstVec = dyn_cast<Constant>(VecIns->getArgOperand(1));
2623 if (!ConstVec)
2624 return std::nullopt;
2625
2626 auto *VecTy = dyn_cast<FixedVectorType>(ConstVec->getType());
2627 auto *OutTy = dyn_cast<ScalableVectorType>(II.getType());
2628 if (!VecTy || !OutTy || VecTy->getNumElements() != OutTy->getMinNumElements())
2629 return std::nullopt;
2630
2631 unsigned NumElts = VecTy->getNumElements();
2632 unsigned PredicateBits = 0;
2633
2634 // Expand intrinsic operands to a 16-bit byte level predicate
2635 for (unsigned I = 0; I < NumElts; ++I) {
2636 auto *Arg = dyn_cast<ConstantInt>(ConstVec->getAggregateElement(I));
2637 if (!Arg)
2638 return std::nullopt;
2639 if (!Arg->isZero())
2640 PredicateBits |= 1 << (I * (16 / NumElts));
2641 }
2642
2643 // If all bits are zero bail early with an empty predicate
2644 if (PredicateBits == 0) {
2645 auto *PFalse = Constant::getNullValue(II.getType());
2646 PFalse->takeName(&II);
2647 return IC.replaceInstUsesWith(II, PFalse);
2648 }
2649
2650 // Calculate largest predicate type used (where byte predicate is largest)
2651 unsigned Mask = 8;
2652 for (unsigned I = 0; I < 16; ++I)
2653 if ((PredicateBits & (1 << I)) != 0)
2654 Mask |= (I % 8);
2655
2656 unsigned PredSize = Mask & -Mask;
2657 auto *PredType = ScalableVectorType::get(
2658 Type::getInt1Ty(Ctx), AArch64::SVEBitsPerBlock / (PredSize * 8));
2659
2660 // Ensure all relevant bits are set
2661 for (unsigned I = 0; I < 16; I += PredSize)
2662 if ((PredicateBits & (1 << I)) == 0)
2663 return std::nullopt;
2664
2665 auto *ConvertToSVBool =
2666 IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_convert_to_svbool,
2667 PredType, ConstantInt::getTrue(PredType));
2668 auto *ConvertFromSVBool =
2669 IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_convert_from_svbool,
2670 II.getType(), ConvertToSVBool);
2671
2672 ConvertFromSVBool->takeName(&II);
2673 return IC.replaceInstUsesWith(II, ConvertFromSVBool);
2674}
2675
2676static std::optional<Instruction *> instCombineSVELast(InstCombiner &IC,
2677 IntrinsicInst &II) {
2678 Value *Pg = II.getArgOperand(0);
2679 Value *Vec = II.getArgOperand(1);
2680 auto IntrinsicID = II.getIntrinsicID();
2681 bool IsAfter = IntrinsicID == Intrinsic::aarch64_sve_lasta;
2682
2683 // lastX(splat(X)) --> X
2684 if (auto *SplatVal = getSplatValue(Vec))
2685 return IC.replaceInstUsesWith(II, SplatVal);
2686
2687 // If x and/or y is a splat value then:
2688 // lastX (binop (x, y)) --> binop(lastX(x), lastX(y))
2689 Value *LHS, *RHS;
2690 if (match(Vec, m_OneUse(m_BinOp(m_Value(LHS), m_Value(RHS))))) {
2691 if (isSplatValue(LHS) || isSplatValue(RHS)) {
2692 auto *OldBinOp = cast<BinaryOperator>(Vec);
2693 auto OpC = OldBinOp->getOpcode();
2694 auto *NewLHS =
2695 IC.Builder.CreateIntrinsic(IntrinsicID, {Vec->getType()}, {Pg, LHS});
2696 auto *NewRHS =
2697 IC.Builder.CreateIntrinsic(IntrinsicID, {Vec->getType()}, {Pg, RHS});
2699 OpC, NewLHS, NewRHS, OldBinOp, OldBinOp->getName(), II.getIterator());
2700 return IC.replaceInstUsesWith(II, NewBinOp);
2701 }
2702 }
2703
2704 auto *C = dyn_cast<Constant>(Pg);
2705 if (IsAfter && C && C->isNullValue()) {
2706 // The intrinsic is extracting lane 0 so use an extract instead.
2707 auto *IdxTy = Type::getInt64Ty(II.getContext());
2708 auto *Extract = ExtractElementInst::Create(Vec, ConstantInt::get(IdxTy, 0));
2709 Extract->insertBefore(II.getIterator());
2710 Extract->takeName(&II);
2711 return IC.replaceInstUsesWith(II, Extract);
2712 }
2713
2714 auto *IntrPG = dyn_cast<IntrinsicInst>(Pg);
2715 if (!IntrPG)
2716 return std::nullopt;
2717
2718 if (IntrPG->getIntrinsicID() != Intrinsic::aarch64_sve_ptrue)
2719 return std::nullopt;
2720
2721 const auto PTruePattern =
2722 cast<ConstantInt>(IntrPG->getOperand(0))->getZExtValue();
2723
2724 // Can the intrinsic's predicate be converted to a known constant index?
2725 unsigned MinNumElts = getNumElementsFromSVEPredPattern(PTruePattern);
2726 if (!MinNumElts)
2727 return std::nullopt;
2728
2729 unsigned Idx = MinNumElts - 1;
2730 // Increment the index if extracting the element after the last active
2731 // predicate element.
2732 if (IsAfter)
2733 ++Idx;
2734
2735 // Ignore extracts whose index is larger than the known minimum vector
2736 // length. NOTE: This is an artificial constraint where we prefer to
2737 // maintain what the user asked for until an alternative is proven faster.
2738 auto *PgVTy = cast<ScalableVectorType>(Pg->getType());
2739 if (Idx >= PgVTy->getMinNumElements())
2740 return std::nullopt;
2741
2742 // The intrinsic is extracting a fixed lane so use an extract instead.
2743 auto *IdxTy = Type::getInt64Ty(II.getContext());
2744 auto *Extract = ExtractElementInst::Create(Vec, ConstantInt::get(IdxTy, Idx));
2745 Extract->insertBefore(II.getIterator());
2746 Extract->takeName(&II);
2747 return IC.replaceInstUsesWith(II, Extract);
2748}
2749
2750static std::optional<Instruction *> instCombineSVECondLast(InstCombiner &IC,
2751 IntrinsicInst &II) {
2752 // The SIMD&FP variant of CLAST[AB] is significantly faster than the scalar
2753 // integer variant across a variety of micro-architectures. Replace scalar
2754 // integer CLAST[AB] intrinsic with optimal SIMD&FP variant. A simple
2755 // bitcast-to-fp + clast[ab] + bitcast-to-int will cost a cycle or two more
2756 // depending on the micro-architecture, but has been observed as generally
2757 // being faster, particularly when the CLAST[AB] op is a loop-carried
2758 // dependency.
2759 Value *Pg = II.getArgOperand(0);
2760 Value *Fallback = II.getArgOperand(1);
2761 Value *Vec = II.getArgOperand(2);
2762 Type *Ty = II.getType();
2763
2764 if (!Ty->isIntegerTy())
2765 return std::nullopt;
2766
2767 Type *FPTy;
2768 switch (cast<IntegerType>(Ty)->getBitWidth()) {
2769 default:
2770 return std::nullopt;
2771 case 16:
2772 FPTy = IC.Builder.getHalfTy();
2773 break;
2774 case 32:
2775 FPTy = IC.Builder.getFloatTy();
2776 break;
2777 case 64:
2778 FPTy = IC.Builder.getDoubleTy();
2779 break;
2780 }
2781
2782 Value *FPFallBack = IC.Builder.CreateBitCast(Fallback, FPTy);
2783 auto *FPVTy = VectorType::get(
2784 FPTy, cast<VectorType>(Vec->getType())->getElementCount());
2785 Value *FPVec = IC.Builder.CreateBitCast(Vec, FPVTy);
2786 auto *FPII = IC.Builder.CreateIntrinsic(
2787 II.getIntrinsicID(), {FPVec->getType()}, {Pg, FPFallBack, FPVec});
2788 Value *FPIItoInt = IC.Builder.CreateBitCast(FPII, II.getType());
2789 return IC.replaceInstUsesWith(II, FPIItoInt);
2790}
2791
2792static std::optional<Instruction *> instCombineRDFFR(InstCombiner &IC,
2793 IntrinsicInst &II) {
2794 // Replace rdffr with predicated rdffr.z intrinsic, so that optimizePTestInstr
2795 // can work with RDFFR_PP for ptest elimination.
2796 auto *RDFFR = IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_rdffr_z,
2797 ConstantInt::getTrue(II.getType()));
2798 RDFFR->takeName(&II);
2799 return IC.replaceInstUsesWith(II, RDFFR);
2800}
2801
2802static std::optional<Instruction *>
2804 const auto Pattern = cast<ConstantInt>(II.getArgOperand(0))->getZExtValue();
2805
2806 if (Pattern == AArch64SVEPredPattern::all) {
2808 II.getType(), ElementCount::getScalable(NumElts));
2809 Cnt->takeName(&II);
2810 return IC.replaceInstUsesWith(II, Cnt);
2811 }
2812
2813 unsigned MinNumElts = getNumElementsFromSVEPredPattern(Pattern);
2814
2815 return MinNumElts && NumElts >= MinNumElts
2816 ? std::optional<Instruction *>(IC.replaceInstUsesWith(
2817 II, ConstantInt::get(II.getType(), MinNumElts)))
2818 : std::nullopt;
2819}
2820
2821static std::optional<Instruction *>
2823 const AArch64Subtarget *ST) {
2824 if (!ST->isStreaming())
2825 return std::nullopt;
2826
2827 // In streaming-mode, aarch64_sme_cntds is equivalent to aarch64_sve_cntd
2828 // with SVEPredPattern::all
2829 Value *Cnt =
2831 Cnt->takeName(&II);
2832 return IC.replaceInstUsesWith(II, Cnt);
2833}
2834
2835static std::optional<Instruction *> instCombineSVEPTest(InstCombiner &IC,
2836 IntrinsicInst &II) {
2837 Value *PgVal = II.getArgOperand(0);
2838 Value *OpVal = II.getArgOperand(1);
2839
2840 // PTEST_<FIRST|LAST>(X, X) is equivalent to PTEST_ANY(X, X).
2841 // Later optimizations prefer this form.
2842 if (PgVal == OpVal &&
2843 (II.getIntrinsicID() == Intrinsic::aarch64_sve_ptest_first ||
2844 II.getIntrinsicID() == Intrinsic::aarch64_sve_ptest_last)) {
2845 Value *Ops[] = {PgVal, OpVal};
2846 Type *Tys[] = {PgVal->getType()};
2847
2848 auto *PTest =
2849 IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptest_any, Tys, Ops);
2850 PTest->takeName(&II);
2851
2852 return IC.replaceInstUsesWith(II, PTest);
2853 }
2854
2857
2858 if (!Pg || !Op)
2859 return std::nullopt;
2860
2861 Intrinsic::ID OpIID = Op->getIntrinsicID();
2862
2863 if (Pg->getIntrinsicID() == Intrinsic::aarch64_sve_convert_to_svbool &&
2864 OpIID == Intrinsic::aarch64_sve_convert_to_svbool &&
2865 Pg->getArgOperand(0)->getType() == Op->getArgOperand(0)->getType()) {
2866 Value *Ops[] = {Pg->getArgOperand(0), Op->getArgOperand(0)};
2867 Type *Tys[] = {Pg->getArgOperand(0)->getType()};
2868
2869 auto *PTest = IC.Builder.CreateIntrinsic(II.getIntrinsicID(), Tys, Ops);
2870
2871 PTest->takeName(&II);
2872 return IC.replaceInstUsesWith(II, PTest);
2873 }
2874
2875 // Transform PTEST_ANY(X=OP(PG,...), X) -> PTEST_ANY(PG, X)).
2876 // Later optimizations may rewrite sequence to use the flag-setting variant
2877 // of instruction X to remove PTEST.
2878 if ((Pg == Op) && (II.getIntrinsicID() == Intrinsic::aarch64_sve_ptest_any) &&
2879 ((OpIID == Intrinsic::aarch64_sve_brka_z) ||
2880 (OpIID == Intrinsic::aarch64_sve_brkb_z) ||
2881 (OpIID == Intrinsic::aarch64_sve_brkpa_z) ||
2882 (OpIID == Intrinsic::aarch64_sve_brkpb_z) ||
2883 (OpIID == Intrinsic::aarch64_sve_rdffr_z) ||
2884 (OpIID == Intrinsic::aarch64_sve_and_z) ||
2885 (OpIID == Intrinsic::aarch64_sve_bic_z) ||
2886 (OpIID == Intrinsic::aarch64_sve_eor_z) ||
2887 (OpIID == Intrinsic::aarch64_sve_nand_z) ||
2888 (OpIID == Intrinsic::aarch64_sve_nor_z) ||
2889 (OpIID == Intrinsic::aarch64_sve_orn_z) ||
2890 (OpIID == Intrinsic::aarch64_sve_orr_z))) {
2891 Value *Ops[] = {Pg->getArgOperand(0), Pg};
2892 Type *Tys[] = {Pg->getType()};
2893
2894 auto *PTest = IC.Builder.CreateIntrinsic(II.getIntrinsicID(), Tys, Ops);
2895 PTest->takeName(&II);
2896
2897 return IC.replaceInstUsesWith(II, PTest);
2898 }
2899
2900 return std::nullopt;
2901}
2902
2903template <Intrinsic::ID MulOpc, Intrinsic::ID FuseOpc>
2904static std::optional<Instruction *>
2906 bool MergeIntoAddendOp) {
2907 Value *P = II.getOperand(0);
2908 Value *MulOp0, *MulOp1, *AddendOp, *Mul;
2909 if (MergeIntoAddendOp) {
2910 AddendOp = II.getOperand(1);
2911 Mul = II.getOperand(2);
2912 } else {
2913 AddendOp = II.getOperand(2);
2914 Mul = II.getOperand(1);
2915 }
2916
2918 m_Value(MulOp1))))
2919 return std::nullopt;
2920
2921 if (!Mul->hasOneUse())
2922 return std::nullopt;
2923
2924 Instruction *FMFSource = nullptr;
2925 if (II.getType()->isFPOrFPVectorTy()) {
2926 llvm::FastMathFlags FAddFlags = II.getFastMathFlags();
2927 // Stop the combine when the flags on the inputs differ in case dropping
2928 // flags would lead to us missing out on more beneficial optimizations.
2929 if (FAddFlags != cast<CallInst>(Mul)->getFastMathFlags())
2930 return std::nullopt;
2931 if (!FAddFlags.allowContract())
2932 return std::nullopt;
2933 FMFSource = &II;
2934 }
2935
2936 Value *Res;
2937 if (MergeIntoAddendOp)
2938 Res = IC.Builder.CreateIntrinsic(FuseOpc, {II.getType()},
2939 {P, AddendOp, MulOp0, MulOp1}, FMFSource);
2940 else
2941 Res = IC.Builder.CreateIntrinsic(FuseOpc, {II.getType()},
2942 {P, MulOp0, MulOp1, AddendOp}, FMFSource);
2943
2944 return IC.replaceInstUsesWith(II, Res);
2945}
2946
2947static std::optional<Instruction *>
2949 Value *Pred = II.getOperand(0);
2950 Value *PtrOp = II.getOperand(1);
2951 Type *VecTy = II.getType();
2952
2954 LoadInst *Load = IC.Builder.CreateLoad(VecTy, PtrOp);
2955 Load->copyMetadata(II);
2956 return IC.replaceInstUsesWith(II, Load);
2957 }
2958
2959 CallInst *MaskedLoad =
2960 IC.Builder.CreateMaskedLoad(VecTy, PtrOp, PtrOp->getPointerAlignment(DL),
2962 MaskedLoad->copyMetadata(II);
2963 return IC.replaceInstUsesWith(II, MaskedLoad);
2964}
2965
2966static std::optional<Instruction *>
2968 Value *VecOp = II.getOperand(0);
2969 Value *Pred = II.getOperand(1);
2970 Value *PtrOp = II.getOperand(2);
2971
2973 StoreInst *Store = IC.Builder.CreateStore(VecOp, PtrOp);
2974 Store->copyMetadata(II);
2975 return IC.eraseInstFromFunction(II);
2976 }
2977
2978 CallInst *MaskedStore = IC.Builder.CreateMaskedStore(
2979 VecOp, PtrOp, PtrOp->getPointerAlignment(DL), Pred);
2980 MaskedStore->copyMetadata(II);
2981 return IC.eraseInstFromFunction(II);
2982}
2983
2985 switch (Intrinsic) {
2986 case Intrinsic::aarch64_sve_fmul_u:
2987 return Instruction::BinaryOps::FMul;
2988 case Intrinsic::aarch64_sve_fadd_u:
2989 return Instruction::BinaryOps::FAdd;
2990 case Intrinsic::aarch64_sve_fsub_u:
2991 return Instruction::BinaryOps::FSub;
2992 default:
2993 return Instruction::BinaryOpsEnd;
2994 }
2995}
2996
2997static std::optional<Instruction *>
2999 // Bail due to missing support for ISD::STRICT_ scalable vector operations.
3000 if (II.isStrictFP())
3001 return std::nullopt;
3002
3003 auto *OpPredicate = II.getOperand(0);
3004 auto BinOpCode = intrinsicIDToBinOpCode(II.getIntrinsicID());
3005 if (BinOpCode == Instruction::BinaryOpsEnd ||
3006 !isAllActivePredicate(OpPredicate))
3007 return std::nullopt;
3008 auto BinOp = IC.Builder.CreateBinOpFMF(
3009 BinOpCode, II.getOperand(1), II.getOperand(2), II.getFastMathFlags());
3010 return IC.replaceInstUsesWith(II, BinOp);
3011}
3012
3013static std::optional<Instruction *>
3015 assert(II.getIntrinsicID() == Intrinsic::aarch64_sve_mla_u &&
3016 "Expected MLA_U intrinsic");
3017 Value *Acc = II.getArgOperand(1);
3018 Value *MulOp0 = II.getArgOperand(2);
3019 Value *MulOp1 = II.getArgOperand(3);
3020
3021 // For mla_u, inactive lanes are undefined, so it is valid to drop the
3022 // predicate when replacing mla_u(acc, x, 1) with add(acc, x) or
3023 // mla_u(acc, x, -1) with sub(acc, x).
3024 if (match(MulOp0, m_One()))
3025 return IC.replaceInstUsesWith(II, IC.Builder.CreateAdd(Acc, MulOp1));
3026 if (match(MulOp1, m_One()))
3027 return IC.replaceInstUsesWith(II, IC.Builder.CreateAdd(Acc, MulOp0));
3028 if (match(MulOp0, m_AllOnes()))
3029 return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Acc, MulOp1));
3030 if (match(MulOp1, m_AllOnes()))
3031 return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Acc, MulOp0));
3032
3033 if (isa<Constant>(MulOp0) && !isa<Constant>(MulOp1)) {
3034 II.setArgOperand(2, MulOp1);
3035 II.setArgOperand(3, MulOp0);
3036 return &II;
3037 }
3038
3039 return std::nullopt;
3040}
3041
3042static std::optional<Instruction *>
3044 assert((II.getIntrinsicID() == Intrinsic::aarch64_sve_sadalp ||
3045 II.getIntrinsicID() == Intrinsic::aarch64_sve_uadalp) &&
3046 "Expected SADALP or UADALP intrinsic");
3047
3048 // Simplify add(adalp(pg, zeroinitializer, in), wide_acc)
3049 // -> adalp(pg, wide_acc, in)
3050 auto *User = dyn_cast_or_null<Instruction>(II.getUniqueUndroppableUser());
3051 if (!User || !match(II.getArgOperand(1), m_Zero()))
3052 return std::nullopt;
3053
3054 Value *Acc;
3055 if (!match(User, m_c_Add(m_Specific(&II), m_Value(Acc))))
3056 return std::nullopt;
3057
3059 Value *PairwiseAddLong = IC.Builder.CreateIntrinsic(
3060 II.getIntrinsicID(), {II.getType()},
3061 {II.getArgOperand(0), Acc, II.getArgOperand(2)});
3062
3063 IC.replaceInstUsesWith(*User, PairwiseAddLong);
3065 return &II; // II is now trivially dead and will get erased.
3066}
3067
3068static std::optional<Instruction *> instCombineSVEVectorAdd(InstCombiner &IC,
3069 IntrinsicInst &II) {
3070 if (auto MLA = instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_mul,
3071 Intrinsic::aarch64_sve_mla>(
3072 IC, II, true))
3073 return MLA;
3074 if (auto MAD = instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_mul,
3075 Intrinsic::aarch64_sve_mad>(
3076 IC, II, false))
3077 return MAD;
3078 return std::nullopt;
3079}
3080
3081static std::optional<Instruction *>
3083 if (auto FMLA =
3084 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
3085 Intrinsic::aarch64_sve_fmla>(IC, II,
3086 true))
3087 return FMLA;
3088 if (auto FMAD =
3089 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
3090 Intrinsic::aarch64_sve_fmad>(IC, II,
3091 false))
3092 return FMAD;
3093 if (auto FMLA =
3094 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul_u,
3095 Intrinsic::aarch64_sve_fmla>(IC, II,
3096 true))
3097 return FMLA;
3098 return std::nullopt;
3099}
3100
3101static std::optional<Instruction *>
3103 if (auto FMLA =
3104 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
3105 Intrinsic::aarch64_sve_fmla>(IC, II,
3106 true))
3107 return FMLA;
3108 if (auto FMAD =
3109 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
3110 Intrinsic::aarch64_sve_fmad>(IC, II,
3111 false))
3112 return FMAD;
3113 if (auto FMLA_U =
3114 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul_u,
3115 Intrinsic::aarch64_sve_fmla_u>(
3116 IC, II, true))
3117 return FMLA_U;
3118 return instCombineSVEVectorBinOp(IC, II);
3119}
3120
3121static std::optional<Instruction *>
3123 if (auto FMLS =
3124 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
3125 Intrinsic::aarch64_sve_fmls>(IC, II,
3126 true))
3127 return FMLS;
3128 if (auto FMSB =
3129 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
3130 Intrinsic::aarch64_sve_fnmsb>(
3131 IC, II, false))
3132 return FMSB;
3133 if (auto FMLS =
3134 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul_u,
3135 Intrinsic::aarch64_sve_fmls>(IC, II,
3136 true))
3137 return FMLS;
3138 return std::nullopt;
3139}
3140
3141static std::optional<Instruction *>
3143 if (auto FMLS =
3144 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
3145 Intrinsic::aarch64_sve_fmls>(IC, II,
3146 true))
3147 return FMLS;
3148 if (auto FMSB =
3149 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
3150 Intrinsic::aarch64_sve_fnmsb>(
3151 IC, II, false))
3152 return FMSB;
3153 if (auto FMLS_U =
3154 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul_u,
3155 Intrinsic::aarch64_sve_fmls_u>(
3156 IC, II, true))
3157 return FMLS_U;
3158 return instCombineSVEVectorBinOp(IC, II);
3159}
3160
3161static std::optional<Instruction *> instCombineSVEVectorSub(InstCombiner &IC,
3162 IntrinsicInst &II) {
3163 if (auto MLS = instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_mul,
3164 Intrinsic::aarch64_sve_mls>(
3165 IC, II, true))
3166 return MLS;
3167 return std::nullopt;
3168}
3169
3170static std::optional<Instruction *> instCombineSVEUnpack(InstCombiner &IC,
3171 IntrinsicInst &II) {
3172 Value *UnpackArg = II.getArgOperand(0);
3173 auto *RetTy = cast<ScalableVectorType>(II.getType());
3174 bool IsSigned = II.getIntrinsicID() == Intrinsic::aarch64_sve_sunpkhi ||
3175 II.getIntrinsicID() == Intrinsic::aarch64_sve_sunpklo;
3176
3177 // Hi = uunpkhi(splat(X)) --> Hi = splat(extend(X))
3178 // Lo = uunpklo(splat(X)) --> Lo = splat(extend(X))
3179 if (auto *ScalarArg = getSplatValue(UnpackArg)) {
3180 ScalarArg =
3181 IC.Builder.CreateIntCast(ScalarArg, RetTy->getScalarType(), IsSigned);
3182 Value *NewVal =
3183 IC.Builder.CreateVectorSplat(RetTy->getElementCount(), ScalarArg);
3184 NewVal->takeName(&II);
3185 return IC.replaceInstUsesWith(II, NewVal);
3186 }
3187
3188 return std::nullopt;
3189}
3190static std::optional<Instruction *> instCombineSVETBL(InstCombiner &IC,
3191 IntrinsicInst &II) {
3192 auto *OpVal = II.getOperand(0);
3193 auto *OpIndices = II.getOperand(1);
3194 VectorType *VTy = cast<VectorType>(II.getType());
3195
3196 // Check whether OpIndices is a constant splat value < minimal element count
3197 // of result.
3198 auto *SplatValue = dyn_cast_or_null<ConstantInt>(getSplatValue(OpIndices));
3199 if (!SplatValue ||
3200 SplatValue->getValue().uge(VTy->getElementCount().getKnownMinValue()))
3201 return std::nullopt;
3202
3203 // Convert sve_tbl(OpVal sve_dup_x(SplatValue)) to
3204 // splat_vector(extractelement(OpVal, SplatValue)) for further optimization.
3205 auto *Extract = IC.Builder.CreateExtractElement(OpVal, SplatValue);
3206 auto *VectorSplat =
3207 IC.Builder.CreateVectorSplat(VTy->getElementCount(), Extract);
3208
3209 VectorSplat->takeName(&II);
3210 return IC.replaceInstUsesWith(II, VectorSplat);
3211}
3212
3213static std::optional<Instruction *> instCombineSVEUzp1(InstCombiner &IC,
3214 IntrinsicInst &II) {
3215 Value *A, *B;
3216 Type *RetTy = II.getType();
3217 constexpr Intrinsic::ID FromSVB = Intrinsic::aarch64_sve_convert_from_svbool;
3218 constexpr Intrinsic::ID ToSVB = Intrinsic::aarch64_sve_convert_to_svbool;
3219
3220 // uzp1(to_svbool(A), to_svbool(B)) --> <A, B>
3221 // uzp1(from_svbool(to_svbool(A)), from_svbool(to_svbool(B))) --> <A, B>
3222 if ((match(II.getArgOperand(0),
3224 match(II.getArgOperand(1),
3226 (match(II.getArgOperand(0), m_Intrinsic<ToSVB>(m_Value(A))) &&
3227 match(II.getArgOperand(1), m_Intrinsic<ToSVB>(m_Value(B))))) {
3228 auto *TyA = cast<ScalableVectorType>(A->getType());
3229 if (TyA == B->getType() &&
3231 auto *SubVec = IC.Builder.CreateInsertVector(
3232 RetTy, PoisonValue::get(RetTy), A, uint64_t(0));
3233 auto *ConcatVec = IC.Builder.CreateInsertVector(RetTy, SubVec, B,
3234 TyA->getMinNumElements());
3235 ConcatVec->takeName(&II);
3236 return IC.replaceInstUsesWith(II, ConcatVec);
3237 }
3238 }
3239
3240 return std::nullopt;
3241}
3242
3243static std::optional<Instruction *> instCombineSVEZip(InstCombiner &IC,
3244 IntrinsicInst &II) {
3245 // zip1(uzp1(A, B), uzp2(A, B)) --> A
3246 // zip2(uzp1(A, B), uzp2(A, B)) --> B
3247 Value *A, *B;
3248 if (match(II.getArgOperand(0),
3251 m_Specific(A), m_Specific(B))))
3252 return IC.replaceInstUsesWith(
3253 II, (II.getIntrinsicID() == Intrinsic::aarch64_sve_zip1 ? A : B));
3254
3255 return std::nullopt;
3256}
3257
3258static std::optional<Instruction *>
3260 Value *Mask = II.getOperand(0);
3261 Value *BasePtr = II.getOperand(1);
3262 Value *Index = II.getOperand(2);
3263 Type *Ty = II.getType();
3264 Value *PassThru = ConstantAggregateZero::get(Ty);
3265
3266 // Contiguous gather => masked load.
3267 // (sve.ld1.gather.index Mask BasePtr (sve.index IndexBase 1))
3268 // => (masked.load (gep BasePtr IndexBase) Align Mask zeroinitializer)
3269 Value *IndexBase;
3271 m_One()))) {
3272 Align Alignment =
3273 BasePtr->getPointerAlignment(II.getDataLayout());
3274
3275 Value *Ptr = IC.Builder.CreateGEP(cast<VectorType>(Ty)->getElementType(),
3276 BasePtr, IndexBase);
3277 CallInst *MaskedLoad =
3278 IC.Builder.CreateMaskedLoad(Ty, Ptr, Alignment, Mask, PassThru);
3279 MaskedLoad->takeName(&II);
3280 return IC.replaceInstUsesWith(II, MaskedLoad);
3281 }
3282
3283 return std::nullopt;
3284}
3285
3286static std::optional<Instruction *>
3288 Value *Val = II.getOperand(0);
3289 Value *Mask = II.getOperand(1);
3290 Value *BasePtr = II.getOperand(2);
3291 Value *Index = II.getOperand(3);
3292 Type *Ty = Val->getType();
3293
3294 // Contiguous scatter => masked store.
3295 // (sve.st1.scatter.index Value Mask BasePtr (sve.index IndexBase 1))
3296 // => (masked.store Value (gep BasePtr IndexBase) Align Mask)
3297 Value *IndexBase;
3299 m_One()))) {
3300 Align Alignment =
3301 BasePtr->getPointerAlignment(II.getDataLayout());
3302
3303 Value *Ptr = IC.Builder.CreateGEP(cast<VectorType>(Ty)->getElementType(),
3304 BasePtr, IndexBase);
3305 (void)IC.Builder.CreateMaskedStore(Val, Ptr, Alignment, Mask);
3306
3307 return IC.eraseInstFromFunction(II);
3308 }
3309
3310 return std::nullopt;
3311}
3312
3313static std::optional<Instruction *> instCombineSVESDIV(InstCombiner &IC,
3314 IntrinsicInst &II) {
3315 Type *Int32Ty = IC.Builder.getInt32Ty();
3316 Value *Pred = II.getOperand(0);
3317 Value *Vec = II.getOperand(1);
3318 Value *DivVec = II.getOperand(2);
3319
3320 Value *SplatValue = getSplatValue(DivVec);
3321 ConstantInt *SplatConstantInt = dyn_cast_or_null<ConstantInt>(SplatValue);
3322 if (!SplatConstantInt)
3323 return std::nullopt;
3324
3325 APInt Divisor = SplatConstantInt->getValue();
3326 const int64_t DivisorValue = Divisor.getSExtValue();
3327 if (DivisorValue == -1)
3328 return std::nullopt;
3329 if (DivisorValue == 1)
3330 IC.replaceInstUsesWith(II, Vec);
3331
3332 if (Divisor.isPowerOf2()) {
3333 Constant *DivisorLog2 = ConstantInt::get(Int32Ty, Divisor.logBase2());
3334 auto ASRD = IC.Builder.CreateIntrinsic(
3335 Intrinsic::aarch64_sve_asrd, {II.getType()}, {Pred, Vec, DivisorLog2});
3336 return IC.replaceInstUsesWith(II, ASRD);
3337 }
3338 if (Divisor.isNegatedPowerOf2()) {
3339 Divisor.negate();
3340 Constant *DivisorLog2 = ConstantInt::get(Int32Ty, Divisor.logBase2());
3341 auto ASRD = IC.Builder.CreateIntrinsic(
3342 Intrinsic::aarch64_sve_asrd, {II.getType()}, {Pred, Vec, DivisorLog2});
3343 auto NEG = IC.Builder.CreateIntrinsic(
3344 Intrinsic::aarch64_sve_neg, {ASRD->getType()}, {ASRD, Pred, ASRD});
3345 return IC.replaceInstUsesWith(II, NEG);
3346 }
3347
3348 return std::nullopt;
3349}
3350
3351/// Match Or(And(MASK, A), And(Not(MASK), B)), which ISel selects as
3352/// BSL/BIT/BIF. Both Ands must have one use and be in the Or's block. MainAnd,
3353///
3354/// OtherAnd, A and B are out parameters with the corresponding instructions.
3355/// MainAnd refers to And that has Not as one of its operands.
3356static bool matchBSL(const Instruction *I, Instruction *&MainAnd,
3357 Instruction *&OtherAnd, Value *&A, Value *&B) {
3358 Value *MaskValue;
3359 if (!match(I,
3360 m_c_Or(m_OneUse(m_Instruction(OtherAnd)),
3361 m_OneUse(m_c_And(m_Not(m_Value(MaskValue)), m_Value(A))))))
3362 return false;
3363
3364 if (!match(OtherAnd, m_c_And(m_Specific(MaskValue), m_Value(B))))
3365 return false;
3366
3367 MainAnd = I->getOperand(0) == OtherAnd ? cast<Instruction>(I->getOperand(1))
3368 : cast<Instruction>(I->getOperand(0));
3369
3370 // Both Ands should be in same basic block as Or
3371 if (I->getParent() != MainAnd->getParent() ||
3372 I->getParent() != OtherAnd->getParent())
3373 return false;
3374
3375 return true;
3376}
3377
3378bool SimplifyValuePattern(SmallVector<Value *> &Vec, bool AllowPoison) {
3379 size_t VecSize = Vec.size();
3380 if (VecSize == 1)
3381 return true;
3382 if (!isPowerOf2_64(VecSize))
3383 return false;
3384 size_t HalfVecSize = VecSize / 2;
3385
3386 for (auto LHS = Vec.begin(), RHS = Vec.begin() + HalfVecSize;
3387 RHS != Vec.end(); LHS++, RHS++) {
3388 if (*LHS != nullptr && *RHS != nullptr) {
3389 if (*LHS == *RHS)
3390 continue;
3391 else
3392 return false;
3393 }
3394 if (!AllowPoison)
3395 return false;
3396 if (*LHS == nullptr && *RHS != nullptr)
3397 *LHS = *RHS;
3398 }
3399
3400 Vec.resize(HalfVecSize);
3401 SimplifyValuePattern(Vec, AllowPoison);
3402 return true;
3403}
3404
3405// Try to simplify dupqlane patterns like dupqlane(f32 A, f32 B, f32 A, f32 B)
3406// to dupqlane(f64(C)) where C is A concatenated with B
3407static std::optional<Instruction *> instCombineSVEDupqLane(InstCombiner &IC,
3408 IntrinsicInst &II) {
3409 // An out-of-range index generates an all zero result. This means only an
3410 // index of zero has the same defined result across all vector lengths.
3411 if (!match(II.getOperand(1), m_Zero()))
3412 return std::nullopt;
3413
3414 Value *CurrentInsertElt = nullptr, *Default = nullptr;
3415 if (!match(II.getOperand(0),
3417 m_Value(Default), m_Value(CurrentInsertElt), m_Zero())) ||
3418 !isa<FixedVectorType>(CurrentInsertElt->getType()))
3419 return std::nullopt;
3420 auto IIScalableTy = cast<ScalableVectorType>(II.getType());
3421
3422 // Insert the scalars into a container ordered by InsertElement index
3423 SmallVector<Value *> Elts(IIScalableTy->getMinNumElements(), nullptr);
3424 while (auto InsertElt = dyn_cast<InsertElementInst>(CurrentInsertElt)) {
3425 auto Idx = cast<ConstantInt>(InsertElt->getOperand(2));
3426 Elts[Idx->getValue().getZExtValue()] = InsertElt->getOperand(1);
3427 CurrentInsertElt = InsertElt->getOperand(0);
3428 }
3429
3430 bool AllowPoison =
3431 isa<PoisonValue>(CurrentInsertElt) && isa<PoisonValue>(Default);
3432 if (!SimplifyValuePattern(Elts, AllowPoison))
3433 return std::nullopt;
3434
3435 // Rebuild the simplified chain of InsertElements. e.g. (a, b, a, b) as (a, b)
3436 Value *InsertEltChain = PoisonValue::get(CurrentInsertElt->getType());
3437 for (size_t I = 0; I < Elts.size(); I++) {
3438 if (Elts[I] == nullptr)
3439 continue;
3440 InsertEltChain = IC.Builder.CreateInsertElement(InsertEltChain, Elts[I],
3441 IC.Builder.getInt64(I));
3442 }
3443 if (InsertEltChain == nullptr)
3444 return std::nullopt;
3445
3446 // Splat the simplified sequence, e.g. (f16 a, f16 b, f16 c, f16 d) as one i64
3447 // value or (f16 a, f16 b) as one i32 value. This requires an InsertSubvector
3448 // be bitcast to a type wide enough to fit the sequence, be splatted, and then
3449 // be narrowed back to the original type.
3450 unsigned PatternWidth = IIScalableTy->getScalarSizeInBits() * Elts.size();
3451 unsigned PatternElementCount = IIScalableTy->getScalarSizeInBits() *
3452 IIScalableTy->getMinNumElements() /
3453 PatternWidth;
3454
3455 IntegerType *WideTy = IC.Builder.getIntNTy(PatternWidth);
3456 auto *WideScalableTy = ScalableVectorType::get(WideTy, PatternElementCount);
3457 auto *WideShuffleMaskTy =
3458 ScalableVectorType::get(IC.Builder.getInt32Ty(), PatternElementCount);
3459
3460 auto InsertSubvector = IC.Builder.CreateInsertVector(
3461 II.getType(), PoisonValue::get(II.getType()), InsertEltChain,
3462 uint64_t(0));
3463 auto WideBitcast =
3464 IC.Builder.CreateBitOrPointerCast(InsertSubvector, WideScalableTy);
3465 auto WideShuffleMask = ConstantAggregateZero::get(WideShuffleMaskTy);
3466 auto WideShuffle = IC.Builder.CreateShuffleVector(
3467 WideBitcast, PoisonValue::get(WideScalableTy), WideShuffleMask);
3468 auto NarrowBitcast =
3469 IC.Builder.CreateBitOrPointerCast(WideShuffle, II.getType());
3470
3471 return IC.replaceInstUsesWith(II, NarrowBitcast);
3472}
3473
3474static std::optional<Instruction *> instCombineMaxMinNM(InstCombiner &IC,
3475 IntrinsicInst &II) {
3476 Value *A = II.getArgOperand(0);
3477 Value *B = II.getArgOperand(1);
3478 if (A == B)
3479 return IC.replaceInstUsesWith(II, A);
3480
3481 return std::nullopt;
3482}
3483
3484static std::optional<Instruction *> instCombineSVESrshl(InstCombiner &IC,
3485 IntrinsicInst &II) {
3486 Value *Pred = II.getOperand(0);
3487 Value *Vec = II.getOperand(1);
3488 Value *Shift = II.getOperand(2);
3489
3490 // Convert SRSHL into the simpler LSL intrinsic when fed by an ABS intrinsic.
3491 Value *AbsPred, *MergedValue;
3493 m_Value(MergedValue), m_Value(AbsPred), m_Value())) &&
3495 m_Value(MergedValue), m_Value(AbsPred), m_Value())))
3496
3497 return std::nullopt;
3498
3499 // Transform is valid if any of the following are true:
3500 // * The ABS merge value is an undef or non-negative
3501 // * The ABS predicate is all active
3502 // * The ABS predicate and the SRSHL predicates are the same
3503 if (!isa<UndefValue>(MergedValue) && !match(MergedValue, m_NonNegative()) &&
3504 AbsPred != Pred && !isAllActivePredicate(AbsPred))
3505 return std::nullopt;
3506
3507 // Only valid when the shift amount is non-negative, otherwise the rounding
3508 // behaviour of SRSHL cannot be ignored.
3509 if (!match(Shift, m_NonNegative()))
3510 return std::nullopt;
3511
3512 auto LSL = IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_lsl,
3513 {II.getType()}, {Pred, Vec, Shift});
3514
3515 return IC.replaceInstUsesWith(II, LSL);
3516}
3517
3518static std::optional<Instruction *> instCombineSVEInsr(InstCombiner &IC,
3519 IntrinsicInst &II) {
3520 Value *Vec = II.getOperand(0);
3521
3522 if (getSplatValue(Vec) == II.getOperand(1))
3523 return IC.replaceInstUsesWith(II, Vec);
3524
3525 return std::nullopt;
3526}
3527
3528static std::optional<Instruction *>
3530 unsigned LookaheadThreshold) {
3531 // If this barrier is post-dominated by identical one we can remove it
3532 auto *NI = II.getNextNode();
3533 auto CanSkipOver = [](Instruction *I) {
3534 return !I->mayReadOrWriteMemory() && !I->mayHaveSideEffects();
3535 };
3536 while (LookaheadThreshold-- && CanSkipOver(NI)) {
3537 auto *NIBB = NI->getParent();
3538 NI = NI->getNextNode();
3539 if (!NI) {
3540 if (auto *SuccBB = NIBB->getUniqueSuccessor())
3541 NI = &*SuccBB->getFirstNonPHIOrLifetime();
3542 else
3543 break;
3544 }
3545 }
3546 auto *NextII = dyn_cast_or_null<IntrinsicInst>(NI);
3547 if (NextII && II.isIdenticalTo(NextII))
3548 return IC.eraseInstFromFunction(II);
3549
3550 return std::nullopt;
3551}
3552
3553static std::optional<Instruction *> instCombineWhilelo(InstCombiner &IC,
3554 IntrinsicInst &II) {
3555 return IC.replaceInstUsesWith(
3556 II,
3557 IC.Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
3558 {II.getType(), II.getOperand(0)->getType()},
3559 {II.getOperand(0), II.getOperand(1)}));
3560}
3561
3562static std::optional<Instruction *> instCombinePTrue(InstCombiner &IC,
3563 IntrinsicInst &II) {
3564 unsigned PredPattern = cast<ConstantInt>(II.getOperand(0))->getZExtValue();
3565 // SVE vector length is a power-of-two, thus pow2 is synonymous with all.
3566 if (PredPattern == AArch64SVEPredPattern::all ||
3567 PredPattern == AArch64SVEPredPattern::pow2)
3568 return IC.replaceInstUsesWith(II, ConstantInt::getTrue(II.getType()));
3569 return std::nullopt;
3570}
3571
3572static std::optional<Instruction *> instCombineSVEUxt(InstCombiner &IC,
3574 unsigned NumBits) {
3575 Value *Passthru = II.getOperand(0);
3576 Value *Pg = II.getOperand(1);
3577 Value *Op = II.getOperand(2);
3578
3579 // Convert UXT[BHW] to AND.
3580 if (isa<UndefValue>(Passthru) || isAllActivePredicate(Pg)) {
3581 auto *Ty = cast<VectorType>(II.getType());
3582 auto MaskValue = APInt::getLowBitsSet(Ty->getScalarSizeInBits(), NumBits);
3583 auto *Mask = ConstantInt::get(Ty, MaskValue);
3584 auto *And = IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_and_u, {Ty},
3585 {Pg, Op, Mask});
3586 return IC.replaceInstUsesWith(II, And);
3587 }
3588
3589 return std::nullopt;
3590}
3591
3592static std::optional<Instruction *>
3594 SMEAttrs FnSMEAttrs(*II.getFunction());
3595 bool IsStreaming = FnSMEAttrs.hasStreamingInterfaceOrBody();
3596 if (IsStreaming || !FnSMEAttrs.hasStreamingCompatibleInterface())
3597 return IC.replaceInstUsesWith(
3598 II, ConstantInt::getBool(II.getType(), IsStreaming));
3599 return std::nullopt;
3600}
3601
3602static std::optional<Instruction *> instCombineSVEUMin(InstCombiner &IC,
3603 IntrinsicInst &II) {
3604 // umin(umin(A, 1), umin(B, 1)) -> umin(umin(A,B), 1)
3605 constexpr Intrinsic::ID UMinID = Intrinsic::aarch64_sve_umin_u;
3606 Value *A, *B;
3607 Value *Pg = II.getOperand(0);
3608 if (match(II.getOperand(1), m_OneUse(m_Intrinsic<UMinID>(
3609 m_Specific(Pg), m_Value(A), m_One()))) &&
3610 match(II.getOperand(2), m_OneUse(m_Intrinsic<UMinID>(
3611 m_Specific(Pg), m_Value(B), m_One())))) {
3612 Value *NewUMin =
3613 IC.Builder.CreateIntrinsic(UMinID, II.getType(), {Pg, A, B});
3614 Value *NewLogicalUMin = IC.Builder.CreateIntrinsic(
3615 UMinID, II.getType(), {Pg, NewUMin, ConstantInt::get(II.getType(), 1)});
3616 return IC.replaceInstUsesWith(II, NewLogicalUMin);
3617 }
3618
3619 // umin(umin(A, 1), 1) -> umin(A, 1)
3620 if (match(II.getOperand(1),
3622 match(II.getOperand(2), m_One()))
3623 return IC.replaceInstUsesWith(II, II.getOperand(1));
3624
3625 return std::nullopt;
3626}
3627
3628static std::optional<Instruction *> instCombineSVEOrr(InstCombiner &IC,
3629 IntrinsicInst &II) {
3630 // orr(umin(A, 1), umin(B, 1)) -> umin(orr(A, B), 1)
3631 constexpr Intrinsic::ID UMinID = Intrinsic::aarch64_sve_umin_u;
3632 Value *Pg = II.getOperand(0);
3633
3634 Value *A, *B;
3635 if (!match(II.getOperand(1), m_OneUse(m_Intrinsic<UMinID>(
3636 m_Specific(Pg), m_Value(A), m_One()))) ||
3637 !match(II.getOperand(2), m_OneUse(m_Intrinsic<UMinID>(
3638 m_Specific(Pg), m_Value(B), m_One()))))
3639 return std::nullopt;
3640
3641 Value *NewOrr = IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_orr_u,
3642 II.getType(), {Pg, A, B});
3643 Value *NewUMin = IC.Builder.CreateIntrinsic(
3644 UMinID, II.getType(), {Pg, NewOrr, ConstantInt::get(II.getType(), 1)});
3645 return IC.replaceInstUsesWith(II, NewUMin);
3646}
3647
3648static std::optional<Instruction *> instCombineSVEAnd(InstCombiner &IC,
3649 IntrinsicInst &II) {
3650 // and(cmphs(pg, ConstA, A), cmphs(pg, A, ConstB))
3651 // ->
3652 // cmphs(pg, ConstA - ConstB, sub(pg, A, ConstB))
3653 constexpr Intrinsic::ID CmphsID = Intrinsic::aarch64_sve_cmphs;
3654 Value *Pg = II.getOperand(0);
3655 Value *LHS = II.getOperand(1);
3656 Value *RHS = II.getOperand(2);
3657
3658 Value *A, *PgLHS, *PgRHS;
3659 uint64_t ConstA, ConstB;
3660 if (!match(LHS, m_Intrinsic<CmphsID>(m_Value(PgLHS), m_ConstantInt(ConstA),
3661 m_Value(A))) ||
3663 m_ConstantInt(ConstB))) ||
3664 !LHS->hasOneUser() || !RHS->hasOneUser())
3665 return std::nullopt;
3666
3667 // Always false regardless of predication
3668 if (ConstB > ConstA)
3669 return IC.replaceInstUsesWith(II, Constant::getNullValue(II.getType()));
3670
3671 // The predicate for both CMPHSs must match.
3672 // The predicate for the AND can either be equal to the CMPHS predicates, or
3673 // either of the CMPHS values.
3674 if (PgLHS != PgRHS || (Pg != LHS && Pg != RHS && Pg != PgLHS))
3675 return std::nullopt;
3676
3677 Type *VecTy = A->getType();
3678 Constant *Base = ConstantInt::get(VecTy, ConstB);
3679 Value *Sub = IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_sub_u, VecTy,
3680 {PgLHS, A, Base});
3681 Constant *Limit = ConstantInt::get(VecTy, ConstA - ConstB);
3682 Value *NewCmphs =
3683 IC.Builder.CreateIntrinsic(CmphsID, VecTy, {PgLHS, Limit, Sub});
3684
3685 return IC.replaceInstUsesWith(II, NewCmphs);
3686}
3687
3688std::optional<Instruction *>
3690 IntrinsicInst &II) const {
3692 if (std::optional<Instruction *> I = simplifySVEIntrinsic(IC, II, IInfo))
3693 return I;
3694
3695 Intrinsic::ID IID = II.getIntrinsicID();
3696 switch (IID) {
3697 default:
3698 break;
3699 case Intrinsic::aarch64_dmb:
3700 return instCombineDMB(IC, II, ST->getCLOpts().dmb_lookahead_threshold);
3701 case Intrinsic::aarch64_neon_fmaxnm:
3702 case Intrinsic::aarch64_neon_fminnm:
3703 return instCombineMaxMinNM(IC, II);
3704 case Intrinsic::aarch64_sve_convert_from_svbool:
3705 return instCombineConvertFromSVBool(IC, II);
3706 case Intrinsic::aarch64_sve_dup:
3707 return instCombineSVEDup(IC, II);
3708 case Intrinsic::aarch64_sve_dup_x:
3709 return instCombineSVEDupX(IC, II);
3710 case Intrinsic::aarch64_sve_cmpeq:
3711 case Intrinsic::aarch64_sve_cmpeq_wide:
3712 return instCombineXorSVECmpCC(IC, II);
3713 case Intrinsic::aarch64_sve_cmpne:
3714 case Intrinsic::aarch64_sve_cmpne_wide:
3715 return instCombineSVECmpNE(IC, II);
3716 case Intrinsic::aarch64_sve_rdffr:
3717 return instCombineRDFFR(IC, II);
3718 case Intrinsic::aarch64_sve_lasta:
3719 case Intrinsic::aarch64_sve_lastb:
3720 return instCombineSVELast(IC, II);
3721 case Intrinsic::aarch64_sve_clasta_n:
3722 case Intrinsic::aarch64_sve_clastb_n:
3723 return instCombineSVECondLast(IC, II);
3724 case Intrinsic::aarch64_sve_cntd:
3725 return instCombineSVECntElts(IC, II, 2);
3726 case Intrinsic::aarch64_sve_cntw:
3727 return instCombineSVECntElts(IC, II, 4);
3728 case Intrinsic::aarch64_sve_cnth:
3729 return instCombineSVECntElts(IC, II, 8);
3730 case Intrinsic::aarch64_sve_cntb:
3731 return instCombineSVECntElts(IC, II, 16);
3732 case Intrinsic::aarch64_sme_cntsd:
3733 return instCombineSMECntsd(IC, II, ST);
3734 case Intrinsic::aarch64_sve_ptest_any:
3735 case Intrinsic::aarch64_sve_ptest_first:
3736 case Intrinsic::aarch64_sve_ptest_last:
3737 return instCombineSVEPTest(IC, II);
3738 case Intrinsic::aarch64_sve_fadd:
3739 return instCombineSVEVectorFAdd(IC, II);
3740 case Intrinsic::aarch64_sve_fadd_u:
3741 return instCombineSVEVectorFAddU(IC, II);
3742 case Intrinsic::aarch64_sve_fmul_u:
3743 return instCombineSVEVectorBinOp(IC, II);
3744 case Intrinsic::aarch64_sve_fsub:
3745 return instCombineSVEVectorFSub(IC, II);
3746 case Intrinsic::aarch64_sve_fsub_u:
3747 return instCombineSVEVectorFSubU(IC, II);
3748 case Intrinsic::aarch64_sve_add:
3749 return instCombineSVEVectorAdd(IC, II);
3750 case Intrinsic::aarch64_sve_add_u:
3751 return instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_mul_u,
3752 Intrinsic::aarch64_sve_mla_u>(
3753 IC, II, true);
3754 case Intrinsic::aarch64_sve_mla_u:
3755 return instCombineSVEVectorMlaU(IC, II);
3756 case Intrinsic::aarch64_sve_sadalp:
3757 case Intrinsic::aarch64_sve_uadalp:
3759 case Intrinsic::aarch64_sve_sub:
3760 return instCombineSVEVectorSub(IC, II);
3761 case Intrinsic::aarch64_sve_sub_u:
3762 return instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_mul_u,
3763 Intrinsic::aarch64_sve_mls_u>(
3764 IC, II, true);
3765 case Intrinsic::aarch64_sve_tbl:
3766 return instCombineSVETBL(IC, II);
3767 case Intrinsic::aarch64_sve_uunpkhi:
3768 case Intrinsic::aarch64_sve_uunpklo:
3769 case Intrinsic::aarch64_sve_sunpkhi:
3770 case Intrinsic::aarch64_sve_sunpklo:
3771 return instCombineSVEUnpack(IC, II);
3772 case Intrinsic::aarch64_sve_uzp1:
3773 return instCombineSVEUzp1(IC, II);
3774 case Intrinsic::aarch64_sve_zip1:
3775 case Intrinsic::aarch64_sve_zip2:
3776 return instCombineSVEZip(IC, II);
3777 case Intrinsic::aarch64_sve_ld1_gather_index:
3778 return instCombineLD1GatherIndex(IC, II);
3779 case Intrinsic::aarch64_sve_st1_scatter_index:
3780 return instCombineST1ScatterIndex(IC, II);
3781 case Intrinsic::aarch64_sve_ld1:
3782 return instCombineSVELD1(IC, II, DL);
3783 case Intrinsic::aarch64_sve_st1:
3784 return instCombineSVEST1(IC, II, DL);
3785 case Intrinsic::aarch64_sve_sdiv:
3786 return instCombineSVESDIV(IC, II);
3787 case Intrinsic::aarch64_sve_sel:
3788 return instCombineSVESel(IC, II);
3789 case Intrinsic::aarch64_sve_srshl:
3790 return instCombineSVESrshl(IC, II);
3791 case Intrinsic::aarch64_sve_dupq_lane:
3792 return instCombineSVEDupqLane(IC, II);
3793 case Intrinsic::aarch64_sve_insr:
3794 return instCombineSVEInsr(IC, II);
3795 case Intrinsic::aarch64_sve_whilelo:
3796 return instCombineWhilelo(IC, II);
3797 case Intrinsic::aarch64_sve_ptrue:
3798 return instCombinePTrue(IC, II);
3799 case Intrinsic::aarch64_sve_uxtb:
3800 return instCombineSVEUxt(IC, II, 8);
3801 case Intrinsic::aarch64_sve_uxth:
3802 return instCombineSVEUxt(IC, II, 16);
3803 case Intrinsic::aarch64_sve_uxtw:
3804 return instCombineSVEUxt(IC, II, 32);
3805 case Intrinsic::aarch64_sme_in_streaming_mode:
3806 return instCombineInStreamingMode(IC, II);
3807 case Intrinsic::aarch64_sve_umin_u:
3808 return instCombineSVEUMin(IC, II);
3809 case Intrinsic::aarch64_sve_orr_u:
3810 return instCombineSVEOrr(IC, II);
3811 case Intrinsic::aarch64_sve_and_z:
3812 return instCombineSVEAnd(IC, II);
3813 }
3814
3815 return std::nullopt;
3816}
3817
3819 InstCombiner &IC, IntrinsicInst &II, APInt OrigDemandedElts,
3820 APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3,
3821 std::function<void(Instruction *, unsigned, APInt, APInt &)>
3822 SimplifyAndSetOp) const {
3823 switch (II.getIntrinsicID()) {
3824 default:
3825 break;
3826 case Intrinsic::aarch64_neon_fcvtxn:
3827 case Intrinsic::aarch64_neon_rshrn:
3828 case Intrinsic::aarch64_neon_sqrshrn:
3829 case Intrinsic::aarch64_neon_sqrshrun:
3830 case Intrinsic::aarch64_neon_sqshrn:
3831 case Intrinsic::aarch64_neon_sqshrun:
3832 case Intrinsic::aarch64_neon_sqxtn:
3833 case Intrinsic::aarch64_neon_sqxtun:
3834 case Intrinsic::aarch64_neon_uqrshrn:
3835 case Intrinsic::aarch64_neon_uqshrn:
3836 case Intrinsic::aarch64_neon_uqxtn:
3837 SimplifyAndSetOp(&II, 0, OrigDemandedElts, UndefElts);
3838 break;
3839 }
3840
3841 return std::nullopt;
3842}
3843
3845 return ST->isSVEAvailable() ||
3846 (ST->isSVEorStreamingSVEAvailable() &&
3847 ST->getCLOpts().enable_scalable_autovec_in_streaming_mode);
3848}
3849
3852 switch (K) {
3854 return TypeSize::getFixed(64);
3856 if (ST->useSVEForFixedLengthVectors() &&
3857 (ST->isSVEAvailable() ||
3858 ST->getCLOpts().enable_fixedwidth_autovec_in_streaming_mode))
3859 return TypeSize::getFixed(
3860 std::max(ST->getMinSVEVectorSizeInBits(), 128u));
3861 else if (ST->isNeonAvailable())
3862 return TypeSize::getFixed(128);
3863 else
3864 return TypeSize::getFixed(0);
3866 if (ST->isSVEAvailable() ||
3867 (ST->isSVEorStreamingSVEAvailable() &&
3868 ST->getCLOpts().enable_scalable_autovec_in_streaming_mode))
3869 return TypeSize::getScalable(128);
3870 else
3871 return TypeSize::getScalable(0);
3872 }
3873 llvm_unreachable("Unsupported register kind");
3874}
3875
3876bool AArch64TTIImpl::isSingleExtWideningInstruction(
3877 unsigned Opcode, Type *DstTy, ArrayRef<const Value *> Args,
3878 Type *SrcOverrideTy) const {
3879 // A helper that returns a vector type from the given type. The number of
3880 // elements in type Ty determines the vector width.
3881 auto toVectorTy = [&](Type *ArgTy) {
3882 return VectorType::get(ArgTy->getScalarType(),
3883 cast<VectorType>(DstTy)->getElementCount());
3884 };
3885
3886 // Exit early if DstTy is not a vector type whose elements are one of [i16,
3887 // i32, i64]. SVE doesn't generally have the same set of instructions to
3888 // perform an extend with the add/sub/mul. There are SMULLB style
3889 // instructions, but they operate on top/bottom, requiring some sort of lane
3890 // interleaving to be used with zext/sext.
3891 unsigned DstEltSize = DstTy->getScalarSizeInBits();
3892 if (!useNeonVector(DstTy) || Args.size() != 2 ||
3893 (DstEltSize != 16 && DstEltSize != 32 && DstEltSize != 64))
3894 return false;
3895
3896 Type *SrcTy = SrcOverrideTy;
3897 switch (Opcode) {
3898 case Instruction::Add: // UADDW(2), SADDW(2).
3899 case Instruction::Sub: { // USUBW(2), SSUBW(2).
3900 // The second operand needs to be an extend
3901 if (isa<SExtInst>(Args[1]) || isa<ZExtInst>(Args[1])) {
3902 if (!SrcTy)
3903 SrcTy =
3904 toVectorTy(cast<Instruction>(Args[1])->getOperand(0)->getType());
3905 break;
3906 }
3907
3908 if (Opcode == Instruction::Sub)
3909 return false;
3910
3911 // UADDW(2), SADDW(2) can be commutted.
3912 if (isa<SExtInst>(Args[0]) || isa<ZExtInst>(Args[0])) {
3913 if (!SrcTy)
3914 SrcTy =
3915 toVectorTy(cast<Instruction>(Args[0])->getOperand(0)->getType());
3916 break;
3917 }
3918 return false;
3919 }
3920 default:
3921 return false;
3922 }
3923
3924 // Legalize the destination type and ensure it can be used in a widening
3925 // operation.
3926 auto DstTyL = getTypeLegalizationCost(DstTy);
3927 if (!DstTyL.second.isVector() || DstEltSize != DstTy->getScalarSizeInBits())
3928 return false;
3929
3930 // Legalize the source type and ensure it can be used in a widening
3931 // operation.
3932 assert(SrcTy && "Expected some SrcTy");
3933 auto SrcTyL = getTypeLegalizationCost(SrcTy);
3934 unsigned SrcElTySize = SrcTyL.second.getScalarSizeInBits();
3935 if (!SrcTyL.second.isVector() || SrcElTySize != SrcTy->getScalarSizeInBits())
3936 return false;
3937
3938 // Get the total number of vector elements in the legalized types.
3939 InstructionCost NumDstEls =
3940 DstTyL.first * DstTyL.second.getVectorMinNumElements();
3941 InstructionCost NumSrcEls =
3942 SrcTyL.first * SrcTyL.second.getVectorMinNumElements();
3943
3944 // Return true if the legalized types have the same number of vector elements
3945 // and the destination element type size is twice that of the source type.
3946 return NumDstEls == NumSrcEls && 2 * SrcElTySize == DstEltSize;
3947}
3948
3949Type *AArch64TTIImpl::isBinExtWideningInstruction(unsigned Opcode, Type *DstTy,
3951 Type *SrcOverrideTy) const {
3952 if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
3953 Opcode != Instruction::Mul)
3954 return nullptr;
3955
3956 // Exit early if DstTy is not a vector type whose elements are one of [i16,
3957 // i32, i64]. SVE doesn't generally have the same set of instructions to
3958 // perform an extend with the add/sub/mul. There are SMULLB style
3959 // instructions, but they operate on top/bottom, requiring some sort of lane
3960 // interleaving to be used with zext/sext.
3961 unsigned DstEltSize = DstTy->getScalarSizeInBits();
3962 if (!useNeonVector(DstTy) || Args.size() != 2 ||
3963 (DstEltSize != 16 && DstEltSize != 32 && DstEltSize != 64))
3964 return nullptr;
3965
3966 auto getScalarSizeWithOverride = [&](const Value *V) {
3967 if (SrcOverrideTy)
3968 return SrcOverrideTy->getScalarSizeInBits();
3969 return cast<Instruction>(V)
3970 ->getOperand(0)
3971 ->getType()
3972 ->getScalarSizeInBits();
3973 };
3974
3975 unsigned MaxEltSize = 0;
3976 if ((isa<SExtInst>(Args[0]) && isa<SExtInst>(Args[1])) ||
3977 (isa<ZExtInst>(Args[0]) && isa<ZExtInst>(Args[1]))) {
3978 unsigned EltSize0 = getScalarSizeWithOverride(Args[0]);
3979 unsigned EltSize1 = getScalarSizeWithOverride(Args[1]);
3980 MaxEltSize = std::max(EltSize0, EltSize1);
3981 } else if (isa<SExtInst, ZExtInst>(Args[0]) &&
3982 isa<SExtInst, ZExtInst>(Args[1])) {
3983 unsigned EltSize0 = getScalarSizeWithOverride(Args[0]);
3984 unsigned EltSize1 = getScalarSizeWithOverride(Args[1]);
3985 // mul(sext, zext) will become smull(sext, zext) if the extends are large
3986 // enough.
3987 if (EltSize0 >= DstEltSize / 2 || EltSize1 >= DstEltSize / 2)
3988 return nullptr;
3989 MaxEltSize = DstEltSize / 2;
3990 } else if (Opcode == Instruction::Mul &&
3991 (isa<ZExtInst>(Args[0]) || isa<ZExtInst>(Args[1]))) {
3992 // If one of the operands is a Zext and the other has enough zero bits
3993 // to be treated as unsigned, we can still generate a umull, meaning the
3994 // zext is free.
3995 KnownBits Known =
3996 computeKnownBits(isa<ZExtInst>(Args[0]) ? Args[1] : Args[0], DL);
3997 if (Args[0]->getType()->getScalarSizeInBits() -
3998 Known.Zero.countLeadingOnes() >
3999 DstTy->getScalarSizeInBits() / 2)
4000 return nullptr;
4001
4002 MaxEltSize =
4003 getScalarSizeWithOverride(isa<ZExtInst>(Args[0]) ? Args[0] : Args[1]);
4004 } else
4005 return nullptr;
4006
4007 if (MaxEltSize * 2 > DstEltSize)
4008 return nullptr;
4009
4010 Type *ExtTy = DstTy->getWithNewBitWidth(MaxEltSize * 2);
4011 if (ExtTy->getPrimitiveSizeInBits() <= 64)
4012 return nullptr;
4013 return ExtTy;
4014}
4015
4016// s/urhadd instructions implement the following pattern, making the
4017// extends free:
4018// %x = add ((zext i8 -> i16), 1)
4019// %y = (zext i8 -> i16)
4020// trunc i16 (lshr (add %x, %y), 1) -> i8
4021//
4023 Type *Src) const {
4024 // The source should be a legal vector type.
4025 if (!Src->isVectorTy() || !TLI->isTypeLegal(TLI->getValueType(DL, Src)) ||
4026 (Src->isScalableTy() && !ST->hasSVE2()))
4027 return false;
4028
4029 if (ExtUser->getOpcode() != Instruction::Add || !ExtUser->hasOneUse())
4030 return false;
4031
4032 // Look for trunc/shl/add before trying to match the pattern.
4033 const Instruction *Add = ExtUser;
4034 auto *AddUser =
4035 dyn_cast_or_null<Instruction>(Add->getUniqueUndroppableUser());
4036 if (AddUser && AddUser->getOpcode() == Instruction::Add)
4037 Add = AddUser;
4038
4039 auto *Shr = dyn_cast_or_null<Instruction>(Add->getUniqueUndroppableUser());
4040 if (!Shr || Shr->getOpcode() != Instruction::LShr)
4041 return false;
4042
4043 auto *Trunc = dyn_cast_or_null<Instruction>(Shr->getUniqueUndroppableUser());
4044 if (!Trunc || Trunc->getOpcode() != Instruction::Trunc ||
4045 Src->getScalarSizeInBits() !=
4046 cast<CastInst>(Trunc)->getDestTy()->getScalarSizeInBits())
4047 return false;
4048
4049 // Try to match the whole pattern. Ext could be either the first or second
4050 // m_ZExtOrSExt matched.
4051 Instruction *Ex1, *Ex2;
4052 if (!(match(Add, m_c_Add(m_Instruction(Ex1),
4053 m_c_Add(m_Instruction(Ex2), m_One())))))
4054 return false;
4055
4056 // Ensure both extends are of the same type
4057 if (match(Ex1, m_ZExtOrSExt(m_Value())) &&
4058 Ex1->getOpcode() == Ex2->getOpcode())
4059 return true;
4060
4061 return false;
4062}
4063
4065 Type *Src,
4067 TTI::TargetCostKind CostKind,
4068 const Instruction *I) const {
4069 int ISD = TLI->InstructionOpcodeToISD(Opcode);
4070 assert(ISD && "Invalid opcode");
4071
4072 // Codegen is not able to select all <vscale x 1 x Ty> casts yet.
4073 if (auto *VTy = dyn_cast<ScalableVectorType>(Dst);
4074 VTy && VTy->getElementCount() == ElementCount::getScalable(1)) {
4077 ISD))
4079 }
4080
4081 // A non-power-of-2 i1 vector that fits in a single register has no bitmask
4082 // lowering, so its lanes are extracted and combined one by one.
4083 if (auto *SrcVTy = dyn_cast<FixedVectorType>(Src);
4084 ISD == ISD::BITCAST && SrcVTy && Dst->isIntegerTy() &&
4085 Src->isIntOrIntVectorTy(1) && !isPowerOf2_32(SrcVTy->getNumElements()) &&
4086 getTypeLegalizationCost(SrcVTy).first == 1) {
4087 unsigned NumElts = SrcVTy->getNumElements();
4088 return getScalarizationOverhead(SrcVTy, APInt::getAllOnes(NumElts),
4089 /*Insert=*/false, /*Extract=*/true,
4090 CostKind) +
4091 NumElts - 1;
4092 }
4093
4094 // If the cast is observable, and it is used by a widening instruction (e.g.,
4095 // uaddl, saddw, etc.), it may be free.
4096 if (I && !I->users().empty()) {
4097 // Determine whether Usr can absorb the cast from Src to Dst into a
4098 // widening instruction (e.g. uaddl, saddw, urhadd), making the cast free
4099 // with respect to that user.
4100 auto GetUserAbsorbedCastCost =
4101 [&](const Instruction *Usr) -> std::optional<InstructionCost> {
4102 SmallVector<const Value *, 4> Operands(Usr->operand_values());
4103
4104 if (Type *ExtTy = isBinExtWideningInstruction(
4105 Usr->getOpcode(), Dst, Operands,
4106 Src != I->getOperand(0)->getType() ? Src : nullptr)) {
4107 // The cost from Src->Src*2 needs to be added if required, the cost
4108 // from Src*2->ExtTy is free.
4109 if (ExtTy->getScalarSizeInBits() > Src->getScalarSizeInBits() * 2) {
4110 Type *DoubleSrcTy =
4111 Src->getWithNewBitWidth(Src->getScalarSizeInBits() * 2);
4112 return getCastInstrCost(Opcode, DoubleSrcTy, Src,
4113 TTI::CastContextHint::None, CostKind);
4114 }
4115
4116 return 0;
4117 }
4118
4119 if (isSingleExtWideningInstruction(
4120 Usr->getOpcode(), Dst, Operands,
4121 Src != I->getOperand(0)->getType() ? Src : nullptr)) {
4122 // For adds only count the second operand as free if both operands
4123 // are extends but not the same operation. (i.e both operands are
4124 // not free in add(sext, zext)).
4125 if (Usr->getOpcode() == Instruction::Add) {
4126 if (I == Usr->getOperand(1) ||
4127 (isa<CastInst>(Usr->getOperand(1)) &&
4128 cast<CastInst>(Usr->getOperand(1))->getOpcode() == Opcode))
4129 return 0;
4130 } else {
4131 // Others are free so long as isSingleExtWideningInstruction
4132 // returned true.
4133 return 0;
4134 }
4135 }
4136
4138 return std::nullopt;
4139
4140 // The cast will be free for the s/urhadd instructions
4141 if (isExtPartOfAvgExpr(Usr, Dst, Src))
4142 return 0;
4143
4144 // [US]SHLL/SHLL fold a doubling extend into a shift left by a splat
4145 // immediate of at most the source element width.
4146 const APInt *ShAmt;
4147 unsigned SrcBits = Src->getScalarSizeInBits();
4148 if (match(Usr, m_Shl(m_Specific(I), m_APInt(ShAmt))) &&
4149 ShAmt->ule(SrcBits) && useNeonVector(Dst) &&
4150 Dst->getScalarSizeInBits() == 2 * SrcBits &&
4151 getTypeLegalizationCost(Src).second.getScalarSizeInBits() == SrcBits)
4152 return 0;
4153
4154 return std::nullopt;
4155 };
4156
4157 InstructionCost MaxAbsorbedCost = 0;
4158 bool AllUsersAbsorbCast = true;
4159 for (const Instruction *Usr : I->users()) {
4160 std::optional<InstructionCost> UserCost = GetUserAbsorbedCastCost(Usr);
4161 if (!UserCost) {
4162 AllUsersAbsorbCast = false;
4163 break;
4164 }
4165 MaxAbsorbedCost = std::max(MaxAbsorbedCost, *UserCost);
4166 }
4167
4168 if (AllUsersAbsorbCast)
4169 return MaxAbsorbedCost;
4170 }
4171
4172 // A vector compare already produces a lane mask (CMxx/FCMxx), so sign
4173 // extending it to the compare width is free. That only holds while the
4174 // result stays a vector; scalarized lanes still need a CSETM each.
4175 const Instruction *Cmp;
4176 const Value *CmpOp;
4177 if (I && useNeonVector(Dst) &&
4178 match(I, m_SExt(m_Instruction(Cmp, m_Cmp(m_Value(CmpOp), m_Value())))) &&
4179 Cmp->getParent() == I->getParent() &&
4180 CmpOp->getType()->getScalarSizeInBits() == Dst->getScalarSizeInBits() &&
4181 getTypeLegalizationCost(Dst).second.isVector())
4182 return 0;
4183
4184 EVT SrcTy = TLI->getValueType(DL, Src);
4185 EVT DstTy = TLI->getValueType(DL, Dst);
4186
4187 // SVE has no elements wider than 64 bits. The generic cost for a bitcast
4188 // between unsupported scalable types can otherwise appear to be free.
4189 if ((SrcTy.isScalableVector() && SrcTy.getScalarSizeInBits() > 64) ||
4190 (DstTy.isScalableVector() && DstTy.getScalarSizeInBits() > 64))
4192
4193 // A bitcast that crosses register banks is costed as a vector insert/extract.
4194 // Between the same register bank it is free. Note: Some costs are not handled
4195 // well by this, like i1 vectors that need to be packed.
4196 if (ISD == ISD::BITCAST && ST->isLittleEndian()) {
4197 std::pair<InstructionCost, MVT> SrcLT = getTypeLegalizationCost(Src);
4198 std::pair<InstructionCost, MVT> DstLT = getTypeLegalizationCost(Dst);
4199 bool SrcIsFloatOrVec =
4200 SrcLT.second.isVector() || SrcLT.second.isFloatingPoint();
4201 bool DstIsFloatOrVec =
4202 DstLT.second.isVector() || DstLT.second.isFloatingPoint();
4203
4204 // Consider the bitcast free if they are both the same type and have the
4205 // same size after legalization. Scalable vectors are handled specially as
4206 // the type legalization cost of v2i16 is v2i64.
4207 if (SrcIsFloatOrVec == DstIsFloatOrVec &&
4208 (SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits() ||
4209 (SrcLT.second.isScalableVector() &&
4210 SrcLT.second.getScalarSizeInBits() != 1 &&
4211 DstLT.second.getScalarSizeInBits() != 1)))
4212 return 0;
4213
4214 return std::max(SrcLT.first, DstLT.first) *
4215 (CostKind == TTI::TCK_CodeSize
4216 ? 1
4217 : ST->getVectorInsertExtractBaseCost());
4218 }
4219
4220 // From a vector to a scalarized vector will be an series of extract-element
4221 // and extends.
4222 if ((ISD == ISD::ZERO_EXTEND || ISD == ISD::SIGN_EXTEND) &&
4223 DstTy.getScalarSizeInBits() > 64 && SrcTy.getScalarSizeInBits() <= 64 &&
4224 DstTy.isFixedLengthVector()) {
4226 Instruction::ExtractElement, Src, CostKind, -1, nullptr, nullptr);
4228 Opcode, Dst->getScalarType(), Src->getScalarType(), CCH, CostKind);
4229 return DstTy.getVectorNumElements() * (LaneCost + ExtCost);
4230 }
4231
4232 if (!SrcTy.isSimple() || !DstTy.isSimple())
4233 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
4234
4235 // For the moment we do not have lowering for SVE1-only fptrunc f64->bf16 as
4236 // we use fcvtx under SVE2. Give them invalid costs.
4237 if (!ST->hasSVE2() && !ST->isStreamingSVEAvailable() &&
4238 ISD == ISD::FP_ROUND && SrcTy.isScalableVector() &&
4239 DstTy.getScalarType() == MVT::bf16 && SrcTy.getScalarType() == MVT::f64)
4241
4242 static const TypeConversionCostTblEntry BF16Tbl[] = {
4243 {ISD::FP_ROUND, MVT::bf16, MVT::f32, 1}, // bfcvt
4244 {ISD::FP_ROUND, MVT::bf16, MVT::f64, 1}, // bfcvt
4245 {ISD::FP_ROUND, MVT::v4bf16, MVT::v4f32, 1}, // bfcvtn
4246 {ISD::FP_ROUND, MVT::v8bf16, MVT::v8f32, 2}, // bfcvtn+bfcvtn2
4247 {ISD::FP_ROUND, MVT::v2bf16, MVT::v2f64, 2}, // bfcvtn+fcvtn
4248 {ISD::FP_ROUND, MVT::v4bf16, MVT::v4f64, 3}, // fcvtn+fcvtl2+bfcvtn
4249 {ISD::FP_ROUND, MVT::v8bf16, MVT::v8f64, 6}, // 2 * fcvtn+fcvtn2+bfcvtn
4250 {ISD::FP_ROUND, MVT::nxv2bf16, MVT::nxv2f32, 1}, // bfcvt
4251 {ISD::FP_ROUND, MVT::nxv4bf16, MVT::nxv4f32, 1}, // bfcvt
4252 {ISD::FP_ROUND, MVT::nxv8bf16, MVT::nxv8f32, 3}, // bfcvt+bfcvt+uzp1
4253 {ISD::FP_ROUND, MVT::nxv2bf16, MVT::nxv2f64, 2}, // fcvtx+bfcvt
4254 {ISD::FP_ROUND, MVT::nxv4bf16, MVT::nxv4f64, 5}, // 2*fcvtx+2*bfcvt+uzp1
4255 {ISD::FP_ROUND, MVT::nxv8bf16, MVT::nxv8f64, 11}, // 4*fcvt+4*bfcvt+3*uzp
4256 };
4257
4258 if (ST->hasBF16())
4259 if (const auto *Entry = ConvertCostTableLookup(
4260 BF16Tbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
4261 return Entry->Cost;
4262
4263 // We have to estimate a cost of fixed length operation upon
4264 // SVE registers(operations) with the number of registers required
4265 // for a fixed type to be represented upon SVE registers.
4266 EVT WiderTy = SrcTy.bitsGT(DstTy) ? SrcTy : DstTy;
4267 if (SrcTy.isFixedLengthVector() && DstTy.isFixedLengthVector() &&
4268 SrcTy.getVectorNumElements() == DstTy.getVectorNumElements() &&
4269 ST->useSVEForFixedLengthVectors(WiderTy)) {
4270 std::pair<InstructionCost, MVT> LT =
4271 getTypeLegalizationCost(WiderTy.getTypeForEVT(Dst->getContext()));
4272 unsigned NumElements =
4273 AArch64::SVEBitsPerBlock / LT.second.getScalarSizeInBits();
4274 return LT.first *
4276 Opcode,
4277 ScalableVectorType::get(Dst->getScalarType(), NumElements),
4278 ScalableVectorType::get(Src->getScalarType(), NumElements), CCH,
4279 CostKind, I);
4280 }
4281
4282 // Symbolic constants for the SVE sitofp/uitofp entries in the table below
4283 // The cost of unpacking twice is artificially increased for now in order
4284 // to avoid regressions against NEON, which will use tbl instructions directly
4285 // instead of multiple layers of [s|u]unpk[lo|hi].
4286 // We use the unpacks in cases where the destination type is illegal and
4287 // requires splitting of the input, even if the input type itself is legal.
4288 const unsigned int SVE_EXT_COST = 1;
4289 const unsigned int SVE_FCVT_COST = 1;
4290 const unsigned int SVE_UNPACK_ONCE = 4;
4291 const unsigned int SVE_UNPACK_TWICE = 16;
4292
4293 static const TypeConversionCostTblEntry ConversionTbl[] = {
4294 {ISD::TRUNCATE, MVT::v2i8, MVT::v2i64, 1}, // xtn
4295 {ISD::TRUNCATE, MVT::v2i16, MVT::v2i64, 1}, // xtn
4296 {ISD::TRUNCATE, MVT::v2i32, MVT::v2i64, 1}, // xtn
4297 {ISD::TRUNCATE, MVT::v4i8, MVT::v4i32, 1}, // xtn
4298 {ISD::TRUNCATE, MVT::v4i8, MVT::v4i64, 3}, // 2 xtn + 1 uzp1
4299 {ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1}, // xtn
4300 {ISD::TRUNCATE, MVT::v4i16, MVT::v4i64, 2}, // 1 uzp1 + 1 xtn
4301 {ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 1}, // 1 uzp1
4302 {ISD::TRUNCATE, MVT::v8i8, MVT::v8i16, 1}, // 1 xtn
4303 {ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 2}, // 1 uzp1 + 1 xtn
4304 {ISD::TRUNCATE, MVT::v8i8, MVT::v8i64, 4}, // 3 x uzp1 + xtn
4305 {ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 1}, // 1 uzp1
4306 {ISD::TRUNCATE, MVT::v8i16, MVT::v8i64, 3}, // 3 x uzp1
4307 {ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 2}, // 2 x uzp1
4308 {ISD::TRUNCATE, MVT::v16i8, MVT::v16i16, 1}, // uzp1
4309 {ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 3}, // (2 + 1) x uzp1
4310 {ISD::TRUNCATE, MVT::v16i8, MVT::v16i64, 7}, // (4 + 2 + 1) x uzp1
4311 {ISD::TRUNCATE, MVT::v16i16, MVT::v16i32, 2}, // 2 x uzp1
4312 {ISD::TRUNCATE, MVT::v16i16, MVT::v16i64, 6}, // (4 + 2) x uzp1
4313 {ISD::TRUNCATE, MVT::v16i32, MVT::v16i64, 4}, // 4 x uzp1
4314
4315 // Truncations on nxvmiN
4316 {ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i8, 2},
4317 {ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i16, 2},
4318 {ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i32, 2},
4319 {ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i64, 2},
4320 {ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i8, 2},
4321 {ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i16, 2},
4322 {ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i32, 2},
4323 {ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i64, 5},
4324 {ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i8, 2},
4325 {ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i16, 2},
4326 {ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i32, 5},
4327 {ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i64, 11},
4328 {ISD::TRUNCATE, MVT::nxv16i1, MVT::nxv16i8, 2},
4329 {ISD::TRUNCATE, MVT::nxv2i8, MVT::nxv2i16, 0},
4330 {ISD::TRUNCATE, MVT::nxv2i8, MVT::nxv2i32, 0},
4331 {ISD::TRUNCATE, MVT::nxv2i8, MVT::nxv2i64, 0},
4332 {ISD::TRUNCATE, MVT::nxv2i16, MVT::nxv2i32, 0},
4333 {ISD::TRUNCATE, MVT::nxv2i16, MVT::nxv2i64, 0},
4334 {ISD::TRUNCATE, MVT::nxv2i32, MVT::nxv2i64, 0},
4335 {ISD::TRUNCATE, MVT::nxv4i8, MVT::nxv4i16, 0},
4336 {ISD::TRUNCATE, MVT::nxv4i8, MVT::nxv4i32, 0},
4337 {ISD::TRUNCATE, MVT::nxv4i8, MVT::nxv4i64, 1},
4338 {ISD::TRUNCATE, MVT::nxv4i16, MVT::nxv4i32, 0},
4339 {ISD::TRUNCATE, MVT::nxv4i16, MVT::nxv4i64, 1},
4340 {ISD::TRUNCATE, MVT::nxv4i32, MVT::nxv4i64, 1},
4341 {ISD::TRUNCATE, MVT::nxv8i8, MVT::nxv8i16, 0},
4342 {ISD::TRUNCATE, MVT::nxv8i8, MVT::nxv8i32, 1},
4343 {ISD::TRUNCATE, MVT::nxv8i8, MVT::nxv8i64, 3},
4344 {ISD::TRUNCATE, MVT::nxv8i16, MVT::nxv8i32, 1},
4345 {ISD::TRUNCATE, MVT::nxv8i16, MVT::nxv8i64, 3},
4346 {ISD::TRUNCATE, MVT::nxv16i8, MVT::nxv16i16, 1},
4347 {ISD::TRUNCATE, MVT::nxv16i8, MVT::nxv16i32, 3},
4348 {ISD::TRUNCATE, MVT::nxv16i8, MVT::nxv16i64, 7},
4349
4350 // The number of shll instructions for the extension.
4351 {ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3},
4352 {ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3},
4353 {ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 2},
4354 {ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 2},
4355 {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3},
4356 {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3},
4357 {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 2},
4358 {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 2},
4359 {ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7},
4360 {ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7},
4361 {ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6},
4362 {ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6},
4363 {ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2},
4364 {ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2},
4365 {ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6},
4366 {ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6},
4367
4368 // FP Ext and trunc
4369 {ISD::FP_EXTEND, MVT::f64, MVT::f32, 1}, // fcvt
4370 {ISD::FP_EXTEND, MVT::v2f64, MVT::v2f32, 1}, // fcvtl
4371 {ISD::FP_EXTEND, MVT::v4f64, MVT::v4f32, 2}, // fcvtl+fcvtl2
4372 // FP16
4373 {ISD::FP_EXTEND, MVT::f32, MVT::f16, 1}, // fcvt
4374 {ISD::FP_EXTEND, MVT::f64, MVT::f16, 1}, // fcvt
4375 {ISD::FP_EXTEND, MVT::v4f32, MVT::v4f16, 1}, // fcvtl
4376 {ISD::FP_EXTEND, MVT::v8f32, MVT::v8f16, 2}, // fcvtl+fcvtl2
4377 {ISD::FP_EXTEND, MVT::v2f64, MVT::v2f16, 2}, // fcvtl+fcvtl
4378 {ISD::FP_EXTEND, MVT::v4f64, MVT::v4f16, 3}, // fcvtl+fcvtl2+fcvtl
4379 {ISD::FP_EXTEND, MVT::v8f64, MVT::v8f16, 6}, // 2 * fcvtl+fcvtl2+fcvtl
4380 // BF16 (uses shift)
4381 {ISD::FP_EXTEND, MVT::f32, MVT::bf16, 1}, // shl
4382 {ISD::FP_EXTEND, MVT::f64, MVT::bf16, 2}, // shl+fcvt
4383 {ISD::FP_EXTEND, MVT::v4f32, MVT::v4bf16, 1}, // shll
4384 {ISD::FP_EXTEND, MVT::v8f32, MVT::v8bf16, 2}, // shll+shll2
4385 {ISD::FP_EXTEND, MVT::v2f64, MVT::v2bf16, 2}, // shll+fcvtl
4386 {ISD::FP_EXTEND, MVT::v4f64, MVT::v4bf16, 3}, // shll+fcvtl+fcvtl2
4387 {ISD::FP_EXTEND, MVT::v8f64, MVT::v8bf16, 6}, // 2 * shll+fcvtl+fcvtl2
4388 // FP Ext and trunc
4389 {ISD::FP_ROUND, MVT::f32, MVT::f64, 1}, // fcvt
4390 {ISD::FP_ROUND, MVT::v2f32, MVT::v2f64, 1}, // fcvtn
4391 {ISD::FP_ROUND, MVT::v4f32, MVT::v4f64, 2}, // fcvtn+fcvtn2
4392 // FP16
4393 {ISD::FP_ROUND, MVT::f16, MVT::f32, 1}, // fcvt
4394 {ISD::FP_ROUND, MVT::f16, MVT::f64, 1}, // fcvt
4395 {ISD::FP_ROUND, MVT::v4f16, MVT::v4f32, 1}, // fcvtn
4396 {ISD::FP_ROUND, MVT::v8f16, MVT::v8f32, 2}, // fcvtn+fcvtn2
4397 {ISD::FP_ROUND, MVT::v2f16, MVT::v2f64, 2}, // fcvtn+fcvtn
4398 {ISD::FP_ROUND, MVT::v4f16, MVT::v4f64, 3}, // fcvtn+fcvtn2+fcvtn
4399 {ISD::FP_ROUND, MVT::v8f16, MVT::v8f64, 6}, // 2 * fcvtn+fcvtn2+fcvtn
4400 // BF16 (more complex, with +bf16 is handled above)
4401 {ISD::FP_ROUND, MVT::bf16, MVT::f32, 8}, // Expansion is ~8 insns
4402 {ISD::FP_ROUND, MVT::bf16, MVT::f64, 9}, // fcvtn + above
4403 {ISD::FP_ROUND, MVT::v2bf16, MVT::v2f32, 8},
4404 {ISD::FP_ROUND, MVT::v4bf16, MVT::v4f32, 8},
4405 {ISD::FP_ROUND, MVT::v8bf16, MVT::v8f32, 15},
4406 {ISD::FP_ROUND, MVT::v2bf16, MVT::v2f64, 9},
4407 {ISD::FP_ROUND, MVT::v4bf16, MVT::v4f64, 10},
4408 {ISD::FP_ROUND, MVT::v8bf16, MVT::v8f64, 19},
4409
4410 // LowerVectorINT_TO_FP:
4411 {ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1},
4412 {ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1},
4413 {ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 1},
4414 {ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1},
4415 {ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1},
4416 {ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1},
4417
4418 // SVE: to nxv2f16
4419 {ISD::SINT_TO_FP, MVT::nxv2f16, MVT::nxv2i8,
4420 SVE_EXT_COST + SVE_FCVT_COST},
4421 {ISD::SINT_TO_FP, MVT::nxv2f16, MVT::nxv2i16, SVE_FCVT_COST},
4422 {ISD::SINT_TO_FP, MVT::nxv2f16, MVT::nxv2i32, SVE_FCVT_COST},
4423 {ISD::SINT_TO_FP, MVT::nxv2f16, MVT::nxv2i64, SVE_FCVT_COST},
4424 {ISD::UINT_TO_FP, MVT::nxv2f16, MVT::nxv2i8,
4425 SVE_EXT_COST + SVE_FCVT_COST},
4426 {ISD::UINT_TO_FP, MVT::nxv2f16, MVT::nxv2i16, SVE_FCVT_COST},
4427 {ISD::UINT_TO_FP, MVT::nxv2f16, MVT::nxv2i32, SVE_FCVT_COST},
4428 {ISD::UINT_TO_FP, MVT::nxv2f16, MVT::nxv2i64, SVE_FCVT_COST},
4429
4430 // SVE: to nxv4f16
4431 {ISD::SINT_TO_FP, MVT::nxv4f16, MVT::nxv4i8,
4432 SVE_EXT_COST + SVE_FCVT_COST},
4433 {ISD::SINT_TO_FP, MVT::nxv4f16, MVT::nxv4i16, SVE_FCVT_COST},
4434 {ISD::SINT_TO_FP, MVT::nxv4f16, MVT::nxv4i32, SVE_FCVT_COST},
4435 {ISD::UINT_TO_FP, MVT::nxv4f16, MVT::nxv4i8,
4436 SVE_EXT_COST + SVE_FCVT_COST},
4437 {ISD::UINT_TO_FP, MVT::nxv4f16, MVT::nxv4i16, SVE_FCVT_COST},
4438 {ISD::UINT_TO_FP, MVT::nxv4f16, MVT::nxv4i32, SVE_FCVT_COST},
4439
4440 // SVE: to nxv8f16
4441 {ISD::SINT_TO_FP, MVT::nxv8f16, MVT::nxv8i8,
4442 SVE_EXT_COST + SVE_FCVT_COST},
4443 {ISD::SINT_TO_FP, MVT::nxv8f16, MVT::nxv8i16, SVE_FCVT_COST},
4444 {ISD::UINT_TO_FP, MVT::nxv8f16, MVT::nxv8i8,
4445 SVE_EXT_COST + SVE_FCVT_COST},
4446 {ISD::UINT_TO_FP, MVT::nxv8f16, MVT::nxv8i16, SVE_FCVT_COST},
4447
4448 // SVE: to nxv16f16
4449 {ISD::SINT_TO_FP, MVT::nxv16f16, MVT::nxv16i8,
4450 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4451 {ISD::UINT_TO_FP, MVT::nxv16f16, MVT::nxv16i8,
4452 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4453
4454 // Complex: to v2f32
4455 {ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3},
4456 {ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 3},
4457 {ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3},
4458 {ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 3},
4459
4460 // SVE: to nxv2f32
4461 {ISD::SINT_TO_FP, MVT::nxv2f32, MVT::nxv2i8,
4462 SVE_EXT_COST + SVE_FCVT_COST},
4463 {ISD::SINT_TO_FP, MVT::nxv2f32, MVT::nxv2i16, SVE_FCVT_COST},
4464 {ISD::SINT_TO_FP, MVT::nxv2f32, MVT::nxv2i32, SVE_FCVT_COST},
4465 {ISD::SINT_TO_FP, MVT::nxv2f32, MVT::nxv2i64, SVE_FCVT_COST},
4466 {ISD::UINT_TO_FP, MVT::nxv2f32, MVT::nxv2i8,
4467 SVE_EXT_COST + SVE_FCVT_COST},
4468 {ISD::UINT_TO_FP, MVT::nxv2f32, MVT::nxv2i16, SVE_FCVT_COST},
4469 {ISD::UINT_TO_FP, MVT::nxv2f32, MVT::nxv2i32, SVE_FCVT_COST},
4470 {ISD::UINT_TO_FP, MVT::nxv2f32, MVT::nxv2i64, SVE_FCVT_COST},
4471
4472 // Complex: to v4f32
4473 {ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 4},
4474 {ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2},
4475 {ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3},
4476 {ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2},
4477
4478 // SVE: to nxv4f32
4479 {ISD::SINT_TO_FP, MVT::nxv4f32, MVT::nxv4i8,
4480 SVE_EXT_COST + SVE_FCVT_COST},
4481 {ISD::SINT_TO_FP, MVT::nxv4f32, MVT::nxv4i16, SVE_FCVT_COST},
4482 {ISD::SINT_TO_FP, MVT::nxv4f32, MVT::nxv4i32, SVE_FCVT_COST},
4483 {ISD::UINT_TO_FP, MVT::nxv4f32, MVT::nxv4i8,
4484 SVE_EXT_COST + SVE_FCVT_COST},
4485 {ISD::UINT_TO_FP, MVT::nxv4f32, MVT::nxv4i16, SVE_FCVT_COST},
4486 {ISD::SINT_TO_FP, MVT::nxv4f32, MVT::nxv4i32, SVE_FCVT_COST},
4487
4488 // Complex: to v8f32
4489 {ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8, 10},
4490 {ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4},
4491 {ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 10},
4492 {ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4},
4493
4494 // SVE: to nxv8f32
4495 {ISD::SINT_TO_FP, MVT::nxv8f32, MVT::nxv8i8,
4496 SVE_EXT_COST + SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4497 {ISD::SINT_TO_FP, MVT::nxv8f32, MVT::nxv8i16,
4498 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4499 {ISD::UINT_TO_FP, MVT::nxv8f32, MVT::nxv8i8,
4500 SVE_EXT_COST + SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4501 {ISD::UINT_TO_FP, MVT::nxv8f32, MVT::nxv8i16,
4502 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4503
4504 // SVE: to nxv16f32
4505 {ISD::SINT_TO_FP, MVT::nxv16f32, MVT::nxv16i8,
4506 SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
4507 {ISD::UINT_TO_FP, MVT::nxv16f32, MVT::nxv16i8,
4508 SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
4509
4510 // Complex: to v16f32
4511 {ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i8, 21},
4512 {ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i8, 21},
4513
4514 // Complex: to v2f64
4515 {ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 4},
4516 {ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 4},
4517 {ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2},
4518 {ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 4},
4519 {ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 4},
4520 {ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2},
4521
4522 // SVE: to nxv2f64
4523 {ISD::SINT_TO_FP, MVT::nxv2f64, MVT::nxv2i8,
4524 SVE_EXT_COST + SVE_FCVT_COST},
4525 {ISD::SINT_TO_FP, MVT::nxv2f64, MVT::nxv2i16, SVE_FCVT_COST},
4526 {ISD::SINT_TO_FP, MVT::nxv2f64, MVT::nxv2i32, SVE_FCVT_COST},
4527 {ISD::SINT_TO_FP, MVT::nxv2f64, MVT::nxv2i64, SVE_FCVT_COST},
4528 {ISD::UINT_TO_FP, MVT::nxv2f64, MVT::nxv2i8,
4529 SVE_EXT_COST + SVE_FCVT_COST},
4530 {ISD::UINT_TO_FP, MVT::nxv2f64, MVT::nxv2i16, SVE_FCVT_COST},
4531 {ISD::UINT_TO_FP, MVT::nxv2f64, MVT::nxv2i32, SVE_FCVT_COST},
4532 {ISD::UINT_TO_FP, MVT::nxv2f64, MVT::nxv2i64, SVE_FCVT_COST},
4533
4534 // Complex: to v4f64
4535 {ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i32, 4},
4536 {ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i32, 4},
4537
4538 // SVE: to nxv4f64
4539 {ISD::SINT_TO_FP, MVT::nxv4f64, MVT::nxv4i8,
4540 SVE_EXT_COST + SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4541 {ISD::SINT_TO_FP, MVT::nxv4f64, MVT::nxv4i16,
4542 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4543 {ISD::SINT_TO_FP, MVT::nxv4f64, MVT::nxv4i32,
4544 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4545 {ISD::UINT_TO_FP, MVT::nxv4f64, MVT::nxv4i8,
4546 SVE_EXT_COST + SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4547 {ISD::UINT_TO_FP, MVT::nxv4f64, MVT::nxv4i16,
4548 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4549 {ISD::UINT_TO_FP, MVT::nxv4f64, MVT::nxv4i32,
4550 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
4551
4552 // SVE: to nxv8f64
4553 {ISD::SINT_TO_FP, MVT::nxv8f64, MVT::nxv8i8,
4554 SVE_EXT_COST + SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
4555 {ISD::SINT_TO_FP, MVT::nxv8f64, MVT::nxv8i16,
4556 SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
4557 {ISD::UINT_TO_FP, MVT::nxv8f64, MVT::nxv8i8,
4558 SVE_EXT_COST + SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
4559 {ISD::UINT_TO_FP, MVT::nxv8f64, MVT::nxv8i16,
4560 SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
4561
4562 // LowerVectorFP_TO_INT
4563 {ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f32, 1},
4564 {ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1},
4565 {ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 1},
4566 {ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f32, 1},
4567 {ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1},
4568 {ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1},
4569
4570 // Complex, from v2f32: legal type is v2i32 (no cost) or v2i64 (1 ext).
4571 {ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f32, 2},
4572 {ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f32, 1},
4573 {ISD::FP_TO_SINT, MVT::v2i8, MVT::v2f32, 1},
4574 {ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 2},
4575 {ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f32, 1},
4576 {ISD::FP_TO_UINT, MVT::v2i8, MVT::v2f32, 1},
4577
4578 // Complex, from v4f32: legal type is v4i16, 1 narrowing => ~2
4579 {ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2},
4580 {ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 2},
4581 {ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2},
4582 {ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 2},
4583
4584 // Complex, from v2f64: legal type is v2i32, 1 narrowing => ~2.
4585 {ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2},
4586 {ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f64, 2},
4587 {ISD::FP_TO_SINT, MVT::v2i8, MVT::v2f64, 2},
4588 {ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2},
4589 {ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f64, 2},
4590 {ISD::FP_TO_UINT, MVT::v2i8, MVT::v2f64, 2},
4591
4592 // Complex, from nxv2f32.
4593 {ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f32, 1},
4594 {ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f32, 1},
4595 {ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f32, 1},
4596 {ISD::FP_TO_SINT, MVT::nxv2i8, MVT::nxv2f32, 1},
4597 {ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f32, 1},
4598 {ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f32, 1},
4599 {ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f32, 1},
4600 {ISD::FP_TO_UINT, MVT::nxv2i8, MVT::nxv2f32, 1},
4601
4602 // Complex, from nxv2f64.
4603 {ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f64, 1},
4604 {ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f64, 1},
4605 {ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f64, 1},
4606 {ISD::FP_TO_SINT, MVT::nxv2i8, MVT::nxv2f64, 1},
4607 {ISD::FP_TO_SINT, MVT::nxv2i1, MVT::nxv2f64, 1},
4608 {ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f64, 1},
4609 {ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f64, 1},
4610 {ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f64, 1},
4611 {ISD::FP_TO_UINT, MVT::nxv2i8, MVT::nxv2f64, 1},
4612 {ISD::FP_TO_UINT, MVT::nxv2i1, MVT::nxv2f64, 1},
4613
4614 // Complex, from nxv4f32.
4615 {ISD::FP_TO_SINT, MVT::nxv4i64, MVT::nxv4f32, 4},
4616 {ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f32, 1},
4617 {ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f32, 1},
4618 {ISD::FP_TO_SINT, MVT::nxv4i8, MVT::nxv4f32, 1},
4619 {ISD::FP_TO_SINT, MVT::nxv4i1, MVT::nxv4f32, 1},
4620 {ISD::FP_TO_UINT, MVT::nxv4i64, MVT::nxv4f32, 4},
4621 {ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f32, 1},
4622 {ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f32, 1},
4623 {ISD::FP_TO_UINT, MVT::nxv4i8, MVT::nxv4f32, 1},
4624 {ISD::FP_TO_UINT, MVT::nxv4i1, MVT::nxv4f32, 1},
4625
4626 // Complex, from nxv8f64. Illegal -> illegal conversions not required.
4627 {ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f64, 7},
4628 {ISD::FP_TO_SINT, MVT::nxv8i8, MVT::nxv8f64, 7},
4629 {ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f64, 7},
4630 {ISD::FP_TO_UINT, MVT::nxv8i8, MVT::nxv8f64, 7},
4631
4632 // Complex, from nxv4f64. Illegal -> illegal conversions not required.
4633 {ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f64, 3},
4634 {ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f64, 3},
4635 {ISD::FP_TO_SINT, MVT::nxv4i8, MVT::nxv4f64, 3},
4636 {ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f64, 3},
4637 {ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f64, 3},
4638 {ISD::FP_TO_UINT, MVT::nxv4i8, MVT::nxv4f64, 3},
4639
4640 // Complex, from nxv8f32. Illegal -> illegal conversions not required.
4641 {ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f32, 3},
4642 {ISD::FP_TO_SINT, MVT::nxv8i8, MVT::nxv8f32, 3},
4643 {ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f32, 3},
4644 {ISD::FP_TO_UINT, MVT::nxv8i8, MVT::nxv8f32, 3},
4645
4646 // Complex, from nxv8f16.
4647 {ISD::FP_TO_SINT, MVT::nxv8i64, MVT::nxv8f16, 10},
4648 {ISD::FP_TO_SINT, MVT::nxv8i32, MVT::nxv8f16, 4},
4649 {ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f16, 1},
4650 {ISD::FP_TO_SINT, MVT::nxv8i8, MVT::nxv8f16, 1},
4651 {ISD::FP_TO_SINT, MVT::nxv8i1, MVT::nxv8f16, 1},
4652 {ISD::FP_TO_UINT, MVT::nxv8i64, MVT::nxv8f16, 10},
4653 {ISD::FP_TO_UINT, MVT::nxv8i32, MVT::nxv8f16, 4},
4654 {ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f16, 1},
4655 {ISD::FP_TO_UINT, MVT::nxv8i8, MVT::nxv8f16, 1},
4656 {ISD::FP_TO_UINT, MVT::nxv8i1, MVT::nxv8f16, 1},
4657
4658 // Complex, from nxv4f16.
4659 {ISD::FP_TO_SINT, MVT::nxv4i64, MVT::nxv4f16, 4},
4660 {ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f16, 1},
4661 {ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f16, 1},
4662 {ISD::FP_TO_SINT, MVT::nxv4i8, MVT::nxv4f16, 1},
4663 {ISD::FP_TO_UINT, MVT::nxv4i64, MVT::nxv4f16, 4},
4664 {ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f16, 1},
4665 {ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f16, 1},
4666 {ISD::FP_TO_UINT, MVT::nxv4i8, MVT::nxv4f16, 1},
4667
4668 // Complex, from nxv2f16.
4669 {ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f16, 1},
4670 {ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f16, 1},
4671 {ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f16, 1},
4672 {ISD::FP_TO_SINT, MVT::nxv2i8, MVT::nxv2f16, 1},
4673 {ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f16, 1},
4674 {ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f16, 1},
4675 {ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f16, 1},
4676 {ISD::FP_TO_UINT, MVT::nxv2i8, MVT::nxv2f16, 1},
4677
4678 // Truncate from nxvmf32 to nxvmf16.
4679 {ISD::FP_ROUND, MVT::nxv2f16, MVT::nxv2f32, 1},
4680 {ISD::FP_ROUND, MVT::nxv4f16, MVT::nxv4f32, 1},
4681 {ISD::FP_ROUND, MVT::nxv8f16, MVT::nxv8f32, 3},
4682
4683 // Truncate from nxvmf32 to nxvmbf16.
4684 {ISD::FP_ROUND, MVT::nxv2bf16, MVT::nxv2f32, 8},
4685 {ISD::FP_ROUND, MVT::nxv4bf16, MVT::nxv4f32, 8},
4686 {ISD::FP_ROUND, MVT::nxv8bf16, MVT::nxv8f32, 17},
4687
4688 // Truncate from nxvmf64 to nxvmf16.
4689 {ISD::FP_ROUND, MVT::nxv2f16, MVT::nxv2f64, 1},
4690 {ISD::FP_ROUND, MVT::nxv4f16, MVT::nxv4f64, 3},
4691 {ISD::FP_ROUND, MVT::nxv8f16, MVT::nxv8f64, 7},
4692
4693 // Truncate from nxvmf64 to nxvmbf16.
4694 {ISD::FP_ROUND, MVT::nxv2bf16, MVT::nxv2f64, 9},
4695 {ISD::FP_ROUND, MVT::nxv4bf16, MVT::nxv4f64, 19},
4696 {ISD::FP_ROUND, MVT::nxv8bf16, MVT::nxv8f64, 39},
4697
4698 // Truncate from nxvmf64 to nxvmf32.
4699 {ISD::FP_ROUND, MVT::nxv2f32, MVT::nxv2f64, 1},
4700 {ISD::FP_ROUND, MVT::nxv4f32, MVT::nxv4f64, 3},
4701 {ISD::FP_ROUND, MVT::nxv8f32, MVT::nxv8f64, 6},
4702
4703 // Extend from nxvmf16 to nxvmf32.
4704 {ISD::FP_EXTEND, MVT::nxv2f32, MVT::nxv2f16, 1},
4705 {ISD::FP_EXTEND, MVT::nxv4f32, MVT::nxv4f16, 1},
4706 {ISD::FP_EXTEND, MVT::nxv8f32, MVT::nxv8f16, 2},
4707
4708 // Extend from nxvmbf16 to nxvmf32.
4709 {ISD::FP_EXTEND, MVT::nxv2f32, MVT::nxv2bf16, 1}, // lsl
4710 {ISD::FP_EXTEND, MVT::nxv4f32, MVT::nxv4bf16, 1}, // lsl
4711 {ISD::FP_EXTEND, MVT::nxv8f32, MVT::nxv8bf16, 4}, // unpck+unpck+lsl+lsl
4712
4713 // Extend from nxvmf16 to nxvmf64.
4714 {ISD::FP_EXTEND, MVT::nxv2f64, MVT::nxv2f16, 1},
4715 {ISD::FP_EXTEND, MVT::nxv4f64, MVT::nxv4f16, 2},
4716 {ISD::FP_EXTEND, MVT::nxv8f64, MVT::nxv8f16, 4},
4717
4718 // Extend from nxvmbf16 to nxvmf64.
4719 {ISD::FP_EXTEND, MVT::nxv2f64, MVT::nxv2bf16, 2}, // lsl+fcvt
4720 {ISD::FP_EXTEND, MVT::nxv4f64, MVT::nxv4bf16, 6}, // 2*unpck+2*lsl+2*fcvt
4721 {ISD::FP_EXTEND, MVT::nxv8f64, MVT::nxv8bf16, 14}, // 6*unpck+4*lsl+4*fcvt
4722
4723 // Extend from nxvmf32 to nxvmf64.
4724 {ISD::FP_EXTEND, MVT::nxv2f64, MVT::nxv2f32, 1},
4725 {ISD::FP_EXTEND, MVT::nxv4f64, MVT::nxv4f32, 2},
4726 {ISD::FP_EXTEND, MVT::nxv8f64, MVT::nxv8f32, 6},
4727
4728 // Add cost for extending to illegal -too wide- scalable vectors.
4729 // zero/sign extend are implemented by multiple unpack operations,
4730 // where each operation has a cost of 1.
4731 {ISD::ZERO_EXTEND, MVT::nxv16i16, MVT::nxv16i8, 2},
4732 {ISD::ZERO_EXTEND, MVT::nxv16i32, MVT::nxv16i8, 6},
4733 {ISD::ZERO_EXTEND, MVT::nxv16i64, MVT::nxv16i8, 14},
4734 {ISD::ZERO_EXTEND, MVT::nxv8i32, MVT::nxv8i16, 2},
4735 {ISD::ZERO_EXTEND, MVT::nxv8i64, MVT::nxv8i16, 6},
4736 {ISD::ZERO_EXTEND, MVT::nxv4i64, MVT::nxv4i32, 2},
4737
4738 {ISD::SIGN_EXTEND, MVT::nxv16i16, MVT::nxv16i8, 2},
4739 {ISD::SIGN_EXTEND, MVT::nxv16i32, MVT::nxv16i8, 6},
4740 {ISD::SIGN_EXTEND, MVT::nxv16i64, MVT::nxv16i8, 14},
4741 {ISD::SIGN_EXTEND, MVT::nxv8i32, MVT::nxv8i16, 2},
4742 {ISD::SIGN_EXTEND, MVT::nxv8i64, MVT::nxv8i16, 6},
4743 {ISD::SIGN_EXTEND, MVT::nxv4i64, MVT::nxv4i32, 2},
4744 };
4745
4746 if (const auto *Entry = ConvertCostTableLookup(
4747 ConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
4748 return Entry->Cost;
4749
4750 static const TypeConversionCostTblEntry FP16Tbl[] = {
4751 {ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f16, 1}, // fcvtzs
4752 {ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f16, 1},
4753 {ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f16, 1}, // fcvtzs
4754 {ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f16, 1},
4755 {ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f16, 2}, // fcvtl+fcvtzs
4756 {ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f16, 2},
4757 {ISD::FP_TO_SINT, MVT::v8i8, MVT::v8f16, 2}, // fcvtzs+xtn
4758 {ISD::FP_TO_UINT, MVT::v8i8, MVT::v8f16, 2},
4759 {ISD::FP_TO_SINT, MVT::v8i16, MVT::v8f16, 1}, // fcvtzs
4760 {ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f16, 1},
4761 {ISD::FP_TO_SINT, MVT::v8i32, MVT::v8f16, 4}, // 2*fcvtl+2*fcvtzs
4762 {ISD::FP_TO_UINT, MVT::v8i32, MVT::v8f16, 4},
4763 {ISD::FP_TO_SINT, MVT::v16i8, MVT::v16f16, 3}, // 2*fcvtzs+xtn
4764 {ISD::FP_TO_UINT, MVT::v16i8, MVT::v16f16, 3},
4765 {ISD::FP_TO_SINT, MVT::v16i16, MVT::v16f16, 2}, // 2*fcvtzs
4766 {ISD::FP_TO_UINT, MVT::v16i16, MVT::v16f16, 2},
4767 {ISD::FP_TO_SINT, MVT::v16i32, MVT::v16f16, 8}, // 4*fcvtl+4*fcvtzs
4768 {ISD::FP_TO_UINT, MVT::v16i32, MVT::v16f16, 8},
4769 {ISD::UINT_TO_FP, MVT::v8f16, MVT::v8i8, 2}, // ushll + ucvtf
4770 {ISD::SINT_TO_FP, MVT::v8f16, MVT::v8i8, 2}, // sshll + scvtf
4771 {ISD::UINT_TO_FP, MVT::v16f16, MVT::v16i8, 4}, // 2 * ushl(2) + 2 * ucvtf
4772 {ISD::SINT_TO_FP, MVT::v16f16, MVT::v16i8, 4}, // 2 * sshl(2) + 2 * scvtf
4773 };
4774
4775 if (ST->hasFullFP16())
4776 if (const auto *Entry = ConvertCostTableLookup(
4777 FP16Tbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
4778 return Entry->Cost;
4779
4780 // INT_TO_FP of i64->f32 will scalarize, which is required to avoid
4781 // double-rounding issues.
4782 if ((ISD == ISD::SINT_TO_FP || ISD == ISD::UINT_TO_FP) &&
4783 DstTy.getScalarType() == MVT::f32 && SrcTy.getScalarSizeInBits() > 32 &&
4785 return cast<FixedVectorType>(Dst)->getNumElements() *
4786 getCastInstrCost(Opcode, Dst->getScalarType(),
4787 Src->getScalarType(), CCH, CostKind) +
4789 true, CostKind) +
4791 false, CostKind);
4792
4793 if ((ISD == ISD::ZERO_EXTEND || ISD == ISD::SIGN_EXTEND) &&
4795 ST->isSVEorStreamingSVEAvailable() &&
4796 TLI->getTypeAction(Src->getContext(), SrcTy) ==
4798 TLI->getTypeAction(Dst->getContext(), DstTy) ==
4800 // The standard behaviour in the backend for these cases is to split the
4801 // extend up into two parts:
4802 // 1. Perform an extending load or masked load up to the legal type.
4803 // 2. Extend the loaded data to the final type.
4804 std::pair<InstructionCost, MVT> SrcLT = getTypeLegalizationCost(Src);
4805 Type *LegalTy = EVT(SrcLT.second).getTypeForEVT(Src->getContext());
4807 Opcode, LegalTy, Src, CCH, CostKind, I);
4809 Opcode, Dst, LegalTy, TTI::CastContextHint::None, CostKind, I);
4810 return Part1 + Part2;
4811 }
4812
4813 // The BasicTTIImpl version only deals with CCH==TTI::CastContextHint::Normal,
4814 // but we also want to include the TTI::CastContextHint::Masked case too.
4815 if ((ISD == ISD::ZERO_EXTEND || ISD == ISD::SIGN_EXTEND) &&
4817 ST->isSVEorStreamingSVEAvailable() && TLI->isTypeLegal(DstTy))
4819
4820 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
4821}
4822
4825 VectorType *VecTy, unsigned Index,
4826 TTI::TargetCostKind CostKind) const {
4827
4828 // Make sure we were given a valid extend opcode.
4829 assert((Opcode == Instruction::SExt || Opcode == Instruction::ZExt) &&
4830 "Invalid opcode");
4831
4832 // We are extending an element we extract from a vector, so the source type
4833 // of the extend is the element type of the vector.
4834 auto *Src = VecTy->getElementType();
4835
4836 // Sign- and zero-extends are for integer types only.
4837 assert(isa<IntegerType>(Dst) && isa<IntegerType>(Src) && "Invalid type");
4838
4839 // Get the cost for the extract. We compute the cost (if any) for the extend
4840 // below.
4841 InstructionCost Cost = getVectorInstrCost(Instruction::ExtractElement, VecTy,
4842 CostKind, Index, nullptr, nullptr);
4843
4844 // Legalize the types.
4845 auto VecLT = getTypeLegalizationCost(VecTy);
4846 auto DstVT = TLI->getValueType(DL, Dst);
4847 auto SrcVT = TLI->getValueType(DL, Src);
4848
4849 // If the resulting type is still a vector and the destination type is legal,
4850 // we may get the extension for free. If not, get the default cost for the
4851 // extend.
4852 if (!VecLT.second.isVector() || !TLI->isTypeLegal(DstVT))
4853 return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
4854 CostKind);
4855
4856 // The destination type should be larger than the element type. If not, get
4857 // the default cost for the extend.
4858 if (DstVT.getFixedSizeInBits() < SrcVT.getFixedSizeInBits())
4859 return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
4860 CostKind);
4861
4862 switch (Opcode) {
4863 default:
4864 llvm_unreachable("Opcode should be either SExt or ZExt");
4865
4866 // For sign-extends, we only need a smov, which performs the extension
4867 // automatically.
4868 case Instruction::SExt:
4869 return Cost;
4870
4871 // For zero-extends, the extend is performed automatically by a umov unless
4872 // the destination type is i64 and the element type is i8 or i16.
4873 case Instruction::ZExt:
4874 if (DstVT.getSizeInBits() != 64u || SrcVT.getSizeInBits() == 32u)
4875 return Cost;
4876 }
4877
4878 // If we are unable to perform the extend for free, get the default cost.
4879 return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
4880 CostKind);
4881}
4882
4884 TTI::TargetCostKind CostKind,
4885 const Instruction *I) const {
4886 if (CostKind != TTI::TCK_RecipThroughput)
4887 return Opcode == Instruction::PHI ? 0 : 1;
4888 assert(CostKind == TTI::TCK_RecipThroughput && "unexpected CostKind");
4889 // Branches are assumed to be predicted.
4890 return 0;
4891}
4892
4893InstructionCost AArch64TTIImpl::getVectorInstrCostHelper(
4894 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, unsigned Index,
4895 const Instruction *I, Value *Scalar,
4896 ArrayRef<std::tuple<Value *, User *, int>> ScalarUserAndIdx,
4897 TTI::VectorInstrContext VIC) const {
4898 assert(Ty->isVectorTy() && "This must be a vector type");
4899
4900 if (Index != -1U) {
4901 // Legalize the type.
4902 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
4903
4904 // This type is legalized to a scalar type.
4905 if (!LT.second.isVector())
4906 return 0;
4907
4908 // The type may be split. For fixed-width vectors we can normalize the
4909 // index to the new type.
4910 if (LT.second.isFixedLengthVector()) {
4911 unsigned Width = LT.second.getVectorNumElements();
4912 Index = Index % Width;
4913 }
4914
4915 // The element at index zero is already inside the vector.
4916 // - For a insert-element or extract-element
4917 // instruction that extracts integers, an explicit FPR -> GPR move is
4918 // needed. So it has non-zero cost.
4919 if (Index == 0 && !Ty->getScalarType()->isIntegerTy())
4920 return 0;
4921
4922 // SVE has no scalar move to an arbitrary lane above the low 128-bit portion
4923 // of a Z register, e.g. there is no equivalent of "mov z0.d[9], d0".
4924 // Fixed-length vectors wider than 128 bits therefore need
4925 // [splice]/index/pred/splat/cmp/pred-mov when scalarizing inserts for those
4926 // lanes, so model them as more expensive than ordinary NEON lane accesses.
4927 if (ST->useSVEForFixedLengthVectors()) {
4928 InstructionCost Cost = CostKind == TTI::TCK_CodeSize
4929 ? 1
4931 if (Index * Ty->getScalarSizeInBits() < 128)
4932 return Cost;
4933 if (Index * Ty->getScalarSizeInBits() < 512 &&
4934 Opcode == Instruction::ExtractElement)
4935 // Integer extracts (>128b, <512b) require extra mov from FPR -> GPR.
4936 return Ty->getScalarType()->isIntegerTy() ? Cost + 1 : Cost;
4937 if (Opcode == Instruction::ExtractElement)
4938 return Cost + 2; // cost of mov imm + whilels + lastb
4939 if (Opcode == Instruction::InsertElement)
4940 return Cost + 3; // cost of insert with cmp/splice
4941 llvm_unreachable("unexpected opcode");
4942 }
4943
4944 // This is recognising a LD1 single-element structure to one lane of one
4945 // register instruction. I.e., if this is an `insertelement` instruction,
4946 // and its second operand is a load, then we will generate a LD1, which
4947 // are expensive instructions on some uArchs.
4948 if (VIC == TTI::VectorInstrContext::Load) {
4949 if (ST->hasFastLD1Single())
4950 return 0;
4951 return CostKind == TTI::TCK_CodeSize
4952 ? 0
4953 : ST->getVectorInsertExtractBaseCost() + 1;
4954 }
4955
4956 // i1 inserts and extract will include an extra cset or cmp of the vector
4957 // value. Increase the cost by 1 to account.
4958 if (Ty->getScalarSizeInBits() == 1)
4959 return CostKind == TTI::TCK_CodeSize
4960 ? 2
4961 : ST->getVectorInsertExtractBaseCost() + 1;
4962
4963 // FIXME:
4964 // If the extract-element and insert-element instructions could be
4965 // simplified away (e.g., could be combined into users by looking at use-def
4966 // context), they have no cost. This is not done in the first place for
4967 // compile-time considerations.
4968 }
4969
4970 // In case of Neon, if there exists extractelement from lane != 0 such that
4971 // 1. extractelement does not necessitate a move from vector_reg -> GPR.
4972 // 2. extractelement result feeds into fmul.
4973 // 3. Other operand of fmul is an extractelement from lane 0 or lane
4974 // equivalent to 0.
4975 // then the extractelement can be merged with fmul in the backend and it
4976 // incurs no cost.
4977 // e.g.
4978 // define double @foo(<2 x double> %a) {
4979 // %1 = extractelement <2 x double> %a, i32 0
4980 // %2 = extractelement <2 x double> %a, i32 1
4981 // %res = fmul double %1, %2
4982 // ret double %res
4983 // }
4984 // %2 and %res can be merged in the backend to generate fmul d0, d0, v1.d[1]
4985 auto ExtractCanFuseWithFmul = [&]() {
4986 // We bail out if the extract is from lane 0.
4987 if (Index == 0)
4988 return false;
4989
4990 // Check if the scalar element type of the vector operand of ExtractElement
4991 // instruction is one of the allowed types.
4992 auto IsAllowedScalarTy = [&](const Type *T) {
4993 return T->isFloatTy() || T->isDoubleTy() ||
4994 (T->isHalfTy() && ST->hasFullFP16());
4995 };
4996
4997 // Check if the extractelement user is scalar fmul.
4998 auto IsUserFMulScalarTy = [](const Value *EEUser) {
4999 // Check if the user is scalar fmul.
5000 const auto *BO = dyn_cast<BinaryOperator>(EEUser);
5001 return BO && BO->getOpcode() == BinaryOperator::FMul &&
5002 !BO->getType()->isVectorTy();
5003 };
5004
5005 // Check if the extract index is from lane 0 or lane equivalent to 0 for a
5006 // certain scalar type and a certain vector register width.
5007 auto IsExtractLaneEquivalentToZero = [&](unsigned Idx, unsigned EltSz) {
5008 auto RegWidth =
5010 .getFixedValue();
5011 return Idx == 0 || (RegWidth != 0 && (Idx * EltSz) % RegWidth == 0);
5012 };
5013
5014 // Check if the type constraints on input vector type and result scalar type
5015 // of extractelement instruction are satisfied.
5016 if (!isa<FixedVectorType>(Ty) || !IsAllowedScalarTy(Ty->getScalarType()))
5017 return false;
5018
5019 if (Scalar) {
5020 DenseMap<User *, unsigned> UserToExtractIdx;
5021 for (auto *U : Scalar->users()) {
5022 if (!IsUserFMulScalarTy(U))
5023 return false;
5024 // Recording entry for the user is important. Index value is not
5025 // important.
5026 UserToExtractIdx[U];
5027 }
5028 if (UserToExtractIdx.empty())
5029 return false;
5030 for (auto &[S, U, L] : ScalarUserAndIdx) {
5031 for (auto *U : S->users()) {
5032 if (UserToExtractIdx.contains(U)) {
5033 auto *FMul = cast<BinaryOperator>(U);
5034 auto *Op0 = FMul->getOperand(0);
5035 auto *Op1 = FMul->getOperand(1);
5036 if ((Op0 == S && Op1 == S) || Op0 != S || Op1 != S) {
5037 UserToExtractIdx[U] = L;
5038 break;
5039 }
5040 }
5041 }
5042 }
5043 for (auto &[U, L] : UserToExtractIdx) {
5044 if (!IsExtractLaneEquivalentToZero(Index, Ty->getScalarSizeInBits()) &&
5045 !IsExtractLaneEquivalentToZero(L, Ty->getScalarSizeInBits()))
5046 return false;
5047 }
5048 } else {
5049 const auto *EE = cast<ExtractElementInst>(I);
5050
5051 const auto *IdxOp = dyn_cast<ConstantInt>(EE->getIndexOperand());
5052 if (!IdxOp)
5053 return false;
5054
5055 return !EE->users().empty() && all_of(EE->users(), [&](const User *U) {
5056 if (!IsUserFMulScalarTy(U))
5057 return false;
5058
5059 // Check if the other operand of extractelement is also extractelement
5060 // from lane equivalent to 0.
5061 const auto *BO = cast<BinaryOperator>(U);
5062 const auto *OtherEE = dyn_cast<ExtractElementInst>(
5063 BO->getOperand(0) == EE ? BO->getOperand(1) : BO->getOperand(0));
5064 if (OtherEE) {
5065 const auto *IdxOp = dyn_cast<ConstantInt>(OtherEE->getIndexOperand());
5066 if (!IdxOp)
5067 return false;
5068 return IsExtractLaneEquivalentToZero(
5069 cast<ConstantInt>(OtherEE->getIndexOperand())
5070 ->getValue()
5071 .getZExtValue(),
5072 OtherEE->getType()->getScalarSizeInBits());
5073 }
5074 return true;
5075 });
5076 }
5077 return true;
5078 };
5079
5080 if (Opcode == Instruction::ExtractElement && (I || Scalar) &&
5081 ExtractCanFuseWithFmul())
5082 return 0;
5083
5084 // All other insert/extracts cost this much.
5085 return CostKind == TTI::TCK_CodeSize ? 1
5086 : ST->getVectorInsertExtractBaseCost();
5087}
5088
5090 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, unsigned Index,
5091 const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC) const {
5092 // Treat insert at lane 0 into a poison vector as having zero cost. This
5093 // ensures vector broadcasts via an insert + shuffle (and will be lowered to a
5094 // single dup) are treated as cheap.
5095 if (Opcode == Instruction::InsertElement && Index == 0 && Op0 &&
5096 isa<PoisonValue>(Op0))
5097 return 0;
5098 return getVectorInstrCostHelper(Opcode, Ty, CostKind, Index, nullptr, nullptr,
5099 {}, VIC);
5100}
5101
5104 ArrayRef<int> Mask, ArrayRef<Value *> Scalars,
5106 GatherUseOps) const {
5107 if (Scalars.empty() || Mask.empty() || !ST->isNeonAvailable() ||
5108 !ShuffleVectorInst::isZeroEltSplatMask(Mask, Mask.size()))
5110
5111 const auto *SplatIt = find_if_not(Scalars, IsaPred<UndefValue>);
5112 if (SplatIt == Scalars.end() || isa<Constant, ExtractElementInst>(*SplatIt) ||
5113 any_of(Scalars,
5114 [&](Value *V) { return V != *SplatIt && !isa<UndefValue>(V); }))
5116
5117 // The indexed (by element) FMLA/FMLS take the splatted operand from a lane of
5118 // a 128-bit register, see isProfitableToSinkOperands(). SVE indexes within
5119 // each 128-bit segment, so a wider fixed-length SVE vector still needs a dup.
5120 Type *ScalarTy = (*SplatIt)->getType();
5121 if (!ScalarTy->isFloatTy() && !ScalarTy->isDoubleTy() &&
5122 !(ScalarTy->isHalfTy() && ST->hasFullFP16()))
5124 if (ST->useSVEForFixedLengthVectors() &&
5125 Mask.size() * ScalarTy->getPrimitiveSizeInBits().getFixedValue() >
5128
5129 // Same use limit as SLP, bounds the walk over the users of the scalar.
5130 constexpr unsigned MaxUses = 64;
5131 if ((*SplatIt)->hasNUsesOrMore(MaxUses))
5133
5135 if (!GatherUseOps(UserOps) || UserOps.empty() ||
5136 any_of(UserOps, [](const TargetTransformInfo::BuildVectorUseOp &UserOp) {
5137 return UserOp.Opcode != Instruction::FMul;
5138 }))
5140
5141 // Only fmuls fused with their fadd/fsub user (FMLA/FMLS by element) are
5142 // reported. An unfused fmul by element takes the lane too, but reporting it
5143 // makes SLP vectorize VF=2 trees whose alternate fadd/fsub nodes it
5144 // undercounts. Mixed fadd and fsub users form such an alternate node, which
5145 // is not fused.
5146 std::optional<unsigned> FusedOpcode;
5147 if (all_of((*SplatIt)->users(),
5148 [&](const User *U) {
5149 if (!match(U, m_FMul(m_Value(), m_Value())))
5150 return true;
5151 if (!match(U, m_OneUse(m_AllowContract(m_Value()))))
5152 return false;
5153 const auto *FAddSub = dyn_cast<Instruction>(U->user_back());
5154 if (!FAddSub ||
5155 FAddSub->getParent() != cast<Instruction>(U)->getParent() ||
5156 !match(FAddSub, m_AllowContract(m_CombineOr(
5157 m_FAdd(m_Value(), m_Value()),
5158 m_FSub(m_Value(), m_Value())))))
5159 return false;
5160 if (!FusedOpcode)
5161 FusedOpcode = FAddSub->getOpcode();
5162 return *FusedOpcode == FAddSub->getOpcode();
5163 }) &&
5164 FusedOpcode)
5166
5168}
5169
5171 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, unsigned Index,
5172 Value *Scalar, ArrayRef<std::tuple<Value *, User *, int>> ScalarUserAndIdx,
5173 TTI::VectorInstrContext VIC) const {
5174 return getVectorInstrCostHelper(Opcode, Ty, CostKind, Index, nullptr, Scalar,
5175 ScalarUserAndIdx, VIC);
5176}
5177
5180 TTI::TargetCostKind CostKind, unsigned Index,
5181 TTI::VectorInstrContext VIC) const {
5182 return getVectorInstrCostHelper(I.getOpcode(), Ty, CostKind, Index, &I,
5183 nullptr, {}, VIC);
5184}
5185
5188 TTI::TargetCostKind CostKind,
5189 unsigned Index) const {
5190 if (isa<FixedVectorType>(Ty))
5191 return BaseT::getIndexedVectorInstrCostFromEnd(Opcode, Ty, CostKind, Index);
5192
5193 // This typically requires both while and lastb instructions in order
5194 // to extract the last element. If this is in a loop the while
5195 // instruction can at least be hoisted out, although it will consume a
5196 // predicate register. The cost should be more expensive than the base
5197 // extract cost, which is 2 for most CPUs.
5198 return CostKind == TTI::TCK_CodeSize
5199 ? 2
5200 : ST->getVectorInsertExtractBaseCost() + 1;
5201}
5202
5204 VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract,
5205 TTI::TargetCostKind CostKind, bool ForPoisonSrc, ArrayRef<Value *> VL,
5206 TTI::VectorInstrContext VIC) const {
5209
5210 // There's no scalarization overhead if ld1/st1 is cheap and the
5211 // insert/extracts can be folded into the load/stores.
5212 if (ST->hasFastLD1Single()) {
5213 if ((VIC == TTI::VectorInstrContext::Store && Extract) ||
5214 (VIC == TTI::VectorInstrContext::Load && Insert))
5215 return 0;
5216 }
5217
5218 if (Ty->getElementType()->isFloatingPointTy())
5219 return BaseT::getScalarizationOverhead(Ty, DemandedElts, Insert, Extract,
5220 CostKind);
5221 unsigned VecInstCost =
5222 CostKind == TTI::TCK_CodeSize ? 1 : ST->getVectorInsertExtractBaseCost();
5223 return DemandedElts.popcount() * (Insert + Extract) * VecInstCost;
5224}
5225
5226std::optional<InstructionCost> AArch64TTIImpl::getFP16BF16PromoteCost(
5227 Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info,
5228 TTI::OperandValueInfo Op2Info, bool IncludeTrunc, bool CanUseSVE,
5229 std::function<InstructionCost(Type *)> InstCost) const {
5230 if (!Ty->getScalarType()->isHalfTy() && !Ty->getScalarType()->isBFloatTy())
5231 return std::nullopt;
5232 if (Ty->getScalarType()->isHalfTy() && ST->hasFullFP16())
5233 return std::nullopt;
5234 // If we have +sve-b16b16 the operation can be promoted to SVE.
5235 if (CanUseSVE && ST->hasSVEB16B16() && ST->isNonStreamingSVEorSME2Available())
5236 return std::nullopt;
5237
5238 Type *PromotedTy = Ty->getWithNewType(Type::getFloatTy(Ty->getContext()));
5239 InstructionCost Cost = getCastInstrCost(Instruction::FPExt, PromotedTy, Ty,
5240 TTI::CastContextHint::None, CostKind);
5241 if (!Op1Info.isConstant() && !Op2Info.isConstant())
5242 Cost *= 2;
5243 Cost += InstCost(PromotedTy);
5244 if (IncludeTrunc)
5245 Cost += getCastInstrCost(Instruction::FPTrunc, Ty, PromotedTy,
5246 TTI::CastContextHint::None, CostKind);
5247 return Cost;
5248}
5249
5251 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
5253 ArrayRef<const Value *> Args, const Instruction *CtxI,
5254 const TargetLibraryInfo *TLibInfo, ArrayRef<const Value *> Scalars) const {
5255
5256 // The code-generator is currently not able to handle scalable vectors
5257 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
5258 // it until all instructions are vetted.
5259 int ISD = TLI->InstructionOpcodeToISD(Opcode);
5260 if (auto *VTy = dyn_cast<ScalableVectorType>(Ty))
5261 if (VTy->getElementCount() == ElementCount::getScalable(1))
5264
5265 if (CtxI && CtxI->getOpcode() == Opcode && !CtxI->use_empty() &&
5266 useNeonVector(Ty)) {
5267 // The Ands of a bit select are folded into the BSL that the Or becomes.
5268 Instruction *MainAnd, *OtherAnd;
5269 Value *A, *B;
5270 if (Opcode == Instruction::And && CtxI->hasOneUse() &&
5271 matchBSL(CtxI->user_back(), MainAnd, OtherAnd, A, B))
5272 return 0;
5273
5274 // A Not is folded into the BIC, ORN or BSL of each And/Or using it, unless
5275 // that And/Or negates both of its operands.
5276 if (match(CtxI, m_Not(m_Value())) &&
5277 all_of(CtxI->users(), [&](const User *U) {
5278 const auto *UI = cast<Instruction>(U);
5279 return is_contained({Instruction::And, Instruction::Or},
5280 UI->getOpcode()) &&
5281 UI->getParent() == CtxI->getParent() &&
5282 !match(UI, m_BinOp(m_Not(m_Value()), m_Not(m_Value())));
5283 }))
5284 return 0;
5285 }
5286
5287 // Legalize the type.
5288 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
5289
5290 // TODO: Handle more cost kinds for floating point operations.
5291 if (ISD == ISD::FADD || ISD == ISD::FSUB || ISD == ISD::FMUL ||
5292 ISD == ISD::FDIV || ISD == ISD::FREM || ISD == ISD::FNEG)
5293 if (CostKind != TTI::TCK_RecipThroughput)
5294 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
5295 Op2Info, Args, CtxI, TLibInfo,
5296 Scalars);
5297
5298 if (ISD == ISD::FADD || ISD == ISD::FSUB || ISD == ISD::FMUL ||
5299 ISD == ISD::FDIV || ISD == ISD::FREM) {
5300 // Increase the cost for half and bfloat types if not architecturally
5301 // supported.
5302 if (auto PromotedCost = getFP16BF16PromoteCost(
5303 Ty, CostKind, Op1Info, Op2Info, /*IncludeTrunc=*/true,
5304 // There is not native support for fdiv/frem even with +sve-b16b16.
5305 /*CanUseSVE=*/ISD != ISD::FDIV && ISD != ISD::FREM,
5306 [&](Type *PromotedTy) {
5307 return getArithmeticInstrCost(Opcode, PromotedTy, CostKind,
5308 Op1Info, Op2Info);
5309 }))
5310 return *PromotedCost;
5311
5312 // fp128 all go via libcalls
5313 if (Ty->getScalarType()->isFP128Ty())
5314 return (CostKind == TTI::TCK_CodeSize ? 1 : 10) * LT.first;
5315 }
5316
5317 // If the operation is a widening instruction (smull or umull) and both
5318 // operands are extends the cost can be cheaper by considering that the
5319 // operation will operate on the narrowest type size possible (double the
5320 // largest input size) and a further extend.
5321 if (Type *ExtTy = isBinExtWideningInstruction(Opcode, Ty, Args)) {
5322 if (ExtTy != Ty)
5323 return getArithmeticInstrCost(Opcode, ExtTy, CostKind) +
5324 getCastInstrCost(Instruction::ZExt, Ty, ExtTy,
5325 TTI::CastContextHint::None, CostKind);
5326 return LT.first;
5327 }
5328
5329 switch (ISD) {
5330 default:
5331 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
5332 Op2Info);
5333 case ISD::ADD:
5334 case ISD::SUB:
5335 return LT.first; // Also works for i128
5336 case ISD::MUL: {
5337 // i128 multiply is umulh + 2*madd + mul and grows ~O(Bitwidth^2). For
5338 // scalable vectors the cost of LT.first will be invalid, leading to an
5339 // invalid cost overall.
5340 unsigned Mul64CostFactor = (CostKind == TTI::TCK_RecipThroughput &&
5341 ST->hasLimited64bitVectorMulBandwidth())
5342 ? 4
5343 : 1;
5344 if (Ty->getScalarSizeInBits() > 64) {
5345 unsigned NumLanes = isa<FixedVectorType>(Ty)
5346 ? cast<FixedVectorType>(Ty)->getNumElements()
5347 : 1;
5348 InstructionCost CostPerLane = LT.first / NumLanes;
5349 return CostPerLane * CostPerLane * NumLanes * Mul64CostFactor;
5350 }
5351
5352 if (LT.second == MVT::v2i64) {
5353 // When SVE is available, then we can lower the v2i64 operation using
5354 // the SVE mul instruction, which has a lower cost.
5355 if (ST->hasSVE())
5356 return LT.first * Mul64CostFactor;
5357
5358 // When SVE is not available, there is no MUL.2d instruction,
5359 // which means mul <2 x i64> is expensive as elements are extracted
5360 // from the vectors and the muls scalarized.
5361 // As getScalarizationOverhead is a bit too pessimistic, we
5362 // estimate the cost for a i64 vector directly here, which is:
5363 // - four 2-cost i64 extracts,
5364 // - two 2-cost i64 inserts, and
5365 // - two 1-cost muls.
5366 // So, for a v2i64 with LT.First = 1 the cost is 14, and for a v4i64 with
5367 // LT.first = 2 the cost is 28.
5368 return cast<VectorType>(Ty)->getElementCount().getKnownMinValue() *
5369 (getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind) +
5370 getVectorInstrCost(Instruction::ExtractElement, Ty, CostKind, -1,
5371 nullptr, nullptr) *
5372 2 +
5373 getVectorInstrCost(Instruction::InsertElement, Ty, CostKind, -1,
5374 nullptr, nullptr));
5375 }
5376
5377 if (LT.second == MVT::nxv2i64)
5378 return LT.first * Mul64CostFactor;
5379
5380 return LT.first;
5381 }
5382 case ISD::SREM:
5383 case ISD::SDIV:
5384 /*
5385 Notes for sdiv/srem specific costs:
5386 1. This only considers the cases where the divisor is constant, uniform and
5387 (pow-of-2/non-pow-of-2). Other cases are not important since they either
5388 result in some form of (ldr + adrp), corresponding to constant vectors, or
5389 scalarization of the division operation.
5390 2. Constant divisors, either negative in whole or partially, don't result in
5391 significantly different codegen as compared to positive constant divisors.
5392 So, we don't consider negative divisors separately.
5393 3. If the codegen is significantly different with SVE, it has been indicated
5394 using comments at appropriate places.
5395
5396 sdiv specific cases:
5397 -----------------------------------------------------------------------
5398 codegen | pow-of-2 | Type
5399 -----------------------------------------------------------------------
5400 add + cmp + csel + asr | Y | i64
5401 add + cmp + csel + asr | Y | i32
5402 -----------------------------------------------------------------------
5403
5404 srem specific cases:
5405 -----------------------------------------------------------------------
5406 codegen | pow-of-2 | Type
5407 -----------------------------------------------------------------------
5408 negs + and + and + csneg | Y | i64
5409 negs + and + and + csneg | Y | i32
5410 -----------------------------------------------------------------------
5411
5412 other sdiv/srem cases:
5413 -------------------------------------------------------------------------
5414 common codegen | + srem | + sdiv | pow-of-2 | Type
5415 -------------------------------------------------------------------------
5416 smulh + asr + add + add | - | - | N | i64
5417 smull + lsr + add + add | - | - | N | i32
5418 usra | and + sub | sshr | Y | <2 x i64>
5419 2 * (scalar code) | - | - | N | <2 x i64>
5420 usra | bic + sub | sshr + neg | Y | <4 x i32>
5421 smull2 + smull + uzp2 | mls | - | N | <4 x i32>
5422 + sshr + usra | | | |
5423 -------------------------------------------------------------------------
5424 */
5425 if (Op2Info.isConstant() && Op2Info.isUniform()) {
5426 InstructionCost AddCost =
5427 getArithmeticInstrCost(Instruction::Add, Ty, CostKind,
5428 Op1Info.getNoProps(), Op2Info.getNoProps());
5429 InstructionCost AsrCost =
5430 getArithmeticInstrCost(Instruction::AShr, Ty, CostKind,
5431 Op1Info.getNoProps(), Op2Info.getNoProps());
5432 InstructionCost MulCost =
5433 getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
5434 Op1Info.getNoProps(), Op2Info.getNoProps());
5435 // add/cmp/csel/csneg should have similar cost while asr/negs/and should
5436 // have similar cost.
5437 auto VT = TLI->getValueType(DL, Ty);
5438 if (VT.isScalarInteger() && VT.getSizeInBits() <= 64) {
5439 if (Op2Info.isPowerOf2() || Op2Info.isNegatedPowerOf2()) {
5440 // Neg can be folded into the asr instruction.
5441 return ISD == ISD::SDIV ? (3 * AddCost + AsrCost)
5442 : (3 * AsrCost + AddCost);
5443 } else {
5444 return MulCost + AsrCost + 2 * AddCost;
5445 }
5446 } else if (VT.isVector()) {
5447 InstructionCost UsraCost = 2 * AsrCost;
5448 if (Op2Info.isPowerOf2() || Op2Info.isNegatedPowerOf2()) {
5449 // Division with scalable types corresponds to native 'asrd'
5450 // instruction when SVE is available.
5451 // e.g. %1 = sdiv <vscale x 4 x i32> %a, splat (i32 8)
5452
5453 // One more for the negation in SDIV
5455 (Op2Info.isNegatedPowerOf2() && ISD == ISD::SDIV) ? AsrCost : 0;
5456 if (Ty->isScalableTy() && ST->hasSVE())
5457 Cost += 2 * AsrCost;
5458 else {
5459 Cost +=
5460 UsraCost +
5461 (ISD == ISD::SDIV
5462 ? (LT.second.getScalarType() == MVT::i64 ? 1 : 2) * AsrCost
5463 : 2 * AddCost);
5464 }
5465 return Cost;
5466 } else if (LT.second == MVT::v2i64) {
5467 return VT.getVectorNumElements() *
5468 getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind,
5469 Op1Info.getNoProps(),
5470 Op2Info.getNoProps());
5471 } else {
5472 // When SVE is available, we get:
5473 // smulh + lsr + add/sub + asr + add/sub.
5474 if (Ty->isScalableTy() && ST->hasSVE())
5475 return MulCost /*smulh cost*/ + 2 * AddCost + 2 * AsrCost;
5476 return 2 * MulCost + AddCost /*uzp2 cost*/ + AsrCost + UsraCost;
5477 }
5478 }
5479 }
5480 if (Op2Info.isConstant() && !Op2Info.isUniform() &&
5481 LT.second.isFixedLengthVector()) {
5482 // FIXME: When the constant vector is non-uniform, this may result in
5483 // loading the vector from constant pool or in some cases, may also result
5484 // in scalarization. For now, we are approximating this with the
5485 // scalarization cost.
5486 auto ExtractCost = 2 * getVectorInstrCost(Instruction::ExtractElement, Ty,
5487 CostKind, -1, nullptr, nullptr);
5488 auto InsertCost = getVectorInstrCost(Instruction::InsertElement, Ty,
5489 CostKind, -1, nullptr, nullptr);
5490 unsigned NElts = cast<FixedVectorType>(Ty)->getNumElements();
5491 return ExtractCost + InsertCost +
5492 NElts * getArithmeticInstrCost(Opcode, Ty->getScalarType(),
5493 CostKind, Op1Info.getNoProps(),
5494 Op2Info.getNoProps());
5495 }
5496 [[fallthrough]];
5497 case ISD::UDIV:
5498 case ISD::UREM: {
5499 auto VT = TLI->getValueType(DL, Ty);
5500 if (Op2Info.isConstant()) {
5501 // If the operand is a power of 2 we can use the shift or and cost.
5502 if (ISD == ISD::UDIV && Op2Info.isPowerOf2())
5503 return getArithmeticInstrCost(Instruction::LShr, Ty, CostKind,
5504 Op1Info.getNoProps(),
5505 Op2Info.getNoProps());
5506 if (ISD == ISD::UREM && Op2Info.isPowerOf2())
5507 return getArithmeticInstrCost(Instruction::And, Ty, CostKind,
5508 Op1Info.getNoProps(),
5509 Op2Info.getNoProps());
5510
5511 if (ISD == ISD::UDIV || ISD == ISD::UREM) {
5512 // Divides by a constant are expanded to MULHU + SUB + SRL + ADD + SRL.
5513 // The MULHU will be expanded to UMULL for the types not listed below,
5514 // and will become a pair of UMULL+MULL2 for 128bit vectors.
5515 bool HasMULH = VT == MVT::i64 || LT.second == MVT::nxv2i64 ||
5516 LT.second == MVT::nxv4i32 || LT.second == MVT::nxv8i16 ||
5517 LT.second == MVT::nxv16i8;
5518 bool Is128bit = LT.second.is128BitVector();
5519
5520 InstructionCost MulCost =
5521 getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
5522 Op1Info.getNoProps(), Op2Info.getNoProps());
5523 InstructionCost AddCost =
5524 getArithmeticInstrCost(Instruction::Add, Ty, CostKind,
5525 Op1Info.getNoProps(), Op2Info.getNoProps());
5526 InstructionCost ShrCost =
5527 getArithmeticInstrCost(Instruction::AShr, Ty, CostKind,
5528 Op1Info.getNoProps(), Op2Info.getNoProps());
5529 InstructionCost DivCost = MulCost * (Is128bit ? 2 : 1) + // UMULL/UMULH
5530 (HasMULH ? 0 : ShrCost) + // UMULL shift
5531 AddCost * 2 + ShrCost;
5532 return DivCost + (ISD == ISD::UREM ? MulCost + AddCost : 0);
5533 }
5534 }
5535
5536 // div i128's are lowered as libcalls. Pass nullptr as (u)divti3 calls are
5537 // emitted by the backend even when those functions are not declared in the
5538 // module.
5539 if (!VT.isVector() && VT.getSizeInBits() > 64)
5540 return getCallInstrCost(/*Function*/ nullptr, Ty, {Ty, Ty}, CostKind);
5541
5542 InstructionCost Cost = BaseT::getArithmeticInstrCost(
5543 Opcode, Ty, CostKind, Op1Info, Op2Info);
5544 if (Ty->isVectorTy() && (ISD == ISD::SDIV || ISD == ISD::UDIV)) {
5545 if (TLI->isOperationLegalOrCustom(ISD, LT.second) && ST->hasSVE()) {
5546 // SDIV/UDIV operations are lowered using SVE, then we can have less
5547 // costs.
5548 if (VT.isSimple() && isa<FixedVectorType>(Ty) &&
5549 Ty->getPrimitiveSizeInBits().getFixedValue() < 128) {
5550 static const CostTblEntry DivTbl[]{
5551 {ISD::SDIV, MVT::v2i8, 5}, {ISD::SDIV, MVT::v4i8, 8},
5552 {ISD::SDIV, MVT::v8i8, 8}, {ISD::SDIV, MVT::v2i16, 5},
5553 {ISD::SDIV, MVT::v4i16, 5}, {ISD::SDIV, MVT::v2i32, 1},
5554 {ISD::UDIV, MVT::v2i8, 5}, {ISD::UDIV, MVT::v4i8, 8},
5555 {ISD::UDIV, MVT::v8i8, 8}, {ISD::UDIV, MVT::v2i16, 5},
5556 {ISD::UDIV, MVT::v4i16, 5}, {ISD::UDIV, MVT::v2i32, 1}};
5557
5558 const auto *Entry = CostTableLookup(DivTbl, ISD, VT.getSimpleVT());
5559 if (nullptr != Entry)
5560 return Entry->Cost;
5561 }
5562 // A non-power-of-2 count can't divide as a single whole-register op
5563 // (an inactive lane's leftover value could be a zero divisor and
5564 // trap), so the legalizer emits one div per whole register plus one
5565 // per set bit of the remainder (e.g. <7 x i32> emits 3 divs, not 2).
5566 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty);
5567 FVTy && LT.second.isFixedLengthVector()) {
5568 unsigned NumElts = FVTy->getNumElements();
5569 unsigned RegElts = LT.second.getVectorNumElements();
5570 if (RegElts > 0)
5571 Cost = (NumElts / RegElts + popcount(NumElts % RegElts)) * 2;
5572 }
5573 // For 8/16-bit elements, the cost is higher because the type
5574 // requires promotion and possibly splitting:
5575 if (LT.second.getScalarType() == MVT::i8)
5576 Cost *= 8;
5577 else if (LT.second.getScalarType() == MVT::i16)
5578 Cost *= 4;
5579 return Cost;
5580 } else {
5581 // If one of the operands is a uniform constant then the cost for each
5582 // element is Cost for insertion, extraction and division.
5583 // Insertion cost = 2, Extraction Cost = 2, Division = cost for the
5584 // operation with scalar type
5585 if ((Op1Info.isConstant() && Op1Info.isUniform()) ||
5586 (Op2Info.isConstant() && Op2Info.isUniform())) {
5587 if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
5588 InstructionCost DivCost = BaseT::getArithmeticInstrCost(
5589 Opcode, Ty->getScalarType(), CostKind, Op1Info, Op2Info);
5590 return (4 + DivCost) * VTy->getNumElements();
5591 }
5592 }
5593 // On AArch64, without SVE, vector divisions are expanded
5594 // into scalar divisions of each pair of elements.
5595 Cost += getVectorInstrCost(Instruction::ExtractElement, Ty, CostKind,
5596 -1, nullptr, nullptr);
5597 Cost += getVectorInstrCost(Instruction::InsertElement, Ty, CostKind, -1,
5598 nullptr, nullptr);
5599 }
5600
5601 // TODO: if one of the arguments is scalar, then it's not necessary to
5602 // double the cost of handling the vector elements.
5603 Cost += Cost;
5604 }
5605 return Cost;
5606 }
5607 case ISD::XOR:
5608 case ISD::OR:
5609 case ISD::AND:
5610 // TODO: revisit these costs as it's not accurate enough for non-uniform
5611 // constant.
5612 return LT.first;
5613 case ISD::SRL:
5614 case ISD::SRA:
5615 case ISD::SHL: {
5616 // Immediate vector shifts require uniform shift amounts. Non-uniform
5617 // constants therefore use variable shifts and require materializing the
5618 // shift vector. Account for a shift and materialization per legalized
5619 // vector, together with shared setup.
5620 // This cost is for (ldr, shl) + adrp
5621 // TODO: These costs are based on CodeSize only, consider other CostKinds.
5622 if (Op2Info.isConstant() && !Op2Info.isUniform() &&
5623 LT.second.isFixedLengthVector())
5624 return 2 * LT.first + 1;
5625
5626 // Marked 'custom' for combining purposes; a uniform shift amount still
5627 // lowers to a single legal instruction.
5628 return LT.first;
5629 }
5630
5631 case ISD::FNEG:
5632 // Scalar fmul(fneg) or fneg(fmul) can be converted to fnmul
5633 if ((Ty->isFloatTy() || Ty->isDoubleTy() ||
5634 (Ty->isHalfTy() && ST->hasFullFP16())) &&
5635 CtxI &&
5636 ((CtxI->hasOneUse() &&
5637 match(*CtxI->user_begin(), m_FMul(m_Value(), m_Value()))) ||
5638 match(CtxI->getOperand(0), m_FMul(m_Value(), m_Value()))))
5639 return 0;
5640 [[fallthrough]];
5641 case ISD::FADD:
5642 case ISD::FSUB:
5643 if (!Ty->getScalarType()->isFP128Ty())
5644 return LT.first;
5645 [[fallthrough]];
5646 case ISD::FMUL:
5647 case ISD::FDIV:
5648 // These nodes are marked as 'custom' just to lower them to SVE.
5649 // We know said lowering will incur no additional cost.
5650 if (!Ty->getScalarType()->isFP128Ty())
5651 return 2 * LT.first;
5652
5653 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
5654 Op2Info);
5655 case ISD::FREM:
5656 // Pass nullptr as fmod/fmodf calls are emitted by the backend even when
5657 // those functions are not declared in the module.
5658 if (!Ty->isVectorTy())
5659 return getCallInstrCost(/*Function*/ nullptr, Ty, {Ty, Ty}, CostKind);
5660 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
5661 Op2Info);
5662 }
5663}
5664
5667 const SCEV *Ptr,
5668 TTI::TargetCostKind CostKind) const {
5669 // Address computations in vectorized code with non-consecutive addresses will
5670 // likely result in more instructions compared to scalar code where the
5671 // computation can more often be merged into the index mode. The resulting
5672 // extra micro-ops can significantly decrease throughput.
5673 unsigned NumVectorInstToHideOverhead =
5674 ST->getCLOpts().neon_nonconst_stride_overhead;
5675 int MaxMergeDistance = 64;
5676
5677 if (PtrTy->isVectorTy() && SE &&
5678 !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
5679 return NumVectorInstToHideOverhead;
5680
5681 // In many cases the address computation is not merged into the instruction
5682 // addressing mode.
5683 return 1;
5684}
5685
5686/// Check whether Opcode1 has less throughput according to the scheduling
5687/// model than Opcode2. For variant scheduling classes, the lowest throughput
5688/// of Opcode1 and the highest throughput of Opcode2 are compared among all the
5689/// scheduling classes they may be resolved to.
5691 unsigned Opcode1, unsigned Opcode2) const {
5692 const MCSchedModel &Sched = ST->getSchedModel();
5693 const TargetInstrInfo *TII = ST->getInstrInfo();
5694 if (!Sched.hasInstrSchedModel())
5695 return false;
5696
5697 auto GetRThroughput = [&](unsigned Opcode, bool Highest) {
5698 std::optional<double> Res;
5699 SmallVector<unsigned> Worklist = {TII->get(Opcode).getSchedClass()};
5700 while (!Worklist.empty()) {
5701 unsigned SchedClass = Worklist.pop_back_val();
5702 const MCSchedClassDesc *SCD = Sched.getSchedClassDesc(SchedClass);
5703 if (SCD->isVariant()) {
5704 append_range(Worklist, AArch64_MC::getVariantSchedClassTargets(
5705 SchedClass, Sched.getProcessorID()));
5706 continue;
5707 }
5708 if (!SCD->isValid())
5709 continue;
5710 double RThroughput = MCSchedModel::getReciprocalThroughput(*ST, *SCD);
5711 if (!Res || (Highest ? RThroughput > *Res : RThroughput < *Res))
5712 Res = RThroughput;
5713 }
5714 return Res;
5715 };
5716 std::optional<double> RThroughput1 =
5717 GetRThroughput(Opcode1, /*Highest=*/true);
5718 std::optional<double> RThroughput2 =
5719 GetRThroughput(Opcode2, /*Highest=*/false);
5720 return RThroughput1 && RThroughput2 && *RThroughput1 > *RThroughput2;
5721}
5722
5724 unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred,
5726 TTI::OperandValueInfo Op2Info, const Instruction *I) const {
5727 // We don't lower some vector selects well that are wider than the register
5728 // width. TODO: Improve this with different cost kinds.
5729 if (isa<FixedVectorType>(ValTy) && Opcode == Instruction::Select) {
5730 // We would need this many instructions to hide the scalarization happening.
5731 const int AmortizationCost = 20;
5732
5733 // If VecPred is not set, check if we can get a predicate from the context
5734 // instruction, if its type matches the requested ValTy.
5735 if (VecPred == CmpInst::BAD_ICMP_PREDICATE && I && I->getType() == ValTy) {
5736 CmpPredicate CurrentPred;
5737 if (match(I, m_Select(m_Cmp(CurrentPred, m_Value(), m_Value()), m_Value(),
5738 m_Value())))
5739 VecPred = CurrentPred;
5740 }
5741 // Check if we have a compare/select chain that can be lowered using
5742 // a (F)CMxx & BFI pair.
5743 if (CmpInst::isIntPredicate(VecPred) || VecPred == CmpInst::FCMP_OLE ||
5744 VecPred == CmpInst::FCMP_OLT || VecPred == CmpInst::FCMP_OGT ||
5745 VecPred == CmpInst::FCMP_OGE || VecPred == CmpInst::FCMP_OEQ ||
5746 VecPred == CmpInst::FCMP_UNE) {
5747 static const auto ValidMinMaxTys = {
5748 MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16, MVT::v2i32,
5749 MVT::v4i32, MVT::v2i64, MVT::v2f32, MVT::v4f32, MVT::v2f64};
5750 static const auto ValidFP16MinMaxTys = {MVT::v4f16, MVT::v8f16};
5751
5752 auto LT = getTypeLegalizationCost(ValTy);
5753 if (any_of(ValidMinMaxTys, equal_to(LT.second)) ||
5754 (ST->hasFullFP16() &&
5755 any_of(ValidFP16MinMaxTys, equal_to(LT.second))))
5756 return LT.first;
5757 }
5758
5759 static const TypeConversionCostTblEntry VectorSelectTbl[] = {
5760 {Instruction::Select, MVT::v2i1, MVT::v2f32, 2},
5761 {Instruction::Select, MVT::v2i1, MVT::v2f64, 2},
5762 {Instruction::Select, MVT::v4i1, MVT::v4f32, 2},
5763 {Instruction::Select, MVT::v4i1, MVT::v4f16, 2},
5764 {Instruction::Select, MVT::v8i1, MVT::v8f16, 2},
5765 {Instruction::Select, MVT::v16i1, MVT::v16i16, 16},
5766 {Instruction::Select, MVT::v8i1, MVT::v8i32, 8},
5767 {Instruction::Select, MVT::v16i1, MVT::v16i32, 16},
5768 {Instruction::Select, MVT::v4i1, MVT::v4i64, 4 * AmortizationCost},
5769 {Instruction::Select, MVT::v8i1, MVT::v8i64, 8 * AmortizationCost},
5770 {Instruction::Select, MVT::v16i1, MVT::v16i64, 16 * AmortizationCost}};
5771
5772 EVT SelCondTy = TLI->getValueType(DL, CondTy);
5773 EVT SelValTy = TLI->getValueType(DL, ValTy);
5774 if (SelCondTy.isSimple() && SelValTy.isSimple()) {
5775 if (const auto *Entry = ConvertCostTableLookup(VectorSelectTbl, Opcode,
5776 SelCondTy.getSimpleVT(),
5777 SelValTy.getSimpleVT()))
5778 return Entry->Cost;
5779 }
5780 }
5781
5782 if (Opcode == Instruction::FCmp) {
5783 if (auto PromotedCost = getFP16BF16PromoteCost(
5784 ValTy, CostKind, Op1Info, Op2Info, /*IncludeTrunc=*/false,
5785 // TODO: Consider costing SVE FCMPs.
5786 /*CanUseSVE=*/false, [&](Type *PromotedTy) {
5788 getCmpSelInstrCost(Opcode, PromotedTy, CondTy, VecPred,
5789 CostKind, Op1Info, Op2Info);
5790 if (isa<VectorType>(PromotedTy))
5792 Instruction::Trunc,
5795 TTI::CastContextHint::None, CostKind);
5796 return Cost;
5797 }))
5798 return *PromotedCost;
5799
5800 auto LT = getTypeLegalizationCost(ValTy);
5801 // Model unknown fp compares as a libcall.
5802 if (LT.second.getScalarType() != MVT::f64 &&
5803 LT.second.getScalarType() != MVT::f32 &&
5804 LT.second.getScalarType() != MVT::f16)
5805 return LT.first * getCallInstrCost(/*Function*/ nullptr, ValTy,
5806 {ValTy, ValTy}, CostKind);
5807
5808 // Some comparison operators require expanding to multiple compares + or.
5809 unsigned Factor = 1;
5810 if (!CondTy->isVectorTy() &&
5811 (VecPred == FCmpInst::FCMP_ONE || VecPred == FCmpInst::FCMP_UEQ))
5812 Factor = 2; // fcmp with 2 selects
5813 else if (isa<FixedVectorType>(ValTy) &&
5814 (VecPred == FCmpInst::FCMP_ONE || VecPred == FCmpInst::FCMP_UEQ ||
5815 VecPred == FCmpInst::FCMP_ORD || VecPred == FCmpInst::FCMP_UNO))
5816 Factor = 3; // fcmxx+fcmyy+or
5817 else if (isa<ScalableVectorType>(ValTy) &&
5818 (VecPred == FCmpInst::FCMP_ONE || VecPred == FCmpInst::FCMP_UEQ))
5819 Factor = 3; // fcmxx+fcmyy+or
5820
5821 if (isa<ScalableVectorType>(ValTy) &&
5822 CostKind == TTI::TCK_RecipThroughput &&
5823 hasKnownLowerThroughputFromSchedulingModel(AArch64::FCMEQ_PPzZZ_S,
5824 AArch64::FCMEQv4f32))
5825 Factor *= 2;
5826
5827 return Factor * (CostKind == TTI::TCK_Latency ? 2 : LT.first);
5828 }
5829
5830 // Treat the icmp in icmp(and, 0) or icmp(and, -1/1) when it can be folded to
5831 // icmp(and, 0) as free, as we can make use of ands, but only if the
5832 // comparison is not unsigned. FIXME: Enable for non-throughput cost kinds
5833 // providing it will not cause performance regressions.
5834 if (CostKind == TTI::TCK_RecipThroughput && ValTy->isIntegerTy() &&
5835 Opcode == Instruction::ICmp && I && !CmpInst::isUnsigned(VecPred) &&
5836 TLI->isTypeLegal(TLI->getValueType(DL, ValTy)) &&
5837 match(I->getOperand(0), m_And(m_Value(), m_Value()))) {
5838 if (match(I->getOperand(1), m_Zero()))
5839 return 0;
5840
5841 // x >= 1 / x < 1 -> x > 0 / x <= 0
5842 if (match(I->getOperand(1), m_One()) &&
5843 (VecPred == CmpInst::ICMP_SLT || VecPred == CmpInst::ICMP_SGE))
5844 return 0;
5845
5846 // x <= -1 / x > -1 -> x > 0 / x <= 0
5847 if (match(I->getOperand(1), m_AllOnes()) &&
5848 (VecPred == CmpInst::ICMP_SLE || VecPred == CmpInst::ICMP_SGT))
5849 return 0;
5850 }
5851
5852 // The base case handles scalable vectors fine for now, since it treats the
5853 // cost as 1 * legalization cost.
5855 Opcode, ValTy, CondTy, VecPred, CostKind, Op1Info, Op2Info, I);
5856 if (Opcode == Instruction::ICmp && isa<ScalableVectorType>(ValTy) &&
5857 CostKind == TTI::TCK_RecipThroughput &&
5858 hasKnownLowerThroughputFromSchedulingModel(AArch64::CMPEQ_PPzZZ_S,
5859 AArch64::CMEQv4i32))
5860 Cost *= 2;
5861 return Cost;
5862}
5863
5865AArch64TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
5867 if (ST->requiresStrictAlign()) {
5868 // TODO: Add cost modeling for strict align. Misaligned loads expand to
5869 // a bunch of instructions when strict align is enabled.
5870 return Options;
5871 }
5872 Options.AllowOverlappingLoads = true;
5873 Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
5874 Options.NumLoadsPerBlock = IsZeroCmp ? Options.MaxNumLoads : 1;
5875 // TODO: Though vector loads usually perform well on AArch64, in some targets
5876 // they may wake up the FP unit, which raises the power consumption. Perhaps
5877 // they could be used with no holds barred (-O3).
5878 Options.LoadSizes = {8, 4, 2, 1};
5879 Options.AllowedTailExpansions = {3, 5, 6};
5880 return Options;
5881}
5882
5884 return ST->hasSVE();
5885}
5886
5889 TTI::TargetCostKind CostKind) const {
5890 switch (MICA.getID()) {
5891 case Intrinsic::masked_scatter:
5892 case Intrinsic::masked_gather:
5893 return getGatherScatterOpCost(MICA, CostKind);
5894 case Intrinsic::masked_load:
5895 case Intrinsic::masked_store:
5896 case Intrinsic::masked_expandload:
5897 case Intrinsic::masked_compressstore:
5898 return getMaskedMemoryOpCost(MICA, CostKind);
5899 }
5900 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
5901}
5902
5905 TTI::TargetCostKind CostKind) const {
5906 Type *Src = MICA.getDataType();
5907
5908 if (useNeonVector(Src))
5909 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
5910 auto LT = getTypeLegalizationCost(Src);
5911 if (!LT.first.isValid())
5913
5914 // Return an invalid cost for element types that we are unable to lower.
5915 auto *VT = cast<VectorType>(Src);
5916 if (VT->getElementType()->isIntegerTy(1))
5918
5919 // <vscale x 1 x eltty> operations require mask adaptation.
5920 // Allow it for normal masked ld/st
5921 if (VT->getElementCount() == ElementCount::getScalable(1))
5922 return is_contained({Intrinsic::masked_load, Intrinsic::masked_store},
5923 MICA.getID())
5924 ? LT.first + 1
5926
5927 InstructionCost MemOpCost = LT.first;
5928 if (MICA.getID() == Intrinsic::masked_expandload) {
5929 // Fall back to the base cost (we can expand fixed-width expandloads).
5930 if (!isLegalMaskedExpandLoad(Src, MICA.getAlignment()))
5931 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
5932
5933 // Operation will be split into expand of masked.load
5934 // Something like:
5935 // cntp x8, p0, p0.s
5936 // whilelo p1.s, xzr, x8
5937 // ld1w { z1.s }, p1/z, [x0]
5938 // expand z1.s, p0, z1.s
5939 MemOpCost *= 4;
5940 }
5941
5942 if (MICA.getID() == Intrinsic::masked_compressstore) {
5943 // Fall back to the base cost (we can expand fixed-width compressstores).
5944 if (!isLegalMaskedCompressStore(Src, MICA.getAlignment()))
5945 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
5946
5947 // A compress store lowers to something like:
5948 // compact z0.s, p0, z0.s
5949 // cntp x8, p1, p0.s
5950 // whilelo p0.s, xzr, x8
5951 // st1w { z0.s }, p0, [x0]
5952 MemOpCost *= 4;
5953 }
5954
5955 // If we need to split the memory operation, we will also need to split the
5956 // mask. This will likely lead to overestimating the cost in some cases if
5957 // multiple memory operations use the same mask, but we often don't have
5958 // enough context to figure that out here.
5959 //
5960 // If the elements being loaded are bytes then the mask will already be split,
5961 // since the number of bits in a P register matches the number of bytes in a
5962 // Z register.
5963 if (LT.first > 1 && LT.second.getScalarSizeInBits() > 8)
5964 return MemOpCost * 2;
5965
5966 return MemOpCost;
5967}
5968
5969// This function returns gather/scatter overhead either from
5970// user-provided value or specialized values per-target from \p ST.
5971static unsigned getSVEGatherScatterOverhead(unsigned Opcode,
5972 const AArch64Subtarget *ST) {
5973 assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
5974 "Should be called on only load or stores.");
5975 switch (Opcode) {
5976 case Instruction::Load:
5977 return ST->getCLOpts().sve_gather_overhead.value_or(
5978 ST->getGatherOverhead());
5979 break;
5980 case Instruction::Store:
5981 return ST->getCLOpts().sve_scatter_overhead.value_or(
5982 ST->getScatterOverhead());
5983 break;
5984 default:
5985 llvm_unreachable("Shouldn't have reached here");
5986 }
5987}
5988
5991 TTI::TargetCostKind CostKind) const {
5992
5993 unsigned Opcode = (MICA.getID() == Intrinsic::masked_gather ||
5994 MICA.getID() == Intrinsic::vp_gather)
5995 ? Instruction::Load
5996 : Instruction::Store;
5997
5998 Type *DataTy = MICA.getDataType();
5999 Align Alignment = MICA.getAlignment();
6000 const Instruction *I = MICA.getInst();
6001
6002 // No need to call useNeonVector here since isLegalMaskedGatherScatter
6003 // determines if we're using SVE for fixed-length vectors.
6004 if (!isLegalMaskedGatherScatter(DataTy))
6005 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
6006 auto *VT = cast<VectorType>(DataTy);
6007 auto LT = getTypeLegalizationCost(DataTy);
6008 if (!LT.first.isValid())
6010
6011 // Return an invalid cost for element types that we are unable to lower.
6012 if (!LT.second.isVector() ||
6013 !isElementTypeLegalForScalableVector(VT->getElementType()) ||
6014 VT->getElementType()->isIntegerTy(1))
6016
6017 // The code-generator is currently not able to handle scalable vectors
6018 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
6019 // it. This change will be removed when code-generation for these types is
6020 // sufficiently reliable.
6021 if (VT->getElementCount() == ElementCount::getScalable(1))
6023
6024 ElementCount LegalVF = LT.second.getVectorElementCount();
6025 InstructionCost MemOpCost =
6026 getMemoryOpCost(Opcode, VT->getElementType(), Alignment, 0, CostKind,
6027 {TTI::OK_AnyValue, TTI::OP_None}, I);
6028 // Add on an overhead cost for using gathers/scatters.
6029 MemOpCost *= getSVEGatherScatterOverhead(Opcode, ST);
6030 return LT.first * MemOpCost * getMaxNumElements(LegalVF);
6031}
6032
6034 return isa<FixedVectorType>(Ty) && !ST->useSVEForFixedLengthVectors();
6035}
6036
6037// Get the latency of NumInst of Inst according to the scheduling model. The
6038// latency will be the latency of the last instruction plus the time it gets to
6039// get there, which will be the amount of other instructions before that (i.e.
6040// NumInst - 1) multiplied by how long it takes to get through them (the
6041// reciprocal of the throughput). If the model has no information for this
6042// instruction then we assume the reciprocal throughput is 1 and use
6043// DefaultLatency for the latency.
6044static InstructionCost
6046 unsigned NumInst, InstructionCost DefaultLatency) {
6047 assert(NumInst != 0 && "Can't calculate latency of zero instructions");
6048 const MCSchedModel &Sched = ST->getSchedModel();
6049 const TargetInstrInfo *TII = ST->getInstrInfo();
6050 unsigned SchedClass = TII->get(Inst).getSchedClass();
6051 const MCSchedClassDesc *SCD = Sched.hasInstrSchedModel()
6052 ? Sched.getSchedClassDesc(SchedClass)
6053 : nullptr;
6054 // If the cpu has no scheduling model, or it doesn't describe the
6055 // instruction, then fall back to the default latency. Variant
6056 // scheduling classes can't be resolved without a MachineInstr, so
6057 // treat them the same way.
6058 if (!SCD || !SCD->isValid() || SCD->isVariant())
6059 return (NumInst - 1) + DefaultLatency;
6060 // We need to convert the number of instructions before the last to a float
6061 // here, as the reciprocal throughput may be fractional.
6062 return (float)(NumInst - 1) * Sched.getReciprocalThroughput(*ST, *SCD) +
6063 Sched.computeInstrLatency(*ST, *SCD);
6064}
6065
6067 Align Alignment,
6068 unsigned AddressSpace,
6069 TTI::TargetCostKind CostKind,
6070 TTI::OperandValueInfo OpInfo,
6071 const Instruction *I) const {
6072 EVT VT = TLI->getValueType(DL, Ty, true);
6073 // Type legalization can't handle structs
6074 if (VT == MVT::Other)
6075 return BaseT::getMemoryOpCost(Opcode, Ty, Alignment, AddressSpace,
6076 CostKind);
6077
6078 auto LT = getTypeLegalizationCost(Ty);
6079 if (!LT.first.isValid())
6081
6082 if (auto *VTy = dyn_cast<ScalableVectorType>(Ty)) {
6083
6084 // We only support full register predicate loads and stores.
6085 if (VTy->getElementType()->isIntegerTy(1) &&
6086 !VTy->getElementCount().isKnownMultipleOf(
6089
6090 // <vscale x 1 x eltty> operations require crafting a new mask.
6091 if (VTy->getElementCount() == ElementCount::getScalable(1)) {
6092 Intrinsic::ID IID = Opcode == Instruction::Load ? Intrinsic::masked_load
6093 : Intrinsic::masked_store;
6094 return getMaskedMemoryOpCost(
6095 MemIntrinsicCostAttributes(IID, Ty, Alignment, AddressSpace),
6096 CostKind) +
6097 1;
6098 }
6099 }
6100
6101 // TODO: consider latency as well for TCK_SizeAndLatency.
6102 if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency)
6103 return LT.first;
6104
6105 if (CostKind == TTI::TCK_Latency) {
6106 // Latency doesn't make much sense for stores, so just return 1
6107 if (Opcode == Instruction::Store)
6108 return 1;
6109 // If the subtarget has overridden the load latency then use that instead of
6110 // querying the SchedModel.
6111 if (ST->getFixedLoadLatency())
6112 return (LT.first - 1) + ST->getFixedLoadLatency();
6113 // We expect the load to become LT.first loads of type LT.second. We
6114 // calculate the latency using the SchedModel, and assume that the loads
6115 // become the variant with unsigned integer offset.
6116 unsigned Inst = 0;
6117 if (LT.second.isScalableVector() ||
6118 ST->useSVEForFixedLengthVectors(LT.second)) {
6119 Inst = AArch64::LDR_ZXI;
6120 } else if (LT.second.isVector() || LT.second.isFloatingPoint()) {
6121 switch (LT.second.getSizeInBits()) {
6122 case 8:
6123 Inst = AArch64::LDRBui;
6124 break;
6125 case 16:
6126 Inst = AArch64::LDRHui;
6127 break;
6128 case 32:
6129 Inst = AArch64::LDRSui;
6130 break;
6131 case 64:
6132 Inst = AArch64::LDRDui;
6133 break;
6134 case 128:
6135 Inst = AArch64::LDRQui;
6136 break;
6137 default:
6138 llvm_unreachable("Unexpected float or vector type");
6139 }
6140 } else {
6141 switch (LT.second.getSizeInBits()) {
6142 case 8:
6143 Inst = AArch64::LDRBBui;
6144 break;
6145 case 16:
6146 Inst = AArch64::LDRHHui;
6147 break;
6148 case 32:
6149 Inst = AArch64::LDRWui;
6150 break;
6151 case 64:
6152 Inst = AArch64::LDRXui;
6153 break;
6154 default:
6155 llvm_unreachable("Unexpected integer type");
6156 }
6157 }
6158 return getLatencyFromSchedModel(ST, Inst, LT.first.getValue(),
6159 ST->getLoadLatency());
6160 }
6161
6162 if (ST->isMisaligned128StoreSlow() && Opcode == Instruction::Store &&
6163 LT.second.is128BitVector() && Alignment < Align(16)) {
6164 // Unaligned stores are extremely inefficient. We don't split all
6165 // unaligned 128-bit stores because the negative impact that has shown in
6166 // practice on inlined block copy code.
6167 // We make such stores expensive so that we will only vectorize if there
6168 // are 6 other instructions getting vectorized.
6169 const int AmortizationCost = 6;
6170
6171 return LT.first * 2 * AmortizationCost;
6172 }
6173
6174 // Opaque ptr or ptr vector types are i64s and can be lowered to STP/LDPs.
6175 if (Ty->isPtrOrPtrVectorTy())
6176 return LT.first;
6177
6178 if (useNeonVector(Ty)) {
6179 // Check truncating stores and extending loads.
6180 if (Ty->getScalarSizeInBits() != LT.second.getScalarSizeInBits()) {
6181 // v4i8 types are lowered to scalar a load/store and sshll/xtn.
6182 if (VT == MVT::v4i8)
6183 return 2;
6184 // Otherwise we need to scalarize.
6185 return cast<FixedVectorType>(Ty)->getNumElements() * 2;
6186 }
6187 EVT EltVT = VT.getVectorElementType();
6188 unsigned EltSize = EltVT.getScalarSizeInBits();
6189 if (!isPowerOf2_32(EltSize) || EltSize < 8 || EltSize > 64)
6190 return LT.first;
6191 // FIXME: v3i8 lowering currently is very inefficient, due to automatic
6192 // widening to v4i8, which produces suboptimal results.
6193 if (VT.getVectorNumElements() == 3 && EltVT == MVT::i8)
6194 return LT.first;
6195
6196 // Check non-power-of-2 loads/stores for legal vector element types with
6197 // NEON. Non-power-of-2 memory ops will get broken down to a set of
6198 // operations on smaller power-of-2 ops, including ld1/st1.
6199 InstructionCost Cost = VT.getVectorNumElements() / (128 / EltSize);
6200 unsigned Remainder = VT.getVectorNumElements() % (128 / EltSize);
6201 if (Remainder != 0) {
6203 TypeWorklist.push_back({Remainder, 0});
6204 while (!TypeWorklist.empty()) {
6205 auto [CurrNumElements, Offset] = TypeWorklist.pop_back_val();
6206 // Loads with sufficient alignment are widened to the next power of two,
6207 // so only a single load is needed.
6208 if (isPowerOf2_32(CurrNumElements) ||
6209 (Opcode == Instruction::Load &&
6210 Alignment >= PowerOf2Ceil(CurrNumElements) * EltSize / 8)) {
6211 // 1 per load/store + possible lane insert.
6212 Cost += 1 + (Offset == 0 ? 0 : 1);
6213 continue;
6214 }
6215
6216 unsigned PrevPow2 = NextPowerOf2(CurrNumElements) / 2;
6217 TypeWorklist.push_back({PrevPow2, Offset});
6218 TypeWorklist.push_back({CurrNumElements - PrevPow2, Offset + PrevPow2});
6219 }
6220 }
6221 return Cost;
6222 }
6223
6224 return LT.first;
6225}
6226
6228 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
6229 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
6230 bool UseMaskForCond, bool UseMaskForGaps) const {
6231 assert(Factor >= 2 && "Invalid interleave factor");
6232 auto *VecVTy = cast<VectorType>(VecTy);
6233
6234 if (VecTy->isScalableTy() && !ST->hasSVE())
6236
6237 // Scalable VFs emit vector.[de]interleave intrinsics, for which the target
6238 // supports factors up to the maximum supported interleave factor.
6239 if (VecTy->isScalableTy()) {
6240 if (Factor > TLI->getMaxSupportedInterleaveFactor())
6242
6243 if (Factor == 3 &&
6244 DL.getTypeSizeInBits(VecTy).getKnownMinValue() != (3 * 128))
6246 }
6247
6248 auto LT = getTypeLegalizationCost(VecTy);
6249 unsigned MaxNativeInterleaveFactor = TLI->getMaxSupportedInterleaveFactor();
6250 // Vectorization for masked interleaved accesses is only enabled for scalable
6251 // VF. For fixed-length SVE, avoid non-native interleave factor because
6252 // the generic fallback costs wide fixed-vector shuffles too optimistically.
6253 if (!VecTy->isScalableTy() &&
6254 (UseMaskForCond || UseMaskForGaps ||
6255 (Factor > MaxNativeInterleaveFactor &&
6256 TLI->useSVEForFixedLengthVectorVT(LT.second))))
6258
6259 if (!UseMaskForGaps && Factor <= MaxNativeInterleaveFactor) {
6260 ElementCount EC = VecVTy->getElementCount();
6261 auto *SubVecTy = VectorType::get(VecVTy->getElementType(),
6262 EC.divideCoefficientBy(Factor));
6263
6264 // ldN/stN only support legal vector types of size 64 or 128 in bits.
6265 // Accesses having vector types that are a multiple of 128 bits can be
6266 // matched to more than one ldN/stN instruction.
6267 bool UseScalable;
6268
6269 if (EC.isKnownMultipleOf(Factor) &&
6270 TLI->isLegalInterleavedAccessType(SubVecTy, DL, UseScalable)) {
6271 unsigned Num = TLI->getNumInterleavedAccesses(SubVecTy, DL, UseScalable);
6272 if (CostKind == TTI::TCK_Latency) {
6273 // Latency doesn't make much sense for stores, so just return 1
6274 if (Opcode == Instruction::Store)
6275 return 1;
6276 // If the subtarget has overridden the load latency then use that
6277 // instead of querying the SchedModel.
6278 if (ST->getFixedLoadLatency())
6279 return (LT.first - 1) + ST->getFixedLoadLatency();
6280 // Lookup the load opcode based on whether we're using SVE, interleaving
6281 // factor, and element size.
6282 const unsigned Opcodes[2][3][4] = {
6283 {
6284 {AArch64::LD2Twov16b, AArch64::LD2Twov8h, AArch64::LD2Twov4s,
6285 AArch64::LD2Twov2d},
6286 {AArch64::LD3Threev16b, AArch64::LD3Threev8h,
6287 AArch64::LD3Threev4s, AArch64::LD3Threev2d},
6288 {AArch64::LD4Fourv16b, AArch64::LD4Fourv8h, AArch64::LD4Fourv4s,
6289 AArch64::LD4Fourv2d},
6290 },
6291 {
6292 {AArch64::LD2B, AArch64::LD2H, AArch64::LD2W, AArch64::LD2D},
6293 {AArch64::LD3B, AArch64::LD3H, AArch64::LD3W, AArch64::LD3D},
6294 {AArch64::LD4B, AArch64::LD4H, AArch64::LD4W, AArch64::LD4D},
6295 }};
6296 unsigned LogElemSize =
6297 Log2_32(DL.getTypeSizeInBits(SubVecTy->getElementType()));
6298 assert(LogElemSize >= 3 && LogElemSize <= 6 &&
6299 "Unexpected element size");
6300 assert(Factor <= 4 && "Unexpected interleaving factor");
6301 unsigned Inst = Opcodes[UseScalable][Factor - 2][LogElemSize - 3];
6302 return getLatencyFromSchedModel(ST, Inst, Num, ST->getLoadLatency());
6303 }
6304 return Factor * Num;
6305 }
6306
6307 // Cost the alternative approach for scalable vectors where the interleave
6308 // factor is larger than the VF: use a contiguous load/store of the full
6309 // wide vector followed by deinterleave/interleave shuffles.
6310 if (VecTy->isScalableTy() && EC.isKnownMultipleOf(Factor)) {
6311 if (SubVecTy->getElementCount() == ElementCount::getScalable(1))
6313
6314 // Cost of the contiguous memory operation on the wide vector.
6315 InstructionCost MemCost;
6316 if (UseMaskForCond) {
6317 unsigned IID = Opcode == Instruction::Load ? Intrinsic::masked_load
6318 : Intrinsic::masked_store;
6319 MemCost = getMemIntrinsicInstrCost(
6320 MemIntrinsicCostAttributes(IID, VecTy, Alignment, AddressSpace),
6321 CostKind);
6322 } else {
6323 MemCost =
6324 getMemoryOpCost(Opcode, VecTy, Alignment, AddressSpace, CostKind);
6325 }
6326
6327 // llvm.vector.deinterleaveN is lowered as a binary tree of deinterleave2
6328 // operations. The tree has Log2(Factor) levels, with Factor UZP/ZIP
6329 // operations at each level, giving a total shuffle cost of
6330 // Factor * Log2(Factor).
6331 auto SubVecCost = getTypeLegalizationCost(SubVecTy);
6332 auto ResultCost = getTypeLegalizationCost(VecTy);
6333 llvm::InstructionCost LegalizationCost = SubVecCost.first;
6334
6335 // FIXME: A temporary increase to the cost in cases where the input
6336 // element type is 4x the output type. Otherwise it produces an SVE tail
6337 // loop which is significantly larger than the NEON equivalent.
6338 if (Opcode == Instruction::Store && Factor == 4 &&
6339 SubVecCost.second.getScalarSizeInBits() ==
6340 (4 * ResultCost.second.getScalarSizeInBits()))
6341 LegalizationCost *= 4;
6342
6343 return MemCost + (Factor * LegalizationCost) + (Factor * Log2_64(Factor));
6344 }
6345 }
6346
6347 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
6348 Alignment, AddressSpace, CostKind,
6349 UseMaskForCond, UseMaskForGaps);
6350}
6351
6356 for (auto *I : Tys) {
6357 if (!I->isVectorTy())
6358 continue;
6359 auto LT = getTypeLegalizationCost(I);
6360 if (!LT.second.is128BitVector())
6361 continue;
6362 // Each legal part is spilled as a whole Q register.
6363 Type *LegalTy = EVT(LT.second).getTypeForEVT(I->getContext());
6364 Cost +=
6365 LT.first *
6366 (getMemoryOpCost(Instruction::Store, LegalTy, Align(16), 0, CostKind) +
6367 getMemoryOpCost(Instruction::Load, LegalTy, Align(16), 0, CostKind));
6368 }
6369 return Cost;
6370}
6371
6373 Align Alignment) const {
6374 // Neon types should be scalarised when we are not choosing to use SVE.
6375 if (useNeonVector(DataTy))
6376 return false;
6377
6379 return false;
6380
6381 // Return true only if we are able to lower using the SVE2p2/SME2p2
6382 // expand instruction.
6383 return (ST->isSVEAvailable() && ST->hasSVE2p2()) ||
6384 (ST->isSVEorStreamingSVEAvailable() && ST->hasSME2p2());
6385}
6386
6388 unsigned AddressSpace) const {
6389 // Matches AArch64TargetLowering::emitCanLoadSpeculatively: only address
6390 // space 0 and power-of-2 sizes up to the 16-byte MTE tag granule.
6391 // TODO: Support scalable vectors.
6392 if (AddressSpace != 0)
6393 return false;
6394 TypeSize Size = DL.getTypeStoreSize(DataType);
6395 return !Size.isScalable() && isPowerOf2_64(Size.getFixedValue()) &&
6396 Size.getFixedValue() <= 16;
6397}
6398
6400 unsigned NumVectors, TTI::MaskSource Mask, VectorType *VectorTy,
6401 bool IsStore, std::optional<Instruction::CastOps> CastHint) const {
6402 if (NumVectors <= 1 || !ST->enableSubRegLiveness() || !ST->hasSVE2p1())
6403 return false;
6404
6405 switch (Mask) {
6407 return false;
6410 break;
6411 }
6412
6413 // A null vector type queries whether the target supports multi-vector memory
6414 // operations in general.
6415 if (!VectorTy)
6416 return true;
6417
6418 if (!isa<ScalableVectorType>(VectorTy))
6419 return false;
6420
6421 // Conservatively, avoid using multi-vector loads when it's possible we could
6422 // use extending loads instead. Note: We can ignore stores as we only use
6423 // truncating stores when the store vector-width is < a full SVE vector.
6424 if (!IsStore &&
6425 (CastHint == Instruction::ZExt || CastHint == Instruction::SExt))
6426 return false;
6427
6428 TypeSize VectorWidth = DL.getTypeSizeInBits(VectorTy);
6430 return false;
6431
6432 // For masked loads/stores only allow operations that map to two or four
6433 // vectors (as these can use a single predicate-as-counter).
6434 if (Mask == TTI::MaskSource::ActiveLaneMask) {
6435 unsigned NumSVEVectors = (VectorWidth * NumVectors).getKnownMinValue() /
6437 return NumSVEVectors == 2 || NumSVEVectors == 4;
6438 }
6439
6440 // For unpredicated loads/stores allow any pow-of-two multiple of a vector >=
6441 // to a single z-register. We can split operations wider than a single
6442 // multi-vector load/store during ISEL.
6443 return isPowerOf2_32(NumVectors);
6444}
6445
6446unsigned
6448 bool HasUnorderedReductions) const {
6449 if (VF.isScalar() || (HasUnorderedReductions && VF.getKnownMinValue() <= 4))
6450 return 4;
6451 return ST->getMaxInterleaveFactor();
6452}
6453
6454// For Falkor, we want to avoid having too many strided loads in a loop since
6455// that can exhaust the HW prefetcher resources. We adjust the unroller
6456// MaxCount preference below to attempt to ensure unrolling doesn't create too
6457// many strided loads.
6458static void
6461 enum { MaxStridedLoads = 7 };
6462 auto countStridedLoads = [](Loop *L, ScalarEvolution &SE) {
6463 int StridedLoads = 0;
6464 // FIXME? We could make this more precise by looking at the CFG and
6465 // e.g. not counting loads in each side of an if-then-else diamond.
6466 for (const auto BB : L->blocks()) {
6467 for (auto &I : *BB) {
6468 LoadInst *LMemI = dyn_cast<LoadInst>(&I);
6469 if (!LMemI)
6470 continue;
6471
6472 Value *PtrValue = LMemI->getPointerOperand();
6473 if (L->isLoopInvariant(PtrValue))
6474 continue;
6475
6476 const SCEV *LSCEV = SE.getSCEV(PtrValue);
6477 const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
6478 if (!LSCEVAddRec || !LSCEVAddRec->isAffine())
6479 continue;
6480
6481 // FIXME? We could take pairing of unrolled load copies into account
6482 // by looking at the AddRec, but we would probably have to limit this
6483 // to loops with no stores or other memory optimization barriers.
6484 ++StridedLoads;
6485 // We've seen enough strided loads that seeing more won't make a
6486 // difference.
6487 if (StridedLoads > MaxStridedLoads / 2)
6488 return StridedLoads;
6489 }
6490 }
6491 return StridedLoads;
6492 };
6493
6494 int StridedLoads = countStridedLoads(L, SE);
6495 LLVM_DEBUG(dbgs() << "falkor-hwpf: detected " << StridedLoads
6496 << " strided loads\n");
6497 // Pick the largest power of 2 unroll count that won't result in too many
6498 // strided loads.
6499 if (StridedLoads) {
6500 UP.MaxCount = 1 << Log2_32(MaxStridedLoads / StridedLoads);
6501 LLVM_DEBUG(dbgs() << "falkor-hwpf: setting unroll MaxCount to "
6502 << UP.MaxCount << '\n');
6503 }
6504}
6505
6506// This function returns true if the loop:
6507// 1. Has a valid cost, and
6508// 2. Has a cost within the supplied budget.
6509// Otherwise it returns false.
6511 InstructionCost Budget,
6512 unsigned *FinalSize) {
6513 // Estimate the size of the loop.
6514 InstructionCost LoopCost = 0;
6515
6516 for (auto *BB : L->getBlocks()) {
6517 for (auto &I : *BB) {
6518 SmallVector<const Value *, 4> Operands(I.operand_values());
6519 InstructionCost Cost =
6520 TTI.getInstructionCost(&I, Operands, TTI::TCK_CodeSize);
6521 // This can happen with intrinsics that don't currently have a cost model
6522 // or for some operations that require SVE.
6523 if (!Cost.isValid())
6524 return false;
6525
6526 LoopCost += Cost;
6527 if (LoopCost > Budget)
6528 return false;
6529 }
6530 }
6531
6532 if (FinalSize)
6533 *FinalSize = LoopCost.getValue();
6534 return true;
6535}
6536
6538 const AArch64TTIImpl &TTI) {
6539 // Only consider loops with unknown trip counts for which we can determine
6540 // a symbolic expression. Multi-exit loops with small known trip counts will
6541 // likely be unrolled anyway.
6542 const SCEV *BTC = SE.getSymbolicMaxBackedgeTakenCount(L);
6544 return false;
6545
6546 // It might not be worth unrolling loops with low max trip counts. Restrict
6547 // this to max trip counts > 32 for now.
6548 unsigned MaxTC = SE.getSmallConstantMaxTripCount(L);
6549 if (MaxTC > 0 && MaxTC <= 32)
6550 return false;
6551
6552 // Make sure the loop size is <= 5.
6553 if (!isLoopSizeWithinBudget(L, TTI, 5, nullptr))
6554 return false;
6555
6556 // Small search loops with multiple exits can be highly beneficial to unroll.
6557 // We only care about loops with exactly two exiting blocks, although each
6558 // block could jump to the same exit block.
6559 ArrayRef<BasicBlock *> Blocks = L->getBlocks();
6560 if (Blocks.size() != 2)
6561 return false;
6562
6563 if (any_of(Blocks, [](BasicBlock *BB) {
6565 }))
6566 return false;
6567
6568 return true;
6569}
6570
6571/// For Apple CPUs, we want to runtime-unroll loops to make better use if the
6572/// OOO engine's wide instruction window and various predictors.
6573static void
6576 const AArch64TTIImpl &TTI) {
6577 // Limit loops with structure that is highly likely to benefit from runtime
6578 // unrolling; that is we exclude outer loops and loops with many blocks (i.e.
6579 // likely with complex control flow). Note that the heuristics here may be
6580 // overly conservative and we err on the side of avoiding runtime unrolling
6581 // rather than unroll excessively. They are all subject to further refinement.
6582 if (!L->isInnermost() || L->getNumBlocks() > 8)
6583 return;
6584
6585 // Loops with multiple exits are handled by common code.
6586 if (!L->getExitBlock())
6587 return;
6588
6589 // Check if the loop contains any reductions that could be parallelized when
6590 // unrolling. If so, enable partial unrolling, if the trip count is know to be
6591 // a multiple of 2.
6592 bool HasParellelizableReductions =
6593 L->getNumBlocks() == 1 &&
6594 any_of(L->getHeader()->phis(),
6595 [&SE, L](PHINode &Phi) {
6596 return canParallelizeReductionWhenUnrolling(Phi, L, &SE);
6597 }) &&
6598 isLoopSizeWithinBudget(L, TTI, 12, nullptr);
6599 if (HasParellelizableReductions &&
6600 SE.getSmallConstantTripMultiple(L, L->getExitingBlock()) % 2 == 0) {
6601 UP.Partial = true;
6602 UP.MaxCount = 4;
6603 UP.AddAdditionalAccumulators = true;
6604 }
6605
6606 const SCEV *BTC = SE.getSymbolicMaxBackedgeTakenCount(L);
6608 (SE.getSmallConstantMaxTripCount(L) > 0 &&
6609 SE.getSmallConstantMaxTripCount(L) <= 32))
6610 return;
6611
6612 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.runtime.disable"))
6613 return;
6614
6616 return;
6617
6618 // Limit to loops with trip counts that are cheap to expand.
6619 UP.SCEVExpansionBudget = 1;
6620
6621 if (HasParellelizableReductions) {
6622 UP.Runtime = true;
6624 UP.AddAdditionalAccumulators = true;
6625 }
6626
6627 // Try to unroll small, single-block loops with low budget, if they have
6628 // load/store dependencies, to expose more parallel memory access streams,
6629 // or if they do little work inside a block (i.e. load -> X -> store pattern).
6630 BasicBlock *Header = L->getHeader();
6631 BasicBlock *Latch = L->getLoopLatch();
6632 if (Header == Latch) {
6633 // Estimate the size of the loop.
6634 unsigned Size;
6635 unsigned Width = 10;
6636 if (!isLoopSizeWithinBudget(L, TTI, Width, &Size))
6637 return;
6638
6639 // Try to find an unroll count that maximizes the use of the instruction
6640 // window, i.e. trying to fetch as many instructions per cycle as possible.
6641 constexpr unsigned MaxInstsPerLine = 16;
6642 constexpr unsigned MaxLines = 3;
6643 constexpr unsigned MaxSizeWithUC = MaxInstsPerLine * MaxLines;
6644 constexpr unsigned MaxUC = 8;
6645
6646 unsigned BestUC = 1;
6647 unsigned BestLineRemainder = Size % MaxInstsPerLine;
6648 for (unsigned UC = 2; UC <= MaxUC; ++UC) {
6649 unsigned SizeWithUC = UC * Size;
6650 if (SizeWithUC > MaxSizeWithUC)
6651 break;
6652 unsigned LineRemainder = SizeWithUC % MaxInstsPerLine;
6653 if (LineRemainder == 0 ||
6654 (BestLineRemainder != 0 && BestLineRemainder < LineRemainder)) {
6655 BestUC = UC;
6656 BestLineRemainder = LineRemainder;
6657 }
6658 }
6659
6660 if (BestUC == 1)
6661 return;
6662
6663 SmallPtrSet<Value *, 8> LoadedValuesPlus;
6665 for (auto *BB : L->blocks()) {
6666 for (auto &I : *BB) {
6668 if (!Ptr)
6669 continue;
6670 const SCEV *PtrSCEV = SE.getSCEV(Ptr);
6671 if (SE.isLoopInvariant(PtrSCEV, L))
6672 continue;
6673 if (isa<LoadInst>(&I)) {
6674 LoadedValuesPlus.insert(&I);
6675 // Include in-loop 1st users of loaded values.
6676 for (Instruction *U : I.users())
6677 if (L->contains(U))
6678 LoadedValuesPlus.insert(U);
6679 } else
6680 Stores.push_back(cast<StoreInst>(&I));
6681 }
6682 }
6683
6684 if (none_of(Stores, [&LoadedValuesPlus](StoreInst *SI) {
6685 return LoadedValuesPlus.contains(SI->getOperand(0));
6686 }))
6687 return;
6688
6689 UP.Runtime = true;
6690 UP.DefaultUnrollRuntimeCount = BestUC;
6691 return;
6692 }
6693
6694 // Try to runtime-unroll loops with early-continues depending on loop-varying
6695 // loads; this helps with branch-prediction for the early-continues.
6696 auto *Term = dyn_cast<CondBrInst>(Header->getTerminator());
6698 if (!Term || Preds.size() == 1 || !llvm::is_contained(Preds, Header) ||
6699 none_of(Preds, [L](BasicBlock *Pred) { return L->contains(Pred); }))
6700 return;
6701
6702 std::function<bool(Instruction *, unsigned)> DependsOnLoopLoad =
6703 [&](Instruction *I, unsigned Depth) -> bool {
6704 if (isa<PHINode>(I) || L->isLoopInvariant(I) || Depth > 8)
6705 return false;
6706
6707 if (isa<LoadInst>(I))
6708 return true;
6709
6710 return any_of(I->operands(), [&](Value *V) {
6711 auto *I = dyn_cast<Instruction>(V);
6712 return I && DependsOnLoopLoad(I, Depth + 1);
6713 });
6714 };
6716 Instruction *I;
6717 if (match(Term, m_Br(m_ICmp(Pred, m_Instruction(I), m_Value()), m_Value(),
6718 m_Value())) &&
6719 DependsOnLoopLoad(I, 0)) {
6720 UP.Runtime = true;
6721 }
6722}
6723
6726 OptimizationRemarkEmitter *ORE) const {
6727 // Enable partial unrolling and runtime unrolling.
6728 BaseT::getUnrollingPreferences(L, SE, UP, ORE);
6729
6730 UP.UpperBound = true;
6731
6732 // A loop can have a small maximum trip count while SCEV still cannot
6733 // form an exact backedge count - typically a data-dependent exit, e.g.
6734 // shifting a value until it reaches zero. Unlike for counted loops, the
6735 // unrolled body keeps an exit test per iteration, and whether that pays
6736 // off depends on how many iterations the loop usually runs, which is
6737 // unknown at compile time; the code growth and extra branches are certain.
6738 // Be conservative and hold such loops to a lower upper bound; 5 still lets
6739 // smaller early-exit loops unroll. Also disable runtime unrolling, which
6740 // would clamp the unroll count to the known maximum trip count and produce
6741 // the same complete unroll.
6742 if (L->getExitingBlock() && !SE.isBackedgeTakenCountMaxOrZero(L) &&
6744 UP.MaxUpperBound = 5;
6745 UP.Runtime = false;
6746 }
6747
6748 // For inner loop, it is more likely to be a hot one, and the runtime check
6749 // can be promoted out from LICM pass, so the overhead is less, let's try
6750 // a larger threshold to unroll more loops.
6751 if (L->getLoopDepth() > 1)
6752 UP.PartialThreshold *= 2;
6753
6754 // Disable partial & runtime unrolling on -Os.
6756
6757 // Scan the loop: don't unroll loops with calls as this could prevent
6758 // inlining. Don't unroll auto-vectorized loops either, though do allow
6759 // unrolling of the scalar remainder.
6760 bool IsVectorized = getBooleanLoopAttribute(L, "llvm.loop.isvectorized");
6762 for (auto *BB : L->getBlocks()) {
6763 for (auto &I : *BB) {
6764 // Both auto-vectorized loops and the scalar remainder have the
6765 // isvectorized attribute, so differentiate between them by the presence
6766 // of vector instructions.
6767 if (IsVectorized && I.getType()->isVectorTy())
6768 return;
6769 if (isa<CallBase>(I)) {
6772 if (!isLoweredToCall(F))
6773 continue;
6774 return;
6775 }
6776
6777 // The cost is only compared against Aarch64ForceUnrollThreshold below.
6778 if (Cost >= ST->getCLOpts().force_unroll_threshold)
6779 continue;
6780 SmallVector<const Value *, 4> Operands(I.operand_values());
6783 }
6784 }
6785
6786 // Apply subtarget-specific unrolling preferences.
6787 if (ST->isAppleMLike())
6788 getAppleRuntimeUnrollPreferences(L, SE, UP, *this);
6789 else if (ST->getProcFamily() == AArch64Subtarget::Falkor &&
6790 ST->getCLOpts().enable_falkor_hwpf_unroll_fix)
6792
6793 // If this is a small, multi-exit loop similar to something like std::find,
6794 // then there is typically a performance improvement achieved by unrolling.
6795 if (!L->getExitBlock() && shouldUnrollMultiExitLoop(L, SE, *this)) {
6796 UP.RuntimeUnrollMultiExit = true;
6797 UP.Runtime = true;
6798 // Limit unroll count.
6800 // Allow slightly more costly trip-count expansion to catch search loops
6801 // with pointer inductions.
6802 UP.SCEVExpansionBudget = 5;
6803 return;
6804 }
6805
6806 // Enable runtime unrolling for in-order models
6807 // If mcpu is omitted, getProcFamily() returns AArch64Subtarget::Others, so by
6808 // checking for that case, we can ensure that the default behaviour is
6809 // unchanged
6810 if (ST->getProcFamily() != AArch64Subtarget::Generic &&
6811 !ST->getSchedModel().isOutOfOrder()) {
6812 UP.Runtime = true;
6813 UP.Partial = true;
6814 UP.UnrollRemainder = true;
6816
6817 UP.UnrollAndJam = true;
6819 }
6820
6821 // Force unrolling small loops can be very useful because of the branch
6822 // taken cost of the backedge.
6823 if (Cost < ST->getCLOpts().force_unroll_threshold)
6824 UP.Force = true;
6825}
6826
6831
6833 Type *ExpectedType,
6834 bool CanCreate) const {
6835 switch (Inst->getIntrinsicID()) {
6836 default:
6837 return nullptr;
6838 case Intrinsic::aarch64_neon_st1x2:
6839 case Intrinsic::aarch64_neon_st1x3:
6840 case Intrinsic::aarch64_neon_st1x4:
6841 case Intrinsic::aarch64_neon_st2:
6842 case Intrinsic::aarch64_neon_st3:
6843 case Intrinsic::aarch64_neon_st4: {
6844 // Create a struct type
6845 StructType *ST = dyn_cast<StructType>(ExpectedType);
6846 if (!CanCreate || !ST)
6847 return nullptr;
6848 unsigned NumElts = Inst->arg_size() - 1;
6849 if (ST->getNumElements() != NumElts)
6850 return nullptr;
6851 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6852 if (Inst->getArgOperand(i)->getType() != ST->getElementType(i))
6853 return nullptr;
6854 }
6855 Value *Res = PoisonValue::get(ExpectedType);
6856 IRBuilder<> Builder(Inst);
6857 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6858 Value *L = Inst->getArgOperand(i);
6859 Res = Builder.CreateInsertValue(Res, L, i);
6860 }
6861 return Res;
6862 }
6863 case Intrinsic::aarch64_neon_ld1x2:
6864 case Intrinsic::aarch64_neon_ld1x3:
6865 case Intrinsic::aarch64_neon_ld1x4:
6866 case Intrinsic::aarch64_neon_ld2:
6867 case Intrinsic::aarch64_neon_ld3:
6868 case Intrinsic::aarch64_neon_ld4:
6869 if (Inst->getType() == ExpectedType)
6870 return Inst;
6871 return nullptr;
6872 }
6873}
6874
6876 MemIntrinsicInfo &Info) const {
6877 switch (Inst->getIntrinsicID()) {
6878 default:
6879 break;
6880 case Intrinsic::aarch64_neon_ld1x2:
6881 case Intrinsic::aarch64_neon_ld1x3:
6882 case Intrinsic::aarch64_neon_ld1x4:
6883 case Intrinsic::aarch64_neon_ld2:
6884 case Intrinsic::aarch64_neon_ld3:
6885 case Intrinsic::aarch64_neon_ld4:
6886 Info.ReadMem = true;
6887 Info.WriteMem = false;
6888 Info.PtrVal = Inst->getArgOperand(0);
6889 break;
6890 case Intrinsic::aarch64_neon_st1x2:
6891 case Intrinsic::aarch64_neon_st1x3:
6892 case Intrinsic::aarch64_neon_st1x4:
6893 case Intrinsic::aarch64_neon_st2:
6894 case Intrinsic::aarch64_neon_st3:
6895 case Intrinsic::aarch64_neon_st4:
6896 Info.ReadMem = false;
6897 Info.WriteMem = true;
6898 Info.PtrVal = Inst->getArgOperand(Inst->arg_size() - 1);
6899 break;
6900 }
6901
6902 // Use the ID of neon load as the "matching id".
6903 switch (Inst->getIntrinsicID()) {
6904 default:
6905 return false;
6906 case Intrinsic::aarch64_neon_ld1x2:
6907 case Intrinsic::aarch64_neon_st1x2:
6908 Info.MatchingId = Intrinsic::aarch64_neon_ld1x2;
6909 break;
6910 case Intrinsic::aarch64_neon_ld1x3:
6911 case Intrinsic::aarch64_neon_st1x3:
6912 Info.MatchingId = Intrinsic::aarch64_neon_ld1x3;
6913 break;
6914 case Intrinsic::aarch64_neon_ld1x4:
6915 case Intrinsic::aarch64_neon_st1x4:
6916 Info.MatchingId = Intrinsic::aarch64_neon_ld1x4;
6917 break;
6918 case Intrinsic::aarch64_neon_ld2:
6919 case Intrinsic::aarch64_neon_st2:
6920 Info.MatchingId = Intrinsic::aarch64_neon_ld2;
6921 break;
6922 case Intrinsic::aarch64_neon_ld3:
6923 case Intrinsic::aarch64_neon_st3:
6924 Info.MatchingId = Intrinsic::aarch64_neon_ld3;
6925 break;
6926 case Intrinsic::aarch64_neon_ld4:
6927 case Intrinsic::aarch64_neon_st4:
6928 Info.MatchingId = Intrinsic::aarch64_neon_ld4;
6929 break;
6930 }
6931 return true;
6932}
6933
6934/// See if \p I should be considered for address type promotion. We check if \p
6935/// I is a sext with right type and used in memory accesses. If it used in a
6936/// "complex" getelementptr, we allow it to be promoted without finding other
6937/// sext instructions that sign extended the same initial value. A getelementptr
6938/// is considered as "complex" if it has more than 2 operands.
6940 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const {
6941 bool Considerable = false;
6942 AllowPromotionWithoutCommonHeader = false;
6943 if (!isa<SExtInst>(&I))
6944 return false;
6945 Type *ConsideredSExtType =
6946 Type::getInt64Ty(I.getParent()->getParent()->getContext());
6947 if (I.getType() != ConsideredSExtType)
6948 return false;
6949 // See if the sext is the one with the right type and used in at least one
6950 // GetElementPtrInst.
6951 for (const User *U : I.users()) {
6952 if (const GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
6953 Considerable = true;
6954 // A getelementptr is considered as "complex" if it has more than 2
6955 // operands. We will promote a SExt used in such complex GEP as we
6956 // expect some computation to be merged if they are done on 64 bits.
6957 if (GEPInst->getNumOperands() > 2) {
6958 AllowPromotionWithoutCommonHeader = true;
6959 break;
6960 }
6961 }
6962 }
6963 return Considerable;
6964}
6965
6967 const RecurrenceDescriptor &RdxDesc, ElementCount VF) const {
6968 if (!VF.isScalable())
6969 return true;
6970
6971 Type *Ty = RdxDesc.getRecurrenceType();
6972 if (Ty->isBFloatTy() || !isElementTypeLegalForScalableVector(Ty))
6973 return false;
6974
6975 switch (RdxDesc.getRecurrenceKind()) {
6976 case RecurKind::Sub:
6977 case RecurKind::FSub:
6980 case RecurKind::Add:
6981 case RecurKind::FAdd:
6982 case RecurKind::And:
6983 case RecurKind::Or:
6984 case RecurKind::Xor:
6985 case RecurKind::SMin:
6986 case RecurKind::SMax:
6987 case RecurKind::UMin:
6988 case RecurKind::UMax:
6989 case RecurKind::FMin:
6990 case RecurKind::FMax:
6991 case RecurKind::FMulAdd:
6992 case RecurKind::AnyOf:
6994 return true;
6995 default:
6996 return false;
6997 }
6998}
6999
7002 FastMathFlags FMF,
7003 TTI::TargetCostKind CostKind) const {
7004 // The code-generator is currently not able to handle scalable vectors
7005 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
7006 // it. This change will be removed when code-generation for these types is
7007 // sufficiently reliable.
7008 if (auto *VTy = dyn_cast<ScalableVectorType>(Ty))
7009 if (VTy->getElementCount() == ElementCount::getScalable(1))
7011
7012 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
7013
7014 if (LT.second.getScalarType() == MVT::f16 && !ST->hasFullFP16())
7015 return BaseT::getMinMaxReductionCost(IID, Ty, FMF, CostKind);
7016
7017 InstructionCost LegalizationCost = 0;
7018 if (LT.first > 1) {
7019 Type *LegalVTy = EVT(LT.second).getTypeForEVT(Ty->getContext());
7020 IntrinsicCostAttributes Attrs(IID, LegalVTy, {LegalVTy, LegalVTy}, FMF);
7021 LegalizationCost = getIntrinsicInstrCost(Attrs, CostKind) * (LT.first - 1);
7022 }
7023
7024 return LegalizationCost + /*Cost of horizontal reduction*/ 2;
7025}
7026
7028 unsigned Opcode, VectorType *ValTy, TTI::TargetCostKind CostKind) const {
7029 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
7030 InstructionCost LegalizationCost = 0;
7031 if (LT.first > 1) {
7032 Type *LegalVTy = EVT(LT.second).getTypeForEVT(ValTy->getContext());
7033 LegalizationCost = getArithmeticInstrCost(Opcode, LegalVTy, CostKind);
7034 LegalizationCost *= LT.first - 1;
7035 }
7036
7037 int ISD = TLI->InstructionOpcodeToISD(Opcode);
7038 assert(ISD && "Invalid opcode");
7039 // Add the final reduction cost for the legal horizontal reduction
7040 switch (ISD) {
7041 case ISD::ADD:
7042 case ISD::AND:
7043 case ISD::OR:
7044 case ISD::XOR:
7045 case ISD::FADD:
7046 return LegalizationCost + 2;
7047 default:
7049 }
7050}
7051
7054 std::optional<FastMathFlags> FMF,
7055 TTI::TargetCostKind CostKind) const {
7056 // The code-generator is currently not able to handle scalable vectors
7057 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
7058 // it. This change will be removed when code-generation for these types is
7059 // sufficiently reliable.
7060 if (auto *VTy = dyn_cast<ScalableVectorType>(ValTy))
7061 if (VTy->getElementCount() == ElementCount::getScalable(1))
7063
7065 if (auto *FixedVTy = dyn_cast<FixedVectorType>(ValTy)) {
7066 InstructionCost BaseCost =
7067 BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
7068 // Add on extra cost to reflect the extra overhead on some CPUs. We still
7069 // end up vectorizing for more computationally intensive loops.
7070 return BaseCost + FixedVTy->getNumElements();
7071 }
7072
7073 if (Opcode != Instruction::FAdd || ValTy->getElementType()->isBFloatTy())
7075
7076 auto *VTy = cast<ScalableVectorType>(ValTy);
7078 getArithmeticInstrCost(Opcode, VTy->getScalarType(), CostKind);
7079 Cost *= getMaxNumElements(VTy->getElementCount());
7080 return Cost;
7081 }
7082
7083 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
7084 MVT MTy = LT.second;
7085
7086 if (isa<ScalableVectorType>(ValTy) || TLI->useSVEForFixedLengthVectorVT(MTy))
7087 return getArithmeticReductionCostSVE(Opcode, ValTy, CostKind);
7088
7089 int ISD = TLI->InstructionOpcodeToISD(Opcode);
7090 assert(ISD && "Invalid opcode");
7091
7092 // Horizontal adds can use the 'addv' instruction. We model the cost of these
7093 // instructions as twice a normal vector add, plus 1 for each legalization
7094 // step (LT.first). This is the only arithmetic vector reduction operation for
7095 // which we have an instruction.
7096 // OR, XOR and AND costs should match the codegen from:
7097 // OR: llvm/test/CodeGen/AArch64/reduce-or.ll
7098 // XOR: llvm/test/CodeGen/AArch64/reduce-xor.ll
7099 // AND: llvm/test/CodeGen/AArch64/reduce-and.ll
7100 static const CostTblEntry CostTblNoPairwise[]{
7101 {ISD::ADD, MVT::v8i8, 2},
7102 {ISD::ADD, MVT::v16i8, 2},
7103 {ISD::ADD, MVT::v4i16, 2},
7104 {ISD::ADD, MVT::v8i16, 2},
7105 {ISD::ADD, MVT::v2i32, 2},
7106 {ISD::ADD, MVT::v4i32, 2},
7107 {ISD::ADD, MVT::v2i64, 2},
7108 {ISD::OR, MVT::v8i8, 5}, // fmov + orr_lsr + orr_lsr + lsr + orr
7109 {ISD::OR, MVT::v16i8, 7}, // ext + orr + same as v8i8
7110 {ISD::OR, MVT::v4i16, 4}, // fmov + orr_lsr + lsr + orr
7111 {ISD::OR, MVT::v8i16, 6}, // ext + orr + same as v4i16
7112 {ISD::OR, MVT::v2i32, 3}, // fmov + lsr + orr
7113 {ISD::OR, MVT::v4i32, 5}, // ext + orr + same as v2i32
7114 {ISD::OR, MVT::v2i64, 3}, // ext + orr + fmov
7115 {ISD::XOR, MVT::v8i8, 5}, // Same as above for or...
7116 {ISD::XOR, MVT::v16i8, 7},
7117 {ISD::XOR, MVT::v4i16, 4},
7118 {ISD::XOR, MVT::v8i16, 6},
7119 {ISD::XOR, MVT::v2i32, 3},
7120 {ISD::XOR, MVT::v4i32, 5},
7121 {ISD::XOR, MVT::v2i64, 3},
7122 {ISD::AND, MVT::v8i8, 5}, // Same as above for or...
7123 {ISD::AND, MVT::v16i8, 7},
7124 {ISD::AND, MVT::v4i16, 4},
7125 {ISD::AND, MVT::v8i16, 6},
7126 {ISD::AND, MVT::v2i32, 3},
7127 {ISD::AND, MVT::v4i32, 5},
7128 {ISD::AND, MVT::v2i64, 3},
7129 };
7130 switch (ISD) {
7131 default:
7132 break;
7133 case ISD::FADD:
7134 if (Type *EltTy = ValTy->getScalarType();
7135 // FIXME: For half types without fullfp16 support, this could extend and
7136 // use a fp32 faddp reduction but current codegen unrolls.
7137 MTy.isVector() && (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
7138 (EltTy->isHalfTy() && ST->hasFullFP16()))) {
7139 const unsigned NElts = MTy.getVectorNumElements();
7140 if (ValTy->getElementCount().getFixedValue() >= 2 && NElts >= 2 &&
7141 isPowerOf2_32(NElts))
7142 // Reduction corresponding to series of fadd instructions is lowered to
7143 // series of faddp instructions. faddp has latency/throughput that
7144 // matches fadd instruction and hence, every faddp instruction can be
7145 // considered to have a relative cost = 1 with
7146 // CostKind = TCK_RecipThroughput.
7147 // An faddp will pairwise add vector elements, so the size of input
7148 // vector reduces by half every time, requiring
7149 // #(faddp instructions) = log2_32(NElts).
7150 return (LT.first - 1) + /*No of faddp instructions*/ Log2_32(NElts);
7151 }
7152 break;
7153 case ISD::ADD:
7154 if (const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy))
7155 return (LT.first - 1) + Entry->Cost;
7156 break;
7157 case ISD::XOR:
7158 case ISD::AND:
7159 case ISD::OR:
7160 const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy);
7161 if (!Entry)
7162 break;
7163 auto *ValVTy = cast<FixedVectorType>(ValTy);
7164 // A non-power-of-2 i1 vector is widened with the identity and reduced as
7165 // the promoted integer vector, the i1 min/max lowering does not apply. The
7166 // zero identity of or/xor is set by a single masking and.
7167 if (ValTy->isIntOrIntVectorTy(1) &&
7168 !isPowerOf2_32(ValVTy->getNumElements()) && LT.first == 1) {
7169 unsigned PaddedElts = MTy.getVectorNumElements();
7170 auto *PaddedTy =
7171 FixedVectorType::get(ValVTy->getElementType(), PaddedElts);
7172 if (ISD != ISD::AND)
7173 return Entry->Cost +
7174 getArithmeticInstrCost(Instruction::And, PaddedTy, CostKind);
7175 return Entry->Cost +
7177 PaddedTy,
7178 APInt::getBitsSetFrom(PaddedElts, ValVTy->getNumElements()),
7179 /*Insert=*/true, /*Extract=*/false, CostKind);
7180 }
7181 if (MTy.getVectorNumElements() <= ValVTy->getNumElements() &&
7182 isPowerOf2_32(ValVTy->getNumElements())) {
7183 InstructionCost ExtraCost = 0;
7184 if (LT.first != 1) {
7185 // Type needs to be split, so there is an extra cost of LT.first - 1
7186 // arithmetic ops.
7187 auto *Ty = FixedVectorType::get(ValTy->getElementType(),
7188 MTy.getVectorNumElements());
7189 ExtraCost = getArithmeticInstrCost(Opcode, Ty, CostKind);
7190 ExtraCost *= LT.first - 1;
7191 }
7192 // All and/or/xor of i1 will be lowered with maxv/minv/addv + fmov
7193 auto Cost = ValVTy->getElementType()->isIntegerTy(1) ? 2 : Entry->Cost;
7194 return Cost + ExtraCost;
7195 }
7196 break;
7197 }
7198 return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
7199}
7200
7202 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *VecTy,
7203 std::optional<FastMathFlags> FMF, TTI::TargetCostKind CostKind) const {
7204 EVT VecVT = TLI->getValueType(DL, VecTy);
7205 EVT ResVT = TLI->getValueType(DL, ResTy);
7206
7207 if (IsUnsigned && Opcode == Instruction::Add &&
7208 VecVT.isScalableVectorOf(MVT::i1) && ResVT.isSimple() &&
7209 getTLI()->isTypeLegal(VecVT)) {
7210 // This is vecreduce.add(ZExt(mask)) which can lower as cntp(mask).
7211 return 1;
7212 }
7213
7214 if (Opcode == Instruction::Add && VecVT.isSimple() && ResVT.isSimple() &&
7215 !VecVT.isScalableVT() && VecVT.getFixedSizeInBits() >= 64) {
7216 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(VecTy);
7217
7218 // The legal cases are:
7219 // UADDLV 8/16/32->32
7220 // UADDLP 32->64
7221 unsigned RevVTSize = ResVT.getSizeInBits();
7222 if (((LT.second == MVT::v8i8 || LT.second == MVT::v16i8) &&
7223 RevVTSize <= 32) ||
7224 ((LT.second == MVT::v4i16 || LT.second == MVT::v8i16) &&
7225 RevVTSize <= 32) ||
7226 ((LT.second == MVT::v2i32 || LT.second == MVT::v4i32) &&
7227 RevVTSize <= 64))
7228 return (LT.first - 1) * 2 + 2;
7229 }
7230
7231 return BaseT::getExtendedReductionCost(Opcode, IsUnsigned, ResTy, VecTy, FMF,
7232 CostKind);
7233}
7234
7236AArch64TTIImpl::getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode,
7237 Type *ResTy, VectorType *VecTy,
7238 TTI::TargetCostKind CostKind) const {
7239 EVT VecVT = TLI->getValueType(DL, VecTy);
7240 EVT ResVT = TLI->getValueType(DL, ResTy);
7241
7242 if (ST->hasDotProd() && VecVT.isSimple() && ResVT.isSimple() &&
7243 RedOpcode == Instruction::Add) {
7244 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(VecTy);
7245
7246 // The legal cases with dotprod are
7247 // UDOT 8->32
7248 // Which requires an additional uaddv to sum the i32 values.
7249 if ((LT.second == MVT::v8i8 || LT.second == MVT::v16i8) &&
7250 ResVT == MVT::i32)
7251 return LT.first + 2;
7252 }
7253
7254 return BaseT::getMulAccReductionCost(IsUnsigned, RedOpcode, ResTy, VecTy,
7255 CostKind);
7256}
7257
7260 TTI::TargetCostKind CostKind) const {
7261 static const CostTblEntry ShuffleTbl[] = {
7262 { TTI::SK_Splice, MVT::nxv16i8, 1 },
7263 { TTI::SK_Splice, MVT::nxv8i16, 1 },
7264 { TTI::SK_Splice, MVT::nxv4i32, 1 },
7265 { TTI::SK_Splice, MVT::nxv2i64, 1 },
7266 { TTI::SK_Splice, MVT::nxv2f16, 1 },
7267 { TTI::SK_Splice, MVT::nxv4f16, 1 },
7268 { TTI::SK_Splice, MVT::nxv8f16, 1 },
7269 { TTI::SK_Splice, MVT::nxv2bf16, 1 },
7270 { TTI::SK_Splice, MVT::nxv4bf16, 1 },
7271 { TTI::SK_Splice, MVT::nxv8bf16, 1 },
7272 { TTI::SK_Splice, MVT::nxv2f32, 1 },
7273 { TTI::SK_Splice, MVT::nxv4f32, 1 },
7274 { TTI::SK_Splice, MVT::nxv2f64, 1 },
7275 };
7276
7277 // The code-generator is currently not able to handle scalable vectors
7278 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
7279 // it. This change will be removed when code-generation for these types is
7280 // sufficiently reliable.
7283
7284 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Tp);
7285 Type *LegalVTy = EVT(LT.second).getTypeForEVT(Tp->getContext());
7286 EVT PromotedVT = LT.second.getScalarType() == MVT::i1
7287 ? TLI->getPromotedVTForPredicate(EVT(LT.second))
7288 : LT.second;
7289 Type *PromotedVTy = EVT(PromotedVT).getTypeForEVT(Tp->getContext());
7290 InstructionCost LegalizationCost = 0;
7291 if (Index < 0) {
7292 LegalizationCost =
7293 getCmpSelInstrCost(Instruction::ICmp, PromotedVTy, PromotedVTy,
7294 CmpInst::BAD_ICMP_PREDICATE, CostKind) +
7295 getCmpSelInstrCost(Instruction::Select, PromotedVTy, LegalVTy,
7296 CmpInst::BAD_ICMP_PREDICATE, CostKind);
7297 }
7298
7299 // Predicated splice are promoted when lowering. See AArch64ISelLowering.cpp
7300 // Cost performed on a promoted type.
7301 if (LT.second.getScalarType() == MVT::i1) {
7302 LegalizationCost +=
7303 getCastInstrCost(Instruction::ZExt, PromotedVTy, LegalVTy,
7304 TTI::CastContextHint::None, CostKind) +
7305 getCastInstrCost(Instruction::Trunc, LegalVTy, PromotedVTy,
7306 TTI::CastContextHint::None, CostKind);
7307 }
7308
7309 const auto *Entry =
7310 CostTableLookup(ShuffleTbl, TTI::SK_Splice, PromotedVT.getSimpleVT());
7311 if (!Entry)
7313
7314 LegalizationCost += Entry->Cost;
7315 return LegalizationCost * LT.first;
7316}
7317
7319 unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType,
7321 TTI::PartialReductionExtendKind OpBExtend, std::optional<unsigned> BinOp,
7322 TTI::TargetCostKind CostKind, std::optional<FastMathFlags> FMF) const {
7324
7325 if (CostKind != TTI::TCK_RecipThroughput)
7326 return Invalid;
7327
7328 if ((Opcode != Instruction::Add && Opcode != Instruction::Sub &&
7329 Opcode != Instruction::FAdd && Opcode != Instruction::FSub))
7330 return Invalid;
7331
7332 // Floating-point partial reductions are invalid if `reassoc` and `contract`
7333 // are not allowed.
7334 if (AccumType->isFloatingPointTy()) {
7335 assert(FMF && "Missing FastMathFlags for floating-point partial reduction");
7336 if (!FMF->allowReassoc() || !FMF->allowContract())
7337 return Invalid;
7338 } else {
7339 assert(!FMF &&
7340 "FastMathFlags only apply to floating-point partial reductions");
7341 }
7342
7343 assert((BinOp || (OpBExtend == TTI::PR_None && !InputTypeB)) &&
7344 (!BinOp || (OpBExtend != TTI::PR_None && InputTypeB)) &&
7345 "Unexpected values for OpBExtend or InputTypeB");
7346
7347 // We only support multiply binary operations for now, and for muls we
7348 // require the types being extended to be the same.
7349 if (BinOp && ((*BinOp != Instruction::Mul && *BinOp != Instruction::FMul) ||
7350 InputTypeA != InputTypeB))
7351 return Invalid;
7352
7353 // We only support the following element sizes.
7354 if (!is_contained({8u, 16u, 32u, 64u}, AccumType->getScalarSizeInBits()))
7355 return Invalid;
7356
7357 // If none of the operands are extended and there's no extra BinOp, just
7358 // cost this as the equivalent arithmetic instruction.
7359 // TODO: Depending on VF and element type, we may be able to improve on this.
7360 if (!OpAExtend) {
7361 assert(!OpBExtend && "Extended second operand without extended first.");
7362 assert(InputTypeA == AccumType && "Type mismatch with no extensions.");
7363
7364 VectorType *VTy = VectorType::get(AccumType, VF);
7365 return getArithmeticInstrCost(Opcode, VTy, CostKind);
7366 }
7367
7368 bool IsUSDot = OpBExtend != TTI::PR_None && OpAExtend != OpBExtend;
7369 // USDot is natively supported with +i8mm. With plain +dotprod, SUMLA is
7370 // lowered to two udots plus an eor and a sub.
7371 if (IsUSDot && !ST->hasMatMulInt8() && !ST->hasDotProd())
7372 // FIXME: Remove this early bailout in favour of expand cost.
7373 return Invalid;
7374
7375 unsigned Ratio =
7376 AccumType->getScalarSizeInBits() / InputTypeA->getScalarSizeInBits();
7377 if (VF.getKnownMinValue() <= Ratio)
7378 return Invalid;
7379
7380 VectorType *InputVectorType = VectorType::get(InputTypeA, VF);
7381 VectorType *AccumVectorType =
7382 VectorType::get(AccumType, VF.divideCoefficientBy(Ratio));
7383 // We don't yet support all kinds of legalization.
7384 auto TC = TLI->getTypeConversion(AccumVectorType->getContext(),
7385 EVT::getEVT(AccumVectorType));
7386 switch (TC.first) {
7387 default:
7388 return Invalid;
7392 // The legalised type (e.g. after splitting) must be legal too.
7393 if (TLI->getTypeAction(AccumVectorType->getContext(), TC.second) !=
7395 return Invalid;
7396 break;
7397 }
7398
7399 std::pair<InstructionCost, MVT> AccumLT =
7400 getTypeLegalizationCost(AccumVectorType);
7401 std::pair<InstructionCost, MVT> InputLT =
7402 getTypeLegalizationCost(InputVectorType);
7403
7404 // Returns true if the subtarget supports the operation for a given type.
7405 auto IsSupported = [&](bool SVEPred, bool NEONPred) -> bool {
7406 return (ST->isSVEorStreamingSVEAvailable() && SVEPred) ||
7407 (AccumLT.second.isFixedLengthVector() &&
7408 AccumLT.second.getSizeInBits() <= 128 && ST->isNeonAvailable() &&
7409 NEONPred);
7410 };
7411
7412 bool IsSub = Opcode == Instruction::Sub || Opcode == Instruction::FSub;
7413 InstructionCost Cost = InputLT.first * TTI::TCC_Basic;
7414 // Integer partial sub-reductions that don't map to a specific instruction,
7415 // carry an extra cost for implementing a double negation:
7416 // partial_reduce_umls acc, lhs, rhs
7417 // <=> -partial_reduce_umla -acc, lhs, rhs
7418 InstructionCost INegCost = IsSub ? 2 * InputLT.first * TTI::TCC_Basic : 0;
7419
7420 if (AccumLT.second.getScalarType() == MVT::i32 &&
7421 InputLT.second.getScalarType() == MVT::i8) {
7422 // i8 -> i32 is natively supported with udot/sdot for both NEON and SVE.
7423 if (!IsUSDot && IsSupported(true, ST->hasDotProd()))
7424 return Cost + INegCost;
7425 // i8 -> i32 usdot requires +i8mm
7426 if (IsUSDot && IsSupported(ST->hasMatMulInt8(), ST->hasMatMulInt8()))
7427 return Cost + INegCost;
7428 // Without +i8mm, lower SUMLA via two udots plus an eor and a sub on plain
7429 // +dotprod targets. Note that this is only implemented for NEON, as all
7430 // modern CPUs with SVE also have +i8mm. Charge an extra factor for the
7431 // expansion.
7432 if (IsUSDot && IsSupported(false, ST->hasDotProd()))
7433 return Cost * 3 + INegCost;
7434 }
7435
7436 if (ST->isSVEorStreamingSVEAvailable() && !IsUSDot) {
7437 // i16 -> i64 is natively supported for udot/sdot
7438 if (AccumLT.second.getScalarType() == MVT::i64 &&
7439 InputLT.second.getScalarType() == MVT::i16)
7440 return Cost + INegCost;
7441 // i16 -> i32 is natively supported with SVE2p1 udot/sdot.
7442 // For sub-reductions, we prefer using the *mlslb/t instructions.
7443 if (AccumLT.second.getScalarType() == MVT::i32 &&
7444 InputLT.second.getScalarType() == MVT::i16 &&
7445 (ST->hasSVE2p1() || ST->hasSME2()) && !IsSub)
7446 return Cost;
7447 // i8 -> i64 is supported with an extra level of extends
7448 if (AccumLT.second.getScalarType() == MVT::i64 &&
7449 InputLT.second.getScalarType() == MVT::i8)
7450 // FIXME: Also account for folding the i32 dot product results into the
7451 // i64 accumulator, as the NEON case below does.
7452 return Cost + INegCost;
7453 // i8 -> i16 is natively supported with SVE2p3 udot/sdot
7454 // For sub-reductions, we prefer using the *mlslb/t instructions.
7455 if (AccumLT.second.getScalarType() == MVT::i16 &&
7456 InputLT.second.getScalarType() == MVT::i8 &&
7457 (ST->hasSVE2p3() || ST->hasSME2p3()) && !IsSub)
7458 return Cost;
7459 }
7460
7461 // With +dotprod, NEON lowers an extended i8 -> i64 partial reduction to a
7462 // udot/sdot into a zeroed i32 vector followed by an [SU]ADALP into the i64
7463 // accumulator. Charge one basic cost for each of the two steps per legal
7464 // input vector. This must stay after the SVE cases, as IsSupported's NEON
7465 // predicate also holds for fixed-length vectors on SVE targets.
7466 // TODO: Handle zero-extended multiplies and sub-reductions. In loops,
7467 // CodeGenPrepare turns zero extends that do not directly feed the partial
7468 // reduction (such as the operands of a multiply, or of the negation in a
7469 // sub-reduction) into TBLs, which hides the udot from instruction selection.
7470 // Sign-extended sub-reductions have not been measured yet.
7471 // TODO: Without +dotprod, pure adds with a ratio of 4 or 8 lower to a chain
7472 // of [SU]ADDLPs and an [SU]ADALP, which is not costed yet either.
7473 bool IsSExtMul = BinOp && OpAExtend == TTI::PR_SignExtend &&
7474 OpBExtend == TTI::PR_SignExtend;
7475 if ((!BinOp || IsSExtMul) && !IsSub &&
7476 AccumLT.second.getScalarType() == MVT::i64 &&
7477 InputLT.second.getScalarType() == MVT::i8 &&
7478 IsSupported(false, ST->hasDotProd()))
7479 return Cost * 2;
7480
7481 // f16 -> f32 is natively supported for fdot using either
7482 // SVE or NEON instruction.
7483 if (Opcode == Instruction::FAdd && !IsSub &&
7484 IsSupported(ST->hasSME2() || ST->hasSVE2p1(), ST->hasF16F32DOT()) &&
7485 AccumLT.second.getScalarType() == MVT::f32 &&
7486 InputLT.second.getScalarType() == MVT::f16)
7487 return Cost;
7488
7489 // For a ratio of 2, we can use *mlal and *mlsl top/bottom instructions.
7490 if (Ratio == 2 && !IsUSDot) {
7491 MVT InVT = InputLT.second.getScalarType();
7492
7493 // SVE2 [us]ml[as]lb/t and NEON [us]ml[as]l(2). A pure widening add with a
7494 // ratio of 2 can use [SU]ADALP instead.
7495 if (IsSupported(ST->hasSVE2() || ST->hasSME(), true) &&
7496 llvm::is_contained({MVT::i8, MVT::i16, MVT::i32}, InVT.SimpleTy))
7497 return (BinOp || IsSub) ? Cost * 2 : Cost;
7498
7499 // SVE2 fml[as]lb/t and NEON fml[as]l(2)
7500 if (IsSupported(ST->hasSVE2(), ST->hasFP16FML()) && InVT == MVT::f16)
7501 return Cost * 2;
7502
7503 // SME2/SVE2p1 bfmlslb/t
7504 if (IsSupported(ST->hasSVE2p1() || ST->hasSME2(), false) &&
7505 InVT == MVT::bf16 && IsSub)
7506 return Cost * 2;
7507
7508 // FP partial sub-reductions that don't map to a specific instruction,
7509 // carry an extra cost for implementing an extra negation:
7510 // partial_reduce_fmls acc, lhs, rhs
7511 // <=> partial_reduce_fmla acc, lhs, -rhs
7512 InstructionCost FNegCost = IsSub ? InputLT.first * TTI::TCC_Basic : 0;
7513
7514 // SVE and NEON bfmlalb/t
7515 if (IsSupported(ST->hasBF16(), ST->hasBF16()) && InVT == MVT::bf16)
7516 return Cost * 2 + FNegCost;
7517 }
7518
7519 return BaseT::getPartialReductionCost(Opcode, InputTypeA, InputTypeB,
7520 AccumType, VF, OpAExtend, OpBExtend,
7521 BinOp, CostKind, FMF);
7522}
7523
7525 TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy,
7526 TTI::TargetCostKind CostKind, ArrayRef<int> Mask, int Index,
7527 VectorType *SubTp, ArrayRef<const Value *> Args, const Instruction *CtxI,
7528 TTI::VectorInstrContext VIC) const {
7529 assert((Mask.empty() || DstTy->isScalableTy() ||
7530 Mask.size() == DstTy->getElementCount().getKnownMinValue()) &&
7531 "Expected the Mask to match the return size if given");
7532 assert(SrcTy->getScalarType() == DstTy->getScalarType() &&
7533 "Expected the same scalar types");
7534 if (VIC == TTI::VectorInstrContext::SplatOpFolded) {
7535 int TmpIndex = Index;
7536 VectorType *TmpSubTp = SubTp;
7537 if (improveShuffleKindFromMask(Kind, Mask, SrcTy, TmpIndex, TmpSubTp) ==
7539 return TTI::TCC_Free;
7540 }
7541 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(SrcTy);
7542
7543 // If we have a Mask, and the LT is being legalized somehow, split the Mask
7544 // into smaller vectors and sum the cost of each shuffle.
7545 if (!Mask.empty() && isa<FixedVectorType>(SrcTy) && LT.second.isVector() &&
7546 LT.second.getScalarSizeInBits() * Mask.size() > 128 &&
7547 SrcTy->getScalarSizeInBits() == LT.second.getScalarSizeInBits() &&
7548 Mask.size() > LT.second.getVectorNumElements() && !Index && !SubTp) {
7549 // Check for LD3/LD4 instructions, which are represented in llvm IR as
7550 // deinterleaving-shuffle(load). The shuffle cost could potentially be free,
7551 // but we model it with a cost of LT.first so that LD3/LD4 have a higher
7552 // cost than just the load.
7553 if (Args.size() >= 1 && isa<LoadInst>(Args[0]) &&
7556 return std::max<InstructionCost>(1, LT.first / 4);
7557
7558 // Check for ST3/ST4 instructions, which are represented in llvm IR as
7559 // store(interleaving-shuffle). The shuffle cost could potentially be free,
7560 // but we model it with a cost of LT.first so that ST3/ST4 have a higher
7561 // cost than just the store.
7562 if (CtxI && CtxI->hasOneUse() && isa<StoreInst>(*CtxI->user_begin()) &&
7564 Mask, 4, SrcTy->getElementCount().getKnownMinValue() * 2) ||
7566 Mask, 3, SrcTy->getElementCount().getKnownMinValue() * 2)))
7567 return LT.first;
7568
7569 unsigned TpNumElts = Mask.size();
7570 unsigned LTNumElts = LT.second.getVectorNumElements();
7571 unsigned NumVecs = (TpNumElts + LTNumElts - 1) / LTNumElts;
7572 VectorType *NTp = VectorType::get(SrcTy->getScalarType(),
7573 LT.second.getVectorElementCount());
7575 std::map<std::tuple<unsigned, unsigned, SmallVector<int>>, InstructionCost>
7576 PreviousCosts;
7577 for (unsigned N = 0; N < NumVecs; N++) {
7578 SmallVector<int> NMask;
7579 // Split the existing mask into chunks of size LTNumElts. Track the source
7580 // sub-vectors to ensure the result has at most 2 inputs.
7581 unsigned Source1 = -1U, Source2 = -1U;
7582 unsigned NumSources = 0;
7583 for (unsigned E = 0; E < LTNumElts; E++) {
7584 int MaskElt = (N * LTNumElts + E < TpNumElts) ? Mask[N * LTNumElts + E]
7586 if (MaskElt < 0) {
7588 continue;
7589 }
7590
7591 // Calculate which source from the input this comes from and whether it
7592 // is new to us.
7593 unsigned Source = MaskElt / LTNumElts;
7594 if (NumSources == 0) {
7595 Source1 = Source;
7596 NumSources = 1;
7597 } else if (NumSources == 1 && Source != Source1) {
7598 Source2 = Source;
7599 NumSources = 2;
7600 } else if (NumSources >= 2 && Source != Source1 && Source != Source2) {
7601 NumSources++;
7602 }
7603
7604 // Add to the new mask. For the NumSources>2 case these are not correct,
7605 // but are only used for the modular lane number.
7606 if (Source == Source1)
7607 NMask.push_back(MaskElt % LTNumElts);
7608 else if (Source == Source2)
7609 NMask.push_back(MaskElt % LTNumElts + LTNumElts);
7610 else
7611 NMask.push_back(MaskElt % LTNumElts);
7612 }
7613 // Check if we have already generated this sub-shuffle, which means we
7614 // will have already generated the output. For example a <16 x i32> splat
7615 // will be the same sub-splat 4 times, which only needs to be generated
7616 // once and reused.
7617 auto Result =
7618 PreviousCosts.insert({std::make_tuple(Source1, Source2, NMask), 0});
7619 // Check if it was already in the map (already costed).
7620 if (!Result.second)
7621 continue;
7622 // If the sub-mask has at most 2 input sub-vectors then re-cost it using
7623 // getShuffleCost. If not then cost it using the worst case as the number
7624 // of element moves into a new vector.
7625 InstructionCost NCost =
7626 NumSources <= 2
7627 ? getShuffleCost(NumSources <= 1 ? TTI::SK_PermuteSingleSrc
7629 NTp, NTp, CostKind, NMask, 0, nullptr, Args,
7630 CtxI)
7631 : LTNumElts;
7632 Result.first->second = NCost;
7633 Cost += NCost;
7634 }
7635 return Cost;
7636 }
7637
7638 Kind = improveShuffleKindFromMask(Kind, Mask, SrcTy, Index, SubTp);
7639 bool IsExtractSubvector = Kind == TTI::SK_ExtractSubvector;
7640 // A subvector extract can be implemented with a NEON/SVE ext (or trivial
7641 // extract, if from lane 0) for 128-bit NEON vectors or legal SVE vectors.
7642 // This currently only handles low or high extracts to prevent SLP vectorizer
7643 // regressions.
7644 // Note that SVE's ext instruction is destructive, but it can be fused with
7645 // a movprfx to act like a constructive instruction.
7646 if (IsExtractSubvector && LT.second.isFixedLengthVector()) {
7647 if (LT.second.getFixedSizeInBits() >= 128 &&
7648 cast<FixedVectorType>(SubTp)->getNumElements() ==
7649 LT.second.getVectorNumElements() / 2) {
7650 if (Index == 0)
7651 return 0;
7652 if (Index == (int)LT.second.getVectorNumElements() / 2)
7653 return 1;
7654 }
7656 }
7657 // FIXME: This was added to keep the costs equal when adding DstTys. Update
7658 // the code to handle length-changing shuffles.
7659 if (Kind == TTI::SK_InsertSubvector) {
7660 LT = getTypeLegalizationCost(DstTy);
7661 SrcTy = DstTy;
7662 }
7663
7664 // Check for identity masks, which we can treat as free for both fixed and
7665 // scalable vector paths.
7666 if (!Mask.empty() && LT.second.isFixedLengthVector() &&
7667 (Kind == TTI::SK_PermuteTwoSrc || Kind == TTI::SK_PermuteSingleSrc) &&
7668 all_of(enumerate(Mask), [](const auto &M) {
7669 return M.value() < 0 || M.value() == (int)M.index();
7670 }))
7671 return 0;
7672
7673 // Segmented shuffle matching.
7674 if (Kind == TTI::SK_PermuteSingleSrc && isa<FixedVectorType>(SrcTy) &&
7675 !Mask.empty() && SrcTy->getPrimitiveSizeInBits().isNonZero() &&
7676 SrcTy->getPrimitiveSizeInBits().isKnownMultipleOf(
7678
7680 unsigned Segments =
7682 unsigned SegmentElts = VTy->getNumElements() / Segments;
7683
7684 // dupq zd.t, zn.t[idx]
7685 if ((ST->hasSVE2p1() || ST->hasSME2p1()) &&
7686 ST->isSVEorStreamingSVEAvailable() &&
7687 isDUPQMask(Mask, Segments, SegmentElts))
7688 return LT.first;
7689
7690 // mov zd.q, vn
7691 if (ST->isSVEorStreamingSVEAvailable() &&
7692 isDUPFirstSegmentMask(Mask, Segments, SegmentElts))
7693 return LT.first;
7694 }
7695
7696 // Check for broadcast loads, which are supported by the LD1R instruction.
7697 // In terms of code-size, the shuffle vector is free when a load + dup get
7698 // folded into a LD1R. That's what we check and return here. For performance
7699 // and reciprocal throughput, a LD1R is not completely free. In this case, we
7700 // return the cost for the broadcast below (i.e. 1 for most/all types), so
7701 // that we model the load + dup sequence slightly higher because LD1R is a
7702 // high latency instruction.
7703 if (CostKind == TTI::TCK_CodeSize && Kind == TTI::SK_Broadcast) {
7704 bool IsLoad = !Args.empty() && isa<LoadInst>(Args[0]);
7705 if (IsLoad && LT.second.isVector() &&
7706 isLegalBroadcastLoad(SrcTy->getElementType(),
7707 LT.second.getVectorElementCount()))
7708 return 0;
7709 }
7710
7711 // If we have 4 elements for the shuffle and a Mask, get the cost straight
7712 // from the perfect shuffle tables.
7713 if (Mask.size() == 4 &&
7714 SrcTy->getElementCount() == ElementCount::getFixed(4) &&
7715 (SrcTy->getScalarSizeInBits() == 16 ||
7716 SrcTy->getScalarSizeInBits() == 32) &&
7717 all_of(Mask, [](int E) { return E < 8; }))
7718 return getPerfectShuffleCost(Mask);
7719
7720 // Check for other shuffles that are not SK_ kinds but we have native
7721 // instructions for, for example ZIP and UZP.
7722 unsigned Unused;
7723 if (LT.second.isFixedLengthVector() &&
7724 LT.second.getVectorNumElements() == Mask.size() &&
7725 (Kind == TTI::SK_PermuteTwoSrc || Kind == TTI::SK_PermuteSingleSrc ||
7726 // Discrepancies between isTRNMask and ShuffleVectorInst::isTransposeMask
7727 // mean that we can end up with shuffles that satisfy isTRNMask, but end
7728 // up labelled as TTI::SK_InsertSubvector. (e.g. {2, 0}).
7729 Kind == TTI::SK_InsertSubvector) &&
7730 (isZIPMask(Mask, LT.second.getVectorNumElements(), Unused, Unused) ||
7731 isTRNMask(Mask, LT.second.getVectorNumElements(), Unused, Unused) ||
7732 isUZPMask(Mask, LT.second.getVectorNumElements(), Unused) ||
7733 isREVMask(Mask, LT.second.getScalarSizeInBits(),
7734 LT.second.getVectorNumElements(), 16) ||
7735 isREVMask(Mask, LT.second.getScalarSizeInBits(),
7736 LT.second.getVectorNumElements(), 32) ||
7737 isREVMask(Mask, LT.second.getScalarSizeInBits(),
7738 LT.second.getVectorNumElements(), 64) ||
7739 // Check for non-zero lane splats
7740 all_of(drop_begin(Mask),
7741 [&Mask](int M) { return M < 0 || M == Mask[0]; })))
7742 return 1;
7743
7744 if (Kind == TTI::SK_Broadcast || Kind == TTI::SK_Transpose ||
7745 Kind == TTI::SK_Select || Kind == TTI::SK_PermuteSingleSrc ||
7746 Kind == TTI::SK_Reverse || Kind == TTI::SK_Splice) {
7747 static const CostTblEntry ShuffleTbl[] = {
7748 // Broadcast shuffle kinds can be performed with 'dup'.
7749 {TTI::SK_Broadcast, MVT::v8i8, 1},
7750 {TTI::SK_Broadcast, MVT::v16i8, 1},
7751 {TTI::SK_Broadcast, MVT::v4i16, 1},
7752 {TTI::SK_Broadcast, MVT::v8i16, 1},
7753 {TTI::SK_Broadcast, MVT::v2i32, 1},
7754 {TTI::SK_Broadcast, MVT::v4i32, 1},
7755 {TTI::SK_Broadcast, MVT::v2i64, 1},
7756 {TTI::SK_Broadcast, MVT::v4f16, 1},
7757 {TTI::SK_Broadcast, MVT::v8f16, 1},
7758 {TTI::SK_Broadcast, MVT::v4bf16, 1},
7759 {TTI::SK_Broadcast, MVT::v8bf16, 1},
7760 {TTI::SK_Broadcast, MVT::v2f32, 1},
7761 {TTI::SK_Broadcast, MVT::v4f32, 1},
7762 {TTI::SK_Broadcast, MVT::v2f64, 1},
7763 // Transpose shuffle kinds can be performed with 'trn1/trn2' and
7764 // 'zip1/zip2' instructions.
7765 {TTI::SK_Transpose, MVT::v8i8, 1},
7766 {TTI::SK_Transpose, MVT::v16i8, 1},
7767 {TTI::SK_Transpose, MVT::v4i16, 1},
7768 {TTI::SK_Transpose, MVT::v8i16, 1},
7769 {TTI::SK_Transpose, MVT::v2i32, 1},
7770 {TTI::SK_Transpose, MVT::v4i32, 1},
7771 {TTI::SK_Transpose, MVT::v2i64, 1},
7772 {TTI::SK_Transpose, MVT::v4f16, 1},
7773 {TTI::SK_Transpose, MVT::v8f16, 1},
7774 {TTI::SK_Transpose, MVT::v4bf16, 1},
7775 {TTI::SK_Transpose, MVT::v8bf16, 1},
7776 {TTI::SK_Transpose, MVT::v2f32, 1},
7777 {TTI::SK_Transpose, MVT::v4f32, 1},
7778 {TTI::SK_Transpose, MVT::v2f64, 1},
7779 // Select shuffle kinds.
7780 // TODO: handle vXi8/vXi16.
7781 {TTI::SK_Select, MVT::v2i32, 1}, // mov.
7782 {TTI::SK_Select, MVT::v4i32, 2}, // rev+trn (or similar).
7783 {TTI::SK_Select, MVT::v2i64, 1}, // mov.
7784 {TTI::SK_Select, MVT::v2f32, 1}, // mov.
7785 {TTI::SK_Select, MVT::v4f32, 2}, // rev+trn (or similar).
7786 {TTI::SK_Select, MVT::v2f64, 1}, // mov.
7787 // PermuteSingleSrc shuffle kinds.
7788 {TTI::SK_PermuteSingleSrc, MVT::v2i32, 1}, // mov.
7789 {TTI::SK_PermuteSingleSrc, MVT::v4i32, 3}, // perfectshuffle worst case.
7790 {TTI::SK_PermuteSingleSrc, MVT::v2i64, 1}, // mov.
7791 {TTI::SK_PermuteSingleSrc, MVT::v2f32, 1}, // mov.
7792 {TTI::SK_PermuteSingleSrc, MVT::v4f32, 3}, // perfectshuffle worst case.
7793 {TTI::SK_PermuteSingleSrc, MVT::v2f64, 1}, // mov.
7794 {TTI::SK_PermuteSingleSrc, MVT::v4i16, 3}, // perfectshuffle worst case.
7795 {TTI::SK_PermuteSingleSrc, MVT::v4f16, 3}, // perfectshuffle worst case.
7796 {TTI::SK_PermuteSingleSrc, MVT::v4bf16, 3}, // same
7797 {TTI::SK_PermuteSingleSrc, MVT::v8i16, 8}, // constpool + load + tbl
7798 {TTI::SK_PermuteSingleSrc, MVT::v8f16, 8}, // constpool + load + tbl
7799 {TTI::SK_PermuteSingleSrc, MVT::v8bf16, 8}, // constpool + load + tbl
7800 {TTI::SK_PermuteSingleSrc, MVT::v8i8, 8}, // constpool + load + tbl
7801 {TTI::SK_PermuteSingleSrc, MVT::v16i8, 8}, // constpool + load + tbl
7802 // Reverse can be lowered with `rev`.
7803 {TTI::SK_Reverse, MVT::v2i32, 1}, // REV64
7804 {TTI::SK_Reverse, MVT::v4i32, 2}, // REV64; EXT
7805 {TTI::SK_Reverse, MVT::v2i64, 1}, // EXT
7806 {TTI::SK_Reverse, MVT::v2f32, 1}, // REV64
7807 {TTI::SK_Reverse, MVT::v4f32, 2}, // REV64; EXT
7808 {TTI::SK_Reverse, MVT::v2f64, 1}, // EXT
7809 {TTI::SK_Reverse, MVT::v8f16, 2}, // REV64; EXT
7810 {TTI::SK_Reverse, MVT::v8bf16, 2}, // REV64; EXT
7811 {TTI::SK_Reverse, MVT::v8i16, 2}, // REV64; EXT
7812 {TTI::SK_Reverse, MVT::v16i8, 2}, // REV64; EXT
7813 {TTI::SK_Reverse, MVT::v4f16, 1}, // REV64
7814 {TTI::SK_Reverse, MVT::v4bf16, 1}, // REV64
7815 {TTI::SK_Reverse, MVT::v4i16, 1}, // REV64
7816 {TTI::SK_Reverse, MVT::v8i8, 1}, // REV64
7817 // Splice can all be lowered as `ext`.
7818 {TTI::SK_Splice, MVT::v2i32, 1},
7819 {TTI::SK_Splice, MVT::v4i32, 1},
7820 {TTI::SK_Splice, MVT::v2i64, 1},
7821 {TTI::SK_Splice, MVT::v2f32, 1},
7822 {TTI::SK_Splice, MVT::v4f32, 1},
7823 {TTI::SK_Splice, MVT::v2f64, 1},
7824 {TTI::SK_Splice, MVT::v8f16, 1},
7825 {TTI::SK_Splice, MVT::v8bf16, 1},
7826 {TTI::SK_Splice, MVT::v8i16, 1},
7827 {TTI::SK_Splice, MVT::v16i8, 1},
7828 {TTI::SK_Splice, MVT::v4f16, 1},
7829 {TTI::SK_Splice, MVT::v4bf16, 1},
7830 {TTI::SK_Splice, MVT::v4i16, 1},
7831 {TTI::SK_Splice, MVT::v8i8, 1},
7832 // Broadcast shuffle kinds for scalable vectors
7833 {TTI::SK_Broadcast, MVT::nxv16i8, 1},
7834 {TTI::SK_Broadcast, MVT::nxv8i16, 1},
7835 {TTI::SK_Broadcast, MVT::nxv4i32, 1},
7836 {TTI::SK_Broadcast, MVT::nxv2i64, 1},
7837 {TTI::SK_Broadcast, MVT::nxv2f16, 1},
7838 {TTI::SK_Broadcast, MVT::nxv4f16, 1},
7839 {TTI::SK_Broadcast, MVT::nxv8f16, 1},
7840 {TTI::SK_Broadcast, MVT::nxv2bf16, 1},
7841 {TTI::SK_Broadcast, MVT::nxv4bf16, 1},
7842 {TTI::SK_Broadcast, MVT::nxv8bf16, 1},
7843 {TTI::SK_Broadcast, MVT::nxv2f32, 1},
7844 {TTI::SK_Broadcast, MVT::nxv4f32, 1},
7845 {TTI::SK_Broadcast, MVT::nxv2f64, 1},
7846 {TTI::SK_Broadcast, MVT::nxv16i1, 1},
7847 {TTI::SK_Broadcast, MVT::nxv8i1, 1},
7848 {TTI::SK_Broadcast, MVT::nxv4i1, 1},
7849 {TTI::SK_Broadcast, MVT::nxv2i1, 1},
7850 // Handle the cases for vector.reverse with scalable vectors
7851 {TTI::SK_Reverse, MVT::nxv16i8, 1},
7852 {TTI::SK_Reverse, MVT::nxv8i16, 1},
7853 {TTI::SK_Reverse, MVT::nxv4i32, 1},
7854 {TTI::SK_Reverse, MVT::nxv2i64, 1},
7855 {TTI::SK_Reverse, MVT::nxv2f16, 1},
7856 {TTI::SK_Reverse, MVT::nxv4f16, 1},
7857 {TTI::SK_Reverse, MVT::nxv8f16, 1},
7858 {TTI::SK_Reverse, MVT::nxv2bf16, 1},
7859 {TTI::SK_Reverse, MVT::nxv4bf16, 1},
7860 {TTI::SK_Reverse, MVT::nxv8bf16, 1},
7861 {TTI::SK_Reverse, MVT::nxv2f32, 1},
7862 {TTI::SK_Reverse, MVT::nxv4f32, 1},
7863 {TTI::SK_Reverse, MVT::nxv2f64, 1},
7864 {TTI::SK_Reverse, MVT::nxv16i1, 1},
7865 {TTI::SK_Reverse, MVT::nxv8i1, 1},
7866 {TTI::SK_Reverse, MVT::nxv4i1, 1},
7867 {TTI::SK_Reverse, MVT::nxv2i1, 1},
7868 };
7869 if (const auto *Entry = CostTableLookup(ShuffleTbl, Kind, LT.second))
7870 return LT.first * Entry->Cost;
7871 }
7872
7873 if (Kind == TTI::SK_Splice && isa<ScalableVectorType>(SrcTy))
7874 return getSpliceCost(SrcTy, Index, CostKind);
7875
7876 // Inserting a subvector can often be done with either a D, S or H register
7877 // move, so long as the inserted vector is "aligned".
7878 if (Kind == TTI::SK_InsertSubvector && LT.second.isFixedLengthVector() &&
7879 LT.second.getSizeInBits() <= 128 && SubTp) {
7880 std::pair<InstructionCost, MVT> SubLT = getTypeLegalizationCost(SubTp);
7881 if (SubLT.second.isVector()) {
7882 int NumElts = LT.second.getVectorNumElements();
7883 int NumSubElts = SubLT.second.getVectorNumElements();
7884 if ((Index % NumSubElts) == 0 && (NumElts % NumSubElts) == 0)
7885 return SubLT.first;
7886 }
7887 }
7888
7889 // A two-source shuffle narrower than its legal type costs the same as that
7890 // shuffle of the legal type.
7891 auto *SrcVTy = dyn_cast<FixedVectorType>(SrcTy);
7892 if (Kind == TTI::SK_PermuteTwoSrc && !Mask.empty() && SrcVTy &&
7893 LT.first == 1 && LT.second.isFixedLengthVector() &&
7894 LT.second.getScalarSizeInBits() == SrcTy->getScalarSizeInBits()) {
7895 unsigned NumSrcElts = SrcVTy->getNumElements();
7896 unsigned NumLTElts = LT.second.getVectorNumElements();
7897 // Widen only if the result fits in the legal type and either the sources
7898 // or the result is narrower than it. The widened shuffle has the legal
7899 // width in both so the recursive call does not widen it again.
7900 if (Mask.size() <= NumLTElts &&
7901 (NumSrcElts < NumLTElts || Mask.size() < NumLTElts)) {
7902 SmallVector<int, 16> WideMask(NumLTElts, PoisonMaskElem);
7903 for (auto [I, M] : enumerate(Mask)) {
7904 if (M == PoisonMaskElem)
7905 continue;
7906 WideMask[I] = (M < (int)NumSrcElts) ? M : (M - NumSrcElts + NumLTElts);
7907 }
7908 auto *WideTy = FixedVectorType::get(SrcTy->getScalarType(), NumLTElts);
7909 return getShuffleCost(Kind, WideTy, WideTy, CostKind, WideMask, Index,
7910 SubTp, Args, CtxI);
7911 }
7912 }
7913
7914 // Restore optimal kind.
7915 if (IsExtractSubvector)
7917 return BaseT::getShuffleCost(Kind, DstTy, SrcTy, CostKind, Mask, Index, SubTp,
7918 Args, CtxI);
7919}
7920
7923 const DominatorTree &DT) {
7924 const auto &Strides = SymbolicStrideMap();
7925 for (BasicBlock *BB : TheLoop->blocks()) {
7926 // Scan the instructions in the block and look for addresses that are
7927 // consecutive and decreasing.
7928 for (Instruction &I : *BB) {
7929 if (isa<LoadInst>(&I) || isa<StoreInst>(&I)) {
7931 Type *AccessTy = getLoadStoreType(&I);
7932 // Analyze assuming predicates will be added, but discard them; this
7933 // query only guides tail-folding and must not add runtime checks to the
7934 // loop.
7936 if (getPtrStride(*PSE, AccessTy, Ptr, TheLoop, DT, Strides,
7937 /*ShouldCheckWrap=*/false, &Predicates)
7938 .value_or(0) < 0)
7939 return true;
7940 }
7941 }
7942 }
7943 return false;
7944}
7945
7947 return valueOr(ST->getCLOpts().sve_prefer_fixed_over_scalable_if_equal,
7948 ST->useFixedOverScalableIfEqualCost());
7949}
7950
7952 return ST->getEpilogueVectorizationMinVF();
7953}
7954
7956 TailFoldingOpts DefaultOpts = ST->getSVETailFoldingDefaultOpts();
7957 if (!ST->hasSVE() || TailFoldingOptionLoc.isDisabled(DefaultOpts))
7958 return false;
7959
7960 // We don't currently support vectorisation with interleaving for SVE - with
7961 // such loops we're better off not using tail-folding. This gives us a chance
7962 // to fall back on fixed-width vectorisation using NEON's ld2/st2/etc.
7963 if (TFI->IAI->hasGroups())
7964 return false;
7965
7967 if (TFI->LVL->getReductionVars().size())
7968 Required |= TailFoldingOpts::Reductions;
7969 if (TFI->LVL->getFixedOrderRecurrences().size())
7970 Required |= TailFoldingOpts::Recurrences;
7971
7972 // We call this to discover whether any load/store pointers in the loop have
7973 // negative strides. This will require extra work to reverse the loop
7974 // predicate, which may be expensive.
7977 *TFI->LVL->getDominatorTree()))
7978 Required |= TailFoldingOpts::Reverse;
7979 if (Required == TailFoldingOpts::Disabled)
7980 Required |= TailFoldingOpts::Simple;
7981
7982 if (!TailFoldingOptionLoc.satisfies(DefaultOpts, Required))
7983 return false;
7984
7985 // Don't tail-fold for tight loops where we would be better off interleaving
7986 // with an unpredicated loop.
7987 unsigned NumInsns = 0;
7988 for (BasicBlock *BB : TFI->LVL->getLoop()->blocks()) {
7989 NumInsns += BB->size();
7990 }
7991
7992 // We expect 4 of these to be a IV PHI, IV add, IV compare and branch.
7993 return NumInsns >= ST->getCLOpts().sve_tail_folding_insn_threshold;
7994}
7995
7998 StackOffset BaseOffset, bool HasBaseReg,
7999 int64_t Scale, unsigned AddrSpace) const {
8000 // Scaling factors are not free at all.
8001 // Operands | Rt Latency
8002 // -------------------------------------------
8003 // Rt, [Xn, Xm] | 4
8004 // -------------------------------------------
8005 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8006 // Rt, [Xn, Wm, <extend> #imm] |
8008 AM.BaseGV = BaseGV;
8009 AM.BaseOffs = BaseOffset.getFixed();
8010 AM.HasBaseReg = HasBaseReg;
8011 AM.Scale = Scale;
8012 AM.ScalableOffset = BaseOffset.getScalable();
8013 if (getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace))
8014 // Scale represents reg2 * scale, thus account for 1 if
8015 // it is not equal to 0 or 1.
8016 return AM.Scale != 0 && AM.Scale != 1;
8018}
8019
8021 const Instruction *I) const {
8022 if (ST->getCLOpts().enable_aarch64_or_like_select) {
8023 // For the binary operators (e.g. or) we need to be more careful than
8024 // selects, here we only transform them if they are already at a natural
8025 // break point in the code - the end of a block with an unconditional
8026 // terminator.
8027 if (I->getOpcode() == Instruction::Or &&
8028 isa<UncondBrInst>(I->getNextNode()))
8029 return true;
8030
8031 if (I->getOpcode() == Instruction::Add ||
8032 I->getOpcode() == Instruction::Sub)
8033 return true;
8034 }
8036}
8037
8040 const TargetTransformInfo::LSRCost &C2) const {
8041 // AArch64 specific here is adding the number of instructions to the
8042 // comparison (though not as the first consideration, as some targets do),
8043 // preferring lower number of pre/post-index if numregs and insns are equal,
8044 // as typically pre/post-index instructions use extra processor resources,
8045 // along with changing the priority of the base additions.
8046 // TODO: Maybe a more nuanced tradeoff between instruction count
8047 // and number of registers? To be investigated at a later date.
8048 if (ST->getCLOpts().enable_aarch64_lsr_cost_opt)
8049 return std::tie(C1.NumRegs, C1.Insns, C1.NumPrePostIndex, C1.NumBaseAdds,
8050 C1.AddRecCost, C1.NumIVMuls, C1.ScaleCost, C1.ImmCost,
8051 C1.SetupCost) <
8052 std::tie(C2.NumRegs, C2.Insns, C2.NumPrePostIndex, C2.NumBaseAdds,
8053 C2.AddRecCost, C2.NumIVMuls, C2.ScaleCost, C2.ImmCost,
8054 C2.SetupCost);
8055
8057}
8058
8059static bool isSplatShuffle(Value *V) {
8060 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V))
8061 return all_equal(Shuf->getShuffleMask());
8062 return false;
8063}
8064
8065/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8066/// or upper half of the vector elements.
8067static bool areExtractShuffleVectors(Value *Op1, Value *Op2,
8068 bool AllowSplat = false) {
8069 // Scalable types can't be extract shuffle vectors.
8070 if (Op1->getType()->isScalableTy() || Op2->getType()->isScalableTy())
8071 return false;
8072
8073 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8074 auto *FullTy = FullV->getType();
8075 auto *HalfTy = HalfV->getType();
8076 return FullTy->getPrimitiveSizeInBits().getFixedValue() ==
8077 2 * HalfTy->getPrimitiveSizeInBits().getFixedValue();
8078 };
8079
8080 auto extractHalf = [](Value *FullV, Value *HalfV) {
8081 auto *FullVT = cast<FixedVectorType>(FullV->getType());
8082 auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
8083 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8084 };
8085
8086 ArrayRef<int> M1, M2;
8087 Value *S1Op1 = nullptr, *S2Op1 = nullptr;
8088 if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
8089 !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
8090 return false;
8091
8092 // If we allow splats, set S1Op1/S2Op1 to nullptr for the relevant arg so that
8093 // it is not checked as an extract below.
8094 if (AllowSplat && isSplatShuffle(Op1))
8095 S1Op1 = nullptr;
8096 if (AllowSplat && isSplatShuffle(Op2))
8097 S2Op1 = nullptr;
8098
8099 // Check that the operands are half as wide as the result and we extract
8100 // half of the elements of the input vectors.
8101 if ((S1Op1 && (!areTypesHalfed(S1Op1, Op1) || !extractHalf(S1Op1, Op1))) ||
8102 (S2Op1 && (!areTypesHalfed(S2Op1, Op2) || !extractHalf(S2Op1, Op2))))
8103 return false;
8104
8105 // Check the mask extracts either the lower or upper half of vector
8106 // elements.
8107 int M1Start = 0;
8108 int M2Start = 0;
8109 int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
8110 if ((S1Op1 &&
8111 !ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start)) ||
8112 (S2Op1 &&
8113 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start)))
8114 return false;
8115
8116 if ((M1Start != 0 && M1Start != (NumElements / 2)) ||
8117 (M2Start != 0 && M2Start != (NumElements / 2)))
8118 return false;
8119 if (S1Op1 && S2Op1 && M1Start != M2Start)
8120 return false;
8121
8122 return true;
8123}
8124
8125/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8126/// of the vector elements.
8127static bool areExtractExts(Value *Ext1, Value *Ext2) {
8128 auto areExtDoubled = [](Instruction *Ext) {
8129 return Ext->getType()->getScalarSizeInBits() ==
8130 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8131 };
8132
8133 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8134 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8135 !areExtDoubled(cast<Instruction>(Ext1)) ||
8136 !areExtDoubled(cast<Instruction>(Ext2)))
8137 return false;
8138
8139 return true;
8140}
8141
8142/// Check if Op could be used with vmull_high_p64 intrinsic.
8144 Value *VectorOperand = nullptr;
8145 ConstantInt *ElementIndex = nullptr;
8146 return match(Op, m_ExtractElt(m_Value(VectorOperand),
8147 m_ConstantInt(ElementIndex))) &&
8148 ElementIndex->getValue() == 1 &&
8149 isa<FixedVectorType>(VectorOperand->getType()) &&
8150 cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
8151}
8152
8153/// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
8154static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
8156}
8157
8159 // Restrict ourselves to the form CodeGenPrepare typically constructs.
8160 auto *GEP = dyn_cast<GetElementPtrInst>(Ptrs);
8161 if (!GEP || GEP->getNumOperands() != 2)
8162 return false;
8163
8164 Value *Base = GEP->getOperand(0);
8165 Value *Offsets = GEP->getOperand(1);
8166
8167 // We only care about scalar_base+vector_offsets.
8168 if (Base->getType()->isVectorTy() || !Offsets->getType()->isVectorTy())
8169 return false;
8170
8171 // Sink extends that would allow us to use 32-bit offset vectors.
8172 if (isa<SExtInst>(Offsets) || isa<ZExtInst>(Offsets)) {
8173 auto *OffsetsInst = cast<Instruction>(Offsets);
8174 if (OffsetsInst->getType()->getScalarSizeInBits() > 32 &&
8175 OffsetsInst->getOperand(0)->getType()->getScalarSizeInBits() <= 32)
8176 Ops.push_back(&GEP->getOperandUse(1));
8177 }
8178
8179 // Sink the GEP.
8180 return true;
8181}
8182
8183/// We want to sink following cases:
8184/// (add|sub|gep) A, ((mul|shl) vscale, imm); (add|sub|gep) A, vscale;
8185/// (add|sub|gep) A, ((mul|shl) zext(vscale), imm);
8187 if (match(Op, m_VScale()))
8188 return true;
8189 if (match(Op, m_Shl(m_VScale(), m_ConstantInt())) ||
8191 Ops.push_back(&cast<Instruction>(Op)->getOperandUse(0));
8192 return true;
8193 }
8194 if (match(Op, m_Shl(m_ZExt(m_VScale()), m_ConstantInt())) ||
8196 Value *ZExtOp = cast<Instruction>(Op)->getOperand(0);
8197 Ops.push_back(&cast<Instruction>(ZExtOp)->getOperandUse(0));
8198 Ops.push_back(&cast<Instruction>(Op)->getOperandUse(0));
8199 return true;
8200 }
8201 return false;
8202}
8203
8204static bool isFNeg(Value *Op) {
8205 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
8206 return match(Op, m_FNegOrFSubNegZero(m_Value()));
8207}
8208
8209/// Check if sinking \p I's operands to I's basic block is profitable, because
8210/// the operands can be folded into a target instruction, e.g.
8211/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8214 const LoopInfo *LI) const {
8216 switch (II->getIntrinsicID()) {
8217 case Intrinsic::aarch64_neon_smull:
8218 case Intrinsic::aarch64_neon_umull:
8219 if (areExtractShuffleVectors(II->getOperand(0), II->getOperand(1),
8220 /*AllowSplat=*/true)) {
8221 Ops.push_back(&II->getOperandUse(0));
8222 Ops.push_back(&II->getOperandUse(1));
8223 return true;
8224 }
8225 [[fallthrough]];
8226
8227 case Intrinsic::fma:
8228 case Intrinsic::fmuladd:
8229 if (isa<VectorType>(I->getType()) &&
8230 cast<VectorType>(I->getType())->getElementType()->isHalfTy() &&
8231 !ST->hasFullFP16())
8232 return false;
8233
8234 if (isFNeg(II->getOperand(0)))
8235 Ops.push_back(&II->getOperandUse(0));
8236 if (isFNeg(II->getOperand(1)))
8237 Ops.push_back(&II->getOperandUse(1));
8238
8239 [[fallthrough]];
8240 case Intrinsic::aarch64_neon_sqdmull:
8241 case Intrinsic::aarch64_neon_sqdmulh:
8242 case Intrinsic::aarch64_neon_sqrdmulh:
8243 // Sink splats for index lane variants
8244 if (isSplatShuffle(II->getOperand(0)))
8245 Ops.push_back(&II->getOperandUse(0));
8246 if (isSplatShuffle(II->getOperand(1)))
8247 Ops.push_back(&II->getOperandUse(1));
8248 return !Ops.empty();
8249 case Intrinsic::aarch64_neon_fmlal:
8250 case Intrinsic::aarch64_neon_fmlal2:
8251 case Intrinsic::aarch64_neon_fmlsl:
8252 case Intrinsic::aarch64_neon_fmlsl2:
8253 // Sink splats for index lane variants
8254 if (isSplatShuffle(II->getOperand(1)))
8255 Ops.push_back(&II->getOperandUse(1));
8256 if (isSplatShuffle(II->getOperand(2)))
8257 Ops.push_back(&II->getOperandUse(2));
8258 return !Ops.empty();
8259 case Intrinsic::aarch64_sve_ptest_first:
8260 case Intrinsic::aarch64_sve_ptest_last:
8261 if (auto *IIOp = dyn_cast<IntrinsicInst>(II->getOperand(0)))
8262 if (IIOp->getIntrinsicID() == Intrinsic::aarch64_sve_ptrue)
8263 Ops.push_back(&II->getOperandUse(0));
8264 return !Ops.empty();
8265 case Intrinsic::aarch64_sme_write_horiz:
8266 case Intrinsic::aarch64_sme_write_vert:
8267 case Intrinsic::aarch64_sme_writeq_horiz:
8268 case Intrinsic::aarch64_sme_writeq_vert: {
8269 auto *Idx = dyn_cast<Instruction>(II->getOperand(1));
8270 if (!Idx || Idx->getOpcode() != Instruction::Add)
8271 return false;
8272 Ops.push_back(&II->getOperandUse(1));
8273 return true;
8274 }
8275 case Intrinsic::aarch64_sme_read_horiz:
8276 case Intrinsic::aarch64_sme_read_vert:
8277 case Intrinsic::aarch64_sme_readq_horiz:
8278 case Intrinsic::aarch64_sme_readq_vert:
8279 case Intrinsic::aarch64_sme_ld1b_vert:
8280 case Intrinsic::aarch64_sme_ld1h_vert:
8281 case Intrinsic::aarch64_sme_ld1w_vert:
8282 case Intrinsic::aarch64_sme_ld1d_vert:
8283 case Intrinsic::aarch64_sme_ld1q_vert:
8284 case Intrinsic::aarch64_sme_st1b_vert:
8285 case Intrinsic::aarch64_sme_st1h_vert:
8286 case Intrinsic::aarch64_sme_st1w_vert:
8287 case Intrinsic::aarch64_sme_st1d_vert:
8288 case Intrinsic::aarch64_sme_st1q_vert:
8289 case Intrinsic::aarch64_sme_ld1b_horiz:
8290 case Intrinsic::aarch64_sme_ld1h_horiz:
8291 case Intrinsic::aarch64_sme_ld1w_horiz:
8292 case Intrinsic::aarch64_sme_ld1d_horiz:
8293 case Intrinsic::aarch64_sme_ld1q_horiz:
8294 case Intrinsic::aarch64_sme_st1b_horiz:
8295 case Intrinsic::aarch64_sme_st1h_horiz:
8296 case Intrinsic::aarch64_sme_st1w_horiz:
8297 case Intrinsic::aarch64_sme_st1d_horiz:
8298 case Intrinsic::aarch64_sme_st1q_horiz: {
8299 auto *Idx = dyn_cast<Instruction>(II->getOperand(3));
8300 if (!Idx || Idx->getOpcode() != Instruction::Add)
8301 return false;
8302 Ops.push_back(&II->getOperandUse(3));
8303 return true;
8304 }
8305 case Intrinsic::aarch64_neon_pmull:
8306 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8307 return false;
8308 Ops.push_back(&II->getOperandUse(0));
8309 Ops.push_back(&II->getOperandUse(1));
8310 return true;
8311 case Intrinsic::aarch64_neon_pmull64:
8312 if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
8313 II->getArgOperand(1)))
8314 return false;
8315 Ops.push_back(&II->getArgOperandUse(0));
8316 Ops.push_back(&II->getArgOperandUse(1));
8317 return true;
8318 case Intrinsic::masked_gather:
8319 if (!shouldSinkVectorOfPtrs(II->getArgOperand(0), Ops))
8320 return false;
8321 Ops.push_back(&II->getArgOperandUse(0));
8322 return true;
8323 case Intrinsic::masked_scatter:
8324 if (!shouldSinkVectorOfPtrs(II->getArgOperand(1), Ops))
8325 return false;
8326 Ops.push_back(&II->getArgOperandUse(1));
8327 return true;
8328 default:
8329 return false;
8330 }
8331 }
8332
8333 auto ShouldSinkCondition = [](Value *Cond,
8334 SmallVectorImpl<Use *> &Ops) -> bool {
8336 return false;
8338 if (II->getIntrinsicID() != Intrinsic::vector_reduce_or ||
8339 !isa<ScalableVectorType>(II->getOperand(0)->getType()))
8340 return false;
8341 if (isa<CmpInst>(II->getOperand(0)))
8342 Ops.push_back(&II->getOperandUse(0));
8343 return true;
8344 };
8345
8346 switch (I->getOpcode()) {
8347 case Instruction::Store: {
8348 auto *SI = cast<StoreInst>(I);
8349 auto *II = dyn_cast<IntrinsicInst>(SI->getValueOperand());
8350 if (!SI->isSimple() || !II)
8351 break;
8352
8353 if (!LI ||
8354 LI->getLoopFor(SI->getParent()) != LI->getLoopFor(II->getParent()))
8355 break;
8356
8357 unsigned Factor = getInterleaveIntrinsicFactor(II->getIntrinsicID());
8358 if (Factor) {
8359 Ops.push_back(&SI->getOperandUse(0));
8360 return true;
8361 }
8362 break;
8363 }
8364 case Instruction::GetElementPtr:
8365 case Instruction::Add:
8366 case Instruction::Sub:
8367 // Sink vscales closer to uses for better isel
8368 for (unsigned Op = 0; Op < I->getNumOperands(); ++Op) {
8369 if (shouldSinkVScale(I->getOperand(Op), Ops)) {
8370 Ops.push_back(&I->getOperandUse(Op));
8371 return true;
8372 }
8373 }
8374 break;
8375 case Instruction::Select: {
8376 if (!ShouldSinkCondition(I->getOperand(0), Ops))
8377 return false;
8378
8379 Ops.push_back(&I->getOperandUse(0));
8380 return true;
8381 }
8382 case Instruction::UncondBr:
8383 return false;
8384 case Instruction::CondBr: {
8385 if (!ShouldSinkCondition(cast<CondBrInst>(I)->getCondition(), Ops))
8386 return false;
8387
8388 Ops.push_back(&I->getOperandUse(0));
8389 return true;
8390 }
8391 case Instruction::FMul:
8392 // fmul with contract flag can be combined with fadd into fma.
8393 // Sinking fneg into this block enables fmls pattern.
8394 if (cast<FPMathOperator>(I)->hasAllowContract()) {
8395 if (isFNeg(I->getOperand(0)))
8396 Ops.push_back(&I->getOperandUse(0));
8397 if (isFNeg(I->getOperand(1)))
8398 Ops.push_back(&I->getOperandUse(1));
8399 }
8400 break;
8401
8402 // Type | BIC | ORN | EON
8403 // ----------------+-----------+-----------+-----------
8404 // scalar | Base | Base | Base
8405 // scalar w/shift | - | - | -
8406 // fixed vector | NEON/Base | NEON/Base | BSL2N/Base
8407 // scalable vector | SVE | - | BSL2N
8408 case Instruction::Xor:
8409 // EON only for scalars (possibly expanded fixed vectors)
8410 // and vectors using the SVE2/SME BSL2N instruction.
8411 if (I->getType()->isVectorTy() && ST->isNeonAvailable()) {
8412 bool HasBSL2N =
8413 ST->isSVEorStreamingSVEAvailable() && (ST->hasSVE2() || ST->hasSME());
8414 if (!HasBSL2N)
8415 break;
8416 }
8417 [[fallthrough]];
8418 case Instruction::And:
8419 case Instruction::Or:
8420 // Even though we could use the SVE2/SME BSL2N instruction,
8421 // it might pessimize with an extra MOV depending on register allocation.
8422 if (I->getOpcode() == Instruction::Or &&
8423 isa<ScalableVectorType>(I->getType()))
8424 break;
8425 // Shift can be fold into scalar AND/ORR/EOR,
8426 // but not the non-negated operand of BIC/ORN/EON.
8427 if (!(I->getType()->isVectorTy() && ST->hasNEON()) &&
8429 break;
8430 for (auto &Op : I->operands()) {
8431 // (and/or/xor X, (not Y)) -> (bic/orn/eon X, Y)
8432 if (match(Op.get(), m_Not(m_Value()))) {
8433 Ops.push_back(&Op);
8434 return true;
8435 }
8436 // (and/or/xor X, (splat (not Y))) -> (bic/orn/eon X, (splat Y))
8437 if (match(Op.get(),
8439 m_Value(), m_ZeroMask()))) {
8440 Use &InsertElt = cast<Instruction>(Op)->getOperandUse(0);
8441 Use &Not = cast<Instruction>(InsertElt)->getOperandUse(1);
8442 Ops.push_back(&Not);
8443 Ops.push_back(&InsertElt);
8444 Ops.push_back(&Op);
8445 return true;
8446 }
8447 }
8448 break;
8449 default:
8450 break;
8451 }
8452
8453 if (!I->getType()->isVectorTy())
8454 return !Ops.empty();
8455
8456 switch (I->getOpcode()) {
8457 case Instruction::Sub:
8458 case Instruction::Add: {
8459 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8460 return false;
8461
8462 // If the exts' operands extract either the lower or upper elements, we
8463 // can sink them too.
8464 auto Ext1 = cast<Instruction>(I->getOperand(0));
8465 auto Ext2 = cast<Instruction>(I->getOperand(1));
8466 if (areExtractShuffleVectors(Ext1->getOperand(0), Ext2->getOperand(0))) {
8467 Ops.push_back(&Ext1->getOperandUse(0));
8468 Ops.push_back(&Ext2->getOperandUse(0));
8469 }
8470
8471 Ops.push_back(&I->getOperandUse(0));
8472 Ops.push_back(&I->getOperandUse(1));
8473
8474 return true;
8475 }
8476 case Instruction::Or: {
8477 // Pattern: Or(And(MaskValue, A), And(Not(MaskValue), B)) ->
8478 // bitselect(MaskValue, A, B) where Not(MaskValue) = Xor(MaskValue, -1)
8479 if (ST->hasNEON()) {
8480 // MainAnd refers to And instruction that has 'Not' as one of its operands
8481 Instruction *MainAnd, *OtherAnd;
8482 Value *A, *B;
8483 if (matchBSL(I, MainAnd, OtherAnd, A, B)) {
8484 Ops.push_back(
8485 &MainAnd->getOperandUse(MainAnd->getOperand(0) == A ? 1 : 0));
8486 Ops.push_back(&I->getOperandUse(0));
8487 Ops.push_back(&I->getOperandUse(1));
8488
8489 return true;
8490 }
8491 }
8492
8493 return false;
8494 }
8495 case Instruction::Mul: {
8496 auto ShouldSinkSplatForIndexedVariant = [](Value *V) {
8497 auto *Ty = cast<VectorType>(V->getType());
8498 // For SVE the lane-indexing is within 128-bits, so we can't fold splats.
8499 if (Ty->isScalableTy())
8500 return false;
8501
8502 // Indexed variants of Mul exist for i16 and i32 element types only.
8503 return Ty->getScalarSizeInBits() == 16 || Ty->getScalarSizeInBits() == 32;
8504 };
8505
8506 int NumZExts = 0, NumSExts = 0;
8507 for (auto &Op : I->operands()) {
8508 // Make sure we are not already sinking this operand
8509 if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
8510 continue;
8511
8512 if (match(&Op, m_ZExtOrSExt(m_Value()))) {
8513 auto *Ext = cast<Instruction>(Op);
8514 auto *ExtOp = Ext->getOperand(0);
8515 if (isSplatShuffle(ExtOp) && ShouldSinkSplatForIndexedVariant(ExtOp))
8516 Ops.push_back(&Ext->getOperandUse(0));
8517 Ops.push_back(&Op);
8518
8519 if (isa<SExtInst>(Ext)) {
8520 NumSExts++;
8521 } else {
8522 NumZExts++;
8523 // A zext(a) is also a sext(zext(a)), if we take more than 2 steps.
8524 if (Ext->getOperand(0)->getType()->getScalarSizeInBits() * 2 <
8525 I->getType()->getScalarSizeInBits())
8526 NumSExts++;
8527 }
8528
8529 continue;
8530 }
8531
8533 if (!Shuffle)
8534 continue;
8535
8536 // If the Shuffle is a splat and the operand is a zext/sext, sinking the
8537 // operand and the s/zext can help create indexed s/umull. This is
8538 // especially useful to prevent i64 mul being scalarized.
8539 if (isSplatShuffle(Shuffle) &&
8540 match(Shuffle->getOperand(0), m_ZExtOrSExt(m_Value()))) {
8541 Ops.push_back(&Shuffle->getOperandUse(0));
8542 Ops.push_back(&Op);
8543 if (match(Shuffle->getOperand(0), m_SExt(m_Value())))
8544 NumSExts++;
8545 else
8546 NumZExts++;
8547 continue;
8548 }
8549
8550 Value *ShuffleOperand = Shuffle->getOperand(0);
8551 InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand);
8552 if (!Insert)
8553 continue;
8554
8555 Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1));
8556 if (!OperandInstr)
8557 continue;
8558
8559 ConstantInt *ElementConstant =
8560 dyn_cast<ConstantInt>(Insert->getOperand(2));
8561 // Check that the insertelement is inserting into element 0
8562 if (!ElementConstant || !ElementConstant->isZero())
8563 continue;
8564
8565 unsigned Opcode = OperandInstr->getOpcode();
8566 if (Opcode == Instruction::SExt)
8567 NumSExts++;
8568 else if (Opcode == Instruction::ZExt)
8569 NumZExts++;
8570 else {
8571 // If we find that the top bits are known 0, then we can sink and allow
8572 // the backend to generate a umull.
8573 unsigned Bitwidth = I->getType()->getScalarSizeInBits();
8574 APInt UpperMask = APInt::getHighBitsSet(Bitwidth, Bitwidth / 2);
8575 if (!MaskedValueIsZero(OperandInstr, UpperMask, DL))
8576 continue;
8577 NumZExts++;
8578 }
8579
8580 // And(Load) is excluded to prevent CGP getting stuck in a loop of sinking
8581 // the And, just to hoist it again back to the load.
8582 if (!match(OperandInstr, m_And(m_Load(m_Value()), m_Value())))
8583 Ops.push_back(&Insert->getOperandUse(1));
8584 Ops.push_back(&Shuffle->getOperandUse(0));
8585 Ops.push_back(&Op);
8586 }
8587
8588 // It is profitable to sink if we found two of the same type of extends.
8589 if (!Ops.empty() && (NumSExts == 2 || NumZExts == 2))
8590 return true;
8591
8592 // Otherwise, see if we should sink splats for indexed variants.
8593 if (!ShouldSinkSplatForIndexedVariant(I))
8594 return false;
8595
8596 Ops.clear();
8597 if (isSplatShuffle(I->getOperand(0)))
8598 Ops.push_back(&I->getOperandUse(0));
8599 if (isSplatShuffle(I->getOperand(1)))
8600 Ops.push_back(&I->getOperandUse(1));
8601
8602 return !Ops.empty();
8603 }
8604 case Instruction::FMul: {
8605 // For SVE the lane-indexing is within 128-bits, so we can't fold splats.
8606 if (I->getType()->isScalableTy())
8607 return !Ops.empty();
8608
8609 if (cast<VectorType>(I->getType())->getElementType()->isHalfTy() &&
8610 !ST->hasFullFP16())
8611 return !Ops.empty();
8612
8613 // Sink splats for index lane variants
8614 if (isSplatShuffle(I->getOperand(0)))
8615 Ops.push_back(&I->getOperandUse(0));
8616 if (isSplatShuffle(I->getOperand(1)))
8617 Ops.push_back(&I->getOperandUse(1));
8618 return !Ops.empty();
8619 }
8620 default:
8621 return false;
8622 }
8623 return false;
8624}
8625
8627 Align Alignment) const {
8628 if (!(ST->isSVEAvailable() ||
8629 (ST->isSVEorStreamingSVEAvailable() && ST->hasSME2p2())))
8630 return false;
8631
8632 if (isa<FixedVectorType>(DataType) &&
8633 DataType->getPrimitiveSizeInBits().getFixedValue() < 128)
8634 return false;
8635
8636 if (!isa<VectorType>(DataType))
8637 return isElementTypeLegalForScalableVector(DataType);
8638
8639 auto LT = getTypeLegalizationCost(DataType);
8640 if (!LT.first.isValid() || !LT.second.isVector())
8641 return false;
8642
8643 // Use the i32 or i64 compact instructions for f16/bf16 unpacked types.
8644 LLVMContext &Ctx = DataType->getContext();
8645 switch (LT.second.SimpleTy) {
8646 case MVT::nxv2f16:
8647 case MVT::nxv2bf16:
8649 case MVT::nxv4f16:
8650 case MVT::nxv4bf16:
8652 default:
8653 break;
8654 }
8655
8657 EVT(LT.second.getScalarType()).getTypeForEVT(Ctx));
8658}
const TargetLowering & TLI
SDValue Pred
static bool isAllActivePredicate(const SelectionDAG &DAG, SDValue N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static std::optional< Instruction * > instCombinePTrue(InstCombiner &IC, IntrinsicInst &II)
TailFoldingOption TailFoldingOptionLoc
static std::optional< Instruction * > instCombineSVEVectorFAdd(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEVectorFuseMulAddSub(InstCombiner &IC, IntrinsicInst &II, bool MergeIntoAddendOp)
static std::optional< Instruction * > instCombineZExtSVECmpNE(InstCombiner &IC, IntrinsicInst &II)
static void getFalkorUnrollingPreferences(Loop *L, ScalarEvolution &SE, TargetTransformInfo::UnrollingPreferences &UP)
bool SimplifyValuePattern(SmallVector< Value * > &Vec, bool AllowPoison)
static std::optional< Instruction * > instCombineSVESel(InstCombiner &IC, IntrinsicInst &II)
static bool shouldSinkVScale(Value *Op, SmallVectorImpl< Use * > &Ops)
We want to sink following cases: (add|sub|gep) A, ((mul|shl) vscale, imm); (add|sub|gep) A,...
static std::optional< Instruction * > tryCombineFromSVBoolBinOp(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEUnpack(InstCombiner &IC, IntrinsicInst &II)
static void getAppleRuntimeUnrollPreferences(Loop *L, ScalarEvolution &SE, TargetTransformInfo::UnrollingPreferences &UP, const AArch64TTIImpl &TTI)
For Apple CPUs, we want to runtime-unroll loops to make better use if the OOO engine's wide instructi...
static std::optional< Instruction * > instCombineWhilelo(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEVectorFAddU(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEPairwiseAddLong(InstCombiner &IC, IntrinsicInst &II)
static bool areExtractExts(Value *Ext1, Value *Ext2)
Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth of the vector elements.
static std::optional< Instruction * > instCombineSVEUMin(InstCombiner &IC, IntrinsicInst &II)
static bool shouldSinkVectorOfPtrs(Value *Ptrs, SmallVectorImpl< Use * > &Ops)
static bool shouldUnrollMultiExitLoop(Loop *L, ScalarEvolution &SE, const AArch64TTIImpl &TTI)
static std::optional< Instruction * > simplifySVEIntrinsicBinOp(InstCombiner &IC, IntrinsicInst &II, const SVEIntrinsicInfo &IInfo)
static std::optional< Instruction * > instCombineSVEVectorSub(InstCombiner &IC, IntrinsicInst &II)
static bool isLoopSizeWithinBudget(Loop *L, const AArch64TTIImpl &TTI, InstructionCost Budget, unsigned *FinalSize)
static std::optional< Instruction * > instCombineLD1GatherIndex(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEVectorFSub(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > processPhiNode(InstCombiner &IC, IntrinsicInst &II)
The function will remove redundant reinterprets casting in the presence of the control flow.
static std::optional< Instruction * > instCombineSVEInsr(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSMECntsd(InstCombiner &IC, IntrinsicInst &II, const AArch64Subtarget *ST)
static void extractAttrFeatures(const Function &F, const AArch64TTIImpl *TTI, SmallVectorImpl< StringRef > &Features)
static std::optional< Instruction * > instCombineST1ScatterIndex(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVESDIV(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEST1(InstCombiner &IC, IntrinsicInst &II, const DataLayout &DL)
static Value * stripInactiveLanes(Value *V, const Value *Pg)
static bool isUnpackedVectorVT(EVT VecVT)
static std::optional< Instruction * > instCombineSVEDupX(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVECmpNE(InstCombiner &IC, IntrinsicInst &II)
static SVEIntrinsicInfo constructSVEIntrinsicInfo(IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEVectorFSubU(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineRDFFR(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineMaxMinNM(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > simplifySVEIntrinsicCompare(InstCombiner &IC, IntrinsicInst &II, const SVEIntrinsicInfo &IInfo)
static InstructionCost getLatencyFromSchedModel(const AArch64Subtarget *ST, unsigned Inst, unsigned NumInst, InstructionCost DefaultLatency)
static std::optional< Instruction * > instCombineSVECondLast(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEPTest(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEZip(InstCombiner &IC, IntrinsicInst &II)
static bool matchBSL(const Instruction *I, Instruction *&MainAnd, Instruction *&OtherAnd, Value *&A, Value *&B)
Match Or(And(MASK, A), And(Not(MASK), B)), which ISel selects as BSL/BIT/BIF.
static std::optional< Instruction * > instCombineSVEDup(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineConvertFromSVBool(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEUzp1(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEVectorBinOp(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVETBL(InstCombiner &IC, IntrinsicInst &II)
static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2)
Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
static bool isFNeg(Value *Op)
static Instruction::BinaryOps intrinsicIDToBinOpCode(unsigned Intrinsic)
static bool containsDecreasingPointers(Loop *TheLoop, PredicatedScalarEvolution *PSE, const DominatorTree &DT)
static std::optional< Instruction * > instCombineSVEAnd(InstCombiner &IC, IntrinsicInst &II)
static bool isSplatShuffle(Value *V)
static std::optional< Instruction * > instCombineSVELD1(InstCombiner &IC, IntrinsicInst &II, const DataLayout &DL)
static std::optional< Instruction * > instCombineSVESrshl(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineXorSVECmpCC(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > simplifySVEIntrinsic(InstCombiner &IC, IntrinsicInst &II, const SVEIntrinsicInfo &IInfo)
static unsigned getSVEGatherScatterOverhead(unsigned Opcode, const AArch64Subtarget *ST)
static std::optional< Instruction * > instCombineSVEVectorMlaU(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineDMB(InstCombiner &IC, IntrinsicInst &II, unsigned LookaheadThreshold)
static bool isOperandOfVmullHighP64(Value *Op)
Check if Op could be used with vmull_high_p64 intrinsic.
static std::optional< Instruction * > instCombineInStreamingMode(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVELast(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEOrr(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVECntElts(InstCombiner &IC, IntrinsicInst &II, unsigned NumElts)
static std::optional< Instruction * > instCombineSVEUxt(InstCombiner &IC, IntrinsicInst &II, unsigned NumBits)
static cl::opt< TailFoldingOption, true, cl::parser< std::string > > SVETailFolding("sve-tail-folding", cl::desc("Control the use of vectorisation using tail-folding for SVE where the" " option is specified in the form (Initial)[+(Flag1|Flag2|...)]:" "\ndisabled (Initial) No loop types will vectorize using " "tail-folding" "\ndefault (Initial) Uses the default tail-folding settings for " "the target CPU" "\nall (Initial) All legal loop types will vectorize using " "tail-folding" "\nsimple (Initial) Use tail-folding for simple loops (not " "reductions or recurrences)" "\nreductions Use tail-folding for loops containing reductions" "\nnoreductions Inverse of above" "\nrecurrences Use tail-folding for loops containing fixed order " "recurrences" "\nnorecurrences Inverse of above" "\nreverse Use tail-folding for loops requiring reversed " "predicates" "\nnoreverse Inverse of above"), cl::location(TailFoldingOptionLoc))
static bool areExtractShuffleVectors(Value *Op1, Value *Op2, bool AllowSplat=false)
Check if both Op1 and Op2 are shufflevector extracts of either the lower or upper half of the vector ...
static std::optional< Instruction * > instCombineSVEVectorAdd(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEDupqLane(InstCombiner &IC, IntrinsicInst &II)
This file a TargetTransformInfoImplBase conforming object specific to the AArch64 target machine.
uint64_t uint64_t
uint64_t Imm
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
static Error reportError(StringRef Message)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Cost tables and simple lookup functions.
This file defines the DenseMap class.
@ Default
static Value * getCondition(Instruction *I)
Hexagon Common GEP
const HexagonInstrInfo * TII
#define _
This file provides the interface for the instcombine pass implementation.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
This file defines the LoopVectorizationLegality class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const Function * getCalledFunction(const MachineInstr &MI)
#define T
AttributeSet CallAttrs
uint64_t IntrinsicInst * II
#define P(N)
int64_t C1
static uint64_t getBits(uint64_t Val, int Start, int End)
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI Fold Operands
static unsigned getFastMathFlags(const MachineInstr &I, const SPIRVSubtarget &ST)
#define LLVM_DEBUG(...)
Definition Debug.h:119
static unsigned getScalarSizeInBits(Type *Ty)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file describes how to lower LLVM code to machine code.
This pass exposes codegen information to IR-level passes.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
BinaryOperator * Mul
This file implements the C++20 <bit> header.
unsigned getVectorInsertExtractBaseCost() const
bool useSVEForFixedLengthVectors() const
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getCostOfKeepingLiveOverCall(ArrayRef< Type * > Tys) const override
InstructionCost getMaskedMemoryOpCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
InstructionCost getGatherScatterOpCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
bool hasPossibleIncompatibleOps(const Function *F, bool ConsiderZA, bool ConsiderZT, bool ConsiderSM) const
Returns true if the function has explicit operations that can only be lowered using incompatible inst...
bool isLegalBroadcastLoad(Type *ElementTy, ElementCount NumElements) const override
InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *SE, const SCEV *Ptr, TTI::TargetCostKind CostKind) const override
bool isExtPartOfAvgExpr(const Instruction *ExtUser, Type *Dst, Type *Src) const
InstructionCost getIntImmCost(int64_t Val) const
Calculate the cost of materializing a 64-bit value.
InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, unsigned Index) const override
std::optional< InstructionCost > getFP16BF16PromoteCost(Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info, TTI::OperandValueInfo Op2Info, bool IncludeTrunc, bool CanUseSVE, std::function< InstructionCost(Type *)> InstCost) const
FP16 and BF16 operations are lowered to fptrunc(op(fpext, fpext) if the architecture features are not...
bool prefersVectorizedAddressing() const override
bool preferFixedOverScalableIfEqualCost() const override
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const override
bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops, const LoopInfo *LI) const override
Check if sinking I's operands to I's basic block is profitable, because the operands can be folded in...
InstructionCost getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode, Type *ResTy, VectorType *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const override
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, unsigned Index, const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
bool shouldMaximizeVectorBandwidth(TargetTransformInfo::VectorKind K, Type *ElementTy) const override
InstructionCost getIntImmCostInst(unsigned Opcode, unsigned Idx, const APInt &Imm, Type *Ty, TTI::TargetCostKind CostKind, Instruction *Inst=nullptr) const override
bool isElementTypeLegalForScalableVector(Type *Ty) const override
bool hasMultiVectorLoadStore(unsigned NumVectors, TTI::MaskSource Mask, VectorType *VectorTy, bool IsStore, std::optional< Instruction::CastOps > CastHint) const override
void getPeelingPreferences(Loop *L, ScalarEvolution &SE, TTI::PeelingPreferences &PP) const override
InstructionCost getPartialReductionCost(unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType, ElementCount VF, TTI::PartialReductionExtendKind OpAExtend, TTI::PartialReductionExtendKind OpBExtend, std::optional< unsigned > BinOp, TTI::TargetCostKind CostKind, std::optional< FastMathFlags > FMF) const override
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
void getUnrollingPreferences(Loop *L, ScalarEvolution &SE, TTI::UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const override
bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const override
bool preferTailFoldingOverEpilogue(TailFoldingInfo *TFI) const override
InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) const override
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, TTI::OperandValueInfo OpInfo={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
APInt getPriorityMask(const Function &F) const override
InstructionCost getShuffleCost(TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask, int Index, VectorType *SubTp, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
bool isLSRCostLess(const TargetTransformInfo::LSRCost &C1, const TargetTransformInfo::LSRCost &C2) const override
InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
std::optional< Value * > simplifyDemandedVectorEltsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp) const override
bool useNeonVector(const Type *Ty) const
std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const override
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
InstructionCost getHistogramCost(const AArch64Subtarget *ST, const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
Gets the cost for a histogram operation, consisting of at least one set of gather + histcnt + scatter...
InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *ValTy, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
bool isLegalSpeculativeLoad(Type *DataType, unsigned AddressSpace) const override
bool isLegalMaskedExpandLoad(Type *DataTy, Align Alignment) const override
bool isElementTypeLegalForCompressStore(Type *Ty) const
InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy, unsigned Index, TTI::TargetCostKind CostKind) const override
unsigned getInlineCallPenalty(const Function *F, const CallBase &Call, unsigned DefaultCallPenalty) const override
bool areInlineCompatible(const Function *Caller, const Function *Callee) const override
The compiler must not inline when that may alter the behavior of the program.
unsigned getMaxNumElements(ElementCount VF) const
Try to return an estimate cost factor that can be used as a multiplier when scalarizing an operation ...
bool shouldTreatInstructionLikeSelect(const Instruction *I) const override
bool isMultiversionedFunction(const Function &F) const override
TypeSize getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const override
bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc, ElementCount VF) const override
TTI::MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const override
bool isLegalMaskedCompressStore(Type *DataType, Align Alignment) const override
InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty, TTI::TargetCostKind CostKind) const override
bool isLegalMaskedGatherScatter(Type *DataType) const
InstructionCost getBranchMispredictPenalty() const override
bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const override
See if I should be considered for address type promotion.
APInt getFeatureMask(const Function &F) const override
InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false) const override
TargetTransformInfo::VectorInstrContext getBuildVectorContextHint(ArrayRef< int > Mask, ArrayRef< Value * > Scalars, function_ref< bool(SmallVectorImpl< TargetTransformInfo::BuildVectorUseOp > &)> GatherUseOps) const override
bool areTypesABICompatible(const Function *Caller, const Function *Callee, ArrayRef< Type * > Types) const override
bool enableScalableVectorization() const override
InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const override
Value * getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst, Type *ExpectedType, bool CanCreate=true) const override
bool hasKnownLowerThroughputFromSchedulingModel(unsigned Opcode1, unsigned Opcode2) const
Check whether Opcode1 has less throughput according to the scheduling model than Opcode2.
unsigned getEpilogueVectorizationMinVF() const override
InstructionCost getSpliceCost(VectorType *Tp, int Index, TTI::TargetCostKind CostKind) const
InstructionCost getArithmeticReductionCostSVE(unsigned Opcode, VectorType *ValTy, TTI::TargetCostKind CostKind) const
InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, StackOffset BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace) const override
Return the cost of the scaling factor used in the addressing mode represented by AM for this target,...
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const override
unsigned getMaxInterleaveFactor(ElementCount VF, bool HasUnorderedReductions) const override
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
void negate()
Negate this APInt in place.
Definition APInt.h:1488
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
unsigned logBase2() const
Definition APInt.h:1781
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false) const override
InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) const override
TTI::ShuffleKind improveShuffleKindFromMask(TTI::ShuffleKind Kind, ArrayRef< int > Mask, VectorType *SrcTy, int &Index, VectorType *&SubTy) const
bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace, Instruction *I=nullptr, int64_t ScalableOffset=0) const override
bool areInlineCompatible(const Function *Caller, const Function *Callee) const override
InstructionCost getScalarizationOverhead(VectorType *InTy, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
InstructionCost getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind) const override
void getUnrollingPreferences(Loop *L, ScalarEvolution &SE, TTI::UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const override
void getPeelingPreferences(Loop *L, ScalarEvolution &SE, TTI::PeelingPreferences &PP) const override
InstructionCost getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode, Type *ResTy, VectorType *Ty, TTI::TargetCostKind CostKind) const override
InstructionCost getShuffleCost(TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask, int Index, VectorType *SubTp, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const override
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
std::pair< InstructionCost, MVT > getTypeLegalizationCost(Type *Ty) const
InstructionCost getPartialReductionCost(unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType, ElementCount VF, TTI::PartialReductionExtendKind OpAExtend, TTI::PartialReductionExtendKind OpBExtend, std::optional< unsigned > BinOp, TTI::TargetCostKind CostKind, std::optional< FastMathFlags > FMF) const override
InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const override
InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const override
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, TTI::OperandValueInfo OpInfo={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
bool isTypeLegal(Type *Ty) const override
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:254
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Value * getArgOperand(unsigned i) const
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
This is an important base class in LLVM.
Definition Constant.h:44
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:793
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
bool empty() const
Definition DenseMap.h:716
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:309
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static bool isCommutative(Predicate Pred)
This provides a helper for copying FMF from an instruction or setting specified flags.
Definition IRBuilder.h:90
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
bool approxFunc() const
Definition FMF.h:70
bool allowContract() const
Definition FMF.h:69
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static bool isCommutative(Predicate P)
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2748
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2736
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition IRBuilder.h:541
Type * getDoubleTy()
Fetch the type representing a 64-bit floating point value.
Definition IRBuilder.h:561
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
LLVM_ABI CallInst * CreateMaskedLoad(Type *Ty, Value *Ptr, Align Alignment, Value *Mask, Value *PassThru=nullptr, const Twine &Name="")
Create a call to Masked Load intrinsic.
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:528
Type * getHalfTy()
Fetch the type representing a 16-bit floating point value.
Definition IRBuilder.h:546
LLVM_ABI Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:476
Value * CreateLogicalAnd(Value *Cond1, Value *Cond2, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition IRBuilder.h:1772
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2408
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2626
Value * CreateBinOpFMF(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1739
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1441
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2319
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1913
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2770
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1931
LLVM_ABI CallInst * CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment, Value *Mask)
Create a call to Masked Store intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
Type * getFloatTy()
Fetch the type representing a 32-bit floating point value.
Definition IRBuilder.h:556
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2399
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Value * CreateInsertVector(Type *DstType, Value *SrcVec, Value *SubVec, Value *Idx, const Twine &Name="")
Create a call to the vector.insert intrinsic.
Definition IRBuilder.h:1128
LLVM_ABI Value * CreateElementCount(Type *Ty, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
This instruction inserts a single (scalar) element into a VectorType value.
The core instruction combiner logic.
virtual Instruction * eraseInstFromFunction(Instruction &I)=0
Combiner aware instruction erasure.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
static InstructionCost getInvalid(CostType Val=0)
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
bool isBinaryOp() const
Instruction * user_back()
iterator_range< user_iterator > users()
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
user_iterator user_begin()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Class to represent integer types.
bool hasGroups() const
Returns true if we have any interleave groups.
const SmallVectorImpl< Type * > & getArgTypes() const
const SmallVectorImpl< const Value * > & getArgs() const
const IntrinsicInst * getInst() const
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
Value * getPointerOperand()
iterator_range< block_iterator > blocks() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
RecurrenceSet & getFixedOrderRecurrences()
Return the fixed-order recurrences found in the loop.
PredicatedScalarEvolution * getPredicatedScalarEvolution() const
const ReductionList & getReductionVars() const
Returns the reduction variables found in the loop.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Machine Value Type.
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool isScalableVector() const
Return true if this is a vector value type where the runtime length is machine dependent.
static MVT getScalableVectorVT(MVT VT, unsigned NumElements)
bool isFixedLengthVector() const
MVT getVectorElementType() const
size_type size() const
Definition MapVector.h:59
Information for memory intrinsic cost model.
const Instruction * getInst() const
The optimization diagnostic interface.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Type * getRecurrenceType() const
Returns the type of the recurrence.
RecurKind getRecurrenceKind() const
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
This class represents an analyzed expression in the program.
SMEAttrs is a utility class to parse the SME ACLE attributes on functions.
bool hasStreamingCompatibleInterface() const
bool hasStreamingInterfaceOrBody() const
SMECallAttrs is a utility class to hold the SMEAttrs for a callsite.
static LLVM_ABI ScalableVectorType * get(Type *ElementType, unsigned MinNumElts)
Definition Type.cpp:860
static ScalableVectorType * getDoubleElementsVectorType(ScalableVectorType *VTy)
The main scalar evolution driver.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isZeroEltSplatMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses all elements with the same value as the first element of exa...
static LLVM_ABI bool isDeInterleaveMaskOfFactor(ArrayRef< int > Mask, unsigned Factor, unsigned &Index)
Check if the mask is a DE-interleave mask of the given factor Factor like: <Index,...
static LLVM_ABI bool isExtractSubvectorMask(ArrayRef< int > Mask, int NumSrcElts, int &Index)
Return true if this shuffle mask is an extract subvector mask.
static LLVM_ABI bool isInterleaveMask(ArrayRef< int > Mask, unsigned Factor, unsigned NumInputElts, SmallVectorImpl< unsigned > &StartIndexes)
Return true if the mask interleaves one or more input vectors together.
size_type size() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator insert(iterator I, T &&Elt)
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:40
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
Class to represent struct types.
TargetInstrInfo - Interface to description of machine instruction set.
Provides information about what library functions are available for the current target.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
std::pair< LegalizeTypeAction, EVT > LegalizeKind
LegalizeKind holds the legalization kind that needs to happen to EVT in order to type-legalize it.
virtual const DataLayout & getDataLayout() const
virtual bool shouldTreatInstructionLikeSelect(const Instruction *I) const
virtual bool isLoweredToCall(const Function *F) const
virtual bool isLSRCostLess(const TTI::LSRCost &C1, const TTI::LSRCost &C2) const
bool isConstantStridedAccessLessThan(ScalarEvolution *SE, const SCEV *Ptr, int64_t MergeDistance) const
virtual bool areTypesABICompatible(const Function *Caller, const Function *Callee, ArrayRef< Type * > Types) const
InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TTI::TargetCostKind CostKind) const override
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
static bool requiresOrderedReduction(std::optional< FastMathFlags > FMF)
A helper function to determine the type of reduction algorithm used for a given Opcode and set of Fas...
MaskSource
Enum describing the source/producer of a mask.
@ ArbitraryPredicate
The operation is masked with an arbitrary predicate.
@ ActiveLaneMask
The operation is masked with a contiguous active lane mask.
llvm::VectorInstrContext VectorInstrContext
@ TCC_Free
Expected to fold away in lowering.
@ TCC_Basic
The cost of a typical 'add' instruction.
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_InsertSubvector
InsertSubvector. Index indicates start offset.
@ SK_Select
Selects elements from the corresponding lane of either source operand.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_Transpose
Transpose two vectors.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Broadcast
Broadcast element 0 to all other elements.
@ SK_PermuteTwoSrc
Merge elements from two source vectors into one with any shuffle mask.
@ SK_Reverse
Reverse the order of the vector.
@ SK_ExtractSubvector
ExtractSubvector Index indicates start offset.
CastContextHint
Represents a hint about the context in which a cast is used.
@ Masked
The cast is used with a masked load/store.
@ Normal
The cast is used with a normal load/store.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
static constexpr TypeSize getScalable(ScalarTy MinimumSize)
Definition TypeSize.h:355
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
bool isFP128Ty() const
Return true if this is 'fp128'.
Definition Type.h:164
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI Type * getWithNewType(Type *EltTy) const
Given vector type, change the element type, whilst keeping the old number of elements.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:271
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
const Use & getOperandUse(unsigned i) const
Definition User.h:220
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
bool use_empty() const
Definition Value.h:348
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static VectorType * getInteger(VectorType *VTy)
This static method gets a VectorType with the same number of elements as the input type,...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
constexpr bool isKnownMultipleOf(ScalarTy RHS) const
This function tells the caller whether the element count is known at compile time to be a multiple of...
Definition TypeSize.h:181
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:253
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static bool isLogicalImmediate(uint64_t imm, unsigned regSize)
isLogicalImmediate - Return true if the immediate is valid for a logical immediate instruction of the...
void expandMOVImm(uint64_t Imm, unsigned BitSize, SmallVectorImpl< ImmInsnModel > &Insn)
Expand a MOVi32imm or MOVi64imm pseudo instruction to one or more real move-immediate instructions to...
LLVM_ABI APInt getCpuSupportsMask(ArrayRef< StringRef > Features)
static constexpr unsigned SVEBitsPerBlock
LLVM_ABI APInt getFMVPriority(ArrayRef< StringRef > Features)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Entry
Definition COFF.h:862
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:26
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ CTTZ_ELTS
Returns the number of number of trailing (least significant) zero elements in a vector.
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
AllOnesConstantMatch m_AllOnes()
CheckType m_SpecificType(LLT Ty)
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
LogicalOp_match< LHS, RHS, Instruction::And > m_LogicalAnd(const LHS &L, const RHS &R)
Matches L && R either in the form of L & R or L ?
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
auto m_VScale()
Matches a call to llvm.vscale().
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_Undef()
Match an arbitrary undef constant.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
LocationClass< Ty > location(Ty &L)
InstructionCost getVectorInstrCost(const TargetTransformInfo &TTI, bool ReVec, Type *ScalarTy, unsigned Opcode, Type *Val, const TTI::TargetCostKind CostKind, unsigned Index, Value *Scalar, ArrayRef< std::tuple< Value *, User *, int > > ScalarUserAndIdx, TTI::VectorInstrContext VIC)
This is similar to TargetTransformInfo::getVectorInstrCost, but if ScalarTy is a FixedVectorType,...
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
std::optional< unsigned > isDUPQMask(ArrayRef< int > Mask, unsigned Segments, unsigned SegmentSize)
isDUPQMask - matches a splat of equivalent lanes within segments of a given number of elements.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
const CostTblEntryT< CostType > * CostTableLookup(ArrayRef< CostTblEntryT< CostType > > Tbl, int ISD, MVT Ty)
Find in cost table.
Definition CostTable.h:36
LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name)
Returns true if Name is applied to TheLoop and enabled.
bool isZIPMask(ArrayRef< int > M, unsigned NumElts, unsigned &WhichResultOut, unsigned &OperandOrderOut)
Return true for zip1 or zip2 masks of the form: <0, 8, 1, 9, 2, 10, 3, 11> (WhichResultOut = 0,...
TailFoldingOpts
An enum to describe what types of loops we should attempt to tail-fold: Disabled: None Reductions: Lo...
InstructionCost Cost
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Known
Known to have no common set bits.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
bool isDUPFirstSegmentMask(ArrayRef< int > Mask, unsigned Segments, unsigned SegmentSize)
isDUPFirstSegmentMask - matches a splat of the first 128b segment.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Uninitialized
Definition Threading.h:60
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ None
The instruction is not folded.
@ SplatOpFolded
All of the value's users support splatting the value.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI std::optional< int64_t > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DominatorTree &DT, const SymbolicStrideMap &StridesMap=SymbolicStrideMap(), bool ShouldCheckWrap=true, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
If the pointer has a constant stride return it in units of the access type size.
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
unsigned M1(unsigned Val)
Definition VE.h:394
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
unsigned getPerfectShuffleCost(llvm::ArrayRef< int > M)
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
DenseMap< Value *, const SCEVUnknown * > SymbolicStrideMap
Maps a pointer to its symbolic (non-constant) stride.
auto find_if_not(R &&Range, UnaryPredicate P)
Definition STLExtras.h:1793
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
bool isUZPMask(ArrayRef< int > M, unsigned NumElts, unsigned &WhichResultOut)
Return true for uzp1 or uzp2 masks of the form: <0, 2, 4, 6, 8, 10, 12, 14> or <1,...
LLVM_ABI unsigned getInterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.interleaveN intrinsics.
bool isREVMask(ArrayRef< int > M, unsigned EltSize, unsigned NumElts, unsigned BlockSize)
isREVMask - Check if a vector shuffle corresponds to a REV instruction with the specified blocksize.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr int PoisonMaskElem
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
TargetTransformInfo TTI
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Or
Bitwise or logical OR of integers.
@ FSub
Subtraction of floats.
@ FAddChainWithSubs
A chain of fadds and fsubs.
@ AnyOf
AnyOf reduction with select(cond,x,y) where one of (x,y) is loop invariant, and both x and y are inte...
@ Xor
Bitwise or logical XOR of integers.
@ FindLast
FindLast reduction with select(cmp(),x,y) where x and y.
@ FMax
FP max as select(cmp()) with nnan/nsz, or llvm.maxnum.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ FMul
Product of floats.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ FMin
FP min as select(cmp()) with nnan/nsz, or llvm.minnum.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FAdd
Sum of floats.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
DWARFExpression::Operation Op
TypeConversionCostTblEntryT< uint16_t > TypeConversionCostTblEntry
Definition CostTable.h:62
CostTblEntryT< uint16_t > CostTblEntry
Definition CostTable.h:31
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
unsigned getNumElementsFromSVEPredPattern(unsigned Pattern)
Return the number of active elements for VL1 to VL256 predicate pattern, zero for all other patterns.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
constexpr bool valueOr(BoolOrDefault X, bool Default)
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI Value * simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
const TypeConversionCostTblEntryT< CostType > * ConvertCostTableLookup(ArrayRef< TypeConversionCostTblEntryT< CostType > > Tbl, int ISD, MVT Dst, MVT Src)
Find in type conversion cost table.
Definition CostTable.h:67
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
bool isTRNMask(ArrayRef< int > M, unsigned NumElts, unsigned &WhichResultOut, unsigned &OperandOrderOut)
Return true for trn1 or trn2 masks of the form: <0, 8, 2, 10, 4, 12, 6, 14> (WhichResultOut = 0,...
#define N
static SVEIntrinsicInfo defaultMergingUnaryNarrowingTopOp()
static SVEIntrinsicInfo defaultZeroingOp()
SVEIntrinsicInfo & setOperandIdxInactiveLanesTakenFrom(unsigned Index)
static SVEIntrinsicInfo defaultMergingOp(Intrinsic::ID IID=Intrinsic::not_intrinsic)
SVEIntrinsicInfo & setOperandIdxWithNoActiveLanes(unsigned Index)
unsigned getOperandIdxWithNoActiveLanes() const
CmpInst::Predicate getCmpPredicate() const
SVEIntrinsicInfo & setInactiveLanesAreUnused()
SVEIntrinsicInfo & setInactiveLanesAreNotDefined()
SVEIntrinsicInfo & setGoverningPredicateOperandIdx(unsigned Index)
static SVEIntrinsicInfo defaultUndefOp()
Intrinsic::ID getMatchingUndefIntrinsic() const
SVEIntrinsicInfo & setResultIsZeroInitialized()
static SVEIntrinsicInfo defaultMergingUnaryOp()
SVEIntrinsicInfo & setMatchingUndefIntrinsic(Intrinsic::ID IID)
unsigned getGoverningPredicateOperandIdx() const
SVEIntrinsicInfo & setCmpPredicate(CmpInst::Predicate Pred)
SVEIntrinsicInfo & setMatchingIROpcode(unsigned Opcode)
unsigned getOperandIdxInactiveLanesTakenFrom() const
static SVEIntrinsicInfo defaultVoidOp(unsigned GPIndex)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
bool isScalableVectorOf(EVT EltVT) const
Return true if this is a scalable vector with matching element type.
Definition ValueTypes.h:207
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:397
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:419
bool isScalableVT() const
Return true if the type is a scalable type.
Definition ValueTypes.h:225
bool isFixedLengthVector() const
Definition ValueTypes.h:214
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:202
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition MCSchedule.h:124
bool isVariant() const
Definition MCSchedule.h:145
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:268
static LLVM_ABI double getReciprocalThroughput(const MCSubtargetInfo &STI, const MCSchedClassDesc &SCDesc)
Matching combinators.
Information about a load/store intrinsic defined by the target.
InterleavedAccessInfo * IAI
LoopVectorizationLegality * LVL
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
Stores information about the uses of a build vector.
unsigned Insns
TODO: Some of these could be merged.
Returns options for expansion of memcmp. IsZeroCmp is.
Parameters that control the generic loop unrolling transformation.
bool UpperBound
Allow using trip count upper bound to unroll loops.
bool Force
Apply loop unroll on any kind of loop (mainly to loops that fail runtime unrolling).
unsigned PartialOptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size, like OptSizeThreshold,...
unsigned DefaultUnrollRuntimeCount
Default unroll count for loops with run-time trip count.
bool RuntimeUnrollMultiExit
Allow runtime unrolling multi-exit loops.
unsigned SCEVExpansionBudget
Don't allow runtime unrolling if expanding the trip count takes more than SCEVExpansionBudget.
bool AddAdditionalAccumulators
Allow unrolling to add parallel reduction phis.
unsigned UnrollAndJamInnerLoopThreshold
Threshold for unroll and jam, for inner loop size.
bool UnrollAndJam
Allow unroll and jam. Used to enable unroll and jam for the target.
bool UnrollRemainder
Allow unrolling of all the iterations of the runtime loop remainder.
unsigned PartialThreshold
The cost threshold for the unrolled loop, like Threshold, but used for partial/runtime unrolling (set...
bool Runtime
Allow runtime unrolling (unrolling of loops to expand the size of the loop body even when the number ...
bool Partial
Allow partial unrolling (unrolling of loops to expand the size of the loop body, not only to eliminat...
unsigned MaxUpperBound
Set the maximum upper bound of trip count.