LLVM 23.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"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/IntrinsicsAArch64.h"
25#include "llvm/Support/Debug.h"
30#include <algorithm>
31#include <optional>
32using namespace llvm;
33using namespace llvm::PatternMatch;
34
35#define DEBUG_TYPE "aarch64tti"
36
37static cl::opt<bool> EnableFalkorHWPFUnrollFix("enable-falkor-hwpf-unroll-fix",
38 cl::init(true), cl::Hidden);
39
41 "sve-prefer-fixed-over-scalable-if-equal", cl::Hidden);
42
43static cl::opt<unsigned> SVEGatherOverhead("sve-gather-overhead", cl::init(10),
45
46static cl::opt<unsigned> SVEScatterOverhead("sve-scatter-overhead",
47 cl::init(10), cl::Hidden);
48
49static cl::opt<unsigned> SVETailFoldInsnThreshold("sve-tail-folding-insn-threshold",
50 cl::init(15), cl::Hidden);
51
53 NeonNonConstStrideOverhead("neon-nonconst-stride-overhead", cl::init(10),
55
57 "call-penalty-sm-change", cl::init(5), cl::Hidden,
59 "Penalty of calling a function that requires a change to PSTATE.SM"));
60
62 "inline-call-penalty-sm-change", cl::init(10), cl::Hidden,
63 cl::desc("Penalty of inlining a call that requires a change to PSTATE.SM"));
64
65static cl::opt<bool> EnableOrLikeSelectOpt("enable-aarch64-or-like-select",
66 cl::init(true), cl::Hidden);
67
68static cl::opt<bool> EnableLSRCostOpt("enable-aarch64-lsr-cost-opt",
69 cl::init(true), cl::Hidden);
70
71// A complete guess as to a reasonable cost.
73 BaseHistCntCost("aarch64-base-histcnt-cost", cl::init(8), cl::Hidden,
74 cl::desc("The cost of a histcnt instruction"));
75
77 "dmb-lookahead-threshold", cl::init(10), cl::Hidden,
78 cl::desc("The number of instructions to search for a redundant dmb"));
79
81 "aarch64-force-unroll-threshold", cl::init(0), cl::Hidden,
82 cl::desc("Threshold for forced unrolling of small loops in AArch64"));
83
84namespace {
85class TailFoldingOption {
86 // These bitfields will only ever be set to something non-zero in operator=,
87 // when setting the -sve-tail-folding option. This option should always be of
88 // the form (default|simple|all|disable)[+(Flag1|Flag2|etc)], where here
89 // InitialBits is one of (disabled|all|simple). EnableBits represents
90 // additional flags we're enabling, and DisableBits for those flags we're
91 // disabling. The default flag is tracked in the variable NeedsDefault, since
92 // at the time of setting the option we may not know what the default value
93 // for the CPU is.
97
98 // This value needs to be initialised to true in case the user does not
99 // explicitly set the -sve-tail-folding option.
100 bool NeedsDefault = true;
101
102 void setInitialBits(TailFoldingOpts Bits) { InitialBits = Bits; }
103
104 void setNeedsDefault(bool V) { NeedsDefault = V; }
105
106 void setEnableBit(TailFoldingOpts Bit) {
107 EnableBits |= Bit;
108 DisableBits &= ~Bit;
109 }
110
111 void setDisableBit(TailFoldingOpts Bit) {
112 EnableBits &= ~Bit;
113 DisableBits |= Bit;
114 }
115
116 TailFoldingOpts getBits(TailFoldingOpts DefaultBits) const {
117 TailFoldingOpts Bits = TailFoldingOpts::Disabled;
118
119 assert((InitialBits == TailFoldingOpts::Disabled || !NeedsDefault) &&
120 "Initial bits should only include one of "
121 "(disabled|all|simple|default)");
122 Bits = NeedsDefault ? DefaultBits : InitialBits;
123 Bits |= EnableBits;
124 Bits &= ~DisableBits;
125
126 return Bits;
127 }
128
129 void reportError(std::string Opt) {
130 errs() << "invalid argument '" << Opt
131 << "' to -sve-tail-folding=; the option should be of the form\n"
132 " (disabled|all|default|simple)[+(reductions|recurrences"
133 "|reverse|noreductions|norecurrences|noreverse)]\n";
134 report_fatal_error("Unrecognised tail-folding option");
135 }
136
137public:
138
139 void operator=(const std::string &Val) {
140 // If the user explicitly sets -sve-tail-folding= then treat as an error.
141 if (Val.empty()) {
142 reportError("");
143 return;
144 }
145
146 // Since the user is explicitly setting the option we don't automatically
147 // need the default unless they require it.
148 setNeedsDefault(false);
149
150 SmallVector<StringRef, 4> TailFoldTypes;
151 StringRef(Val).split(TailFoldTypes, '+', -1, false);
152
153 unsigned StartIdx = 1;
154 if (TailFoldTypes[0] == "disabled")
155 setInitialBits(TailFoldingOpts::Disabled);
156 else if (TailFoldTypes[0] == "all")
157 setInitialBits(TailFoldingOpts::All);
158 else if (TailFoldTypes[0] == "default")
159 setNeedsDefault(true);
160 else if (TailFoldTypes[0] == "simple")
161 setInitialBits(TailFoldingOpts::Simple);
162 else {
163 StartIdx = 0;
164 setInitialBits(TailFoldingOpts::Disabled);
165 }
166
167 for (unsigned I = StartIdx; I < TailFoldTypes.size(); I++) {
168 if (TailFoldTypes[I] == "reductions")
169 setEnableBit(TailFoldingOpts::Reductions);
170 else if (TailFoldTypes[I] == "recurrences")
171 setEnableBit(TailFoldingOpts::Recurrences);
172 else if (TailFoldTypes[I] == "reverse")
173 setEnableBit(TailFoldingOpts::Reverse);
174 else if (TailFoldTypes[I] == "noreductions")
175 setDisableBit(TailFoldingOpts::Reductions);
176 else if (TailFoldTypes[I] == "norecurrences")
177 setDisableBit(TailFoldingOpts::Recurrences);
178 else if (TailFoldTypes[I] == "noreverse")
179 setDisableBit(TailFoldingOpts::Reverse);
180 else
181 reportError(Val);
182 }
183 }
184
185 bool satisfies(TailFoldingOpts DefaultBits, TailFoldingOpts Required) const {
186 return (getBits(DefaultBits) & Required) == Required;
187 }
188};
189} // namespace
190
191TailFoldingOption TailFoldingOptionLoc;
192
194 "sve-tail-folding",
195 cl::desc(
196 "Control the use of vectorisation using tail-folding for SVE where the"
197 " option is specified in the form (Initial)[+(Flag1|Flag2|...)]:"
198 "\ndisabled (Initial) No loop types will vectorize using "
199 "tail-folding"
200 "\ndefault (Initial) Uses the default tail-folding settings for "
201 "the target CPU"
202 "\nall (Initial) All legal loop types will vectorize using "
203 "tail-folding"
204 "\nsimple (Initial) Use tail-folding for simple loops (not "
205 "reductions or recurrences)"
206 "\nreductions Use tail-folding for loops containing reductions"
207 "\nnoreductions Inverse of above"
208 "\nrecurrences Use tail-folding for loops containing fixed order "
209 "recurrences"
210 "\nnorecurrences Inverse of above"
211 "\nreverse Use tail-folding for loops requiring reversed "
212 "predicates"
213 "\nnoreverse Inverse of above"),
215
216// Experimental option that will only be fully functional when the
217// code-generator is changed to use SVE instead of NEON for all fixed-width
218// operations.
220 "enable-fixedwidth-autovec-in-streaming-mode", cl::init(false), cl::Hidden);
221
222// Experimental option that will only be fully functional when the cost-model
223// and code-generator have been changed to avoid using scalable vector
224// instructions that are not legal in streaming SVE mode.
226 "enable-scalable-autovec-in-streaming-mode", cl::init(false), cl::Hidden);
227
228static bool isSMEABIRoutineCall(const CallInst &CI,
229 const AArch64TargetLowering &TLI) {
230 const auto *F = CI.getCalledFunction();
231 return F &&
233}
234
235/// Returns true if the function has explicit operations that can only be
236/// lowered using incompatible instructions for the selected mode. This also
237/// returns true if the function F may use or modify ZA state.
239 const AArch64TargetLowering &TLI) {
240 for (const BasicBlock &BB : *F) {
241 for (const Instruction &I : BB) {
242 // Be conservative for now and assume that any call to inline asm or to
243 // intrinsics could could result in non-streaming ops (e.g. calls to
244 // @llvm.aarch64.* or @llvm.gather/scatter intrinsics). We can assume that
245 // all native LLVM instructions can be lowered to compatible instructions.
246 if (isa<CallInst>(I) && !I.isDebugOrPseudoInst() &&
247 (cast<CallInst>(I).isInlineAsm() || isa<IntrinsicInst>(I) ||
249 return true;
250 }
251 }
252 return false;
253}
254
256 SmallVectorImpl<StringRef> &Features) {
257 StringRef AttributeStr =
258 TTI->isMultiversionedFunction(F) ? "fmv-features" : "target-features";
259 StringRef FeatureStr = F.getFnAttribute(AttributeStr).getValueAsString();
260 FeatureStr.split(Features, ",");
261}
262
265 extractAttrFeatures(F, this, Features);
266 return AArch64::getCpuSupportsMask(Features);
267}
268
271 extractAttrFeatures(F, this, Features);
272 return AArch64::getFMVPriority(Features);
273}
274
276 return F.hasFnAttribute("fmv-features");
277}
278
280 const Function *Callee) const {
281 SMECallAttrs CallAttrs(*Caller, *Callee);
282
283 // Never inline a function explicitly marked as being streaming,
284 // into a non-streaming function. Assume it was marked as streaming
285 // for a reason.
286 if (CallAttrs.caller().hasNonStreamingInterfaceAndBody() &&
288 return false;
289
290 // When inlining, we should consider the body of the function, not the
291 // interface.
292 if (CallAttrs.callee().hasStreamingBody()) {
293 CallAttrs.callee().set(SMEAttrs::SM_Compatible, false);
294 CallAttrs.callee().set(SMEAttrs::SM_Enabled, true);
295 }
296
297 if (CallAttrs.callee().isNewZA() || CallAttrs.callee().isNewZT0())
298 return false;
299
300 if (CallAttrs.requiresLazySave() || CallAttrs.requiresSMChange() ||
301 CallAttrs.requiresPreservingZT0() ||
302 CallAttrs.requiresPreservingAllZAState()) {
303 if (hasPossibleIncompatibleOps(Callee, *getTLI()))
304 return false;
305 }
306
307 return BaseT::areInlineCompatible(Caller, Callee);
308}
309
311 const Function *Callee,
312 ArrayRef<Type *> Types) const {
313 if (!BaseT::areTypesABICompatible(Caller, Callee, Types))
314 return false;
315
316 // We need to ensure that argument promotion does not attempt to promote
317 // pointers to fixed-length vector types larger than 128 bits like
318 // <8 x float> (and pointers to aggregate types which have such fixed-length
319 // vector type members) into the values of the pointees. Such vector types
320 // are used for SVE VLS but there is no ABI for SVE VLS arguments and the
321 // backend cannot lower such value arguments. The 128-bit fixed-length SVE
322 // types can be safely treated as 128-bit NEON types and they cannot be
323 // distinguished in IR.
324 if (ST->useSVEForFixedLengthVectors() && llvm::any_of(Types, [](Type *Ty) {
325 auto FVTy = dyn_cast<FixedVectorType>(Ty);
326 return FVTy &&
327 FVTy->getScalarSizeInBits() * FVTy->getNumElements() > 128;
328 }))
329 return false;
330
331 return true;
332}
333
334unsigned
336 unsigned DefaultCallPenalty) const {
337 // This function calculates a penalty for executing Call in F.
338 //
339 // There are two ways this function can be called:
340 // (1) F:
341 // call from F -> G (the call here is Call)
342 //
343 // For (1), Call.getCaller() == F, so it will always return a high cost if
344 // a streaming-mode change is required (thus promoting the need to inline the
345 // function)
346 //
347 // (2) F:
348 // call from F -> G (the call here is not Call)
349 // G:
350 // call from G -> H (the call here is Call)
351 //
352 // For (2), if after inlining the body of G into F the call to H requires a
353 // streaming-mode change, and the call to G from F would also require a
354 // streaming-mode change, then there is benefit to do the streaming-mode
355 // change only once and avoid inlining of G into F.
356
357 SMEAttrs FAttrs(*F);
358 SMECallAttrs CallAttrs(Call, &getTLI()->getRuntimeLibcallsInfo());
359
360 if (SMECallAttrs(FAttrs, CallAttrs.callee()).requiresSMChange()) {
361 if (F == Call.getCaller()) // (1)
362 return CallPenaltyChangeSM * DefaultCallPenalty;
363 if (SMECallAttrs(FAttrs, CallAttrs.caller()).requiresSMChange()) // (2)
364 return InlineCallPenaltyChangeSM * DefaultCallPenalty;
365 }
366
367 return DefaultCallPenalty;
368}
369
373
374 if (K == TargetTransformInfo::RGK_FixedWidthVector && ST->isNeonAvailable())
375 return true;
376
378 ST->isSVEorStreamingSVEAvailable() &&
379 !ST->disableMaximizeScalableBandwidth();
380}
381
382/// Calculate the cost of materializing a 64-bit value. This helper
383/// method might only calculate a fraction of a larger immediate. Therefore it
384/// is valid to return a cost of ZERO.
386 // Check if the immediate can be encoded within an instruction.
387 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, 64))
388 return 0;
389
390 if (Val < 0)
391 Val = ~Val;
392
393 // Calculate how many moves we will need to materialize this constant.
395 AArch64_IMM::expandMOVImm(Val, 64, Insn);
396 return Insn.size();
397}
398
399/// Calculate the cost of materializing the given constant.
403 assert(Ty->isIntegerTy());
404
405 unsigned BitSize = Ty->getPrimitiveSizeInBits();
406 if (BitSize == 0)
407 return ~0U;
408
409 // Sign-extend all constants to a multiple of 64-bit.
410 APInt ImmVal = Imm;
411 if (BitSize & 0x3f)
412 ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
413
414 // Split the constant into 64-bit chunks and calculate the cost for each
415 // chunk.
417 for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
418 APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
419 int64_t Val = Tmp.getSExtValue();
420 Cost += getIntImmCost(Val);
421 }
422 // We need at least one instruction to materialze the constant.
423 return std::max<InstructionCost>(1, Cost);
424}
425
427 const APInt &Imm, Type *Ty,
429 Instruction *Inst) const {
430 assert(Ty->isIntegerTy());
431
432 unsigned BitSize = Ty->getPrimitiveSizeInBits();
433 // There is no cost model for constants with a bit size of 0. Return TCC_Free
434 // here, so that constant hoisting will ignore this constant.
435 if (BitSize == 0)
436 return TTI::TCC_Free;
437
438 unsigned ImmIdx = ~0U;
439 switch (Opcode) {
440 default:
441 return TTI::TCC_Free;
442 case Instruction::GetElementPtr:
443 // Always hoist the base address of a GetElementPtr.
444 if (Idx == 0)
445 return 2 * TTI::TCC_Basic;
446 return TTI::TCC_Free;
447 case Instruction::Store:
448 ImmIdx = 0;
449 break;
450 case Instruction::Add:
451 case Instruction::Sub:
452 case Instruction::Mul:
453 case Instruction::UDiv:
454 case Instruction::SDiv:
455 case Instruction::URem:
456 case Instruction::SRem:
457 case Instruction::And:
458 case Instruction::Or:
459 case Instruction::Xor:
460 case Instruction::ICmp:
461 ImmIdx = 1;
462 break;
463 // Always return TCC_Free for the shift value of a shift instruction.
464 case Instruction::Shl:
465 case Instruction::LShr:
466 case Instruction::AShr:
467 if (Idx == 1)
468 return TTI::TCC_Free;
469 break;
470 case Instruction::Trunc:
471 case Instruction::ZExt:
472 case Instruction::SExt:
473 case Instruction::IntToPtr:
474 case Instruction::PtrToInt:
475 case Instruction::BitCast:
476 case Instruction::PHI:
477 case Instruction::Call:
478 case Instruction::Select:
479 case Instruction::Ret:
480 case Instruction::Load:
481 break;
482 }
483
484 if (Idx == ImmIdx) {
485 int NumConstants = (BitSize + 63) / 64;
487 return (Cost <= NumConstants * TTI::TCC_Basic)
488 ? static_cast<int>(TTI::TCC_Free)
489 : Cost;
490 }
492}
493
496 const APInt &Imm, Type *Ty,
498 assert(Ty->isIntegerTy());
499
500 unsigned BitSize = Ty->getPrimitiveSizeInBits();
501 // There is no cost model for constants with a bit size of 0. Return TCC_Free
502 // here, so that constant hoisting will ignore this constant.
503 if (BitSize == 0)
504 return TTI::TCC_Free;
505
506 // Most (all?) AArch64 intrinsics do not support folding immediates into the
507 // selected instruction, so we compute the materialization cost for the
508 // immediate directly.
509 if (IID >= Intrinsic::aarch64_addg && IID <= Intrinsic::aarch64_udiv)
511
512 switch (IID) {
513 default:
514 return TTI::TCC_Free;
515 case Intrinsic::sadd_with_overflow:
516 case Intrinsic::uadd_with_overflow:
517 case Intrinsic::ssub_with_overflow:
518 case Intrinsic::usub_with_overflow:
519 case Intrinsic::smul_with_overflow:
520 case Intrinsic::umul_with_overflow:
521 if (Idx == 1) {
522 int NumConstants = (BitSize + 63) / 64;
524 return (Cost <= NumConstants * TTI::TCC_Basic)
525 ? static_cast<int>(TTI::TCC_Free)
526 : Cost;
527 }
528 break;
529 case Intrinsic::experimental_stackmap:
530 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
531 return TTI::TCC_Free;
532 break;
533 case Intrinsic::experimental_patchpoint_void:
534 case Intrinsic::experimental_patchpoint:
535 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
536 return TTI::TCC_Free;
537 break;
538 case Intrinsic::experimental_gc_statepoint:
539 if ((Idx < 5) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
540 return TTI::TCC_Free;
541 break;
542 }
544}
545
547AArch64TTIImpl::getPopcntSupport(unsigned TyWidth) const {
548 assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
549 if (TyWidth == 32 || TyWidth == 64)
551 // TODO: AArch64TargetLowering::LowerCTPOP() supports 128bit popcount.
552 return TTI::PSK_Software;
553}
554
556 // MispredictPenalty is defined per-CPU in AArch64Sched*.td (e.g.,
557 // AArch64SchedNeoverseV2.td).
558 return ST->getSchedModel().MispredictPenalty;
559}
560
561static bool isUnpackedVectorVT(EVT VecVT) {
562 return VecVT.isScalableVector() &&
564}
565
567 const IntrinsicCostAttributes &ICA) {
568 // We need to know at least the number of elements in the vector of buckets
569 // and the size of each element to update.
570 if (ICA.getArgTypes().size() < 2)
572
573 // Only interested in costing for the hardware instruction from SVE2.
574 if (!ST->hasSVE2())
576
577 Type *BucketPtrsTy = ICA.getArgTypes()[0]; // Type of vector of pointers
578 Type *EltTy = ICA.getArgTypes()[1]; // Type of bucket elements
579 unsigned TotalHistCnts = 1;
580
581 unsigned EltSize = EltTy->getScalarSizeInBits();
582 // Only allow (up to 64b) integers or pointers
583 if ((!EltTy->isIntegerTy() && !EltTy->isPointerTy()) || EltSize > 64)
585
586 // FIXME: We should be able to generate histcnt for fixed-length vectors
587 // using ptrue with a specific VL.
588 if (VectorType *VTy = dyn_cast<VectorType>(BucketPtrsTy)) {
589 unsigned EC = VTy->getElementCount().getKnownMinValue();
590 if (!isPowerOf2_64(EC) || !VTy->isScalableTy())
592
593 // HistCnt only supports 32b and 64b element types
594 unsigned LegalEltSize = EltSize <= 32 ? 32 : 64;
595
596 if (EC == 2 || (LegalEltSize == 32 && EC == 4))
598
599 unsigned NaturalVectorWidth = AArch64::SVEBitsPerBlock / LegalEltSize;
600 TotalHistCnts = EC / NaturalVectorWidth;
601
602 return InstructionCost(BaseHistCntCost * TotalHistCnts);
603 }
604
606}
607
611 // The code-generator is currently not able to handle scalable vectors
612 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
613 // it. This change will be removed when code-generation for these types is
614 // sufficiently reliable.
615 auto *RetTy = ICA.getReturnType();
616 if (auto *VTy = dyn_cast<ScalableVectorType>(RetTy))
617 if (VTy->getElementCount() == ElementCount::getScalable(1))
619
620 switch (ICA.getID()) {
621 case Intrinsic::experimental_vector_histogram_add: {
622 InstructionCost HistCost = getHistogramCost(ST, ICA);
623 // If the cost isn't valid, we may still be able to scalarize
624 if (HistCost.isValid())
625 return HistCost;
626 break;
627 }
628 case Intrinsic::clmul: {
629 auto LT = getTypeLegalizationCost(RetTy);
630
631 // PMUL v8i8/v16i8 is always available on AArch64
632 if (ST->hasNEON()) {
633 if (LT.second == MVT::v8i8 || LT.second == MVT::v16i8)
634 return LT.first;
635
636 // Scalar i8 lowers through scalar/vector moves around PMUL.
637 if (TLI->getValueType(DL, RetTy, true) == MVT::i8) {
638 auto *VecTy =
639 FixedVectorType::get(Type::getInt8Ty(RetTy->getContext()), 8);
640 return 1 +
641 getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind,
642 -1, nullptr, nullptr) *
643 2 +
644 getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind,
645 -1, nullptr, nullptr);
646 }
647 }
648
649 if (LT.second.SimpleTy == MVT::nxv2i64)
650 if (ST->hasSVEAES() && (ST->isSVEAvailable() || ST->hasSSVE_AES()))
651 return LT.first * 3;
652
653 if (ST->hasSVE2() || ST->hasSME()) {
654 switch (LT.second.SimpleTy) {
655 case MVT::nxv16i8:
656 return LT.first;
657 case MVT::nxv8i16:
658 return LT.first * 6;
659 case MVT::nxv4i32:
660 return LT.first * 3;
661 case MVT::nxv2i64:
662 return LT.first * 8;
663 default:
664 break;
665 }
666 }
667
668 // Avoid +sve giving this cost 2 due to custom lowering: It's very slow
669 if (LT.second.SimpleTy == MVT::nxv2i64)
670 return 192;
671
672 if (ST->hasAES()) {
673 switch (LT.second.SimpleTy) {
674 case MVT::i16:
675 case MVT::i32:
676 case MVT::i64:
677 case MVT::i128: {
678 auto *VecTy =
679 FixedVectorType::get(Type::getInt64Ty(RetTy->getContext()), 1);
680 return LT.first *
681 (1 +
682 getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind,
683 -1, nullptr, nullptr) *
684 2 +
685 getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind,
686 -1, nullptr, nullptr));
687 }
688 case MVT::v1i64:
689 return LT.first;
690 case MVT::v2i64:
691 return LT.first * 3;
692 case MVT::v2i32:
693 return LT.first * 6;
694 case MVT::v4i32:
695 return LT.first * 11;
696 case MVT::v4i16:
697 return LT.first * 14;
698 default:
699 break;
700 }
701 }
702 break;
703 }
704 case Intrinsic::umin:
705 case Intrinsic::umax:
706 case Intrinsic::smin:
707 case Intrinsic::smax: {
708 static const auto ValidMinMaxTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16,
709 MVT::v8i16, MVT::v2i32, MVT::v4i32,
710 MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32,
711 MVT::nxv2i64};
712 auto LT = getTypeLegalizationCost(RetTy);
713 // v2i64 types get converted to cmp+bif hence the cost of 2
714 if (LT.second == MVT::v2i64)
715 return LT.first * 2;
716 if (any_of(ValidMinMaxTys, equal_to(LT.second)))
717 return LT.first;
718 break;
719 }
720 case Intrinsic::scmp:
721 case Intrinsic::ucmp: {
722 static const CostTblEntry BitreverseTbl[] = {
723 {Intrinsic::scmp, MVT::i32, 3}, // cmp+cset+csinv
724 {Intrinsic::scmp, MVT::i64, 3}, // cmp+cset+csinv
725 {Intrinsic::scmp, MVT::v8i8, 3}, // cmgt+cmgt+sub
726 {Intrinsic::scmp, MVT::v16i8, 3}, // cmgt+cmgt+sub
727 {Intrinsic::scmp, MVT::v4i16, 3}, // cmgt+cmgt+sub
728 {Intrinsic::scmp, MVT::v8i16, 3}, // cmgt+cmgt+sub
729 {Intrinsic::scmp, MVT::v2i32, 3}, // cmgt+cmgt+sub
730 {Intrinsic::scmp, MVT::v4i32, 3}, // cmgt+cmgt+sub
731 {Intrinsic::scmp, MVT::v1i64, 3}, // cmgt+cmgt+sub
732 {Intrinsic::scmp, MVT::v2i64, 3}, // cmgt+cmgt+sub
733 };
734 const auto LT = getTypeLegalizationCost(RetTy);
735 const auto *Entry =
736 CostTableLookup(BitreverseTbl, Intrinsic::scmp, LT.second);
737 if (Entry)
738 return Entry->Cost * LT.first;
739 break;
740 }
741 case Intrinsic::sadd_sat:
742 case Intrinsic::ssub_sat:
743 case Intrinsic::uadd_sat:
744 case Intrinsic::usub_sat: {
745 static const auto ValidSatTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16,
746 MVT::v8i16, MVT::v2i32, MVT::v4i32,
747 MVT::v2i64};
748 auto LT = getTypeLegalizationCost(RetTy);
749 // This is a base cost of 1 for the vadd, plus 3 extract shifts if we
750 // need to extend the type, as it uses shr(qadd(shl, shl)).
751 unsigned Instrs =
752 LT.second.getScalarSizeInBits() == RetTy->getScalarSizeInBits() ? 1 : 4;
753 if (any_of(ValidSatTys, equal_to(LT.second)))
754 return LT.first * Instrs;
755
757 uint64_t VectorSize = TS.getKnownMinValue();
758
759 if (ST->isSVEAvailable() && VectorSize >= 128 && isPowerOf2_64(VectorSize))
760 return LT.first * Instrs;
761
762 break;
763 }
764 case Intrinsic::abs: {
765 static const auto ValidAbsTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16,
766 MVT::v8i16, MVT::v2i32, MVT::v4i32,
767 MVT::v2i64, MVT::nxv16i8, MVT::nxv8i16,
768 MVT::nxv4i32, MVT::nxv2i64};
769 auto LT = getTypeLegalizationCost(RetTy);
770 if (any_of(ValidAbsTys, equal_to(LT.second)))
771 return LT.first;
772 break;
773 }
774 case Intrinsic::bswap: {
775 static const auto ValidAbsTys = {MVT::v4i16, MVT::v8i16, MVT::v2i32,
776 MVT::v4i32, MVT::v2i64};
777 auto LT = getTypeLegalizationCost(RetTy);
778 if (any_of(ValidAbsTys, equal_to(LT.second)) &&
779 LT.second.getScalarSizeInBits() == RetTy->getScalarSizeInBits())
780 return LT.first;
781 break;
782 }
783 case Intrinsic::fma:
784 case Intrinsic::fmuladd: {
785 // Given a fma or fmuladd, cost it the same as a fmul instruction which are
786 // usually the same for costs. TODO: Add fp16 and bf16 expansion costs.
787 Type *EltTy = RetTy->getScalarType();
788 if (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
789 (EltTy->isHalfTy() && ST->hasFullFP16()))
790 return getArithmeticInstrCost(Instruction::FMul, RetTy, CostKind);
791 break;
792 }
793 case Intrinsic::stepvector: {
794 InstructionCost Cost = 1; // Cost of the `index' instruction
795 auto LT = getTypeLegalizationCost(RetTy);
796 // Legalisation of illegal vectors involves an `index' instruction plus
797 // (LT.first - 1) vector adds.
798 if (LT.first > 1) {
799 Type *LegalVTy = EVT(LT.second).getTypeForEVT(RetTy->getContext());
800 InstructionCost AddCost =
801 getArithmeticInstrCost(Instruction::Add, LegalVTy, CostKind);
802 Cost += AddCost * (LT.first - 1);
803 }
804 return Cost;
805 }
806 case Intrinsic::vector_extract:
807 case Intrinsic::vector_insert: {
808 // If both the vector and subvector types are legal types and the index
809 // is 0, then this should be a no-op or simple operation; return a
810 // relatively low cost.
811
812 // If arguments aren't actually supplied, then we cannot determine the
813 // value of the index. We also want to skip predicate types.
814 if (ICA.getArgs().size() != ICA.getArgTypes().size() ||
816 break;
817
818 LLVMContext &C = RetTy->getContext();
819 EVT VecVT = getTLI()->getValueType(DL, ICA.getArgTypes()[0]);
820 bool IsExtract = ICA.getID() == Intrinsic::vector_extract;
821 EVT SubVecVT = IsExtract ? getTLI()->getValueType(DL, RetTy)
822 : getTLI()->getValueType(DL, ICA.getArgTypes()[1]);
823 // Skip this if either the vector or subvector types are unpacked
824 // SVE types; they may get lowered to stack stores and loads.
825 if (isUnpackedVectorVT(VecVT) || isUnpackedVectorVT(SubVecVT))
826 break;
827
829 getTLI()->getTypeConversion(C, SubVecVT);
831 getTLI()->getTypeConversion(C, VecVT);
832 const Value *Idx = IsExtract ? ICA.getArgs()[1] : ICA.getArgs()[2];
833 const ConstantInt *CIdx = cast<ConstantInt>(Idx);
834 if (SubVecLK.first == TargetLoweringBase::TypeLegal &&
835 VecLK.first == TargetLoweringBase::TypeLegal && CIdx->isZero())
836 return TTI::TCC_Free;
837 break;
838 }
839 case Intrinsic::bitreverse: {
840 static const CostTblEntry BitreverseTbl[] = {
841 {Intrinsic::bitreverse, MVT::i32, 1},
842 {Intrinsic::bitreverse, MVT::i64, 1},
843 {Intrinsic::bitreverse, MVT::v8i8, 1},
844 {Intrinsic::bitreverse, MVT::v16i8, 1},
845 {Intrinsic::bitreverse, MVT::v4i16, 2},
846 {Intrinsic::bitreverse, MVT::v8i16, 2},
847 {Intrinsic::bitreverse, MVT::v2i32, 2},
848 {Intrinsic::bitreverse, MVT::v4i32, 2},
849 {Intrinsic::bitreverse, MVT::v1i64, 2},
850 {Intrinsic::bitreverse, MVT::v2i64, 2},
851 };
852 const auto LegalisationCost = getTypeLegalizationCost(RetTy);
853 const auto *Entry =
854 CostTableLookup(BitreverseTbl, ICA.getID(), LegalisationCost.second);
855 if (Entry) {
856 // Cost Model is using the legal type(i32) that i8 and i16 will be
857 // converted to +1 so that we match the actual lowering cost
858 if (TLI->getValueType(DL, RetTy, true) == MVT::i8 ||
859 TLI->getValueType(DL, RetTy, true) == MVT::i16)
860 return LegalisationCost.first * Entry->Cost + 1;
861
862 return LegalisationCost.first * Entry->Cost;
863 }
864 break;
865 }
866 case Intrinsic::ctpop: {
867 if (!ST->hasNEON()) {
868 // 32-bit or 64-bit ctpop without NEON is 12 instructions.
869 return getTypeLegalizationCost(RetTy).first * 12;
870 }
871 static const CostTblEntry CtpopCostTbl[] = {
872 {ISD::CTPOP, MVT::v2i64, 4},
873 {ISD::CTPOP, MVT::v4i32, 3},
874 {ISD::CTPOP, MVT::v8i16, 2},
875 {ISD::CTPOP, MVT::v16i8, 1},
876 {ISD::CTPOP, MVT::i64, 4},
877 {ISD::CTPOP, MVT::v2i32, 3},
878 {ISD::CTPOP, MVT::v4i16, 2},
879 {ISD::CTPOP, MVT::v8i8, 1},
880 {ISD::CTPOP, MVT::i32, 5},
881 // SVE types (For targets that override NEON for fixed length vectors)
882 {ISD::CTPOP, MVT::nxv2i64, 1},
883 {ISD::CTPOP, MVT::nxv4i32, 1},
884 {ISD::CTPOP, MVT::nxv8i16, 1},
885 {ISD::CTPOP, MVT::nxv16i8, 1},
886 };
887 auto LT = getTypeLegalizationCost(RetTy);
888 MVT MTy = LT.second;
889
890 // When SVE is available CNT will be used for fixed and scalable vectors.
891 if (ST->isSVEorStreamingSVEAvailable() && MTy.isFixedLengthVector())
893 128 / MTy.getScalarSizeInBits());
894
895 if (const auto *Entry = CostTableLookup(CtpopCostTbl, ISD::CTPOP, MTy)) {
896 // Extra cost of +1 when illegal vector types are legalized by promoting
897 // the integer type.
898 int ExtraCost = MTy.isVector() && MTy.getScalarSizeInBits() !=
899 RetTy->getScalarSizeInBits()
900 ? 1
901 : 0;
902 return LT.first * Entry->Cost + ExtraCost;
903 }
904 break;
905 }
906 case Intrinsic::sadd_with_overflow:
907 case Intrinsic::uadd_with_overflow:
908 case Intrinsic::ssub_with_overflow:
909 case Intrinsic::usub_with_overflow:
910 case Intrinsic::smul_with_overflow:
911 case Intrinsic::umul_with_overflow: {
912 static const CostTblEntry WithOverflowCostTbl[] = {
913 {Intrinsic::sadd_with_overflow, MVT::i8, 3},
914 {Intrinsic::uadd_with_overflow, MVT::i8, 3},
915 {Intrinsic::sadd_with_overflow, MVT::i16, 3},
916 {Intrinsic::uadd_with_overflow, MVT::i16, 3},
917 {Intrinsic::sadd_with_overflow, MVT::i32, 1},
918 {Intrinsic::uadd_with_overflow, MVT::i32, 1},
919 {Intrinsic::sadd_with_overflow, MVT::i64, 1},
920 {Intrinsic::uadd_with_overflow, MVT::i64, 1},
921 {Intrinsic::ssub_with_overflow, MVT::i8, 3},
922 {Intrinsic::usub_with_overflow, MVT::i8, 3},
923 {Intrinsic::ssub_with_overflow, MVT::i16, 3},
924 {Intrinsic::usub_with_overflow, MVT::i16, 3},
925 {Intrinsic::ssub_with_overflow, MVT::i32, 1},
926 {Intrinsic::usub_with_overflow, MVT::i32, 1},
927 {Intrinsic::ssub_with_overflow, MVT::i64, 1},
928 {Intrinsic::usub_with_overflow, MVT::i64, 1},
929 {Intrinsic::smul_with_overflow, MVT::i8, 5},
930 {Intrinsic::umul_with_overflow, MVT::i8, 4},
931 {Intrinsic::smul_with_overflow, MVT::i16, 5},
932 {Intrinsic::umul_with_overflow, MVT::i16, 4},
933 {Intrinsic::smul_with_overflow, MVT::i32, 2}, // eg umull;tst
934 {Intrinsic::umul_with_overflow, MVT::i32, 2}, // eg umull;cmp sxtw
935 {Intrinsic::smul_with_overflow, MVT::i64, 3}, // eg mul;smulh;cmp
936 {Intrinsic::umul_with_overflow, MVT::i64, 3}, // eg mul;umulh;cmp asr
937 };
938 EVT MTy = TLI->getValueType(DL, RetTy->getContainedType(0), true);
939 if (MTy.isSimple())
940 if (const auto *Entry = CostTableLookup(WithOverflowCostTbl, ICA.getID(),
941 MTy.getSimpleVT()))
942 return Entry->Cost;
943 break;
944 }
945 case Intrinsic::fptosi_sat:
946 case Intrinsic::fptoui_sat: {
947 if (ICA.getArgTypes().empty())
948 break;
949 bool IsSigned = ICA.getID() == Intrinsic::fptosi_sat;
950 auto LT = getTypeLegalizationCost(ICA.getArgTypes()[0]);
951 EVT MTy = TLI->getValueType(DL, RetTy);
952 // Check for the legal types, which are where the size of the input and the
953 // output are the same, or we are using cvt f64->i32 or f32->i64.
954 if ((LT.second == MVT::f32 || LT.second == MVT::f64 ||
955 LT.second == MVT::v2f32 || LT.second == MVT::v4f32 ||
956 LT.second == MVT::v2f64)) {
957 if ((LT.second.getScalarSizeInBits() == MTy.getScalarSizeInBits() ||
958 (LT.second == MVT::f64 && MTy == MVT::i32) ||
959 (LT.second == MVT::f32 && MTy == MVT::i64)))
960 return LT.first;
961 // Extending vector types v2f32->v2i64, fcvtl*2 + fcvt*2
962 if (LT.second.getScalarType() == MVT::f32 && MTy.isFixedLengthVector() &&
963 MTy.getScalarSizeInBits() == 64)
964 return LT.first * (MTy.getVectorNumElements() > 2 ? 4 : 2);
965 }
966 // Similarly for fp16 sizes. Without FullFP16 we generally need to fcvt to
967 // f32.
968 if (LT.second.getScalarType() == MVT::f16 && !ST->hasFullFP16())
969 return LT.first + getIntrinsicInstrCost(
970 {ICA.getID(),
971 RetTy,
972 {ICA.getArgTypes()[0]->getWithNewType(
973 Type::getFloatTy(RetTy->getContext()))}},
974 CostKind);
975 if ((LT.second == MVT::f16 && MTy == MVT::i32) ||
976 (LT.second == MVT::f16 && MTy == MVT::i64) ||
977 ((LT.second == MVT::v4f16 || LT.second == MVT::v8f16) &&
978 (LT.second.getScalarSizeInBits() == MTy.getScalarSizeInBits())))
979 return LT.first;
980 // Extending vector types v8f16->v8i32, fcvtl*2 + fcvt*2
981 if (LT.second.getScalarType() == MVT::f16 && MTy.isFixedLengthVector() &&
982 MTy.getScalarSizeInBits() == 32)
983 return LT.first * (MTy.getVectorNumElements() > 4 ? 4 : 2);
984 // Extending vector types v8f16->v8i32. These current scalarize but the
985 // codegen could be better.
986 if (LT.second.getScalarType() == MVT::f16 && MTy.isFixedLengthVector() &&
987 MTy.getScalarSizeInBits() == 64)
988 return MTy.getVectorNumElements() * 3;
989
990 // If we can we use a legal convert followed by a min+max
991 if ((LT.second.getScalarType() == MVT::f32 ||
992 LT.second.getScalarType() == MVT::f64 ||
993 LT.second.getScalarType() == MVT::f16) &&
994 LT.second.getScalarSizeInBits() >= MTy.getScalarSizeInBits()) {
995 Type *LegalTy =
996 Type::getIntNTy(RetTy->getContext(), LT.second.getScalarSizeInBits());
997 if (LT.second.isVector())
998 LegalTy = VectorType::get(LegalTy, LT.second.getVectorElementCount());
1000 IntrinsicCostAttributes Attrs1(IsSigned ? Intrinsic::smin
1001 : Intrinsic::umin,
1002 LegalTy, {LegalTy, LegalTy});
1004 IntrinsicCostAttributes Attrs2(IsSigned ? Intrinsic::smax
1005 : Intrinsic::umax,
1006 LegalTy, {LegalTy, LegalTy});
1008 return LT.first * Cost +
1009 ((LT.second.getScalarType() != MVT::f16 || ST->hasFullFP16()) ? 0
1010 : 1);
1011 }
1012 // Otherwise we need to follow the default expansion that clamps the value
1013 // using a float min/max with a fcmp+sel for nan handling when signed.
1014 Type *FPTy = ICA.getArgTypes()[0]->getScalarType();
1015 RetTy = RetTy->getScalarType();
1016 if (LT.second.isVector()) {
1017 FPTy = VectorType::get(FPTy, LT.second.getVectorElementCount());
1018 RetTy = VectorType::get(RetTy, LT.second.getVectorElementCount());
1019 }
1020 IntrinsicCostAttributes Attrs1(Intrinsic::minnum, FPTy, {FPTy, FPTy});
1022 IntrinsicCostAttributes Attrs2(Intrinsic::maxnum, FPTy, {FPTy, FPTy});
1024 Cost +=
1025 getCastInstrCost(IsSigned ? Instruction::FPToSI : Instruction::FPToUI,
1026 RetTy, FPTy, TTI::CastContextHint::None, CostKind);
1027 if (IsSigned) {
1028 Type *CondTy = RetTy->getWithNewBitWidth(1);
1029 Cost += getCmpSelInstrCost(BinaryOperator::FCmp, FPTy, CondTy,
1031 Cost += getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
1033 }
1034 return LT.first * Cost;
1035 }
1036 case Intrinsic::fshl:
1037 case Intrinsic::fshr: {
1038 if (ICA.getArgs().empty())
1039 break;
1040
1041 const TTI::OperandValueInfo OpInfoZ = TTI::getOperandInfo(ICA.getArgs()[2]);
1042
1043 // ROTR / ROTL is a funnel shift with equal first and second operand. For
1044 // ROTR on integer registers (i32/i64) this can be done in a single ror
1045 // instruction. A fshl with a non-constant shift uses a neg + ror.
1046 if (RetTy->isIntegerTy() && ICA.getArgs()[0] == ICA.getArgs()[1] &&
1047 (RetTy->getPrimitiveSizeInBits() == 32 ||
1048 RetTy->getPrimitiveSizeInBits() == 64)) {
1049 InstructionCost NegCost =
1050 (ICA.getID() == Intrinsic::fshl && !OpInfoZ.isConstant()) ? 1 : 0;
1051 return 1 + NegCost;
1052 }
1053
1054 // TODO: Add handling for fshl where third argument is not a constant.
1055 if (!OpInfoZ.isConstant())
1056 break;
1057
1058 const auto LegalisationCost = getTypeLegalizationCost(RetTy);
1059 if (OpInfoZ.isUniform()) {
1060 static const CostTblEntry FshlTbl[] = {
1061 {Intrinsic::fshl, MVT::v4i32, 2}, // shl + usra
1062 {Intrinsic::fshl, MVT::v2i64, 2}, {Intrinsic::fshl, MVT::v16i8, 2},
1063 {Intrinsic::fshl, MVT::v8i16, 2}, {Intrinsic::fshl, MVT::v2i32, 2},
1064 {Intrinsic::fshl, MVT::v8i8, 2}, {Intrinsic::fshl, MVT::v4i16, 2}};
1065 // Costs for both fshl & fshr are the same, so just pass Intrinsic::fshl
1066 // to avoid having to duplicate the costs.
1067 const auto *Entry =
1068 CostTableLookup(FshlTbl, Intrinsic::fshl, LegalisationCost.second);
1069 if (Entry)
1070 return LegalisationCost.first * Entry->Cost;
1071 }
1072
1073 auto TyL = getTypeLegalizationCost(RetTy);
1074 if (!RetTy->isIntegerTy())
1075 break;
1076
1077 // Estimate cost manually, as types like i8 and i16 will get promoted to
1078 // i32 and CostTableLookup will ignore the extra conversion cost.
1079 bool HigherCost = (RetTy->getScalarSizeInBits() != 32 &&
1080 RetTy->getScalarSizeInBits() < 64) ||
1081 (RetTy->getScalarSizeInBits() % 64 != 0);
1082 unsigned ExtraCost = HigherCost ? 1 : 0;
1083 if (RetTy->getScalarSizeInBits() == 32 ||
1084 RetTy->getScalarSizeInBits() == 64)
1085 ExtraCost = 0; // fhsl/fshr for i32 and i64 can be lowered to a single
1086 // extr instruction.
1087 else if (HigherCost)
1088 ExtraCost = 1;
1089 else
1090 break;
1091 return TyL.first + ExtraCost;
1092 }
1093 case Intrinsic::get_active_lane_mask: {
1094 auto RetTy = cast<VectorType>(ICA.getReturnType());
1095 EVT RetVT = getTLI()->getValueType(DL, RetTy);
1096 EVT OpVT = getTLI()->getValueType(DL, ICA.getArgTypes()[0]);
1097 if (getTLI()->shouldExpandGetActiveLaneMask(RetVT, OpVT))
1098 break;
1099
1100 if (RetTy->isScalableTy()) {
1101 if (TLI->getTypeAction(RetTy->getContext(), RetVT) !=
1103 break;
1104
1105 auto LT = getTypeLegalizationCost(RetTy);
1106 InstructionCost Cost = LT.first;
1107 // When SVE2p1 or SME2 is available, we can halve getTypeLegalizationCost
1108 // as get_active_lane_mask may lower to the sve_whilelo_x2 intrinsic, e.g.
1109 // nxv32i1 = get_active_lane_mask(base, idx) ->
1110 // {nxv16i1, nxv16i1} = sve_whilelo_x2(base, idx)
1111 if (ST->hasSVE2p1() || ST->hasSME2()) {
1112 Cost /= 2;
1113 if (Cost == 1)
1114 return Cost;
1115 }
1116
1117 // If more than one whilelo intrinsic is required, include the extra cost
1118 // required by the saturating add & select required to increment the
1119 // start value after the first intrinsic call.
1120 Type *OpTy = ICA.getArgTypes()[0];
1121 IntrinsicCostAttributes AddAttrs(Intrinsic::uadd_sat, OpTy, {OpTy, OpTy});
1122 InstructionCost SplitCost = getIntrinsicInstrCost(AddAttrs, CostKind);
1123 Type *CondTy = OpTy->getWithNewBitWidth(1);
1124 SplitCost += getCmpSelInstrCost(Instruction::Select, OpTy, CondTy,
1126 return Cost + (SplitCost * (Cost - 1));
1127 } else if (!getTLI()->isTypeLegal(RetVT)) {
1128 // We don't have enough context at this point to determine if the mask
1129 // is going to be kept live after the block, which will force the vXi1
1130 // type to be expanded to legal vectors of integers, e.g. v4i1->v4i32.
1131 // For now, we just assume the vectorizer created this intrinsic and
1132 // the result will be the input for a PHI. In this case the cost will
1133 // be extremely high for fixed-width vectors.
1134 // NOTE: getScalarizationOverhead returns a cost that's far too
1135 // pessimistic for the actual generated codegen. In reality there are
1136 // two instructions generated per lane.
1137 return cast<FixedVectorType>(RetTy)->getNumElements() * 2;
1138 }
1139 break;
1140 }
1141 case Intrinsic::experimental_vector_match: {
1142 auto *NeedleTy = cast<FixedVectorType>(ICA.getArgTypes()[1]);
1143 EVT SearchVT = getTLI()->getValueType(DL, ICA.getArgTypes()[0]);
1144 unsigned SearchSize = NeedleTy->getNumElements();
1145 if (!getTLI()->shouldExpandVectorMatch(SearchVT, SearchSize)) {
1146 // Base cost for MATCH instructions. At least on the Neoverse V2 and
1147 // Neoverse V3, these are cheap operations with the same latency as a
1148 // vector ADD. In most cases, however, we also need to do an extra DUP.
1149 // For fixed-length vectors we currently need an extra five--six
1150 // instructions besides the MATCH.
1152 if (isa<FixedVectorType>(RetTy))
1153 Cost += 10;
1154 return Cost;
1155 }
1156 break;
1157 }
1158 case Intrinsic::cttz: {
1159 auto LT = getTypeLegalizationCost(ICA.getArgTypes()[0]);
1160 if (LT.second == MVT::v8i8 || LT.second == MVT::v16i8)
1161 return LT.first * 2;
1162 if (LT.second == MVT::v4i16 || LT.second == MVT::v8i16 ||
1163 LT.second == MVT::v2i32 || LT.second == MVT::v4i32)
1164 return LT.first * 3;
1165 break;
1166 }
1167 case Intrinsic::experimental_cttz_elts: {
1168 EVT ArgVT = getTLI()->getValueType(DL, ICA.getArgTypes()[0]);
1169 if (!getTLI()->shouldExpandCttzElements(ArgVT)) {
1170 // This will consist of a SVE brkb and a cntp instruction. These
1171 // typically have the same latency and half the throughput as a vector
1172 // add instruction.
1173 return 4;
1174 }
1175 break;
1176 }
1177 case Intrinsic::loop_dependence_raw_mask:
1178 case Intrinsic::loop_dependence_war_mask: {
1179 // The whilewr/rw instructions require SVE2 or SME.
1180 if (ST->hasSVE2() || ST->hasSME()) {
1181 EVT VecVT = getTLI()->getValueType(DL, RetTy);
1182 unsigned EltSizeInBytes =
1183 cast<ConstantInt>(ICA.getArgs()[2])->getZExtValue();
1184 if (!is_contained({1u, 2u, 4u, 8u}, EltSizeInBytes) ||
1185 VecVT.getVectorMinNumElements() != (16 / EltSizeInBytes))
1186 break;
1187 // For fixed-vector types we need to AND the mask with a ptrue vl<N>.
1188 return isa<FixedVectorType>(RetTy) ? 2 : 1;
1189 }
1190 break;
1191 }
1192 case Intrinsic::experimental_vector_extract_last_active:
1193 if (ST->isSVEorStreamingSVEAvailable()) {
1194 auto [LegalCost, _] = getTypeLegalizationCost(ICA.getArgTypes()[0]);
1195 // This should turn into chained clastb instructions.
1196 return LegalCost;
1197 }
1198 break;
1199 case Intrinsic::pow: {
1200 // For scalar calls we know the target has the libcall, and for fixed-width
1201 // vectors we know for the worst case it can be scalarised.
1202 EVT VT = getTLI()->getValueType(DL, RetTy);
1203 RTLIB::Libcall LC = RTLIB::getPOW(VT);
1204 bool HasLibcall = getTLI()->getLibcallImpl(LC) != RTLIB::Unsupported;
1205 bool CanLowerWithLibcalls = !isa<ScalableVectorType>(RetTy) || HasLibcall;
1206
1207 // If we know that the call can be lowered with libcalls then it's safe to
1208 // reduce the costs in some cases. This is important for scalable vectors,
1209 // since we cannot scalarize the call in the absence of a vector math
1210 // library.
1211 if (CanLowerWithLibcalls && ICA.getInst() && !ICA.getArgs().empty()) {
1212 // If we know the fast math flags and the exponent is a constant then the
1213 // cost may be less for some exponents like 0.25 and 0.75.
1214 const Constant *ExpC = dyn_cast<Constant>(ICA.getArgs()[1]);
1215 if (ExpC && isa<VectorType>(ExpC->getType()))
1216 ExpC = ExpC->getSplatValue();
1217 if (auto *ExpF = dyn_cast_or_null<ConstantFP>(ExpC)) {
1218 // The argument must be a FP constant.
1219 bool Is025 = ExpF->getValueAPF().isExactlyValue(0.25);
1220 bool Is075 = ExpF->getValueAPF().isExactlyValue(0.75);
1221 FastMathFlags FMF = ICA.getInst()->getFastMathFlags();
1222 if ((Is025 || Is075) && FMF.noInfs() && FMF.approxFunc() &&
1223 (!Is025 || FMF.noSignedZeros())) {
1224 IntrinsicCostAttributes Attrs(Intrinsic::sqrt, RetTy, {RetTy}, FMF);
1226 if (Is025)
1227 return 2 * Sqrt;
1229 getArithmeticInstrCost(Instruction::FMul, RetTy, CostKind);
1230 return (Sqrt * 2) + FMul;
1231 }
1232 // TODO: For 1/3 exponents we expect the cbrt call to be slightly
1233 // cheaper than pow.
1234 }
1235 }
1236
1237 if (HasLibcall)
1238 return getCallInstrCost(nullptr, RetTy, ICA.getArgTypes(), CostKind);
1239 break;
1240 }
1241 case Intrinsic::sqrt:
1242 case Intrinsic::fabs:
1243 case Intrinsic::ceil:
1244 case Intrinsic::floor:
1245 case Intrinsic::nearbyint:
1246 case Intrinsic::round:
1247 case Intrinsic::rint:
1248 case Intrinsic::roundeven:
1249 case Intrinsic::trunc:
1250 case Intrinsic::minnum:
1251 case Intrinsic::maxnum:
1252 case Intrinsic::minimum:
1253 case Intrinsic::maximum: {
1254 if (isa<ScalableVectorType>(RetTy) && ST->isSVEorStreamingSVEAvailable()) {
1255 auto LT = getTypeLegalizationCost(RetTy);
1256 return LT.first;
1257 }
1258 break;
1259 }
1260 default:
1261 break;
1262 }
1264}
1265
1266/// The function will remove redundant reinterprets casting in the presence
1267/// of the control flow
1268static std::optional<Instruction *> processPhiNode(InstCombiner &IC,
1269 IntrinsicInst &II) {
1271 auto RequiredType = II.getType();
1272
1273 auto *PN = dyn_cast<PHINode>(II.getArgOperand(0));
1274 assert(PN && "Expected Phi Node!");
1275
1276 // Don't create a new Phi unless we can remove the old one.
1277 if (!PN->hasOneUse())
1278 return std::nullopt;
1279
1280 for (Value *IncValPhi : PN->incoming_values()) {
1281 auto *Reinterpret = dyn_cast<IntrinsicInst>(IncValPhi);
1282 if (!Reinterpret ||
1283 Reinterpret->getIntrinsicID() !=
1284 Intrinsic::aarch64_sve_convert_to_svbool ||
1285 RequiredType != Reinterpret->getArgOperand(0)->getType())
1286 return std::nullopt;
1287 }
1288
1289 // Create the new Phi
1290 IC.Builder.SetInsertPoint(PN);
1291 PHINode *NPN = IC.Builder.CreatePHI(RequiredType, PN->getNumIncomingValues());
1292 Worklist.push_back(PN);
1293
1294 for (unsigned I = 0; I < PN->getNumIncomingValues(); I++) {
1295 auto *Reinterpret = cast<Instruction>(PN->getIncomingValue(I));
1296 NPN->addIncoming(Reinterpret->getOperand(0), PN->getIncomingBlock(I));
1297 Worklist.push_back(Reinterpret);
1298 }
1299
1300 // Cleanup Phi Node and reinterprets
1301 return IC.replaceInstUsesWith(II, NPN);
1302}
1303
1304// A collection of properties common to SVE intrinsics that allow for combines
1305// to be written without needing to know the specific intrinsic.
1307 //
1308 // Helper routines for common intrinsic definitions.
1309 //
1310
1311 // e.g. llvm.aarch64.sve.add pg, op1, op2
1312 // with IID ==> llvm.aarch64.sve.add_u
1313 static SVEIntrinsicInfo
1320
1321 // e.g. llvm.aarch64.sve.neg inactive, pg, op
1328
1329 // e.g. llvm.aarch64.sve.fcvtnt inactive, pg, op
1335
1336 // e.g. llvm.aarch64.sve.add_u pg, op1, op2
1342
1343 // e.g. llvm.aarch64.sve.prf pg, ptr (GPIndex = 0)
1344 // llvm.aarch64.sve.st1 data, pg, ptr (GPIndex = 1)
1345 static SVEIntrinsicInfo defaultVoidOp(unsigned GPIndex) {
1346 return SVEIntrinsicInfo()
1349 }
1350
1351 // e.g. llvm.aarch64.sve.cmpeq pg, op1, op2
1352 // llvm.aarch64.sve.ld1 pg, ptr
1359
1360 // All properties relate to predication and thus having a general predicate
1361 // is the minimum requirement to say there is intrinsic info to act on.
1362 explicit operator bool() const { return hasGoverningPredicate(); }
1363
1364 //
1365 // Properties relating to the governing predicate.
1366 //
1367
1369 return GoverningPredicateIdx != std::numeric_limits<unsigned>::max();
1370 }
1371
1373 assert(hasGoverningPredicate() && "Propery not set!");
1374 return GoverningPredicateIdx;
1375 }
1376
1378 assert(!hasGoverningPredicate() && "Cannot set property twice!");
1379 GoverningPredicateIdx = Index;
1380 return *this;
1381 }
1382
1383 //
1384 // Properties relating to operations the intrinsic could be transformed into.
1385 // NOTE: This does not mean such a transformation is always possible, but the
1386 // knowledge makes it possible to reuse existing optimisations without needing
1387 // to embed specific handling for each intrinsic. For example, instruction
1388 // simplification can be used to optimise an intrinsic's active lanes.
1389 //
1390
1392 return UndefIntrinsic != Intrinsic::not_intrinsic;
1393 }
1394
1396 assert(hasMatchingUndefIntrinsic() && "Propery not set!");
1397 return UndefIntrinsic;
1398 }
1399
1401 assert(!hasMatchingUndefIntrinsic() && "Cannot set property twice!");
1402 UndefIntrinsic = IID;
1403 return *this;
1404 }
1405
1406 bool hasMatchingIROpode() const { return IROpcode != 0; }
1407
1408 unsigned getMatchingIROpode() const {
1409 assert(hasMatchingIROpode() && "Propery not set!");
1410 return IROpcode;
1411 }
1412
1414 assert(!hasMatchingIROpode() && "Cannot set property twice!");
1415 IROpcode = Opcode;
1416 return *this;
1417 }
1418
1419 //
1420 // Properties relating to the result of inactive lanes.
1421 //
1422
1424 return ResultLanes == InactiveLanesTakenFromOperand;
1425 }
1426
1428 assert(inactiveLanesTakenFromOperand() && "Propery not set!");
1429 return OperandIdxForInactiveLanes;
1430 }
1431
1433 assert(ResultLanes == Uninitialized && "Cannot set property twice!");
1434 ResultLanes = InactiveLanesTakenFromOperand;
1435 OperandIdxForInactiveLanes = Index;
1436 return *this;
1437 }
1438
1440 return ResultLanes == InactiveLanesAreNotDefined;
1441 }
1442
1444 assert(ResultLanes == Uninitialized && "Cannot set property twice!");
1445 ResultLanes = InactiveLanesAreNotDefined;
1446 return *this;
1447 }
1448
1450 return ResultLanes == InactiveLanesAreUnused;
1451 }
1452
1454 assert(ResultLanes == Uninitialized && "Cannot set property twice!");
1455 ResultLanes = InactiveLanesAreUnused;
1456 return *this;
1457 }
1458
1459 // NOTE: Whilst not limited to only inactive lanes, the common use case is:
1460 // inactiveLanesAreZeroed =
1461 // resultIsZeroInitialized() && inactiveLanesAreUnused()
1462 bool resultIsZeroInitialized() const { return ResultIsZeroInitialized; }
1463
1465 ResultIsZeroInitialized = true;
1466 return *this;
1467 }
1468
1469 //
1470 // The first operand of unary merging operations is typically only used to
1471 // set the result for inactive lanes. Knowing this allows us to deadcode the
1472 // operand when we can prove there are no inactive lanes.
1473 //
1474
1476 return OperandIdxWithNoActiveLanes != std::numeric_limits<unsigned>::max();
1477 }
1478
1480 assert(hasOperandWithNoActiveLanes() && "Propery not set!");
1481 return OperandIdxWithNoActiveLanes;
1482 }
1483
1485 assert(!hasOperandWithNoActiveLanes() && "Cannot set property twice!");
1486 OperandIdxWithNoActiveLanes = Index;
1487 return *this;
1488 }
1489
1490private:
1491 unsigned GoverningPredicateIdx = std::numeric_limits<unsigned>::max();
1492
1493 Intrinsic::ID UndefIntrinsic = Intrinsic::not_intrinsic;
1494 unsigned IROpcode = 0;
1495
1496 enum PredicationStyle {
1498 InactiveLanesTakenFromOperand,
1499 InactiveLanesAreNotDefined,
1500 InactiveLanesAreUnused
1501 } ResultLanes = Uninitialized;
1502
1503 bool ResultIsZeroInitialized = false;
1504 unsigned OperandIdxForInactiveLanes = std::numeric_limits<unsigned>::max();
1505 unsigned OperandIdxWithNoActiveLanes = std::numeric_limits<unsigned>::max();
1506};
1507
1509 // Some SVE intrinsics do not use scalable vector types, but since they are
1510 // not relevant from an SVEIntrinsicInfo perspective, they are also ignored.
1511 if (!isa<ScalableVectorType>(II.getType()) &&
1512 all_of(II.args(), [&](const Value *V) {
1513 return !isa<ScalableVectorType>(V->getType());
1514 }))
1515 return SVEIntrinsicInfo();
1516
1517 Intrinsic::ID IID = II.getIntrinsicID();
1518 switch (IID) {
1519 default:
1520 break;
1521 case Intrinsic::aarch64_sve_fcvt_bf16f32_v2:
1522 case Intrinsic::aarch64_sve_fcvt_f16f32:
1523 case Intrinsic::aarch64_sve_fcvt_f16f64:
1524 case Intrinsic::aarch64_sve_fcvt_f32f16:
1525 case Intrinsic::aarch64_sve_fcvt_f32f64:
1526 case Intrinsic::aarch64_sve_fcvt_f64f16:
1527 case Intrinsic::aarch64_sve_fcvt_f64f32:
1528 case Intrinsic::aarch64_sve_fcvtlt_f32f16:
1529 case Intrinsic::aarch64_sve_fcvtlt_f64f32:
1530 case Intrinsic::aarch64_sve_fcvtx_f32f64:
1531 case Intrinsic::aarch64_sve_fcvtzs:
1532 case Intrinsic::aarch64_sve_fcvtzs_i32f16:
1533 case Intrinsic::aarch64_sve_fcvtzs_i32f64:
1534 case Intrinsic::aarch64_sve_fcvtzs_i64f16:
1535 case Intrinsic::aarch64_sve_fcvtzs_i64f32:
1536 case Intrinsic::aarch64_sve_fcvtzu:
1537 case Intrinsic::aarch64_sve_fcvtzu_i32f16:
1538 case Intrinsic::aarch64_sve_fcvtzu_i32f64:
1539 case Intrinsic::aarch64_sve_fcvtzu_i64f16:
1540 case Intrinsic::aarch64_sve_fcvtzu_i64f32:
1541 case Intrinsic::aarch64_sve_revb:
1542 case Intrinsic::aarch64_sve_revh:
1543 case Intrinsic::aarch64_sve_revw:
1544 case Intrinsic::aarch64_sve_revd:
1545 case Intrinsic::aarch64_sve_scvtf:
1546 case Intrinsic::aarch64_sve_scvtf_f16i32:
1547 case Intrinsic::aarch64_sve_scvtf_f16i64:
1548 case Intrinsic::aarch64_sve_scvtf_f32i64:
1549 case Intrinsic::aarch64_sve_scvtf_f64i32:
1550 case Intrinsic::aarch64_sve_ucvtf:
1551 case Intrinsic::aarch64_sve_ucvtf_f16i32:
1552 case Intrinsic::aarch64_sve_ucvtf_f16i64:
1553 case Intrinsic::aarch64_sve_ucvtf_f32i64:
1554 case Intrinsic::aarch64_sve_ucvtf_f64i32:
1556
1557 case Intrinsic::aarch64_sve_fcvtnt_bf16f32_v2:
1558 case Intrinsic::aarch64_sve_fcvtnt_f16f32:
1559 case Intrinsic::aarch64_sve_fcvtnt_f32f64:
1560 case Intrinsic::aarch64_sve_fcvtxnt_f32f64:
1562
1563 case Intrinsic::aarch64_sve_fabd:
1564 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fabd_u);
1565 case Intrinsic::aarch64_sve_fadd:
1566 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fadd_u)
1567 .setMatchingIROpcode(Instruction::FAdd);
1568 case Intrinsic::aarch64_sve_fdiv:
1569 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fdiv_u)
1570 .setMatchingIROpcode(Instruction::FDiv);
1571 case Intrinsic::aarch64_sve_fmax:
1572 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmax_u);
1573 case Intrinsic::aarch64_sve_fmaxnm:
1574 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmaxnm_u);
1575 case Intrinsic::aarch64_sve_fmin:
1576 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmin_u);
1577 case Intrinsic::aarch64_sve_fminnm:
1578 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fminnm_u);
1579 case Intrinsic::aarch64_sve_fmla:
1580 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmla_u);
1581 case Intrinsic::aarch64_sve_fmls:
1582 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmls_u);
1583 case Intrinsic::aarch64_sve_fmul:
1584 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmul_u)
1585 .setMatchingIROpcode(Instruction::FMul);
1586 case Intrinsic::aarch64_sve_fmulx:
1587 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fmulx_u);
1588 case Intrinsic::aarch64_sve_fnmla:
1589 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fnmla_u);
1590 case Intrinsic::aarch64_sve_fnmls:
1591 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fnmls_u);
1592 case Intrinsic::aarch64_sve_fsub:
1593 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_fsub_u)
1594 .setMatchingIROpcode(Instruction::FSub);
1595 case Intrinsic::aarch64_sve_add:
1596 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_add_u)
1597 .setMatchingIROpcode(Instruction::Add);
1598 case Intrinsic::aarch64_sve_mla:
1599 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_mla_u);
1600 case Intrinsic::aarch64_sve_mls:
1601 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_mls_u);
1602 case Intrinsic::aarch64_sve_mul:
1603 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_mul_u)
1604 .setMatchingIROpcode(Instruction::Mul);
1605 case Intrinsic::aarch64_sve_sabd:
1606 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sabd_u);
1607 case Intrinsic::aarch64_sve_sdiv:
1608 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sdiv_u)
1609 .setMatchingIROpcode(Instruction::SDiv);
1610 case Intrinsic::aarch64_sve_smax:
1611 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_smax_u);
1612 case Intrinsic::aarch64_sve_smin:
1613 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_smin_u);
1614 case Intrinsic::aarch64_sve_smulh:
1615 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_smulh_u);
1616 case Intrinsic::aarch64_sve_sub:
1617 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sub_u)
1618 .setMatchingIROpcode(Instruction::Sub);
1619 case Intrinsic::aarch64_sve_uabd:
1620 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_uabd_u);
1621 case Intrinsic::aarch64_sve_udiv:
1622 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_udiv_u)
1623 .setMatchingIROpcode(Instruction::UDiv);
1624 case Intrinsic::aarch64_sve_umax:
1625 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_umax_u);
1626 case Intrinsic::aarch64_sve_umin:
1627 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_umin_u);
1628 case Intrinsic::aarch64_sve_umulh:
1629 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_umulh_u);
1630 case Intrinsic::aarch64_sve_asr:
1631 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_asr_u)
1632 .setMatchingIROpcode(Instruction::AShr);
1633 case Intrinsic::aarch64_sve_lsl:
1634 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_lsl_u)
1635 .setMatchingIROpcode(Instruction::Shl);
1636 case Intrinsic::aarch64_sve_lsr:
1637 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_lsr_u)
1638 .setMatchingIROpcode(Instruction::LShr);
1639 case Intrinsic::aarch64_sve_and:
1640 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_and_u)
1641 .setMatchingIROpcode(Instruction::And);
1642 case Intrinsic::aarch64_sve_bic:
1643 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_bic_u);
1644 case Intrinsic::aarch64_sve_eor:
1645 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_eor_u)
1646 .setMatchingIROpcode(Instruction::Xor);
1647 case Intrinsic::aarch64_sve_orr:
1648 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_orr_u)
1649 .setMatchingIROpcode(Instruction::Or);
1650 case Intrinsic::aarch64_sve_shsub:
1651 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_shsub_u);
1652 case Intrinsic::aarch64_sve_shsubr:
1654 case Intrinsic::aarch64_sve_sqrshl:
1655 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sqrshl_u);
1656 case Intrinsic::aarch64_sve_sqshl:
1657 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sqshl_u);
1658 case Intrinsic::aarch64_sve_sqsub:
1659 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_sqsub_u);
1660 case Intrinsic::aarch64_sve_srshl:
1661 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_srshl_u);
1662 case Intrinsic::aarch64_sve_uhsub:
1663 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_uhsub_u);
1664 case Intrinsic::aarch64_sve_uhsubr:
1666 case Intrinsic::aarch64_sve_uqrshl:
1667 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_uqrshl_u);
1668 case Intrinsic::aarch64_sve_uqshl:
1669 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_uqshl_u);
1670 case Intrinsic::aarch64_sve_uqsub:
1671 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_uqsub_u);
1672 case Intrinsic::aarch64_sve_urshl:
1673 return SVEIntrinsicInfo::defaultMergingOp(Intrinsic::aarch64_sve_urshl_u);
1674
1675 case Intrinsic::aarch64_sve_add_u:
1677 Instruction::Add);
1678 case Intrinsic::aarch64_sve_and_u:
1680 Instruction::And);
1681 case Intrinsic::aarch64_sve_asr_u:
1683 Instruction::AShr);
1684 case Intrinsic::aarch64_sve_eor_u:
1686 Instruction::Xor);
1687 case Intrinsic::aarch64_sve_fadd_u:
1689 Instruction::FAdd);
1690 case Intrinsic::aarch64_sve_fdiv_u:
1692 Instruction::FDiv);
1693 case Intrinsic::aarch64_sve_fmul_u:
1695 Instruction::FMul);
1696 case Intrinsic::aarch64_sve_fsub_u:
1698 Instruction::FSub);
1699 case Intrinsic::aarch64_sve_lsl_u:
1701 Instruction::Shl);
1702 case Intrinsic::aarch64_sve_lsr_u:
1704 Instruction::LShr);
1705 case Intrinsic::aarch64_sve_mul_u:
1707 Instruction::Mul);
1708 case Intrinsic::aarch64_sve_orr_u:
1710 Instruction::Or);
1711 case Intrinsic::aarch64_sve_sdiv_u:
1713 Instruction::SDiv);
1714 case Intrinsic::aarch64_sve_sub_u:
1716 Instruction::Sub);
1717 case Intrinsic::aarch64_sve_udiv_u:
1719 Instruction::UDiv);
1720
1721 case Intrinsic::aarch64_sve_addqv:
1722 case Intrinsic::aarch64_sve_and_z:
1723 case Intrinsic::aarch64_sve_bic_z:
1724 case Intrinsic::aarch64_sve_brka_z:
1725 case Intrinsic::aarch64_sve_brkb_z:
1726 case Intrinsic::aarch64_sve_brkn_z:
1727 case Intrinsic::aarch64_sve_brkpa_z:
1728 case Intrinsic::aarch64_sve_brkpb_z:
1729 case Intrinsic::aarch64_sve_cntp:
1730 case Intrinsic::aarch64_sve_compact:
1731 case Intrinsic::aarch64_sve_eor_z:
1732 case Intrinsic::aarch64_sve_eorv:
1733 case Intrinsic::aarch64_sve_eorqv:
1734 case Intrinsic::aarch64_sve_nand_z:
1735 case Intrinsic::aarch64_sve_nor_z:
1736 case Intrinsic::aarch64_sve_orn_z:
1737 case Intrinsic::aarch64_sve_orr_z:
1738 case Intrinsic::aarch64_sve_orv:
1739 case Intrinsic::aarch64_sve_orqv:
1740 case Intrinsic::aarch64_sve_pnext:
1741 case Intrinsic::aarch64_sve_rdffr_z:
1742 case Intrinsic::aarch64_sve_saddv:
1743 case Intrinsic::aarch64_sve_uaddv:
1744 case Intrinsic::aarch64_sve_umaxv:
1745 case Intrinsic::aarch64_sve_umaxqv:
1746 case Intrinsic::aarch64_sve_cmpeq:
1747 case Intrinsic::aarch64_sve_cmpeq_wide:
1748 case Intrinsic::aarch64_sve_cmpge:
1749 case Intrinsic::aarch64_sve_cmpge_wide:
1750 case Intrinsic::aarch64_sve_cmpgt:
1751 case Intrinsic::aarch64_sve_cmpgt_wide:
1752 case Intrinsic::aarch64_sve_cmphi:
1753 case Intrinsic::aarch64_sve_cmphi_wide:
1754 case Intrinsic::aarch64_sve_cmphs:
1755 case Intrinsic::aarch64_sve_cmphs_wide:
1756 case Intrinsic::aarch64_sve_cmple_wide:
1757 case Intrinsic::aarch64_sve_cmplo_wide:
1758 case Intrinsic::aarch64_sve_cmpls_wide:
1759 case Intrinsic::aarch64_sve_cmplt_wide:
1760 case Intrinsic::aarch64_sve_cmpne:
1761 case Intrinsic::aarch64_sve_cmpne_wide:
1762 case Intrinsic::aarch64_sve_facge:
1763 case Intrinsic::aarch64_sve_facgt:
1764 case Intrinsic::aarch64_sve_fcmpeq:
1765 case Intrinsic::aarch64_sve_fcmpge:
1766 case Intrinsic::aarch64_sve_fcmpgt:
1767 case Intrinsic::aarch64_sve_fcmpne:
1768 case Intrinsic::aarch64_sve_fcmpuo:
1769 case Intrinsic::aarch64_sve_ld1:
1770 case Intrinsic::aarch64_sve_ld1_gather:
1771 case Intrinsic::aarch64_sve_ld1_gather_index:
1772 case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
1773 case Intrinsic::aarch64_sve_ld1_gather_sxtw:
1774 case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
1775 case Intrinsic::aarch64_sve_ld1_gather_uxtw:
1776 case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
1777 case Intrinsic::aarch64_sve_ld1q_gather_index:
1778 case Intrinsic::aarch64_sve_ld1q_gather_scalar_offset:
1779 case Intrinsic::aarch64_sve_ld1q_gather_vector_offset:
1780 case Intrinsic::aarch64_sve_ld1ro:
1781 case Intrinsic::aarch64_sve_ld1rq:
1782 case Intrinsic::aarch64_sve_ld1udq:
1783 case Intrinsic::aarch64_sve_ld1uwq:
1784 case Intrinsic::aarch64_sve_ld2_sret:
1785 case Intrinsic::aarch64_sve_ld2q_sret:
1786 case Intrinsic::aarch64_sve_ld3_sret:
1787 case Intrinsic::aarch64_sve_ld3q_sret:
1788 case Intrinsic::aarch64_sve_ld4_sret:
1789 case Intrinsic::aarch64_sve_ld4q_sret:
1790 case Intrinsic::aarch64_sve_ldff1:
1791 case Intrinsic::aarch64_sve_ldff1_gather:
1792 case Intrinsic::aarch64_sve_ldff1_gather_index:
1793 case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
1794 case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
1795 case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
1796 case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
1797 case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
1798 case Intrinsic::aarch64_sve_ldnf1:
1799 case Intrinsic::aarch64_sve_ldnt1:
1800 case Intrinsic::aarch64_sve_ldnt1_gather:
1801 case Intrinsic::aarch64_sve_ldnt1_gather_index:
1802 case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
1803 case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
1805
1806 case Intrinsic::aarch64_sve_prf:
1807 case Intrinsic::aarch64_sve_prfb_gather_index:
1808 case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
1809 case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
1810 case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
1811 case Intrinsic::aarch64_sve_prfd_gather_index:
1812 case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
1813 case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
1814 case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
1815 case Intrinsic::aarch64_sve_prfh_gather_index:
1816 case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
1817 case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
1818 case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
1819 case Intrinsic::aarch64_sve_prfw_gather_index:
1820 case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
1821 case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
1822 case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
1824
1825 case Intrinsic::aarch64_sve_st1_scatter:
1826 case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
1827 case Intrinsic::aarch64_sve_st1_scatter_sxtw:
1828 case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
1829 case Intrinsic::aarch64_sve_st1_scatter_uxtw:
1830 case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
1831 case Intrinsic::aarch64_sve_st1dq:
1832 case Intrinsic::aarch64_sve_st1q_scatter_index:
1833 case Intrinsic::aarch64_sve_st1q_scatter_scalar_offset:
1834 case Intrinsic::aarch64_sve_st1q_scatter_vector_offset:
1835 case Intrinsic::aarch64_sve_st1wq:
1836 case Intrinsic::aarch64_sve_stnt1:
1837 case Intrinsic::aarch64_sve_stnt1_scatter:
1838 case Intrinsic::aarch64_sve_stnt1_scatter_index:
1839 case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
1840 case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
1842 case Intrinsic::aarch64_sve_st2:
1843 case Intrinsic::aarch64_sve_st2q:
1845 case Intrinsic::aarch64_sve_st3:
1846 case Intrinsic::aarch64_sve_st3q:
1848 case Intrinsic::aarch64_sve_st4:
1849 case Intrinsic::aarch64_sve_st4q:
1851 }
1852
1853 return SVEIntrinsicInfo();
1854}
1855
1856static bool isAllActivePredicate(Value *Pred) {
1857 Value *UncastedPred;
1858
1859 // Look through predicate casts that only remove lanes.
1861 m_Value(UncastedPred)))) {
1862 auto *OrigPredTy = cast<ScalableVectorType>(Pred->getType());
1863 Pred = UncastedPred;
1864
1866 m_Value(UncastedPred))))
1867 // If the predicate has the same or less lanes than the uncasted predicate
1868 // then we know the casting has no effect.
1869 if (OrigPredTy->getMinNumElements() <=
1870 cast<ScalableVectorType>(UncastedPred->getType())
1871 ->getMinNumElements())
1872 Pred = UncastedPred;
1873 }
1874
1875 auto *C = dyn_cast<Constant>(Pred);
1876 return C && C->isAllOnesValue();
1877}
1878
1879// Simplify `V` by only considering the operations that affect active lanes.
1880// This function should only return existing Values or newly created Constants.
1881static Value *stripInactiveLanes(Value *V, const Value *Pg) {
1882 auto *Dup = dyn_cast<IntrinsicInst>(V);
1883 if (Dup && Dup->getIntrinsicID() == Intrinsic::aarch64_sve_dup &&
1884 Dup->getOperand(1) == Pg && isa<Constant>(Dup->getOperand(2)))
1886 cast<VectorType>(V->getType())->getElementCount(),
1887 cast<Constant>(Dup->getOperand(2)));
1888
1889 return V;
1890}
1891
1892static std::optional<Instruction *>
1894 const SVEIntrinsicInfo &IInfo) {
1895 const unsigned Opc = IInfo.getMatchingIROpode();
1896 assert(Instruction::isBinaryOp(Opc) && "Expected a binary operation!");
1897
1898 Value *Pg = II.getOperand(0);
1899 Value *Op1 = II.getOperand(1);
1900 Value *Op2 = II.getOperand(2);
1901 const DataLayout &DL = II.getDataLayout();
1902
1903 // Canonicalise constants to the RHS.
1905 isa<Constant>(Op1) && !isa<Constant>(Op2)) {
1906 IC.replaceOperand(II, 1, Op2);
1907 IC.replaceOperand(II, 2, Op1);
1908 return &II;
1909 }
1910
1911 // Only active lanes matter when simplifying the operation.
1912 Op1 = stripInactiveLanes(Op1, Pg);
1913 Op2 = stripInactiveLanes(Op2, Pg);
1914
1915 Value *SimpleII;
1916 if (auto FII = dyn_cast<FPMathOperator>(&II))
1917 SimpleII = simplifyBinOp(Opc, Op1, Op2, FII->getFastMathFlags(), DL);
1918 else
1919 SimpleII = simplifyBinOp(Opc, Op1, Op2, DL);
1920
1921 // An SVE intrinsic's result is always defined. However, this is not the case
1922 // for its equivalent IR instruction (e.g. when shifting by an amount more
1923 // than the data's bitwidth). Simplifications to an undefined result must be
1924 // ignored to preserve the intrinsic's expected behaviour.
1925 if (!SimpleII || isa<UndefValue>(SimpleII))
1926 return std::nullopt;
1927
1928 if (IInfo.inactiveLanesAreNotDefined())
1929 return IC.replaceInstUsesWith(II, SimpleII);
1930
1931 Value *Inactive = II.getOperand(IInfo.getOperandIdxInactiveLanesTakenFrom());
1932
1933 // The intrinsic does nothing (e.g. sve.mul(pg, A, 1.0)).
1934 if (SimpleII == Inactive)
1935 return IC.replaceInstUsesWith(II, SimpleII);
1936
1937 // Inactive lanes must be preserved.
1938 SimpleII = IC.Builder.CreateSelect(Pg, SimpleII, Inactive);
1939 return IC.replaceInstUsesWith(II, SimpleII);
1940}
1941
1942// Use SVE intrinsic info to eliminate redundant operands and/or canonicalise
1943// to operations with less strict inactive lane requirements.
1944static std::optional<Instruction *>
1946 const SVEIntrinsicInfo &IInfo) {
1947 if (!IInfo.hasGoverningPredicate())
1948 return std::nullopt;
1949
1950 auto *OpPredicate = II.getOperand(IInfo.getGoverningPredicateOperandIdx());
1951
1952 // If there are no active lanes.
1953 if (match(OpPredicate, m_ZeroInt())) {
1955 return IC.replaceInstUsesWith(
1956 II, II.getOperand(IInfo.getOperandIdxInactiveLanesTakenFrom()));
1957
1958 if (IInfo.inactiveLanesAreUnused()) {
1959 if (IInfo.resultIsZeroInitialized())
1961
1962 return IC.eraseInstFromFunction(II);
1963 }
1964 }
1965
1966 // If there are no inactive lanes.
1967 if (isAllActivePredicate(OpPredicate)) {
1968 if (IInfo.hasOperandWithNoActiveLanes()) {
1969 unsigned OpIdx = IInfo.getOperandIdxWithNoActiveLanes();
1970 if (!isa<UndefValue>(II.getOperand(OpIdx)))
1971 return IC.replaceOperand(II, OpIdx, UndefValue::get(II.getType()));
1972 }
1973
1974 if (IInfo.hasMatchingUndefIntrinsic()) {
1975 auto *NewDecl = Intrinsic::getOrInsertDeclaration(
1976 II.getModule(), IInfo.getMatchingUndefIntrinsic(), {II.getType()});
1977 II.setCalledFunction(NewDecl);
1978 return &II;
1979 }
1980 }
1981
1982 // Operation specific simplifications.
1983 if (IInfo.hasMatchingIROpode() &&
1985 return simplifySVEIntrinsicBinOp(IC, II, IInfo);
1986
1987 return std::nullopt;
1988}
1989
1990// (from_svbool (binop (to_svbool pred) (svbool_t _) (svbool_t _))))
1991// => (binop (pred) (from_svbool _) (from_svbool _))
1992//
1993// The above transformation eliminates a `to_svbool` in the predicate
1994// operand of bitwise operation `binop` by narrowing the vector width of
1995// the operation. For example, it would convert a `<vscale x 16 x i1>
1996// and` into a `<vscale x 4 x i1> and`. This is profitable because
1997// to_svbool must zero the new lanes during widening, whereas
1998// from_svbool is free.
1999static std::optional<Instruction *>
2001 auto BinOp = dyn_cast<IntrinsicInst>(II.getOperand(0));
2002 if (!BinOp)
2003 return std::nullopt;
2004
2005 auto IntrinsicID = BinOp->getIntrinsicID();
2006 switch (IntrinsicID) {
2007 case Intrinsic::aarch64_sve_and_z:
2008 case Intrinsic::aarch64_sve_bic_z:
2009 case Intrinsic::aarch64_sve_eor_z:
2010 case Intrinsic::aarch64_sve_nand_z:
2011 case Intrinsic::aarch64_sve_nor_z:
2012 case Intrinsic::aarch64_sve_orn_z:
2013 case Intrinsic::aarch64_sve_orr_z:
2014 break;
2015 default:
2016 return std::nullopt;
2017 }
2018
2019 auto BinOpPred = BinOp->getOperand(0);
2020 auto BinOpOp1 = BinOp->getOperand(1);
2021 auto BinOpOp2 = BinOp->getOperand(2);
2022
2023 auto PredIntr = dyn_cast<IntrinsicInst>(BinOpPred);
2024 if (!PredIntr ||
2025 PredIntr->getIntrinsicID() != Intrinsic::aarch64_sve_convert_to_svbool)
2026 return std::nullopt;
2027
2028 auto PredOp = PredIntr->getOperand(0);
2029 auto PredOpTy = cast<VectorType>(PredOp->getType());
2030 if (PredOpTy != II.getType())
2031 return std::nullopt;
2032
2033 SmallVector<Value *> NarrowedBinOpArgs = {PredOp};
2034 auto NarrowBinOpOp1 = IC.Builder.CreateIntrinsic(
2035 Intrinsic::aarch64_sve_convert_from_svbool, {PredOpTy}, {BinOpOp1});
2036 NarrowedBinOpArgs.push_back(NarrowBinOpOp1);
2037 if (BinOpOp1 == BinOpOp2)
2038 NarrowedBinOpArgs.push_back(NarrowBinOpOp1);
2039 else
2040 NarrowedBinOpArgs.push_back(IC.Builder.CreateIntrinsic(
2041 Intrinsic::aarch64_sve_convert_from_svbool, {PredOpTy}, {BinOpOp2}));
2042
2043 auto NarrowedBinOp =
2044 IC.Builder.CreateIntrinsic(IntrinsicID, {PredOpTy}, NarrowedBinOpArgs);
2045 return IC.replaceInstUsesWith(II, NarrowedBinOp);
2046}
2047
2048static std::optional<Instruction *>
2050 // If the reinterpret instruction operand is a PHI Node
2051 if (isa<PHINode>(II.getArgOperand(0)))
2052 return processPhiNode(IC, II);
2053
2054 if (auto BinOpCombine = tryCombineFromSVBoolBinOp(IC, II))
2055 return BinOpCombine;
2056
2057 // Ignore converts to/from svcount_t.
2058 if (isa<TargetExtType>(II.getArgOperand(0)->getType()) ||
2059 isa<TargetExtType>(II.getType()))
2060 return std::nullopt;
2061
2062 SmallVector<Instruction *, 32> CandidatesForRemoval;
2063 Value *Cursor = II.getOperand(0), *EarliestReplacement = nullptr;
2064
2065 const auto *IVTy = cast<VectorType>(II.getType());
2066
2067 // Walk the chain of conversions.
2068 while (Cursor) {
2069 // If the type of the cursor has fewer lanes than the final result, zeroing
2070 // must take place, which breaks the equivalence chain.
2071 const auto *CursorVTy = cast<VectorType>(Cursor->getType());
2072 if (CursorVTy->getElementCount().getKnownMinValue() <
2073 IVTy->getElementCount().getKnownMinValue())
2074 break;
2075
2076 // If the cursor has the same type as I, it is a viable replacement.
2077 if (Cursor->getType() == IVTy)
2078 EarliestReplacement = Cursor;
2079
2080 auto *IntrinsicCursor = dyn_cast<IntrinsicInst>(Cursor);
2081
2082 // If this is not an SVE conversion intrinsic, this is the end of the chain.
2083 if (!IntrinsicCursor || !(IntrinsicCursor->getIntrinsicID() ==
2084 Intrinsic::aarch64_sve_convert_to_svbool ||
2085 IntrinsicCursor->getIntrinsicID() ==
2086 Intrinsic::aarch64_sve_convert_from_svbool))
2087 break;
2088
2089 CandidatesForRemoval.insert(CandidatesForRemoval.begin(), IntrinsicCursor);
2090 Cursor = IntrinsicCursor->getOperand(0);
2091 }
2092
2093 // If no viable replacement in the conversion chain was found, there is
2094 // nothing to do.
2095 if (!EarliestReplacement)
2096 return std::nullopt;
2097
2098 return IC.replaceInstUsesWith(II, EarliestReplacement);
2099}
2100
2101static std::optional<Instruction *> instCombineSVESel(InstCombiner &IC,
2102 IntrinsicInst &II) {
2103 // svsel(ptrue, x, y) => x
2104 auto *OpPredicate = II.getOperand(0);
2105 if (isAllActivePredicate(OpPredicate))
2106 return IC.replaceInstUsesWith(II, II.getOperand(1));
2107
2108 auto Select =
2109 IC.Builder.CreateSelect(OpPredicate, II.getOperand(1), II.getOperand(2));
2110 return IC.replaceInstUsesWith(II, Select);
2111}
2112
2113static std::optional<Instruction *> instCombineSVEDup(InstCombiner &IC,
2114 IntrinsicInst &II) {
2115 Value *Pg = II.getOperand(1);
2116
2117 // sve.dup(V, all_active, X) ==> splat(X)
2118 if (isAllActivePredicate(Pg)) {
2119 auto *RetTy = cast<ScalableVectorType>(II.getType());
2120 Value *Splat = IC.Builder.CreateVectorSplat(RetTy->getElementCount(),
2121 II.getArgOperand(2));
2122 return IC.replaceInstUsesWith(II, Splat);
2123 }
2124
2126 m_SpecificInt(AArch64SVEPredPattern::vl1))))
2127 return std::nullopt;
2128
2129 // sve.dup(V, sve.ptrue(vl1), X) ==> insertelement V, X, 0
2130 Value *Insert = IC.Builder.CreateInsertElement(
2131 II.getArgOperand(0), II.getArgOperand(2), uint64_t(0));
2132 return IC.replaceInstUsesWith(II, Insert);
2133}
2134
2135static std::optional<Instruction *> instCombineSVEDupX(InstCombiner &IC,
2136 IntrinsicInst &II) {
2137 // Replace DupX with a regular IR splat.
2138 auto *RetTy = cast<ScalableVectorType>(II.getType());
2139 Value *Splat = IC.Builder.CreateVectorSplat(RetTy->getElementCount(),
2140 II.getArgOperand(0));
2141 Splat->takeName(&II);
2142 return IC.replaceInstUsesWith(II, Splat);
2143}
2144
2145static std::optional<Instruction *> instCombineSVECmpNE(InstCombiner &IC,
2146 IntrinsicInst &II) {
2147 LLVMContext &Ctx = II.getContext();
2148
2149 if (!isAllActivePredicate(II.getArgOperand(0)))
2150 return std::nullopt;
2151
2152 // Check that we have a compare of zero..
2153 auto *SplatValue =
2155 if (!SplatValue || !SplatValue->isZero())
2156 return std::nullopt;
2157
2158 // ..against a dupq
2159 auto *DupQLane = dyn_cast<IntrinsicInst>(II.getArgOperand(1));
2160 if (!DupQLane ||
2161 DupQLane->getIntrinsicID() != Intrinsic::aarch64_sve_dupq_lane)
2162 return std::nullopt;
2163
2164 // Where the dupq is a lane 0 replicate of a vector insert
2165 auto *DupQLaneIdx = dyn_cast<ConstantInt>(DupQLane->getArgOperand(1));
2166 if (!DupQLaneIdx || !DupQLaneIdx->isZero())
2167 return std::nullopt;
2168
2169 auto *VecIns = dyn_cast<IntrinsicInst>(DupQLane->getArgOperand(0));
2170 if (!VecIns || VecIns->getIntrinsicID() != Intrinsic::vector_insert)
2171 return std::nullopt;
2172
2173 // Where the vector insert is a fixed constant vector insert into undef at
2174 // index zero
2175 if (!isa<UndefValue>(VecIns->getArgOperand(0)))
2176 return std::nullopt;
2177
2178 if (!cast<ConstantInt>(VecIns->getArgOperand(2))->isZero())
2179 return std::nullopt;
2180
2181 auto *ConstVec = dyn_cast<Constant>(VecIns->getArgOperand(1));
2182 if (!ConstVec)
2183 return std::nullopt;
2184
2185 auto *VecTy = dyn_cast<FixedVectorType>(ConstVec->getType());
2186 auto *OutTy = dyn_cast<ScalableVectorType>(II.getType());
2187 if (!VecTy || !OutTy || VecTy->getNumElements() != OutTy->getMinNumElements())
2188 return std::nullopt;
2189
2190 unsigned NumElts = VecTy->getNumElements();
2191 unsigned PredicateBits = 0;
2192
2193 // Expand intrinsic operands to a 16-bit byte level predicate
2194 for (unsigned I = 0; I < NumElts; ++I) {
2195 auto *Arg = dyn_cast<ConstantInt>(ConstVec->getAggregateElement(I));
2196 if (!Arg)
2197 return std::nullopt;
2198 if (!Arg->isZero())
2199 PredicateBits |= 1 << (I * (16 / NumElts));
2200 }
2201
2202 // If all bits are zero bail early with an empty predicate
2203 if (PredicateBits == 0) {
2204 auto *PFalse = Constant::getNullValue(II.getType());
2205 PFalse->takeName(&II);
2206 return IC.replaceInstUsesWith(II, PFalse);
2207 }
2208
2209 // Calculate largest predicate type used (where byte predicate is largest)
2210 unsigned Mask = 8;
2211 for (unsigned I = 0; I < 16; ++I)
2212 if ((PredicateBits & (1 << I)) != 0)
2213 Mask |= (I % 8);
2214
2215 unsigned PredSize = Mask & -Mask;
2216 auto *PredType = ScalableVectorType::get(
2217 Type::getInt1Ty(Ctx), AArch64::SVEBitsPerBlock / (PredSize * 8));
2218
2219 // Ensure all relevant bits are set
2220 for (unsigned I = 0; I < 16; I += PredSize)
2221 if ((PredicateBits & (1 << I)) == 0)
2222 return std::nullopt;
2223
2224 auto *ConvertToSVBool =
2225 IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_convert_to_svbool,
2226 PredType, ConstantInt::getTrue(PredType));
2227 auto *ConvertFromSVBool =
2228 IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_convert_from_svbool,
2229 II.getType(), ConvertToSVBool);
2230
2231 ConvertFromSVBool->takeName(&II);
2232 return IC.replaceInstUsesWith(II, ConvertFromSVBool);
2233}
2234
2235static std::optional<Instruction *> instCombineSVELast(InstCombiner &IC,
2236 IntrinsicInst &II) {
2237 Value *Pg = II.getArgOperand(0);
2238 Value *Vec = II.getArgOperand(1);
2239 auto IntrinsicID = II.getIntrinsicID();
2240 bool IsAfter = IntrinsicID == Intrinsic::aarch64_sve_lasta;
2241
2242 // lastX(splat(X)) --> X
2243 if (auto *SplatVal = getSplatValue(Vec))
2244 return IC.replaceInstUsesWith(II, SplatVal);
2245
2246 // If x and/or y is a splat value then:
2247 // lastX (binop (x, y)) --> binop(lastX(x), lastX(y))
2248 Value *LHS, *RHS;
2249 if (match(Vec, m_OneUse(m_BinOp(m_Value(LHS), m_Value(RHS))))) {
2250 if (isSplatValue(LHS) || isSplatValue(RHS)) {
2251 auto *OldBinOp = cast<BinaryOperator>(Vec);
2252 auto OpC = OldBinOp->getOpcode();
2253 auto *NewLHS =
2254 IC.Builder.CreateIntrinsic(IntrinsicID, {Vec->getType()}, {Pg, LHS});
2255 auto *NewRHS =
2256 IC.Builder.CreateIntrinsic(IntrinsicID, {Vec->getType()}, {Pg, RHS});
2258 OpC, NewLHS, NewRHS, OldBinOp, OldBinOp->getName(), II.getIterator());
2259 return IC.replaceInstUsesWith(II, NewBinOp);
2260 }
2261 }
2262
2263 auto *C = dyn_cast<Constant>(Pg);
2264 if (IsAfter && C && C->isNullValue()) {
2265 // The intrinsic is extracting lane 0 so use an extract instead.
2266 auto *IdxTy = Type::getInt64Ty(II.getContext());
2267 auto *Extract = ExtractElementInst::Create(Vec, ConstantInt::get(IdxTy, 0));
2268 Extract->insertBefore(II.getIterator());
2269 Extract->takeName(&II);
2270 return IC.replaceInstUsesWith(II, Extract);
2271 }
2272
2273 auto *IntrPG = dyn_cast<IntrinsicInst>(Pg);
2274 if (!IntrPG)
2275 return std::nullopt;
2276
2277 if (IntrPG->getIntrinsicID() != Intrinsic::aarch64_sve_ptrue)
2278 return std::nullopt;
2279
2280 const auto PTruePattern =
2281 cast<ConstantInt>(IntrPG->getOperand(0))->getZExtValue();
2282
2283 // Can the intrinsic's predicate be converted to a known constant index?
2284 unsigned MinNumElts = getNumElementsFromSVEPredPattern(PTruePattern);
2285 if (!MinNumElts)
2286 return std::nullopt;
2287
2288 unsigned Idx = MinNumElts - 1;
2289 // Increment the index if extracting the element after the last active
2290 // predicate element.
2291 if (IsAfter)
2292 ++Idx;
2293
2294 // Ignore extracts whose index is larger than the known minimum vector
2295 // length. NOTE: This is an artificial constraint where we prefer to
2296 // maintain what the user asked for until an alternative is proven faster.
2297 auto *PgVTy = cast<ScalableVectorType>(Pg->getType());
2298 if (Idx >= PgVTy->getMinNumElements())
2299 return std::nullopt;
2300
2301 // The intrinsic is extracting a fixed lane so use an extract instead.
2302 auto *IdxTy = Type::getInt64Ty(II.getContext());
2303 auto *Extract = ExtractElementInst::Create(Vec, ConstantInt::get(IdxTy, Idx));
2304 Extract->insertBefore(II.getIterator());
2305 Extract->takeName(&II);
2306 return IC.replaceInstUsesWith(II, Extract);
2307}
2308
2309static std::optional<Instruction *> instCombineSVECondLast(InstCombiner &IC,
2310 IntrinsicInst &II) {
2311 // The SIMD&FP variant of CLAST[AB] is significantly faster than the scalar
2312 // integer variant across a variety of micro-architectures. Replace scalar
2313 // integer CLAST[AB] intrinsic with optimal SIMD&FP variant. A simple
2314 // bitcast-to-fp + clast[ab] + bitcast-to-int will cost a cycle or two more
2315 // depending on the micro-architecture, but has been observed as generally
2316 // being faster, particularly when the CLAST[AB] op is a loop-carried
2317 // dependency.
2318 Value *Pg = II.getArgOperand(0);
2319 Value *Fallback = II.getArgOperand(1);
2320 Value *Vec = II.getArgOperand(2);
2321 Type *Ty = II.getType();
2322
2323 if (!Ty->isIntegerTy())
2324 return std::nullopt;
2325
2326 Type *FPTy;
2327 switch (cast<IntegerType>(Ty)->getBitWidth()) {
2328 default:
2329 return std::nullopt;
2330 case 16:
2331 FPTy = IC.Builder.getHalfTy();
2332 break;
2333 case 32:
2334 FPTy = IC.Builder.getFloatTy();
2335 break;
2336 case 64:
2337 FPTy = IC.Builder.getDoubleTy();
2338 break;
2339 }
2340
2341 Value *FPFallBack = IC.Builder.CreateBitCast(Fallback, FPTy);
2342 auto *FPVTy = VectorType::get(
2343 FPTy, cast<VectorType>(Vec->getType())->getElementCount());
2344 Value *FPVec = IC.Builder.CreateBitCast(Vec, FPVTy);
2345 auto *FPII = IC.Builder.CreateIntrinsic(
2346 II.getIntrinsicID(), {FPVec->getType()}, {Pg, FPFallBack, FPVec});
2347 Value *FPIItoInt = IC.Builder.CreateBitCast(FPII, II.getType());
2348 return IC.replaceInstUsesWith(II, FPIItoInt);
2349}
2350
2351static std::optional<Instruction *> instCombineRDFFR(InstCombiner &IC,
2352 IntrinsicInst &II) {
2353 // Replace rdffr with predicated rdffr.z intrinsic, so that optimizePTestInstr
2354 // can work with RDFFR_PP for ptest elimination.
2355 auto *RDFFR = IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_rdffr_z,
2356 ConstantInt::getTrue(II.getType()));
2357 RDFFR->takeName(&II);
2358 return IC.replaceInstUsesWith(II, RDFFR);
2359}
2360
2361static std::optional<Instruction *>
2363 const auto Pattern = cast<ConstantInt>(II.getArgOperand(0))->getZExtValue();
2364
2365 if (Pattern == AArch64SVEPredPattern::all) {
2367 II.getType(), ElementCount::getScalable(NumElts));
2368 Cnt->takeName(&II);
2369 return IC.replaceInstUsesWith(II, Cnt);
2370 }
2371
2372 unsigned MinNumElts = getNumElementsFromSVEPredPattern(Pattern);
2373
2374 return MinNumElts && NumElts >= MinNumElts
2375 ? std::optional<Instruction *>(IC.replaceInstUsesWith(
2376 II, ConstantInt::get(II.getType(), MinNumElts)))
2377 : std::nullopt;
2378}
2379
2380static std::optional<Instruction *>
2382 const AArch64Subtarget *ST) {
2383 if (!ST->isStreaming())
2384 return std::nullopt;
2385
2386 // In streaming-mode, aarch64_sme_cntds is equivalent to aarch64_sve_cntd
2387 // with SVEPredPattern::all
2388 Value *Cnt =
2390 Cnt->takeName(&II);
2391 return IC.replaceInstUsesWith(II, Cnt);
2392}
2393
2394static std::optional<Instruction *> instCombineSVEPTest(InstCombiner &IC,
2395 IntrinsicInst &II) {
2396 Value *PgVal = II.getArgOperand(0);
2397 Value *OpVal = II.getArgOperand(1);
2398
2399 // PTEST_<FIRST|LAST>(X, X) is equivalent to PTEST_ANY(X, X).
2400 // Later optimizations prefer this form.
2401 if (PgVal == OpVal &&
2402 (II.getIntrinsicID() == Intrinsic::aarch64_sve_ptest_first ||
2403 II.getIntrinsicID() == Intrinsic::aarch64_sve_ptest_last)) {
2404 Value *Ops[] = {PgVal, OpVal};
2405 Type *Tys[] = {PgVal->getType()};
2406
2407 auto *PTest =
2408 IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptest_any, Tys, Ops);
2409 PTest->takeName(&II);
2410
2411 return IC.replaceInstUsesWith(II, PTest);
2412 }
2413
2416
2417 if (!Pg || !Op)
2418 return std::nullopt;
2419
2420 Intrinsic::ID OpIID = Op->getIntrinsicID();
2421
2422 if (Pg->getIntrinsicID() == Intrinsic::aarch64_sve_convert_to_svbool &&
2423 OpIID == Intrinsic::aarch64_sve_convert_to_svbool &&
2424 Pg->getArgOperand(0)->getType() == Op->getArgOperand(0)->getType()) {
2425 Value *Ops[] = {Pg->getArgOperand(0), Op->getArgOperand(0)};
2426 Type *Tys[] = {Pg->getArgOperand(0)->getType()};
2427
2428 auto *PTest = IC.Builder.CreateIntrinsic(II.getIntrinsicID(), Tys, Ops);
2429
2430 PTest->takeName(&II);
2431 return IC.replaceInstUsesWith(II, PTest);
2432 }
2433
2434 // Transform PTEST_ANY(X=OP(PG,...), X) -> PTEST_ANY(PG, X)).
2435 // Later optimizations may rewrite sequence to use the flag-setting variant
2436 // of instruction X to remove PTEST.
2437 if ((Pg == Op) && (II.getIntrinsicID() == Intrinsic::aarch64_sve_ptest_any) &&
2438 ((OpIID == Intrinsic::aarch64_sve_brka_z) ||
2439 (OpIID == Intrinsic::aarch64_sve_brkb_z) ||
2440 (OpIID == Intrinsic::aarch64_sve_brkpa_z) ||
2441 (OpIID == Intrinsic::aarch64_sve_brkpb_z) ||
2442 (OpIID == Intrinsic::aarch64_sve_rdffr_z) ||
2443 (OpIID == Intrinsic::aarch64_sve_and_z) ||
2444 (OpIID == Intrinsic::aarch64_sve_bic_z) ||
2445 (OpIID == Intrinsic::aarch64_sve_eor_z) ||
2446 (OpIID == Intrinsic::aarch64_sve_nand_z) ||
2447 (OpIID == Intrinsic::aarch64_sve_nor_z) ||
2448 (OpIID == Intrinsic::aarch64_sve_orn_z) ||
2449 (OpIID == Intrinsic::aarch64_sve_orr_z))) {
2450 Value *Ops[] = {Pg->getArgOperand(0), Pg};
2451 Type *Tys[] = {Pg->getType()};
2452
2453 auto *PTest = IC.Builder.CreateIntrinsic(II.getIntrinsicID(), Tys, Ops);
2454 PTest->takeName(&II);
2455
2456 return IC.replaceInstUsesWith(II, PTest);
2457 }
2458
2459 return std::nullopt;
2460}
2461
2462template <Intrinsic::ID MulOpc, Intrinsic::ID FuseOpc>
2463static std::optional<Instruction *>
2465 bool MergeIntoAddendOp) {
2466 Value *P = II.getOperand(0);
2467 Value *MulOp0, *MulOp1, *AddendOp, *Mul;
2468 if (MergeIntoAddendOp) {
2469 AddendOp = II.getOperand(1);
2470 Mul = II.getOperand(2);
2471 } else {
2472 AddendOp = II.getOperand(2);
2473 Mul = II.getOperand(1);
2474 }
2475
2477 m_Value(MulOp1))))
2478 return std::nullopt;
2479
2480 if (!Mul->hasOneUse())
2481 return std::nullopt;
2482
2483 Instruction *FMFSource = nullptr;
2484 if (II.getType()->isFPOrFPVectorTy()) {
2485 llvm::FastMathFlags FAddFlags = II.getFastMathFlags();
2486 // Stop the combine when the flags on the inputs differ in case dropping
2487 // flags would lead to us missing out on more beneficial optimizations.
2488 if (FAddFlags != cast<CallInst>(Mul)->getFastMathFlags())
2489 return std::nullopt;
2490 if (!FAddFlags.allowContract())
2491 return std::nullopt;
2492 FMFSource = &II;
2493 }
2494
2495 Value *Res;
2496 if (MergeIntoAddendOp)
2497 Res = IC.Builder.CreateIntrinsic(FuseOpc, {II.getType()},
2498 {P, AddendOp, MulOp0, MulOp1}, FMFSource);
2499 else
2500 Res = IC.Builder.CreateIntrinsic(FuseOpc, {II.getType()},
2501 {P, MulOp0, MulOp1, AddendOp}, FMFSource);
2502
2503 return IC.replaceInstUsesWith(II, Res);
2504}
2505
2506static std::optional<Instruction *>
2508 Value *Pred = II.getOperand(0);
2509 Value *PtrOp = II.getOperand(1);
2510 Type *VecTy = II.getType();
2511
2512 if (isAllActivePredicate(Pred)) {
2513 LoadInst *Load = IC.Builder.CreateLoad(VecTy, PtrOp);
2514 Load->copyMetadata(II);
2515 return IC.replaceInstUsesWith(II, Load);
2516 }
2517
2518 CallInst *MaskedLoad =
2519 IC.Builder.CreateMaskedLoad(VecTy, PtrOp, PtrOp->getPointerAlignment(DL),
2520 Pred, ConstantAggregateZero::get(VecTy));
2521 MaskedLoad->copyMetadata(II);
2522 return IC.replaceInstUsesWith(II, MaskedLoad);
2523}
2524
2525static std::optional<Instruction *>
2527 Value *VecOp = II.getOperand(0);
2528 Value *Pred = II.getOperand(1);
2529 Value *PtrOp = II.getOperand(2);
2530
2531 if (isAllActivePredicate(Pred)) {
2532 StoreInst *Store = IC.Builder.CreateStore(VecOp, PtrOp);
2533 Store->copyMetadata(II);
2534 return IC.eraseInstFromFunction(II);
2535 }
2536
2537 CallInst *MaskedStore = IC.Builder.CreateMaskedStore(
2538 VecOp, PtrOp, PtrOp->getPointerAlignment(DL), Pred);
2539 MaskedStore->copyMetadata(II);
2540 return IC.eraseInstFromFunction(II);
2541}
2542
2544 switch (Intrinsic) {
2545 case Intrinsic::aarch64_sve_fmul_u:
2546 return Instruction::BinaryOps::FMul;
2547 case Intrinsic::aarch64_sve_fadd_u:
2548 return Instruction::BinaryOps::FAdd;
2549 case Intrinsic::aarch64_sve_fsub_u:
2550 return Instruction::BinaryOps::FSub;
2551 default:
2552 return Instruction::BinaryOpsEnd;
2553 }
2554}
2555
2556static std::optional<Instruction *>
2558 // Bail due to missing support for ISD::STRICT_ scalable vector operations.
2559 if (II.isStrictFP())
2560 return std::nullopt;
2561
2562 auto *OpPredicate = II.getOperand(0);
2563 auto BinOpCode = intrinsicIDToBinOpCode(II.getIntrinsicID());
2564 if (BinOpCode == Instruction::BinaryOpsEnd ||
2565 !isAllActivePredicate(OpPredicate))
2566 return std::nullopt;
2567 auto BinOp = IC.Builder.CreateBinOpFMF(
2568 BinOpCode, II.getOperand(1), II.getOperand(2), II.getFastMathFlags());
2569 return IC.replaceInstUsesWith(II, BinOp);
2570}
2571
2572static std::optional<Instruction *>
2574 assert(II.getIntrinsicID() == Intrinsic::aarch64_sve_mla_u &&
2575 "Expected MLA_U intrinsic");
2576 Value *Acc = II.getArgOperand(1);
2577 Value *MulOp0 = II.getArgOperand(2);
2578 Value *MulOp1 = II.getArgOperand(3);
2579
2580 // For mla_u, inactive lanes are undefined, so it is valid to drop the
2581 // predicate when replacing mla_u(acc, x, 1) with add(acc, x) or
2582 // mla_u(acc, x, -1) with sub(acc, x).
2583 if (match(MulOp0, m_One()))
2584 return IC.replaceInstUsesWith(II, IC.Builder.CreateAdd(Acc, MulOp1));
2585 if (match(MulOp1, m_One()))
2586 return IC.replaceInstUsesWith(II, IC.Builder.CreateAdd(Acc, MulOp0));
2587 if (match(MulOp0, m_AllOnes()))
2588 return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Acc, MulOp1));
2589 if (match(MulOp1, m_AllOnes()))
2590 return IC.replaceInstUsesWith(II, IC.Builder.CreateSub(Acc, MulOp0));
2591
2592 if (isa<Constant>(MulOp0) && !isa<Constant>(MulOp1)) {
2593 II.setArgOperand(2, MulOp1);
2594 II.setArgOperand(3, MulOp0);
2595 return &II;
2596 }
2597
2598 return std::nullopt;
2599}
2600
2601static std::optional<Instruction *> instCombineSVEVectorAdd(InstCombiner &IC,
2602 IntrinsicInst &II) {
2603 if (auto MLA = instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_mul,
2604 Intrinsic::aarch64_sve_mla>(
2605 IC, II, true))
2606 return MLA;
2607 if (auto MAD = instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_mul,
2608 Intrinsic::aarch64_sve_mad>(
2609 IC, II, false))
2610 return MAD;
2611 return std::nullopt;
2612}
2613
2614static std::optional<Instruction *>
2616 if (auto FMLA =
2617 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
2618 Intrinsic::aarch64_sve_fmla>(IC, II,
2619 true))
2620 return FMLA;
2621 if (auto FMAD =
2622 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
2623 Intrinsic::aarch64_sve_fmad>(IC, II,
2624 false))
2625 return FMAD;
2626 if (auto FMLA =
2627 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul_u,
2628 Intrinsic::aarch64_sve_fmla>(IC, II,
2629 true))
2630 return FMLA;
2631 return std::nullopt;
2632}
2633
2634static std::optional<Instruction *>
2636 if (auto FMLA =
2637 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
2638 Intrinsic::aarch64_sve_fmla>(IC, II,
2639 true))
2640 return FMLA;
2641 if (auto FMAD =
2642 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
2643 Intrinsic::aarch64_sve_fmad>(IC, II,
2644 false))
2645 return FMAD;
2646 if (auto FMLA_U =
2647 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul_u,
2648 Intrinsic::aarch64_sve_fmla_u>(
2649 IC, II, true))
2650 return FMLA_U;
2651 return instCombineSVEVectorBinOp(IC, II);
2652}
2653
2654static std::optional<Instruction *>
2656 if (auto FMLS =
2657 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
2658 Intrinsic::aarch64_sve_fmls>(IC, II,
2659 true))
2660 return FMLS;
2661 if (auto FMSB =
2662 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
2663 Intrinsic::aarch64_sve_fnmsb>(
2664 IC, II, false))
2665 return FMSB;
2666 if (auto FMLS =
2667 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul_u,
2668 Intrinsic::aarch64_sve_fmls>(IC, II,
2669 true))
2670 return FMLS;
2671 return std::nullopt;
2672}
2673
2674static std::optional<Instruction *>
2676 if (auto FMLS =
2677 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
2678 Intrinsic::aarch64_sve_fmls>(IC, II,
2679 true))
2680 return FMLS;
2681 if (auto FMSB =
2682 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul,
2683 Intrinsic::aarch64_sve_fnmsb>(
2684 IC, II, false))
2685 return FMSB;
2686 if (auto FMLS_U =
2687 instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_fmul_u,
2688 Intrinsic::aarch64_sve_fmls_u>(
2689 IC, II, true))
2690 return FMLS_U;
2691 return instCombineSVEVectorBinOp(IC, II);
2692}
2693
2694static std::optional<Instruction *> instCombineSVEVectorSub(InstCombiner &IC,
2695 IntrinsicInst &II) {
2696 if (auto MLS = instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_mul,
2697 Intrinsic::aarch64_sve_mls>(
2698 IC, II, true))
2699 return MLS;
2700 return std::nullopt;
2701}
2702
2703static std::optional<Instruction *> instCombineSVEUnpack(InstCombiner &IC,
2704 IntrinsicInst &II) {
2705 Value *UnpackArg = II.getArgOperand(0);
2706 auto *RetTy = cast<ScalableVectorType>(II.getType());
2707 bool IsSigned = II.getIntrinsicID() == Intrinsic::aarch64_sve_sunpkhi ||
2708 II.getIntrinsicID() == Intrinsic::aarch64_sve_sunpklo;
2709
2710 // Hi = uunpkhi(splat(X)) --> Hi = splat(extend(X))
2711 // Lo = uunpklo(splat(X)) --> Lo = splat(extend(X))
2712 if (auto *ScalarArg = getSplatValue(UnpackArg)) {
2713 ScalarArg =
2714 IC.Builder.CreateIntCast(ScalarArg, RetTy->getScalarType(), IsSigned);
2715 Value *NewVal =
2716 IC.Builder.CreateVectorSplat(RetTy->getElementCount(), ScalarArg);
2717 NewVal->takeName(&II);
2718 return IC.replaceInstUsesWith(II, NewVal);
2719 }
2720
2721 return std::nullopt;
2722}
2723static std::optional<Instruction *> instCombineSVETBL(InstCombiner &IC,
2724 IntrinsicInst &II) {
2725 auto *OpVal = II.getOperand(0);
2726 auto *OpIndices = II.getOperand(1);
2727 VectorType *VTy = cast<VectorType>(II.getType());
2728
2729 // Check whether OpIndices is a constant splat value < minimal element count
2730 // of result.
2731 auto *SplatValue = dyn_cast_or_null<ConstantInt>(getSplatValue(OpIndices));
2732 if (!SplatValue ||
2733 SplatValue->getValue().uge(VTy->getElementCount().getKnownMinValue()))
2734 return std::nullopt;
2735
2736 // Convert sve_tbl(OpVal sve_dup_x(SplatValue)) to
2737 // splat_vector(extractelement(OpVal, SplatValue)) for further optimization.
2738 auto *Extract = IC.Builder.CreateExtractElement(OpVal, SplatValue);
2739 auto *VectorSplat =
2740 IC.Builder.CreateVectorSplat(VTy->getElementCount(), Extract);
2741
2742 VectorSplat->takeName(&II);
2743 return IC.replaceInstUsesWith(II, VectorSplat);
2744}
2745
2746static std::optional<Instruction *> instCombineSVEUzp1(InstCombiner &IC,
2747 IntrinsicInst &II) {
2748 Value *A, *B;
2749 Type *RetTy = II.getType();
2750 constexpr Intrinsic::ID FromSVB = Intrinsic::aarch64_sve_convert_from_svbool;
2751 constexpr Intrinsic::ID ToSVB = Intrinsic::aarch64_sve_convert_to_svbool;
2752
2753 // uzp1(to_svbool(A), to_svbool(B)) --> <A, B>
2754 // uzp1(from_svbool(to_svbool(A)), from_svbool(to_svbool(B))) --> <A, B>
2755 if ((match(II.getArgOperand(0),
2757 match(II.getArgOperand(1),
2759 (match(II.getArgOperand(0), m_Intrinsic<ToSVB>(m_Value(A))) &&
2760 match(II.getArgOperand(1), m_Intrinsic<ToSVB>(m_Value(B))))) {
2761 auto *TyA = cast<ScalableVectorType>(A->getType());
2762 if (TyA == B->getType() &&
2764 auto *SubVec = IC.Builder.CreateInsertVector(
2765 RetTy, PoisonValue::get(RetTy), A, uint64_t(0));
2766 auto *ConcatVec = IC.Builder.CreateInsertVector(RetTy, SubVec, B,
2767 TyA->getMinNumElements());
2768 ConcatVec->takeName(&II);
2769 return IC.replaceInstUsesWith(II, ConcatVec);
2770 }
2771 }
2772
2773 return std::nullopt;
2774}
2775
2776static std::optional<Instruction *> instCombineSVEZip(InstCombiner &IC,
2777 IntrinsicInst &II) {
2778 // zip1(uzp1(A, B), uzp2(A, B)) --> A
2779 // zip2(uzp1(A, B), uzp2(A, B)) --> B
2780 Value *A, *B;
2781 if (match(II.getArgOperand(0),
2784 m_Specific(A), m_Specific(B))))
2785 return IC.replaceInstUsesWith(
2786 II, (II.getIntrinsicID() == Intrinsic::aarch64_sve_zip1 ? A : B));
2787
2788 return std::nullopt;
2789}
2790
2791static std::optional<Instruction *>
2793 Value *Mask = II.getOperand(0);
2794 Value *BasePtr = II.getOperand(1);
2795 Value *Index = II.getOperand(2);
2796 Type *Ty = II.getType();
2797 Value *PassThru = ConstantAggregateZero::get(Ty);
2798
2799 // Contiguous gather => masked load.
2800 // (sve.ld1.gather.index Mask BasePtr (sve.index IndexBase 1))
2801 // => (masked.load (gep BasePtr IndexBase) Align Mask zeroinitializer)
2802 Value *IndexBase;
2804 m_One()))) {
2805 Align Alignment =
2806 BasePtr->getPointerAlignment(II.getDataLayout());
2807
2808 Value *Ptr = IC.Builder.CreateGEP(cast<VectorType>(Ty)->getElementType(),
2809 BasePtr, IndexBase);
2810 CallInst *MaskedLoad =
2811 IC.Builder.CreateMaskedLoad(Ty, Ptr, Alignment, Mask, PassThru);
2812 MaskedLoad->takeName(&II);
2813 return IC.replaceInstUsesWith(II, MaskedLoad);
2814 }
2815
2816 return std::nullopt;
2817}
2818
2819static std::optional<Instruction *>
2821 Value *Val = II.getOperand(0);
2822 Value *Mask = II.getOperand(1);
2823 Value *BasePtr = II.getOperand(2);
2824 Value *Index = II.getOperand(3);
2825 Type *Ty = Val->getType();
2826
2827 // Contiguous scatter => masked store.
2828 // (sve.st1.scatter.index Value Mask BasePtr (sve.index IndexBase 1))
2829 // => (masked.store Value (gep BasePtr IndexBase) Align Mask)
2830 Value *IndexBase;
2832 m_One()))) {
2833 Align Alignment =
2834 BasePtr->getPointerAlignment(II.getDataLayout());
2835
2836 Value *Ptr = IC.Builder.CreateGEP(cast<VectorType>(Ty)->getElementType(),
2837 BasePtr, IndexBase);
2838 (void)IC.Builder.CreateMaskedStore(Val, Ptr, Alignment, Mask);
2839
2840 return IC.eraseInstFromFunction(II);
2841 }
2842
2843 return std::nullopt;
2844}
2845
2846static std::optional<Instruction *> instCombineSVESDIV(InstCombiner &IC,
2847 IntrinsicInst &II) {
2848 Type *Int32Ty = IC.Builder.getInt32Ty();
2849 Value *Pred = II.getOperand(0);
2850 Value *Vec = II.getOperand(1);
2851 Value *DivVec = II.getOperand(2);
2852
2853 Value *SplatValue = getSplatValue(DivVec);
2854 ConstantInt *SplatConstantInt = dyn_cast_or_null<ConstantInt>(SplatValue);
2855 if (!SplatConstantInt)
2856 return std::nullopt;
2857
2858 APInt Divisor = SplatConstantInt->getValue();
2859 const int64_t DivisorValue = Divisor.getSExtValue();
2860 if (DivisorValue == -1)
2861 return std::nullopt;
2862 if (DivisorValue == 1)
2863 IC.replaceInstUsesWith(II, Vec);
2864
2865 if (Divisor.isPowerOf2()) {
2866 Constant *DivisorLog2 = ConstantInt::get(Int32Ty, Divisor.logBase2());
2867 auto ASRD = IC.Builder.CreateIntrinsic(
2868 Intrinsic::aarch64_sve_asrd, {II.getType()}, {Pred, Vec, DivisorLog2});
2869 return IC.replaceInstUsesWith(II, ASRD);
2870 }
2871 if (Divisor.isNegatedPowerOf2()) {
2872 Divisor.negate();
2873 Constant *DivisorLog2 = ConstantInt::get(Int32Ty, Divisor.logBase2());
2874 auto ASRD = IC.Builder.CreateIntrinsic(
2875 Intrinsic::aarch64_sve_asrd, {II.getType()}, {Pred, Vec, DivisorLog2});
2876 auto NEG = IC.Builder.CreateIntrinsic(
2877 Intrinsic::aarch64_sve_neg, {ASRD->getType()}, {ASRD, Pred, ASRD});
2878 return IC.replaceInstUsesWith(II, NEG);
2879 }
2880
2881 return std::nullopt;
2882}
2883
2884bool SimplifyValuePattern(SmallVector<Value *> &Vec, bool AllowPoison) {
2885 size_t VecSize = Vec.size();
2886 if (VecSize == 1)
2887 return true;
2888 if (!isPowerOf2_64(VecSize))
2889 return false;
2890 size_t HalfVecSize = VecSize / 2;
2891
2892 for (auto LHS = Vec.begin(), RHS = Vec.begin() + HalfVecSize;
2893 RHS != Vec.end(); LHS++, RHS++) {
2894 if (*LHS != nullptr && *RHS != nullptr) {
2895 if (*LHS == *RHS)
2896 continue;
2897 else
2898 return false;
2899 }
2900 if (!AllowPoison)
2901 return false;
2902 if (*LHS == nullptr && *RHS != nullptr)
2903 *LHS = *RHS;
2904 }
2905
2906 Vec.resize(HalfVecSize);
2907 SimplifyValuePattern(Vec, AllowPoison);
2908 return true;
2909}
2910
2911// Try to simplify dupqlane patterns like dupqlane(f32 A, f32 B, f32 A, f32 B)
2912// to dupqlane(f64(C)) where C is A concatenated with B
2913static std::optional<Instruction *> instCombineSVEDupqLane(InstCombiner &IC,
2914 IntrinsicInst &II) {
2915 Value *CurrentInsertElt = nullptr, *Default = nullptr;
2916 if (!match(II.getOperand(0),
2918 m_Value(Default), m_Value(CurrentInsertElt), m_Value())) ||
2919 !isa<FixedVectorType>(CurrentInsertElt->getType()))
2920 return std::nullopt;
2921 auto IIScalableTy = cast<ScalableVectorType>(II.getType());
2922
2923 // Insert the scalars into a container ordered by InsertElement index
2924 SmallVector<Value *> Elts(IIScalableTy->getMinNumElements(), nullptr);
2925 while (auto InsertElt = dyn_cast<InsertElementInst>(CurrentInsertElt)) {
2926 auto Idx = cast<ConstantInt>(InsertElt->getOperand(2));
2927 Elts[Idx->getValue().getZExtValue()] = InsertElt->getOperand(1);
2928 CurrentInsertElt = InsertElt->getOperand(0);
2929 }
2930
2931 bool AllowPoison =
2932 isa<PoisonValue>(CurrentInsertElt) && isa<PoisonValue>(Default);
2933 if (!SimplifyValuePattern(Elts, AllowPoison))
2934 return std::nullopt;
2935
2936 // Rebuild the simplified chain of InsertElements. e.g. (a, b, a, b) as (a, b)
2937 Value *InsertEltChain = PoisonValue::get(CurrentInsertElt->getType());
2938 for (size_t I = 0; I < Elts.size(); I++) {
2939 if (Elts[I] == nullptr)
2940 continue;
2941 InsertEltChain = IC.Builder.CreateInsertElement(InsertEltChain, Elts[I],
2942 IC.Builder.getInt64(I));
2943 }
2944 if (InsertEltChain == nullptr)
2945 return std::nullopt;
2946
2947 // Splat the simplified sequence, e.g. (f16 a, f16 b, f16 c, f16 d) as one i64
2948 // value or (f16 a, f16 b) as one i32 value. This requires an InsertSubvector
2949 // be bitcast to a type wide enough to fit the sequence, be splatted, and then
2950 // be narrowed back to the original type.
2951 unsigned PatternWidth = IIScalableTy->getScalarSizeInBits() * Elts.size();
2952 unsigned PatternElementCount = IIScalableTy->getScalarSizeInBits() *
2953 IIScalableTy->getMinNumElements() /
2954 PatternWidth;
2955
2956 IntegerType *WideTy = IC.Builder.getIntNTy(PatternWidth);
2957 auto *WideScalableTy = ScalableVectorType::get(WideTy, PatternElementCount);
2958 auto *WideShuffleMaskTy =
2959 ScalableVectorType::get(IC.Builder.getInt32Ty(), PatternElementCount);
2960
2961 auto InsertSubvector = IC.Builder.CreateInsertVector(
2962 II.getType(), PoisonValue::get(II.getType()), InsertEltChain,
2963 uint64_t(0));
2964 auto WideBitcast =
2965 IC.Builder.CreateBitOrPointerCast(InsertSubvector, WideScalableTy);
2966 auto WideShuffleMask = ConstantAggregateZero::get(WideShuffleMaskTy);
2967 auto WideShuffle = IC.Builder.CreateShuffleVector(
2968 WideBitcast, PoisonValue::get(WideScalableTy), WideShuffleMask);
2969 auto NarrowBitcast =
2970 IC.Builder.CreateBitOrPointerCast(WideShuffle, II.getType());
2971
2972 return IC.replaceInstUsesWith(II, NarrowBitcast);
2973}
2974
2975static std::optional<Instruction *> instCombineMaxMinNM(InstCombiner &IC,
2976 IntrinsicInst &II) {
2977 Value *A = II.getArgOperand(0);
2978 Value *B = II.getArgOperand(1);
2979 if (A == B)
2980 return IC.replaceInstUsesWith(II, A);
2981
2982 return std::nullopt;
2983}
2984
2985static std::optional<Instruction *> instCombineSVESrshl(InstCombiner &IC,
2986 IntrinsicInst &II) {
2987 Value *Pred = II.getOperand(0);
2988 Value *Vec = II.getOperand(1);
2989 Value *Shift = II.getOperand(2);
2990
2991 // Convert SRSHL into the simpler LSL intrinsic when fed by an ABS intrinsic.
2992 Value *AbsPred, *MergedValue;
2994 m_Value(MergedValue), m_Value(AbsPred), m_Value())) &&
2996 m_Value(MergedValue), m_Value(AbsPred), m_Value())))
2997
2998 return std::nullopt;
2999
3000 // Transform is valid if any of the following are true:
3001 // * The ABS merge value is an undef or non-negative
3002 // * The ABS predicate is all active
3003 // * The ABS predicate and the SRSHL predicates are the same
3004 if (!isa<UndefValue>(MergedValue) && !match(MergedValue, m_NonNegative()) &&
3005 AbsPred != Pred && !isAllActivePredicate(AbsPred))
3006 return std::nullopt;
3007
3008 // Only valid when the shift amount is non-negative, otherwise the rounding
3009 // behaviour of SRSHL cannot be ignored.
3010 if (!match(Shift, m_NonNegative()))
3011 return std::nullopt;
3012
3013 auto LSL = IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_lsl,
3014 {II.getType()}, {Pred, Vec, Shift});
3015
3016 return IC.replaceInstUsesWith(II, LSL);
3017}
3018
3019static std::optional<Instruction *> instCombineSVEInsr(InstCombiner &IC,
3020 IntrinsicInst &II) {
3021 Value *Vec = II.getOperand(0);
3022
3023 if (getSplatValue(Vec) == II.getOperand(1))
3024 return IC.replaceInstUsesWith(II, Vec);
3025
3026 return std::nullopt;
3027}
3028
3029static std::optional<Instruction *> instCombineDMB(InstCombiner &IC,
3030 IntrinsicInst &II) {
3031 // If this barrier is post-dominated by identical one we can remove it
3032 auto *NI = II.getNextNode();
3033 unsigned LookaheadThreshold = DMBLookaheadThreshold;
3034 auto CanSkipOver = [](Instruction *I) {
3035 return !I->mayReadOrWriteMemory() && !I->mayHaveSideEffects();
3036 };
3037 while (LookaheadThreshold-- && CanSkipOver(NI)) {
3038 auto *NIBB = NI->getParent();
3039 NI = NI->getNextNode();
3040 if (!NI) {
3041 if (auto *SuccBB = NIBB->getUniqueSuccessor())
3042 NI = &*SuccBB->getFirstNonPHIOrDbgOrLifetime();
3043 else
3044 break;
3045 }
3046 }
3047 auto *NextII = dyn_cast_or_null<IntrinsicInst>(NI);
3048 if (NextII && II.isIdenticalTo(NextII))
3049 return IC.eraseInstFromFunction(II);
3050
3051 return std::nullopt;
3052}
3053
3054static std::optional<Instruction *> instCombineWhilelo(InstCombiner &IC,
3055 IntrinsicInst &II) {
3056 return IC.replaceInstUsesWith(
3057 II,
3058 IC.Builder.CreateIntrinsic(Intrinsic::get_active_lane_mask,
3059 {II.getType(), II.getOperand(0)->getType()},
3060 {II.getOperand(0), II.getOperand(1)}));
3061}
3062
3063static std::optional<Instruction *> instCombinePTrue(InstCombiner &IC,
3064 IntrinsicInst &II) {
3065 unsigned PredPattern = cast<ConstantInt>(II.getOperand(0))->getZExtValue();
3066 // SVE vector length is a power-of-two, thus pow2 is synonymous with all.
3067 if (PredPattern == AArch64SVEPredPattern::all ||
3068 PredPattern == AArch64SVEPredPattern::pow2)
3069 return IC.replaceInstUsesWith(II, ConstantInt::getTrue(II.getType()));
3070 return std::nullopt;
3071}
3072
3073static std::optional<Instruction *> instCombineSVEUxt(InstCombiner &IC,
3075 unsigned NumBits) {
3076 Value *Passthru = II.getOperand(0);
3077 Value *Pg = II.getOperand(1);
3078 Value *Op = II.getOperand(2);
3079
3080 // Convert UXT[BHW] to AND.
3081 if (isa<UndefValue>(Passthru) || isAllActivePredicate(Pg)) {
3082 auto *Ty = cast<VectorType>(II.getType());
3083 auto MaskValue = APInt::getLowBitsSet(Ty->getScalarSizeInBits(), NumBits);
3084 auto *Mask = ConstantInt::get(Ty, MaskValue);
3085 auto *And = IC.Builder.CreateIntrinsic(Intrinsic::aarch64_sve_and_u, {Ty},
3086 {Pg, Op, Mask});
3087 return IC.replaceInstUsesWith(II, And);
3088 }
3089
3090 return std::nullopt;
3091}
3092
3093static std::optional<Instruction *>
3095 SMEAttrs FnSMEAttrs(*II.getFunction());
3096 bool IsStreaming = FnSMEAttrs.hasStreamingInterfaceOrBody();
3097 if (IsStreaming || !FnSMEAttrs.hasStreamingCompatibleInterface())
3098 return IC.replaceInstUsesWith(
3099 II, ConstantInt::getBool(II.getType(), IsStreaming));
3100 return std::nullopt;
3101}
3102
3103std::optional<Instruction *>
3105 IntrinsicInst &II) const {
3107 if (std::optional<Instruction *> I = simplifySVEIntrinsic(IC, II, IInfo))
3108 return I;
3109
3110 Intrinsic::ID IID = II.getIntrinsicID();
3111 switch (IID) {
3112 default:
3113 break;
3114 case Intrinsic::aarch64_dmb:
3115 return instCombineDMB(IC, II);
3116 case Intrinsic::aarch64_neon_fmaxnm:
3117 case Intrinsic::aarch64_neon_fminnm:
3118 return instCombineMaxMinNM(IC, II);
3119 case Intrinsic::aarch64_sve_convert_from_svbool:
3120 return instCombineConvertFromSVBool(IC, II);
3121 case Intrinsic::aarch64_sve_dup:
3122 return instCombineSVEDup(IC, II);
3123 case Intrinsic::aarch64_sve_dup_x:
3124 return instCombineSVEDupX(IC, II);
3125 case Intrinsic::aarch64_sve_cmpne:
3126 case Intrinsic::aarch64_sve_cmpne_wide:
3127 return instCombineSVECmpNE(IC, II);
3128 case Intrinsic::aarch64_sve_rdffr:
3129 return instCombineRDFFR(IC, II);
3130 case Intrinsic::aarch64_sve_lasta:
3131 case Intrinsic::aarch64_sve_lastb:
3132 return instCombineSVELast(IC, II);
3133 case Intrinsic::aarch64_sve_clasta_n:
3134 case Intrinsic::aarch64_sve_clastb_n:
3135 return instCombineSVECondLast(IC, II);
3136 case Intrinsic::aarch64_sve_cntd:
3137 return instCombineSVECntElts(IC, II, 2);
3138 case Intrinsic::aarch64_sve_cntw:
3139 return instCombineSVECntElts(IC, II, 4);
3140 case Intrinsic::aarch64_sve_cnth:
3141 return instCombineSVECntElts(IC, II, 8);
3142 case Intrinsic::aarch64_sve_cntb:
3143 return instCombineSVECntElts(IC, II, 16);
3144 case Intrinsic::aarch64_sme_cntsd:
3145 return instCombineSMECntsd(IC, II, ST);
3146 case Intrinsic::aarch64_sve_ptest_any:
3147 case Intrinsic::aarch64_sve_ptest_first:
3148 case Intrinsic::aarch64_sve_ptest_last:
3149 return instCombineSVEPTest(IC, II);
3150 case Intrinsic::aarch64_sve_fadd:
3151 return instCombineSVEVectorFAdd(IC, II);
3152 case Intrinsic::aarch64_sve_fadd_u:
3153 return instCombineSVEVectorFAddU(IC, II);
3154 case Intrinsic::aarch64_sve_fmul_u:
3155 return instCombineSVEVectorBinOp(IC, II);
3156 case Intrinsic::aarch64_sve_fsub:
3157 return instCombineSVEVectorFSub(IC, II);
3158 case Intrinsic::aarch64_sve_fsub_u:
3159 return instCombineSVEVectorFSubU(IC, II);
3160 case Intrinsic::aarch64_sve_add:
3161 return instCombineSVEVectorAdd(IC, II);
3162 case Intrinsic::aarch64_sve_add_u:
3163 return instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_mul_u,
3164 Intrinsic::aarch64_sve_mla_u>(
3165 IC, II, true);
3166 case Intrinsic::aarch64_sve_mla_u:
3167 return instCombineSVEVectorMlaU(IC, II);
3168 case Intrinsic::aarch64_sve_sub:
3169 return instCombineSVEVectorSub(IC, II);
3170 case Intrinsic::aarch64_sve_sub_u:
3171 return instCombineSVEVectorFuseMulAddSub<Intrinsic::aarch64_sve_mul_u,
3172 Intrinsic::aarch64_sve_mls_u>(
3173 IC, II, true);
3174 case Intrinsic::aarch64_sve_tbl:
3175 return instCombineSVETBL(IC, II);
3176 case Intrinsic::aarch64_sve_uunpkhi:
3177 case Intrinsic::aarch64_sve_uunpklo:
3178 case Intrinsic::aarch64_sve_sunpkhi:
3179 case Intrinsic::aarch64_sve_sunpklo:
3180 return instCombineSVEUnpack(IC, II);
3181 case Intrinsic::aarch64_sve_uzp1:
3182 return instCombineSVEUzp1(IC, II);
3183 case Intrinsic::aarch64_sve_zip1:
3184 case Intrinsic::aarch64_sve_zip2:
3185 return instCombineSVEZip(IC, II);
3186 case Intrinsic::aarch64_sve_ld1_gather_index:
3187 return instCombineLD1GatherIndex(IC, II);
3188 case Intrinsic::aarch64_sve_st1_scatter_index:
3189 return instCombineST1ScatterIndex(IC, II);
3190 case Intrinsic::aarch64_sve_ld1:
3191 return instCombineSVELD1(IC, II, DL);
3192 case Intrinsic::aarch64_sve_st1:
3193 return instCombineSVEST1(IC, II, DL);
3194 case Intrinsic::aarch64_sve_sdiv:
3195 return instCombineSVESDIV(IC, II);
3196 case Intrinsic::aarch64_sve_sel:
3197 return instCombineSVESel(IC, II);
3198 case Intrinsic::aarch64_sve_srshl:
3199 return instCombineSVESrshl(IC, II);
3200 case Intrinsic::aarch64_sve_dupq_lane:
3201 return instCombineSVEDupqLane(IC, II);
3202 case Intrinsic::aarch64_sve_insr:
3203 return instCombineSVEInsr(IC, II);
3204 case Intrinsic::aarch64_sve_whilelo:
3205 return instCombineWhilelo(IC, II);
3206 case Intrinsic::aarch64_sve_ptrue:
3207 return instCombinePTrue(IC, II);
3208 case Intrinsic::aarch64_sve_uxtb:
3209 return instCombineSVEUxt(IC, II, 8);
3210 case Intrinsic::aarch64_sve_uxth:
3211 return instCombineSVEUxt(IC, II, 16);
3212 case Intrinsic::aarch64_sve_uxtw:
3213 return instCombineSVEUxt(IC, II, 32);
3214 case Intrinsic::aarch64_sme_in_streaming_mode:
3215 return instCombineInStreamingMode(IC, II);
3216 }
3217
3218 return std::nullopt;
3219}
3220
3222 InstCombiner &IC, IntrinsicInst &II, APInt OrigDemandedElts,
3223 APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3,
3224 std::function<void(Instruction *, unsigned, APInt, APInt &)>
3225 SimplifyAndSetOp) const {
3226 switch (II.getIntrinsicID()) {
3227 default:
3228 break;
3229 case Intrinsic::aarch64_neon_fcvtxn:
3230 case Intrinsic::aarch64_neon_rshrn:
3231 case Intrinsic::aarch64_neon_sqrshrn:
3232 case Intrinsic::aarch64_neon_sqrshrun:
3233 case Intrinsic::aarch64_neon_sqshrn:
3234 case Intrinsic::aarch64_neon_sqshrun:
3235 case Intrinsic::aarch64_neon_sqxtn:
3236 case Intrinsic::aarch64_neon_sqxtun:
3237 case Intrinsic::aarch64_neon_uqrshrn:
3238 case Intrinsic::aarch64_neon_uqshrn:
3239 case Intrinsic::aarch64_neon_uqxtn:
3240 SimplifyAndSetOp(&II, 0, OrigDemandedElts, UndefElts);
3241 break;
3242 }
3243
3244 return std::nullopt;
3245}
3246
3248 return ST->isSVEAvailable() || (ST->isSVEorStreamingSVEAvailable() &&
3250}
3251
3254 switch (K) {
3256 return TypeSize::getFixed(64);
3258 if (ST->useSVEForFixedLengthVectors() &&
3259 (ST->isSVEAvailable() || EnableFixedwidthAutovecInStreamingMode))
3260 return TypeSize::getFixed(
3261 std::max(ST->getMinSVEVectorSizeInBits(), 128u));
3262 else if (ST->isNeonAvailable())
3263 return TypeSize::getFixed(128);
3264 else
3265 return TypeSize::getFixed(0);
3267 if (ST->isSVEAvailable() || (ST->isSVEorStreamingSVEAvailable() &&
3269 return TypeSize::getScalable(128);
3270 else
3271 return TypeSize::getScalable(0);
3272 }
3273 llvm_unreachable("Unsupported register kind");
3274}
3275
3276bool AArch64TTIImpl::isSingleExtWideningInstruction(
3277 unsigned Opcode, Type *DstTy, ArrayRef<const Value *> Args,
3278 Type *SrcOverrideTy) const {
3279 // A helper that returns a vector type from the given type. The number of
3280 // elements in type Ty determines the vector width.
3281 auto toVectorTy = [&](Type *ArgTy) {
3282 return VectorType::get(ArgTy->getScalarType(),
3283 cast<VectorType>(DstTy)->getElementCount());
3284 };
3285
3286 // Exit early if DstTy is not a vector type whose elements are one of [i16,
3287 // i32, i64]. SVE doesn't generally have the same set of instructions to
3288 // perform an extend with the add/sub/mul. There are SMULLB style
3289 // instructions, but they operate on top/bottom, requiring some sort of lane
3290 // interleaving to be used with zext/sext.
3291 unsigned DstEltSize = DstTy->getScalarSizeInBits();
3292 if (!useNeonVector(DstTy) || Args.size() != 2 ||
3293 (DstEltSize != 16 && DstEltSize != 32 && DstEltSize != 64))
3294 return false;
3295
3296 Type *SrcTy = SrcOverrideTy;
3297 switch (Opcode) {
3298 case Instruction::Add: // UADDW(2), SADDW(2).
3299 case Instruction::Sub: { // USUBW(2), SSUBW(2).
3300 // The second operand needs to be an extend
3301 if (isa<SExtInst>(Args[1]) || isa<ZExtInst>(Args[1])) {
3302 if (!SrcTy)
3303 SrcTy =
3304 toVectorTy(cast<Instruction>(Args[1])->getOperand(0)->getType());
3305 break;
3306 }
3307
3308 if (Opcode == Instruction::Sub)
3309 return false;
3310
3311 // UADDW(2), SADDW(2) can be commutted.
3312 if (isa<SExtInst>(Args[0]) || isa<ZExtInst>(Args[0])) {
3313 if (!SrcTy)
3314 SrcTy =
3315 toVectorTy(cast<Instruction>(Args[0])->getOperand(0)->getType());
3316 break;
3317 }
3318 return false;
3319 }
3320 default:
3321 return false;
3322 }
3323
3324 // Legalize the destination type and ensure it can be used in a widening
3325 // operation.
3326 auto DstTyL = getTypeLegalizationCost(DstTy);
3327 if (!DstTyL.second.isVector() || DstEltSize != DstTy->getScalarSizeInBits())
3328 return false;
3329
3330 // Legalize the source type and ensure it can be used in a widening
3331 // operation.
3332 assert(SrcTy && "Expected some SrcTy");
3333 auto SrcTyL = getTypeLegalizationCost(SrcTy);
3334 unsigned SrcElTySize = SrcTyL.second.getScalarSizeInBits();
3335 if (!SrcTyL.second.isVector() || SrcElTySize != SrcTy->getScalarSizeInBits())
3336 return false;
3337
3338 // Get the total number of vector elements in the legalized types.
3339 InstructionCost NumDstEls =
3340 DstTyL.first * DstTyL.second.getVectorMinNumElements();
3341 InstructionCost NumSrcEls =
3342 SrcTyL.first * SrcTyL.second.getVectorMinNumElements();
3343
3344 // Return true if the legalized types have the same number of vector elements
3345 // and the destination element type size is twice that of the source type.
3346 return NumDstEls == NumSrcEls && 2 * SrcElTySize == DstEltSize;
3347}
3348
3349Type *AArch64TTIImpl::isBinExtWideningInstruction(unsigned Opcode, Type *DstTy,
3351 Type *SrcOverrideTy) const {
3352 if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
3353 Opcode != Instruction::Mul)
3354 return nullptr;
3355
3356 // Exit early if DstTy is not a vector type whose elements are one of [i16,
3357 // i32, i64]. SVE doesn't generally have the same set of instructions to
3358 // perform an extend with the add/sub/mul. There are SMULLB style
3359 // instructions, but they operate on top/bottom, requiring some sort of lane
3360 // interleaving to be used with zext/sext.
3361 unsigned DstEltSize = DstTy->getScalarSizeInBits();
3362 if (!useNeonVector(DstTy) || Args.size() != 2 ||
3363 (DstEltSize != 16 && DstEltSize != 32 && DstEltSize != 64))
3364 return nullptr;
3365
3366 auto getScalarSizeWithOverride = [&](const Value *V) {
3367 if (SrcOverrideTy)
3368 return SrcOverrideTy->getScalarSizeInBits();
3369 return cast<Instruction>(V)
3370 ->getOperand(0)
3371 ->getType()
3372 ->getScalarSizeInBits();
3373 };
3374
3375 unsigned MaxEltSize = 0;
3376 if ((isa<SExtInst>(Args[0]) && isa<SExtInst>(Args[1])) ||
3377 (isa<ZExtInst>(Args[0]) && isa<ZExtInst>(Args[1]))) {
3378 unsigned EltSize0 = getScalarSizeWithOverride(Args[0]);
3379 unsigned EltSize1 = getScalarSizeWithOverride(Args[1]);
3380 MaxEltSize = std::max(EltSize0, EltSize1);
3381 } else if (isa<SExtInst, ZExtInst>(Args[0]) &&
3382 isa<SExtInst, ZExtInst>(Args[1])) {
3383 unsigned EltSize0 = getScalarSizeWithOverride(Args[0]);
3384 unsigned EltSize1 = getScalarSizeWithOverride(Args[1]);
3385 // mul(sext, zext) will become smull(sext, zext) if the extends are large
3386 // enough.
3387 if (EltSize0 >= DstEltSize / 2 || EltSize1 >= DstEltSize / 2)
3388 return nullptr;
3389 MaxEltSize = DstEltSize / 2;
3390 } else if (Opcode == Instruction::Mul &&
3391 (isa<ZExtInst>(Args[0]) || isa<ZExtInst>(Args[1]))) {
3392 // If one of the operands is a Zext and the other has enough zero bits
3393 // to be treated as unsigned, we can still generate a umull, meaning the
3394 // zext is free.
3395 KnownBits Known =
3396 computeKnownBits(isa<ZExtInst>(Args[0]) ? Args[1] : Args[0], DL);
3397 if (Args[0]->getType()->getScalarSizeInBits() -
3398 Known.Zero.countLeadingOnes() >
3399 DstTy->getScalarSizeInBits() / 2)
3400 return nullptr;
3401
3402 MaxEltSize =
3403 getScalarSizeWithOverride(isa<ZExtInst>(Args[0]) ? Args[0] : Args[1]);
3404 } else
3405 return nullptr;
3406
3407 if (MaxEltSize * 2 > DstEltSize)
3408 return nullptr;
3409
3410 Type *ExtTy = DstTy->getWithNewBitWidth(MaxEltSize * 2);
3411 if (ExtTy->getPrimitiveSizeInBits() <= 64)
3412 return nullptr;
3413 return ExtTy;
3414}
3415
3416// s/urhadd instructions implement the following pattern, making the
3417// extends free:
3418// %x = add ((zext i8 -> i16), 1)
3419// %y = (zext i8 -> i16)
3420// trunc i16 (lshr (add %x, %y), 1) -> i8
3421//
3423 Type *Src) const {
3424 // The source should be a legal vector type.
3425 if (!Src->isVectorTy() || !TLI->isTypeLegal(TLI->getValueType(DL, Src)) ||
3426 (Src->isScalableTy() && !ST->hasSVE2()))
3427 return false;
3428
3429 if (ExtUser->getOpcode() != Instruction::Add || !ExtUser->hasOneUse())
3430 return false;
3431
3432 // Look for trunc/shl/add before trying to match the pattern.
3433 const Instruction *Add = ExtUser;
3434 auto *AddUser =
3435 dyn_cast_or_null<Instruction>(Add->getUniqueUndroppableUser());
3436 if (AddUser && AddUser->getOpcode() == Instruction::Add)
3437 Add = AddUser;
3438
3439 auto *Shr = dyn_cast_or_null<Instruction>(Add->getUniqueUndroppableUser());
3440 if (!Shr || Shr->getOpcode() != Instruction::LShr)
3441 return false;
3442
3443 auto *Trunc = dyn_cast_or_null<Instruction>(Shr->getUniqueUndroppableUser());
3444 if (!Trunc || Trunc->getOpcode() != Instruction::Trunc ||
3445 Src->getScalarSizeInBits() !=
3446 cast<CastInst>(Trunc)->getDestTy()->getScalarSizeInBits())
3447 return false;
3448
3449 // Try to match the whole pattern. Ext could be either the first or second
3450 // m_ZExtOrSExt matched.
3451 Instruction *Ex1, *Ex2;
3452 if (!(match(Add, m_c_Add(m_Instruction(Ex1),
3453 m_c_Add(m_Instruction(Ex2), m_One())))))
3454 return false;
3455
3456 // Ensure both extends are of the same type
3457 if (match(Ex1, m_ZExtOrSExt(m_Value())) &&
3458 Ex1->getOpcode() == Ex2->getOpcode())
3459 return true;
3460
3461 return false;
3462}
3463
3465 Type *Src,
3468 const Instruction *I) const {
3469 int ISD = TLI->InstructionOpcodeToISD(Opcode);
3470 assert(ISD && "Invalid opcode");
3471 // If the cast is observable, and it is used by a widening instruction (e.g.,
3472 // uaddl, saddw, etc.), it may be free.
3473 if (I && I->hasOneUser()) {
3474 auto *SingleUser = cast<Instruction>(*I->user_begin());
3475 SmallVector<const Value *, 4> Operands(SingleUser->operand_values());
3476 if (Type *ExtTy = isBinExtWideningInstruction(
3477 SingleUser->getOpcode(), Dst, Operands,
3478 Src != I->getOperand(0)->getType() ? Src : nullptr)) {
3479 // The cost from Src->Src*2 needs to be added if required, the cost from
3480 // Src*2->ExtTy is free.
3481 if (ExtTy->getScalarSizeInBits() > Src->getScalarSizeInBits() * 2) {
3482 Type *DoubleSrcTy =
3483 Src->getWithNewBitWidth(Src->getScalarSizeInBits() * 2);
3484 return getCastInstrCost(Opcode, DoubleSrcTy, Src,
3486 }
3487
3488 return 0;
3489 }
3490
3491 if (isSingleExtWideningInstruction(
3492 SingleUser->getOpcode(), Dst, Operands,
3493 Src != I->getOperand(0)->getType() ? Src : nullptr)) {
3494 // For adds only count the second operand as free if both operands are
3495 // extends but not the same operation. (i.e both operands are not free in
3496 // add(sext, zext)).
3497 if (SingleUser->getOpcode() == Instruction::Add) {
3498 if (I == SingleUser->getOperand(1) ||
3499 (isa<CastInst>(SingleUser->getOperand(1)) &&
3500 cast<CastInst>(SingleUser->getOperand(1))->getOpcode() == Opcode))
3501 return 0;
3502 } else {
3503 // Others are free so long as isSingleExtWideningInstruction
3504 // returned true.
3505 return 0;
3506 }
3507 }
3508
3509 // The cast will be free for the s/urhadd instructions
3510 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
3511 isExtPartOfAvgExpr(SingleUser, Dst, Src))
3512 return 0;
3513 }
3514
3515 EVT SrcTy = TLI->getValueType(DL, Src);
3516 EVT DstTy = TLI->getValueType(DL, Dst);
3517
3518 if (!SrcTy.isSimple() || !DstTy.isSimple())
3519 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
3520
3521 // For the moment we do not have lowering for SVE1-only fptrunc f64->bf16 as
3522 // we use fcvtx under SVE2. Give them invalid costs.
3523 if (!ST->hasSVE2() && !ST->isStreamingSVEAvailable() &&
3524 ISD == ISD::FP_ROUND && SrcTy.isScalableVector() &&
3525 DstTy.getScalarType() == MVT::bf16 && SrcTy.getScalarType() == MVT::f64)
3527
3528 static const TypeConversionCostTblEntry BF16Tbl[] = {
3529 {ISD::FP_ROUND, MVT::bf16, MVT::f32, 1}, // bfcvt
3530 {ISD::FP_ROUND, MVT::bf16, MVT::f64, 1}, // bfcvt
3531 {ISD::FP_ROUND, MVT::v4bf16, MVT::v4f32, 1}, // bfcvtn
3532 {ISD::FP_ROUND, MVT::v8bf16, MVT::v8f32, 2}, // bfcvtn+bfcvtn2
3533 {ISD::FP_ROUND, MVT::v2bf16, MVT::v2f64, 2}, // bfcvtn+fcvtn
3534 {ISD::FP_ROUND, MVT::v4bf16, MVT::v4f64, 3}, // fcvtn+fcvtl2+bfcvtn
3535 {ISD::FP_ROUND, MVT::v8bf16, MVT::v8f64, 6}, // 2 * fcvtn+fcvtn2+bfcvtn
3536 {ISD::FP_ROUND, MVT::nxv2bf16, MVT::nxv2f32, 1}, // bfcvt
3537 {ISD::FP_ROUND, MVT::nxv4bf16, MVT::nxv4f32, 1}, // bfcvt
3538 {ISD::FP_ROUND, MVT::nxv8bf16, MVT::nxv8f32, 3}, // bfcvt+bfcvt+uzp1
3539 {ISD::FP_ROUND, MVT::nxv2bf16, MVT::nxv2f64, 2}, // fcvtx+bfcvt
3540 {ISD::FP_ROUND, MVT::nxv4bf16, MVT::nxv4f64, 5}, // 2*fcvtx+2*bfcvt+uzp1
3541 {ISD::FP_ROUND, MVT::nxv8bf16, MVT::nxv8f64, 11}, // 4*fcvt+4*bfcvt+3*uzp
3542 };
3543
3544 if (ST->hasBF16())
3545 if (const auto *Entry = ConvertCostTableLookup(
3546 BF16Tbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
3547 return Entry->Cost;
3548
3549 // We have to estimate a cost of fixed length operation upon
3550 // SVE registers(operations) with the number of registers required
3551 // for a fixed type to be represented upon SVE registers.
3552 EVT WiderTy = SrcTy.bitsGT(DstTy) ? SrcTy : DstTy;
3553 if (SrcTy.isFixedLengthVector() && DstTy.isFixedLengthVector() &&
3554 SrcTy.getVectorNumElements() == DstTy.getVectorNumElements() &&
3555 ST->useSVEForFixedLengthVectors(WiderTy)) {
3556 std::pair<InstructionCost, MVT> LT =
3557 getTypeLegalizationCost(WiderTy.getTypeForEVT(Dst->getContext()));
3558 unsigned NumElements =
3559 AArch64::SVEBitsPerBlock / LT.second.getScalarSizeInBits();
3560 return LT.first *
3562 Opcode,
3563 ScalableVectorType::get(Dst->getScalarType(), NumElements),
3564 ScalableVectorType::get(Src->getScalarType(), NumElements), CCH,
3565 CostKind, I);
3566 }
3567
3568 // Symbolic constants for the SVE sitofp/uitofp entries in the table below
3569 // The cost of unpacking twice is artificially increased for now in order
3570 // to avoid regressions against NEON, which will use tbl instructions directly
3571 // instead of multiple layers of [s|u]unpk[lo|hi].
3572 // We use the unpacks in cases where the destination type is illegal and
3573 // requires splitting of the input, even if the input type itself is legal.
3574 const unsigned int SVE_EXT_COST = 1;
3575 const unsigned int SVE_FCVT_COST = 1;
3576 const unsigned int SVE_UNPACK_ONCE = 4;
3577 const unsigned int SVE_UNPACK_TWICE = 16;
3578
3579 static const TypeConversionCostTblEntry ConversionTbl[] = {
3580 {ISD::TRUNCATE, MVT::v2i8, MVT::v2i64, 1}, // xtn
3581 {ISD::TRUNCATE, MVT::v2i16, MVT::v2i64, 1}, // xtn
3582 {ISD::TRUNCATE, MVT::v2i32, MVT::v2i64, 1}, // xtn
3583 {ISD::TRUNCATE, MVT::v4i8, MVT::v4i32, 1}, // xtn
3584 {ISD::TRUNCATE, MVT::v4i8, MVT::v4i64, 3}, // 2 xtn + 1 uzp1
3585 {ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1}, // xtn
3586 {ISD::TRUNCATE, MVT::v4i16, MVT::v4i64, 2}, // 1 uzp1 + 1 xtn
3587 {ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 1}, // 1 uzp1
3588 {ISD::TRUNCATE, MVT::v8i8, MVT::v8i16, 1}, // 1 xtn
3589 {ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 2}, // 1 uzp1 + 1 xtn
3590 {ISD::TRUNCATE, MVT::v8i8, MVT::v8i64, 4}, // 3 x uzp1 + xtn
3591 {ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 1}, // 1 uzp1
3592 {ISD::TRUNCATE, MVT::v8i16, MVT::v8i64, 3}, // 3 x uzp1
3593 {ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 2}, // 2 x uzp1
3594 {ISD::TRUNCATE, MVT::v16i8, MVT::v16i16, 1}, // uzp1
3595 {ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 3}, // (2 + 1) x uzp1
3596 {ISD::TRUNCATE, MVT::v16i8, MVT::v16i64, 7}, // (4 + 2 + 1) x uzp1
3597 {ISD::TRUNCATE, MVT::v16i16, MVT::v16i32, 2}, // 2 x uzp1
3598 {ISD::TRUNCATE, MVT::v16i16, MVT::v16i64, 6}, // (4 + 2) x uzp1
3599 {ISD::TRUNCATE, MVT::v16i32, MVT::v16i64, 4}, // 4 x uzp1
3600
3601 // Truncations on nxvmiN
3602 {ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i8, 2},
3603 {ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i16, 2},
3604 {ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i32, 2},
3605 {ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i64, 2},
3606 {ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i8, 2},
3607 {ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i16, 2},
3608 {ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i32, 2},
3609 {ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i64, 5},
3610 {ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i8, 2},
3611 {ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i16, 2},
3612 {ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i32, 5},
3613 {ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i64, 11},
3614 {ISD::TRUNCATE, MVT::nxv16i1, MVT::nxv16i8, 2},
3615 {ISD::TRUNCATE, MVT::nxv2i8, MVT::nxv2i16, 0},
3616 {ISD::TRUNCATE, MVT::nxv2i8, MVT::nxv2i32, 0},
3617 {ISD::TRUNCATE, MVT::nxv2i8, MVT::nxv2i64, 0},
3618 {ISD::TRUNCATE, MVT::nxv2i16, MVT::nxv2i32, 0},
3619 {ISD::TRUNCATE, MVT::nxv2i16, MVT::nxv2i64, 0},
3620 {ISD::TRUNCATE, MVT::nxv2i32, MVT::nxv2i64, 0},
3621 {ISD::TRUNCATE, MVT::nxv4i8, MVT::nxv4i16, 0},
3622 {ISD::TRUNCATE, MVT::nxv4i8, MVT::nxv4i32, 0},
3623 {ISD::TRUNCATE, MVT::nxv4i8, MVT::nxv4i64, 1},
3624 {ISD::TRUNCATE, MVT::nxv4i16, MVT::nxv4i32, 0},
3625 {ISD::TRUNCATE, MVT::nxv4i16, MVT::nxv4i64, 1},
3626 {ISD::TRUNCATE, MVT::nxv4i32, MVT::nxv4i64, 1},
3627 {ISD::TRUNCATE, MVT::nxv8i8, MVT::nxv8i16, 0},
3628 {ISD::TRUNCATE, MVT::nxv8i8, MVT::nxv8i32, 1},
3629 {ISD::TRUNCATE, MVT::nxv8i8, MVT::nxv8i64, 3},
3630 {ISD::TRUNCATE, MVT::nxv8i16, MVT::nxv8i32, 1},
3631 {ISD::TRUNCATE, MVT::nxv8i16, MVT::nxv8i64, 3},
3632 {ISD::TRUNCATE, MVT::nxv16i8, MVT::nxv16i16, 1},
3633 {ISD::TRUNCATE, MVT::nxv16i8, MVT::nxv16i32, 3},
3634 {ISD::TRUNCATE, MVT::nxv16i8, MVT::nxv16i64, 7},
3635
3636 // The number of shll instructions for the extension.
3637 {ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3},
3638 {ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3},
3639 {ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 2},
3640 {ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 2},
3641 {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3},
3642 {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3},
3643 {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 2},
3644 {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 2},
3645 {ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7},
3646 {ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7},
3647 {ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6},
3648 {ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6},
3649 {ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2},
3650 {ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2},
3651 {ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6},
3652 {ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6},
3653
3654 // FP Ext and trunc
3655 {ISD::FP_EXTEND, MVT::f64, MVT::f32, 1}, // fcvt
3656 {ISD::FP_EXTEND, MVT::v2f64, MVT::v2f32, 1}, // fcvtl
3657 {ISD::FP_EXTEND, MVT::v4f64, MVT::v4f32, 2}, // fcvtl+fcvtl2
3658 // FP16
3659 {ISD::FP_EXTEND, MVT::f32, MVT::f16, 1}, // fcvt
3660 {ISD::FP_EXTEND, MVT::f64, MVT::f16, 1}, // fcvt
3661 {ISD::FP_EXTEND, MVT::v4f32, MVT::v4f16, 1}, // fcvtl
3662 {ISD::FP_EXTEND, MVT::v8f32, MVT::v8f16, 2}, // fcvtl+fcvtl2
3663 {ISD::FP_EXTEND, MVT::v2f64, MVT::v2f16, 2}, // fcvtl+fcvtl
3664 {ISD::FP_EXTEND, MVT::v4f64, MVT::v4f16, 3}, // fcvtl+fcvtl2+fcvtl
3665 {ISD::FP_EXTEND, MVT::v8f64, MVT::v8f16, 6}, // 2 * fcvtl+fcvtl2+fcvtl
3666 // BF16 (uses shift)
3667 {ISD::FP_EXTEND, MVT::f32, MVT::bf16, 1}, // shl
3668 {ISD::FP_EXTEND, MVT::f64, MVT::bf16, 2}, // shl+fcvt
3669 {ISD::FP_EXTEND, MVT::v4f32, MVT::v4bf16, 1}, // shll
3670 {ISD::FP_EXTEND, MVT::v8f32, MVT::v8bf16, 2}, // shll+shll2
3671 {ISD::FP_EXTEND, MVT::v2f64, MVT::v2bf16, 2}, // shll+fcvtl
3672 {ISD::FP_EXTEND, MVT::v4f64, MVT::v4bf16, 3}, // shll+fcvtl+fcvtl2
3673 {ISD::FP_EXTEND, MVT::v8f64, MVT::v8bf16, 6}, // 2 * shll+fcvtl+fcvtl2
3674 // FP Ext and trunc
3675 {ISD::FP_ROUND, MVT::f32, MVT::f64, 1}, // fcvt
3676 {ISD::FP_ROUND, MVT::v2f32, MVT::v2f64, 1}, // fcvtn
3677 {ISD::FP_ROUND, MVT::v4f32, MVT::v4f64, 2}, // fcvtn+fcvtn2
3678 // FP16
3679 {ISD::FP_ROUND, MVT::f16, MVT::f32, 1}, // fcvt
3680 {ISD::FP_ROUND, MVT::f16, MVT::f64, 1}, // fcvt
3681 {ISD::FP_ROUND, MVT::v4f16, MVT::v4f32, 1}, // fcvtn
3682 {ISD::FP_ROUND, MVT::v8f16, MVT::v8f32, 2}, // fcvtn+fcvtn2
3683 {ISD::FP_ROUND, MVT::v2f16, MVT::v2f64, 2}, // fcvtn+fcvtn
3684 {ISD::FP_ROUND, MVT::v4f16, MVT::v4f64, 3}, // fcvtn+fcvtn2+fcvtn
3685 {ISD::FP_ROUND, MVT::v8f16, MVT::v8f64, 6}, // 2 * fcvtn+fcvtn2+fcvtn
3686 // BF16 (more complex, with +bf16 is handled above)
3687 {ISD::FP_ROUND, MVT::bf16, MVT::f32, 8}, // Expansion is ~8 insns
3688 {ISD::FP_ROUND, MVT::bf16, MVT::f64, 9}, // fcvtn + above
3689 {ISD::FP_ROUND, MVT::v2bf16, MVT::v2f32, 8},
3690 {ISD::FP_ROUND, MVT::v4bf16, MVT::v4f32, 8},
3691 {ISD::FP_ROUND, MVT::v8bf16, MVT::v8f32, 15},
3692 {ISD::FP_ROUND, MVT::v2bf16, MVT::v2f64, 9},
3693 {ISD::FP_ROUND, MVT::v4bf16, MVT::v4f64, 10},
3694 {ISD::FP_ROUND, MVT::v8bf16, MVT::v8f64, 19},
3695
3696 // LowerVectorINT_TO_FP:
3697 {ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1},
3698 {ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1},
3699 {ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 1},
3700 {ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1},
3701 {ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1},
3702 {ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1},
3703
3704 // SVE: to nxv2f16
3705 {ISD::SINT_TO_FP, MVT::nxv2f16, MVT::nxv2i8,
3706 SVE_EXT_COST + SVE_FCVT_COST},
3707 {ISD::SINT_TO_FP, MVT::nxv2f16, MVT::nxv2i16, SVE_FCVT_COST},
3708 {ISD::SINT_TO_FP, MVT::nxv2f16, MVT::nxv2i32, SVE_FCVT_COST},
3709 {ISD::SINT_TO_FP, MVT::nxv2f16, MVT::nxv2i64, SVE_FCVT_COST},
3710 {ISD::UINT_TO_FP, MVT::nxv2f16, MVT::nxv2i8,
3711 SVE_EXT_COST + SVE_FCVT_COST},
3712 {ISD::UINT_TO_FP, MVT::nxv2f16, MVT::nxv2i16, SVE_FCVT_COST},
3713 {ISD::UINT_TO_FP, MVT::nxv2f16, MVT::nxv2i32, SVE_FCVT_COST},
3714 {ISD::UINT_TO_FP, MVT::nxv2f16, MVT::nxv2i64, SVE_FCVT_COST},
3715
3716 // SVE: to nxv4f16
3717 {ISD::SINT_TO_FP, MVT::nxv4f16, MVT::nxv4i8,
3718 SVE_EXT_COST + SVE_FCVT_COST},
3719 {ISD::SINT_TO_FP, MVT::nxv4f16, MVT::nxv4i16, SVE_FCVT_COST},
3720 {ISD::SINT_TO_FP, MVT::nxv4f16, MVT::nxv4i32, SVE_FCVT_COST},
3721 {ISD::UINT_TO_FP, MVT::nxv4f16, MVT::nxv4i8,
3722 SVE_EXT_COST + SVE_FCVT_COST},
3723 {ISD::UINT_TO_FP, MVT::nxv4f16, MVT::nxv4i16, SVE_FCVT_COST},
3724 {ISD::UINT_TO_FP, MVT::nxv4f16, MVT::nxv4i32, SVE_FCVT_COST},
3725
3726 // SVE: to nxv8f16
3727 {ISD::SINT_TO_FP, MVT::nxv8f16, MVT::nxv8i8,
3728 SVE_EXT_COST + SVE_FCVT_COST},
3729 {ISD::SINT_TO_FP, MVT::nxv8f16, MVT::nxv8i16, SVE_FCVT_COST},
3730 {ISD::UINT_TO_FP, MVT::nxv8f16, MVT::nxv8i8,
3731 SVE_EXT_COST + SVE_FCVT_COST},
3732 {ISD::UINT_TO_FP, MVT::nxv8f16, MVT::nxv8i16, SVE_FCVT_COST},
3733
3734 // SVE: to nxv16f16
3735 {ISD::SINT_TO_FP, MVT::nxv16f16, MVT::nxv16i8,
3736 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3737 {ISD::UINT_TO_FP, MVT::nxv16f16, MVT::nxv16i8,
3738 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3739
3740 // Complex: to v2f32
3741 {ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3},
3742 {ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 3},
3743 {ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3},
3744 {ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 3},
3745
3746 // SVE: to nxv2f32
3747 {ISD::SINT_TO_FP, MVT::nxv2f32, MVT::nxv2i8,
3748 SVE_EXT_COST + SVE_FCVT_COST},
3749 {ISD::SINT_TO_FP, MVT::nxv2f32, MVT::nxv2i16, SVE_FCVT_COST},
3750 {ISD::SINT_TO_FP, MVT::nxv2f32, MVT::nxv2i32, SVE_FCVT_COST},
3751 {ISD::SINT_TO_FP, MVT::nxv2f32, MVT::nxv2i64, SVE_FCVT_COST},
3752 {ISD::UINT_TO_FP, MVT::nxv2f32, MVT::nxv2i8,
3753 SVE_EXT_COST + SVE_FCVT_COST},
3754 {ISD::UINT_TO_FP, MVT::nxv2f32, MVT::nxv2i16, SVE_FCVT_COST},
3755 {ISD::UINT_TO_FP, MVT::nxv2f32, MVT::nxv2i32, SVE_FCVT_COST},
3756 {ISD::UINT_TO_FP, MVT::nxv2f32, MVT::nxv2i64, SVE_FCVT_COST},
3757
3758 // Complex: to v4f32
3759 {ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 4},
3760 {ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2},
3761 {ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3},
3762 {ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2},
3763
3764 // SVE: to nxv4f32
3765 {ISD::SINT_TO_FP, MVT::nxv4f32, MVT::nxv4i8,
3766 SVE_EXT_COST + SVE_FCVT_COST},
3767 {ISD::SINT_TO_FP, MVT::nxv4f32, MVT::nxv4i16, SVE_FCVT_COST},
3768 {ISD::SINT_TO_FP, MVT::nxv4f32, MVT::nxv4i32, SVE_FCVT_COST},
3769 {ISD::UINT_TO_FP, MVT::nxv4f32, MVT::nxv4i8,
3770 SVE_EXT_COST + SVE_FCVT_COST},
3771 {ISD::UINT_TO_FP, MVT::nxv4f32, MVT::nxv4i16, SVE_FCVT_COST},
3772 {ISD::SINT_TO_FP, MVT::nxv4f32, MVT::nxv4i32, SVE_FCVT_COST},
3773
3774 // Complex: to v8f32
3775 {ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8, 10},
3776 {ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4},
3777 {ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 10},
3778 {ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4},
3779
3780 // SVE: to nxv8f32
3781 {ISD::SINT_TO_FP, MVT::nxv8f32, MVT::nxv8i8,
3782 SVE_EXT_COST + SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3783 {ISD::SINT_TO_FP, MVT::nxv8f32, MVT::nxv8i16,
3784 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3785 {ISD::UINT_TO_FP, MVT::nxv8f32, MVT::nxv8i8,
3786 SVE_EXT_COST + SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3787 {ISD::UINT_TO_FP, MVT::nxv8f32, MVT::nxv8i16,
3788 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3789
3790 // SVE: to nxv16f32
3791 {ISD::SINT_TO_FP, MVT::nxv16f32, MVT::nxv16i8,
3792 SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
3793 {ISD::UINT_TO_FP, MVT::nxv16f32, MVT::nxv16i8,
3794 SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
3795
3796 // Complex: to v16f32
3797 {ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i8, 21},
3798 {ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i8, 21},
3799
3800 // Complex: to v2f64
3801 {ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 4},
3802 {ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 4},
3803 {ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2},
3804 {ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 4},
3805 {ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 4},
3806 {ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2},
3807
3808 // SVE: to nxv2f64
3809 {ISD::SINT_TO_FP, MVT::nxv2f64, MVT::nxv2i8,
3810 SVE_EXT_COST + SVE_FCVT_COST},
3811 {ISD::SINT_TO_FP, MVT::nxv2f64, MVT::nxv2i16, SVE_FCVT_COST},
3812 {ISD::SINT_TO_FP, MVT::nxv2f64, MVT::nxv2i32, SVE_FCVT_COST},
3813 {ISD::SINT_TO_FP, MVT::nxv2f64, MVT::nxv2i64, SVE_FCVT_COST},
3814 {ISD::UINT_TO_FP, MVT::nxv2f64, MVT::nxv2i8,
3815 SVE_EXT_COST + SVE_FCVT_COST},
3816 {ISD::UINT_TO_FP, MVT::nxv2f64, MVT::nxv2i16, SVE_FCVT_COST},
3817 {ISD::UINT_TO_FP, MVT::nxv2f64, MVT::nxv2i32, SVE_FCVT_COST},
3818 {ISD::UINT_TO_FP, MVT::nxv2f64, MVT::nxv2i64, SVE_FCVT_COST},
3819
3820 // Complex: to v4f64
3821 {ISD::SINT_TO_FP, MVT::v4f64, MVT::v4i32, 4},
3822 {ISD::UINT_TO_FP, MVT::v4f64, MVT::v4i32, 4},
3823
3824 // SVE: to nxv4f64
3825 {ISD::SINT_TO_FP, MVT::nxv4f64, MVT::nxv4i8,
3826 SVE_EXT_COST + SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3827 {ISD::SINT_TO_FP, MVT::nxv4f64, MVT::nxv4i16,
3828 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3829 {ISD::SINT_TO_FP, MVT::nxv4f64, MVT::nxv4i32,
3830 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3831 {ISD::UINT_TO_FP, MVT::nxv4f64, MVT::nxv4i8,
3832 SVE_EXT_COST + SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3833 {ISD::UINT_TO_FP, MVT::nxv4f64, MVT::nxv4i16,
3834 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3835 {ISD::UINT_TO_FP, MVT::nxv4f64, MVT::nxv4i32,
3836 SVE_UNPACK_ONCE + 2 * SVE_FCVT_COST},
3837
3838 // SVE: to nxv8f64
3839 {ISD::SINT_TO_FP, MVT::nxv8f64, MVT::nxv8i8,
3840 SVE_EXT_COST + SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
3841 {ISD::SINT_TO_FP, MVT::nxv8f64, MVT::nxv8i16,
3842 SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
3843 {ISD::UINT_TO_FP, MVT::nxv8f64, MVT::nxv8i8,
3844 SVE_EXT_COST + SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
3845 {ISD::UINT_TO_FP, MVT::nxv8f64, MVT::nxv8i16,
3846 SVE_UNPACK_TWICE + 4 * SVE_FCVT_COST},
3847
3848 // LowerVectorFP_TO_INT
3849 {ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f32, 1},
3850 {ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1},
3851 {ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 1},
3852 {ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f32, 1},
3853 {ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1},
3854 {ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1},
3855
3856 // Complex, from v2f32: legal type is v2i32 (no cost) or v2i64 (1 ext).
3857 {ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f32, 2},
3858 {ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f32, 1},
3859 {ISD::FP_TO_SINT, MVT::v2i8, MVT::v2f32, 1},
3860 {ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 2},
3861 {ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f32, 1},
3862 {ISD::FP_TO_UINT, MVT::v2i8, MVT::v2f32, 1},
3863
3864 // Complex, from v4f32: legal type is v4i16, 1 narrowing => ~2
3865 {ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2},
3866 {ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 2},
3867 {ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2},
3868 {ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 2},
3869
3870 // Complex, from v2f64: legal type is v2i32, 1 narrowing => ~2.
3871 {ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2},
3872 {ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f64, 2},
3873 {ISD::FP_TO_SINT, MVT::v2i8, MVT::v2f64, 2},
3874 {ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2},
3875 {ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f64, 2},
3876 {ISD::FP_TO_UINT, MVT::v2i8, MVT::v2f64, 2},
3877
3878 // Complex, from nxv2f32.
3879 {ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f32, 1},
3880 {ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f32, 1},
3881 {ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f32, 1},
3882 {ISD::FP_TO_SINT, MVT::nxv2i8, MVT::nxv2f32, 1},
3883 {ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f32, 1},
3884 {ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f32, 1},
3885 {ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f32, 1},
3886 {ISD::FP_TO_UINT, MVT::nxv2i8, MVT::nxv2f32, 1},
3887
3888 // Complex, from nxv2f64.
3889 {ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f64, 1},
3890 {ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f64, 1},
3891 {ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f64, 1},
3892 {ISD::FP_TO_SINT, MVT::nxv2i8, MVT::nxv2f64, 1},
3893 {ISD::FP_TO_SINT, MVT::nxv2i1, MVT::nxv2f64, 1},
3894 {ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f64, 1},
3895 {ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f64, 1},
3896 {ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f64, 1},
3897 {ISD::FP_TO_UINT, MVT::nxv2i8, MVT::nxv2f64, 1},
3898 {ISD::FP_TO_UINT, MVT::nxv2i1, MVT::nxv2f64, 1},
3899
3900 // Complex, from nxv4f32.
3901 {ISD::FP_TO_SINT, MVT::nxv4i64, MVT::nxv4f32, 4},
3902 {ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f32, 1},
3903 {ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f32, 1},
3904 {ISD::FP_TO_SINT, MVT::nxv4i8, MVT::nxv4f32, 1},
3905 {ISD::FP_TO_SINT, MVT::nxv4i1, MVT::nxv4f32, 1},
3906 {ISD::FP_TO_UINT, MVT::nxv4i64, MVT::nxv4f32, 4},
3907 {ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f32, 1},
3908 {ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f32, 1},
3909 {ISD::FP_TO_UINT, MVT::nxv4i8, MVT::nxv4f32, 1},
3910 {ISD::FP_TO_UINT, MVT::nxv4i1, MVT::nxv4f32, 1},
3911
3912 // Complex, from nxv8f64. Illegal -> illegal conversions not required.
3913 {ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f64, 7},
3914 {ISD::FP_TO_SINT, MVT::nxv8i8, MVT::nxv8f64, 7},
3915 {ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f64, 7},
3916 {ISD::FP_TO_UINT, MVT::nxv8i8, MVT::nxv8f64, 7},
3917
3918 // Complex, from nxv4f64. Illegal -> illegal conversions not required.
3919 {ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f64, 3},
3920 {ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f64, 3},
3921 {ISD::FP_TO_SINT, MVT::nxv4i8, MVT::nxv4f64, 3},
3922 {ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f64, 3},
3923 {ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f64, 3},
3924 {ISD::FP_TO_UINT, MVT::nxv4i8, MVT::nxv4f64, 3},
3925
3926 // Complex, from nxv8f32. Illegal -> illegal conversions not required.
3927 {ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f32, 3},
3928 {ISD::FP_TO_SINT, MVT::nxv8i8, MVT::nxv8f32, 3},
3929 {ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f32, 3},
3930 {ISD::FP_TO_UINT, MVT::nxv8i8, MVT::nxv8f32, 3},
3931
3932 // Complex, from nxv8f16.
3933 {ISD::FP_TO_SINT, MVT::nxv8i64, MVT::nxv8f16, 10},
3934 {ISD::FP_TO_SINT, MVT::nxv8i32, MVT::nxv8f16, 4},
3935 {ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f16, 1},
3936 {ISD::FP_TO_SINT, MVT::nxv8i8, MVT::nxv8f16, 1},
3937 {ISD::FP_TO_SINT, MVT::nxv8i1, MVT::nxv8f16, 1},
3938 {ISD::FP_TO_UINT, MVT::nxv8i64, MVT::nxv8f16, 10},
3939 {ISD::FP_TO_UINT, MVT::nxv8i32, MVT::nxv8f16, 4},
3940 {ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f16, 1},
3941 {ISD::FP_TO_UINT, MVT::nxv8i8, MVT::nxv8f16, 1},
3942 {ISD::FP_TO_UINT, MVT::nxv8i1, MVT::nxv8f16, 1},
3943
3944 // Complex, from nxv4f16.
3945 {ISD::FP_TO_SINT, MVT::nxv4i64, MVT::nxv4f16, 4},
3946 {ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f16, 1},
3947 {ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f16, 1},
3948 {ISD::FP_TO_SINT, MVT::nxv4i8, MVT::nxv4f16, 1},
3949 {ISD::FP_TO_UINT, MVT::nxv4i64, MVT::nxv4f16, 4},
3950 {ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f16, 1},
3951 {ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f16, 1},
3952 {ISD::FP_TO_UINT, MVT::nxv4i8, MVT::nxv4f16, 1},
3953
3954 // Complex, from nxv2f16.
3955 {ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f16, 1},
3956 {ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f16, 1},
3957 {ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f16, 1},
3958 {ISD::FP_TO_SINT, MVT::nxv2i8, MVT::nxv2f16, 1},
3959 {ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f16, 1},
3960 {ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f16, 1},
3961 {ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f16, 1},
3962 {ISD::FP_TO_UINT, MVT::nxv2i8, MVT::nxv2f16, 1},
3963
3964 // Truncate from nxvmf32 to nxvmf16.
3965 {ISD::FP_ROUND, MVT::nxv2f16, MVT::nxv2f32, 1},
3966 {ISD::FP_ROUND, MVT::nxv4f16, MVT::nxv4f32, 1},
3967 {ISD::FP_ROUND, MVT::nxv8f16, MVT::nxv8f32, 3},
3968
3969 // Truncate from nxvmf32 to nxvmbf16.
3970 {ISD::FP_ROUND, MVT::nxv2bf16, MVT::nxv2f32, 8},
3971 {ISD::FP_ROUND, MVT::nxv4bf16, MVT::nxv4f32, 8},
3972 {ISD::FP_ROUND, MVT::nxv8bf16, MVT::nxv8f32, 17},
3973
3974 // Truncate from nxvmf64 to nxvmf16.
3975 {ISD::FP_ROUND, MVT::nxv2f16, MVT::nxv2f64, 1},
3976 {ISD::FP_ROUND, MVT::nxv4f16, MVT::nxv4f64, 3},
3977 {ISD::FP_ROUND, MVT::nxv8f16, MVT::nxv8f64, 7},
3978
3979 // Truncate from nxvmf64 to nxvmbf16.
3980 {ISD::FP_ROUND, MVT::nxv2bf16, MVT::nxv2f64, 9},
3981 {ISD::FP_ROUND, MVT::nxv4bf16, MVT::nxv4f64, 19},
3982 {ISD::FP_ROUND, MVT::nxv8bf16, MVT::nxv8f64, 39},
3983
3984 // Truncate from nxvmf64 to nxvmf32.
3985 {ISD::FP_ROUND, MVT::nxv2f32, MVT::nxv2f64, 1},
3986 {ISD::FP_ROUND, MVT::nxv4f32, MVT::nxv4f64, 3},
3987 {ISD::FP_ROUND, MVT::nxv8f32, MVT::nxv8f64, 6},
3988
3989 // Extend from nxvmf16 to nxvmf32.
3990 {ISD::FP_EXTEND, MVT::nxv2f32, MVT::nxv2f16, 1},
3991 {ISD::FP_EXTEND, MVT::nxv4f32, MVT::nxv4f16, 1},
3992 {ISD::FP_EXTEND, MVT::nxv8f32, MVT::nxv8f16, 2},
3993
3994 // Extend from nxvmbf16 to nxvmf32.
3995 {ISD::FP_EXTEND, MVT::nxv2f32, MVT::nxv2bf16, 1}, // lsl
3996 {ISD::FP_EXTEND, MVT::nxv4f32, MVT::nxv4bf16, 1}, // lsl
3997 {ISD::FP_EXTEND, MVT::nxv8f32, MVT::nxv8bf16, 4}, // unpck+unpck+lsl+lsl
3998
3999 // Extend from nxvmf16 to nxvmf64.
4000 {ISD::FP_EXTEND, MVT::nxv2f64, MVT::nxv2f16, 1},
4001 {ISD::FP_EXTEND, MVT::nxv4f64, MVT::nxv4f16, 2},
4002 {ISD::FP_EXTEND, MVT::nxv8f64, MVT::nxv8f16, 4},
4003
4004 // Extend from nxvmbf16 to nxvmf64.
4005 {ISD::FP_EXTEND, MVT::nxv2f64, MVT::nxv2bf16, 2}, // lsl+fcvt
4006 {ISD::FP_EXTEND, MVT::nxv4f64, MVT::nxv4bf16, 6}, // 2*unpck+2*lsl+2*fcvt
4007 {ISD::FP_EXTEND, MVT::nxv8f64, MVT::nxv8bf16, 14}, // 6*unpck+4*lsl+4*fcvt
4008
4009 // Extend from nxvmf32 to nxvmf64.
4010 {ISD::FP_EXTEND, MVT::nxv2f64, MVT::nxv2f32, 1},
4011 {ISD::FP_EXTEND, MVT::nxv4f64, MVT::nxv4f32, 2},
4012 {ISD::FP_EXTEND, MVT::nxv8f64, MVT::nxv8f32, 6},
4013
4014 // Bitcasts from float to integer
4015 {ISD::BITCAST, MVT::nxv2f16, MVT::nxv2i16, 0},
4016 {ISD::BITCAST, MVT::nxv4f16, MVT::nxv4i16, 0},
4017 {ISD::BITCAST, MVT::nxv2f32, MVT::nxv2i32, 0},
4018
4019 // Bitcasts from integer to float
4020 {ISD::BITCAST, MVT::nxv2i16, MVT::nxv2f16, 0},
4021 {ISD::BITCAST, MVT::nxv4i16, MVT::nxv4f16, 0},
4022 {ISD::BITCAST, MVT::nxv2i32, MVT::nxv2f32, 0},
4023
4024 // Add cost for extending to illegal -too wide- scalable vectors.
4025 // zero/sign extend are implemented by multiple unpack operations,
4026 // where each operation has a cost of 1.
4027 {ISD::ZERO_EXTEND, MVT::nxv16i16, MVT::nxv16i8, 2},
4028 {ISD::ZERO_EXTEND, MVT::nxv16i32, MVT::nxv16i8, 6},
4029 {ISD::ZERO_EXTEND, MVT::nxv16i64, MVT::nxv16i8, 14},
4030 {ISD::ZERO_EXTEND, MVT::nxv8i32, MVT::nxv8i16, 2},
4031 {ISD::ZERO_EXTEND, MVT::nxv8i64, MVT::nxv8i16, 6},
4032 {ISD::ZERO_EXTEND, MVT::nxv4i64, MVT::nxv4i32, 2},
4033
4034 {ISD::SIGN_EXTEND, MVT::nxv16i16, MVT::nxv16i8, 2},
4035 {ISD::SIGN_EXTEND, MVT::nxv16i32, MVT::nxv16i8, 6},
4036 {ISD::SIGN_EXTEND, MVT::nxv16i64, MVT::nxv16i8, 14},
4037 {ISD::SIGN_EXTEND, MVT::nxv8i32, MVT::nxv8i16, 2},
4038 {ISD::SIGN_EXTEND, MVT::nxv8i64, MVT::nxv8i16, 6},
4039 {ISD::SIGN_EXTEND, MVT::nxv4i64, MVT::nxv4i32, 2},
4040 };
4041
4042 if (const auto *Entry = ConvertCostTableLookup(
4043 ConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
4044 return Entry->Cost;
4045
4046 static const TypeConversionCostTblEntry FP16Tbl[] = {
4047 {ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f16, 1}, // fcvtzs
4048 {ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f16, 1},
4049 {ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f16, 1}, // fcvtzs
4050 {ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f16, 1},
4051 {ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f16, 2}, // fcvtl+fcvtzs
4052 {ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f16, 2},
4053 {ISD::FP_TO_SINT, MVT::v8i8, MVT::v8f16, 2}, // fcvtzs+xtn
4054 {ISD::FP_TO_UINT, MVT::v8i8, MVT::v8f16, 2},
4055 {ISD::FP_TO_SINT, MVT::v8i16, MVT::v8f16, 1}, // fcvtzs
4056 {ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f16, 1},
4057 {ISD::FP_TO_SINT, MVT::v8i32, MVT::v8f16, 4}, // 2*fcvtl+2*fcvtzs
4058 {ISD::FP_TO_UINT, MVT::v8i32, MVT::v8f16, 4},
4059 {ISD::FP_TO_SINT, MVT::v16i8, MVT::v16f16, 3}, // 2*fcvtzs+xtn
4060 {ISD::FP_TO_UINT, MVT::v16i8, MVT::v16f16, 3},
4061 {ISD::FP_TO_SINT, MVT::v16i16, MVT::v16f16, 2}, // 2*fcvtzs
4062 {ISD::FP_TO_UINT, MVT::v16i16, MVT::v16f16, 2},
4063 {ISD::FP_TO_SINT, MVT::v16i32, MVT::v16f16, 8}, // 4*fcvtl+4*fcvtzs
4064 {ISD::FP_TO_UINT, MVT::v16i32, MVT::v16f16, 8},
4065 {ISD::UINT_TO_FP, MVT::v8f16, MVT::v8i8, 2}, // ushll + ucvtf
4066 {ISD::SINT_TO_FP, MVT::v8f16, MVT::v8i8, 2}, // sshll + scvtf
4067 {ISD::UINT_TO_FP, MVT::v16f16, MVT::v16i8, 4}, // 2 * ushl(2) + 2 * ucvtf
4068 {ISD::SINT_TO_FP, MVT::v16f16, MVT::v16i8, 4}, // 2 * sshl(2) + 2 * scvtf
4069 };
4070
4071 if (ST->hasFullFP16())
4072 if (const auto *Entry = ConvertCostTableLookup(
4073 FP16Tbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
4074 return Entry->Cost;
4075
4076 // INT_TO_FP of i64->f32 will scalarize, which is required to avoid
4077 // double-rounding issues.
4078 if ((ISD == ISD::SINT_TO_FP || ISD == ISD::UINT_TO_FP) &&
4079 DstTy.getScalarType() == MVT::f32 && SrcTy.getScalarSizeInBits() > 32 &&
4081 return cast<FixedVectorType>(Dst)->getNumElements() *
4082 getCastInstrCost(Opcode, Dst->getScalarType(),
4083 Src->getScalarType(), CCH, CostKind) +
4085 true, CostKind) +
4087 false, CostKind);
4088
4089 if ((ISD == ISD::ZERO_EXTEND || ISD == ISD::SIGN_EXTEND) &&
4091 ST->isSVEorStreamingSVEAvailable() &&
4092 TLI->getTypeAction(Src->getContext(), SrcTy) ==
4094 TLI->getTypeAction(Dst->getContext(), DstTy) ==
4096 // The standard behaviour in the backend for these cases is to split the
4097 // extend up into two parts:
4098 // 1. Perform an extending load or masked load up to the legal type.
4099 // 2. Extend the loaded data to the final type.
4100 std::pair<InstructionCost, MVT> SrcLT = getTypeLegalizationCost(Src);
4101 Type *LegalTy = EVT(SrcLT.second).getTypeForEVT(Src->getContext());
4103 Opcode, LegalTy, Src, CCH, CostKind, I);
4105 Opcode, Dst, LegalTy, TTI::CastContextHint::None, CostKind, I);
4106 return Part1 + Part2;
4107 }
4108
4109 // The BasicTTIImpl version only deals with CCH==TTI::CastContextHint::Normal,
4110 // but we also want to include the TTI::CastContextHint::Masked case too.
4111 if ((ISD == ISD::ZERO_EXTEND || ISD == ISD::SIGN_EXTEND) &&
4113 ST->isSVEorStreamingSVEAvailable() && TLI->isTypeLegal(DstTy))
4115
4116 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
4117}
4118
4121 VectorType *VecTy, unsigned Index,
4123
4124 // Make sure we were given a valid extend opcode.
4125 assert((Opcode == Instruction::SExt || Opcode == Instruction::ZExt) &&
4126 "Invalid opcode");
4127
4128 // We are extending an element we extract from a vector, so the source type
4129 // of the extend is the element type of the vector.
4130 auto *Src = VecTy->getElementType();
4131
4132 // Sign- and zero-extends are for integer types only.
4133 assert(isa<IntegerType>(Dst) && isa<IntegerType>(Src) && "Invalid type");
4134
4135 // Get the cost for the extract. We compute the cost (if any) for the extend
4136 // below.
4137 InstructionCost Cost = getVectorInstrCost(Instruction::ExtractElement, VecTy,
4138 CostKind, Index, nullptr, nullptr);
4139
4140 // Legalize the types.
4141 auto VecLT = getTypeLegalizationCost(VecTy);
4142 auto DstVT = TLI->getValueType(DL, Dst);
4143 auto SrcVT = TLI->getValueType(DL, Src);
4144
4145 // If the resulting type is still a vector and the destination type is legal,
4146 // we may get the extension for free. If not, get the default cost for the
4147 // extend.
4148 if (!VecLT.second.isVector() || !TLI->isTypeLegal(DstVT))
4149 return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
4150 CostKind);
4151
4152 // The destination type should be larger than the element type. If not, get
4153 // the default cost for the extend.
4154 if (DstVT.getFixedSizeInBits() < SrcVT.getFixedSizeInBits())
4155 return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
4156 CostKind);
4157
4158 switch (Opcode) {
4159 default:
4160 llvm_unreachable("Opcode should be either SExt or ZExt");
4161
4162 // For sign-extends, we only need a smov, which performs the extension
4163 // automatically.
4164 case Instruction::SExt:
4165 return Cost;
4166
4167 // For zero-extends, the extend is performed automatically by a umov unless
4168 // the destination type is i64 and the element type is i8 or i16.
4169 case Instruction::ZExt:
4170 if (DstVT.getSizeInBits() != 64u || SrcVT.getSizeInBits() == 32u)
4171 return Cost;
4172 }
4173
4174 // If we are unable to perform the extend for free, get the default cost.
4175 return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
4176 CostKind);
4177}
4178
4181 const Instruction *I) const {
4183 return Opcode == Instruction::PHI ? 0 : 1;
4184 assert(CostKind == TTI::TCK_RecipThroughput && "unexpected CostKind");
4185 // Branches are assumed to be predicted.
4186 return 0;
4187}
4188
4189InstructionCost AArch64TTIImpl::getVectorInstrCostHelper(
4190 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index,
4191 const Instruction *I, Value *Scalar,
4192 ArrayRef<std::tuple<Value *, User *, int>> ScalarUserAndIdx,
4193 TTI::VectorInstrContext VIC) const {
4194 assert(Val->isVectorTy() && "This must be a vector type");
4195
4196 if (Index != -1U) {
4197 // Legalize the type.
4198 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Val);
4199
4200 // This type is legalized to a scalar type.
4201 if (!LT.second.isVector())
4202 return 0;
4203
4204 // The type may be split. For fixed-width vectors we can normalize the
4205 // index to the new type.
4206 if (LT.second.isFixedLengthVector()) {
4207 unsigned Width = LT.second.getVectorNumElements();
4208 Index = Index % Width;
4209 }
4210
4211 // The element at index zero is already inside the vector.
4212 // - For a insert-element or extract-element
4213 // instruction that extracts integers, an explicit FPR -> GPR move is
4214 // needed. So it has non-zero cost.
4215 if (Index == 0 && !Val->getScalarType()->isIntegerTy())
4216 return 0;
4217
4218 // This is recognising a LD1 single-element structure to one lane of one
4219 // register instruction. I.e., if this is an `insertelement` instruction,
4220 // and its second operand is a load, then we will generate a LD1, which
4221 // are expensive instructions on some uArchs.
4222 if (VIC == TTI::VectorInstrContext::Load) {
4223 if (ST->hasFastLD1Single())
4224 return 0;
4225 return CostKind == TTI::TCK_CodeSize
4226 ? 0
4228 }
4229
4230 // i1 inserts and extract will include an extra cset or cmp of the vector
4231 // value. Increase the cost by 1 to account.
4232 if (Val->getScalarSizeInBits() == 1)
4233 return CostKind == TTI::TCK_CodeSize
4234 ? 2
4235 : ST->getVectorInsertExtractBaseCost() + 1;
4236
4237 // FIXME:
4238 // If the extract-element and insert-element instructions could be
4239 // simplified away (e.g., could be combined into users by looking at use-def
4240 // context), they have no cost. This is not done in the first place for
4241 // compile-time considerations.
4242 }
4243
4244 // In case of Neon, if there exists extractelement from lane != 0 such that
4245 // 1. extractelement does not necessitate a move from vector_reg -> GPR.
4246 // 2. extractelement result feeds into fmul.
4247 // 3. Other operand of fmul is an extractelement from lane 0 or lane
4248 // equivalent to 0.
4249 // then the extractelement can be merged with fmul in the backend and it
4250 // incurs no cost.
4251 // e.g.
4252 // define double @foo(<2 x double> %a) {
4253 // %1 = extractelement <2 x double> %a, i32 0
4254 // %2 = extractelement <2 x double> %a, i32 1
4255 // %res = fmul double %1, %2
4256 // ret double %res
4257 // }
4258 // %2 and %res can be merged in the backend to generate fmul d0, d0, v1.d[1]
4259 auto ExtractCanFuseWithFmul = [&]() {
4260 // We bail out if the extract is from lane 0.
4261 if (Index == 0)
4262 return false;
4263
4264 // Check if the scalar element type of the vector operand of ExtractElement
4265 // instruction is one of the allowed types.
4266 auto IsAllowedScalarTy = [&](const Type *T) {
4267 return T->isFloatTy() || T->isDoubleTy() ||
4268 (T->isHalfTy() && ST->hasFullFP16());
4269 };
4270
4271 // Check if the extractelement user is scalar fmul.
4272 auto IsUserFMulScalarTy = [](const Value *EEUser) {
4273 // Check if the user is scalar fmul.
4274 const auto *BO = dyn_cast<BinaryOperator>(EEUser);
4275 return BO && BO->getOpcode() == BinaryOperator::FMul &&
4276 !BO->getType()->isVectorTy();
4277 };
4278
4279 // Check if the extract index is from lane 0 or lane equivalent to 0 for a
4280 // certain scalar type and a certain vector register width.
4281 auto IsExtractLaneEquivalentToZero = [&](unsigned Idx, unsigned EltSz) {
4282 auto RegWidth =
4284 .getFixedValue();
4285 return Idx == 0 || (RegWidth != 0 && (Idx * EltSz) % RegWidth == 0);
4286 };
4287
4288 // Check if the type constraints on input vector type and result scalar type
4289 // of extractelement instruction are satisfied.
4290 if (!isa<FixedVectorType>(Val) || !IsAllowedScalarTy(Val->getScalarType()))
4291 return false;
4292
4293 if (Scalar) {
4294 DenseMap<User *, unsigned> UserToExtractIdx;
4295 for (auto *U : Scalar->users()) {
4296 if (!IsUserFMulScalarTy(U))
4297 return false;
4298 // Recording entry for the user is important. Index value is not
4299 // important.
4300 UserToExtractIdx[U];
4301 }
4302 if (UserToExtractIdx.empty())
4303 return false;
4304 for (auto &[S, U, L] : ScalarUserAndIdx) {
4305 for (auto *U : S->users()) {
4306 if (UserToExtractIdx.contains(U)) {
4307 auto *FMul = cast<BinaryOperator>(U);
4308 auto *Op0 = FMul->getOperand(0);
4309 auto *Op1 = FMul->getOperand(1);
4310 if ((Op0 == S && Op1 == S) || Op0 != S || Op1 != S) {
4311 UserToExtractIdx[U] = L;
4312 break;
4313 }
4314 }
4315 }
4316 }
4317 for (auto &[U, L] : UserToExtractIdx) {
4318 if (!IsExtractLaneEquivalentToZero(Index, Val->getScalarSizeInBits()) &&
4319 !IsExtractLaneEquivalentToZero(L, Val->getScalarSizeInBits()))
4320 return false;
4321 }
4322 } else {
4323 const auto *EE = cast<ExtractElementInst>(I);
4324
4325 const auto *IdxOp = dyn_cast<ConstantInt>(EE->getIndexOperand());
4326 if (!IdxOp)
4327 return false;
4328
4329 return !EE->users().empty() && all_of(EE->users(), [&](const User *U) {
4330 if (!IsUserFMulScalarTy(U))
4331 return false;
4332
4333 // Check if the other operand of extractelement is also extractelement
4334 // from lane equivalent to 0.
4335 const auto *BO = cast<BinaryOperator>(U);
4336 const auto *OtherEE = dyn_cast<ExtractElementInst>(
4337 BO->getOperand(0) == EE ? BO->getOperand(1) : BO->getOperand(0));
4338 if (OtherEE) {
4339 const auto *IdxOp = dyn_cast<ConstantInt>(OtherEE->getIndexOperand());
4340 if (!IdxOp)
4341 return false;
4342 return IsExtractLaneEquivalentToZero(
4343 cast<ConstantInt>(OtherEE->getIndexOperand())
4344 ->getValue()
4345 .getZExtValue(),
4346 OtherEE->getType()->getScalarSizeInBits());
4347 }
4348 return true;
4349 });
4350 }
4351 return true;
4352 };
4353
4354 if (Opcode == Instruction::ExtractElement && (I || Scalar) &&
4355 ExtractCanFuseWithFmul())
4356 return 0;
4357
4358 // All other insert/extracts cost this much.
4359 return CostKind == TTI::TCK_CodeSize ? 1
4360 : ST->getVectorInsertExtractBaseCost();
4361}
4362
4364 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index,
4365 const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC) const {
4366 // Treat insert at lane 0 into a poison vector as having zero cost. This
4367 // ensures vector broadcasts via an insert + shuffle (and will be lowered to a
4368 // single dup) are treated as cheap.
4369 if (Opcode == Instruction::InsertElement && Index == 0 && Op0 &&
4370 isa<PoisonValue>(Op0))
4371 return 0;
4372 return getVectorInstrCostHelper(Opcode, Val, CostKind, Index, nullptr,
4373 nullptr, {}, VIC);
4374}
4375
4377 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index,
4378 Value *Scalar, ArrayRef<std::tuple<Value *, User *, int>> ScalarUserAndIdx,
4379 TTI::VectorInstrContext VIC) const {
4380 return getVectorInstrCostHelper(Opcode, Val, CostKind, Index, nullptr, Scalar,
4381 ScalarUserAndIdx, VIC);
4382}
4383
4386 TTI::TargetCostKind CostKind, unsigned Index,
4387 TTI::VectorInstrContext VIC) const {
4388 return getVectorInstrCostHelper(I.getOpcode(), Val, CostKind, Index, &I,
4389 nullptr, {}, VIC);
4390}
4391
4395 unsigned Index) const {
4396 if (isa<FixedVectorType>(Val))
4398 Index);
4399
4400 // This typically requires both while and lastb instructions in order
4401 // to extract the last element. If this is in a loop the while
4402 // instruction can at least be hoisted out, although it will consume a
4403 // predicate register. The cost should be more expensive than the base
4404 // extract cost, which is 2 for most CPUs.
4405 return CostKind == TTI::TCK_CodeSize
4406 ? 2
4407 : ST->getVectorInsertExtractBaseCost() + 1;
4408}
4409
4411 VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract,
4412 TTI::TargetCostKind CostKind, bool ForPoisonSrc, ArrayRef<Value *> VL,
4413 TTI::VectorInstrContext VIC) const {
4416 if (Ty->getElementType()->isFloatingPointTy())
4417 return BaseT::getScalarizationOverhead(Ty, DemandedElts, Insert, Extract,
4418 CostKind);
4419 unsigned VecInstCost =
4420 CostKind == TTI::TCK_CodeSize ? 1 : ST->getVectorInsertExtractBaseCost();
4421 return DemandedElts.popcount() * (Insert + Extract) * VecInstCost;
4422}
4423
4424std::optional<InstructionCost> AArch64TTIImpl::getFP16BF16PromoteCost(
4426 TTI::OperandValueInfo Op2Info, bool IncludeTrunc, bool CanUseSVE,
4427 std::function<InstructionCost(Type *)> InstCost) const {
4428 if (!Ty->getScalarType()->isHalfTy() && !Ty->getScalarType()->isBFloatTy())
4429 return std::nullopt;
4430 if (Ty->getScalarType()->isHalfTy() && ST->hasFullFP16())
4431 return std::nullopt;
4432 // If we have +sve-b16b16 the operation can be promoted to SVE.
4433 if (CanUseSVE && ST->hasSVEB16B16() && ST->isNonStreamingSVEorSME2Available())
4434 return std::nullopt;
4435
4436 Type *PromotedTy = Ty->getWithNewType(Type::getFloatTy(Ty->getContext()));
4437 InstructionCost Cost = getCastInstrCost(Instruction::FPExt, PromotedTy, Ty,
4439 if (!Op1Info.isConstant() && !Op2Info.isConstant())
4440 Cost *= 2;
4441 Cost += InstCost(PromotedTy);
4442 if (IncludeTrunc)
4443 Cost += getCastInstrCost(Instruction::FPTrunc, Ty, PromotedTy,
4445 return Cost;
4446}
4447
4449 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
4451 ArrayRef<const Value *> Args, const Instruction *CxtI) const {
4452
4453 // The code-generator is currently not able to handle scalable vectors
4454 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
4455 // it. This change will be removed when code-generation for these types is
4456 // sufficiently reliable.
4457 if (auto *VTy = dyn_cast<ScalableVectorType>(Ty))
4458 if (VTy->getElementCount() == ElementCount::getScalable(1))
4460
4461 // TODO: Handle more cost kinds.
4463 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
4464 Op2Info, Args, CxtI);
4465
4466 // Legalize the type.
4467 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
4468 int ISD = TLI->InstructionOpcodeToISD(Opcode);
4469
4470 // Increase the cost for half and bfloat types if not architecturally
4471 // supported.
4472 if (ISD == ISD::FADD || ISD == ISD::FSUB || ISD == ISD::FMUL ||
4473 ISD == ISD::FDIV || ISD == ISD::FREM) {
4474 if (auto PromotedCost = getFP16BF16PromoteCost(
4475 Ty, CostKind, Op1Info, Op2Info, /*IncludeTrunc=*/true,
4476 // There is not native support for fdiv/frem even with +sve-b16b16.
4477 /*CanUseSVE=*/ISD != ISD::FDIV && ISD != ISD::FREM,
4478 [&](Type *PromotedTy) {
4479 return getArithmeticInstrCost(Opcode, PromotedTy, CostKind,
4480 Op1Info, Op2Info);
4481 }))
4482 return *PromotedCost;
4483
4484 // fp128 all go via libcalls
4485 if (Ty->getScalarType()->isFP128Ty())
4486 return (CostKind == TTI::TCK_CodeSize ? 1 : 10) * LT.first;
4487 }
4488
4489 // If the operation is a widening instruction (smull or umull) and both
4490 // operands are extends the cost can be cheaper by considering that the
4491 // operation will operate on the narrowest type size possible (double the
4492 // largest input size) and a further extend.
4493 if (Type *ExtTy = isBinExtWideningInstruction(Opcode, Ty, Args)) {
4494 if (ExtTy != Ty)
4495 return getArithmeticInstrCost(Opcode, ExtTy, CostKind) +
4496 getCastInstrCost(Instruction::ZExt, Ty, ExtTy,
4498 return LT.first;
4499 }
4500
4501 switch (ISD) {
4502 default:
4503 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
4504 Op2Info);
4505 case ISD::ADD:
4506 case ISD::SUB:
4507 return LT.first; // Also works for i128
4508 case ISD::MUL:
4509 if (LT.second == MVT::v2i64) {
4510 // When SVE is available, then we can lower the v2i64 operation using
4511 // the SVE mul instruction, which has a lower cost.
4512 if (ST->hasSVE())
4513 return LT.first;
4514
4515 // When SVE is not available, there is no MUL.2d instruction,
4516 // which means mul <2 x i64> is expensive as elements are extracted
4517 // from the vectors and the muls scalarized.
4518 // As getScalarizationOverhead is a bit too pessimistic, we
4519 // estimate the cost for a i64 vector directly here, which is:
4520 // - four 2-cost i64 extracts,
4521 // - two 2-cost i64 inserts, and
4522 // - two 1-cost muls.
4523 // So, for a v2i64 with LT.First = 1 the cost is 14, and for a v4i64 with
4524 // LT.first = 2 the cost is 28.
4525 return cast<VectorType>(Ty)->getElementCount().getKnownMinValue() *
4526 (getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind) +
4527 getVectorInstrCost(Instruction::ExtractElement, Ty, CostKind, -1,
4528 nullptr, nullptr) *
4529 2 +
4530 getVectorInstrCost(Instruction::InsertElement, Ty, CostKind, -1,
4531 nullptr, nullptr));
4532 }
4533 return LT.first;
4534 case ISD::SREM:
4535 case ISD::SDIV:
4536 /*
4537 Notes for sdiv/srem specific costs:
4538 1. This only considers the cases where the divisor is constant, uniform and
4539 (pow-of-2/non-pow-of-2). Other cases are not important since they either
4540 result in some form of (ldr + adrp), corresponding to constant vectors, or
4541 scalarization of the division operation.
4542 2. Constant divisors, either negative in whole or partially, don't result in
4543 significantly different codegen as compared to positive constant divisors.
4544 So, we don't consider negative divisors separately.
4545 3. If the codegen is significantly different with SVE, it has been indicated
4546 using comments at appropriate places.
4547
4548 sdiv specific cases:
4549 -----------------------------------------------------------------------
4550 codegen | pow-of-2 | Type
4551 -----------------------------------------------------------------------
4552 add + cmp + csel + asr | Y | i64
4553 add + cmp + csel + asr | Y | i32
4554 -----------------------------------------------------------------------
4555
4556 srem specific cases:
4557 -----------------------------------------------------------------------
4558 codegen | pow-of-2 | Type
4559 -----------------------------------------------------------------------
4560 negs + and + and + csneg | Y | i64
4561 negs + and + and + csneg | Y | i32
4562 -----------------------------------------------------------------------
4563
4564 other sdiv/srem cases:
4565 -------------------------------------------------------------------------
4566 common codegen | + srem | + sdiv | pow-of-2 | Type
4567 -------------------------------------------------------------------------
4568 smulh + asr + add + add | - | - | N | i64
4569 smull + lsr + add + add | - | - | N | i32
4570 usra | and + sub | sshr | Y | <2 x i64>
4571 2 * (scalar code) | - | - | N | <2 x i64>
4572 usra | bic + sub | sshr + neg | Y | <4 x i32>
4573 smull2 + smull + uzp2 | mls | - | N | <4 x i32>
4574 + sshr + usra | | | |
4575 -------------------------------------------------------------------------
4576 */
4577 if (Op2Info.isConstant() && Op2Info.isUniform()) {
4578 InstructionCost AddCost =
4579 getArithmeticInstrCost(Instruction::Add, Ty, CostKind,
4580 Op1Info.getNoProps(), Op2Info.getNoProps());
4581 InstructionCost AsrCost =
4582 getArithmeticInstrCost(Instruction::AShr, Ty, CostKind,
4583 Op1Info.getNoProps(), Op2Info.getNoProps());
4584 InstructionCost MulCost =
4585 getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
4586 Op1Info.getNoProps(), Op2Info.getNoProps());
4587 // add/cmp/csel/csneg should have similar cost while asr/negs/and should
4588 // have similar cost.
4589 auto VT = TLI->getValueType(DL, Ty);
4590 if (VT.isScalarInteger() && VT.getSizeInBits() <= 64) {
4591 if (Op2Info.isPowerOf2() || Op2Info.isNegatedPowerOf2()) {
4592 // Neg can be folded into the asr instruction.
4593 return ISD == ISD::SDIV ? (3 * AddCost + AsrCost)
4594 : (3 * AsrCost + AddCost);
4595 } else {
4596 return MulCost + AsrCost + 2 * AddCost;
4597 }
4598 } else if (VT.isVector()) {
4599 InstructionCost UsraCost = 2 * AsrCost;
4600 if (Op2Info.isPowerOf2() || Op2Info.isNegatedPowerOf2()) {
4601 // Division with scalable types corresponds to native 'asrd'
4602 // instruction when SVE is available.
4603 // e.g. %1 = sdiv <vscale x 4 x i32> %a, splat (i32 8)
4604
4605 // One more for the negation in SDIV
4607 (Op2Info.isNegatedPowerOf2() && ISD == ISD::SDIV) ? AsrCost : 0;
4608 if (Ty->isScalableTy() && ST->hasSVE())
4609 Cost += 2 * AsrCost;
4610 else {
4611 Cost +=
4612 UsraCost +
4613 (ISD == ISD::SDIV
4614 ? (LT.second.getScalarType() == MVT::i64 ? 1 : 2) * AsrCost
4615 : 2 * AddCost);
4616 }
4617 return Cost;
4618 } else if (LT.second == MVT::v2i64) {
4619 return VT.getVectorNumElements() *
4620 getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind,
4621 Op1Info.getNoProps(),
4622 Op2Info.getNoProps());
4623 } else {
4624 // When SVE is available, we get:
4625 // smulh + lsr + add/sub + asr + add/sub.
4626 if (Ty->isScalableTy() && ST->hasSVE())
4627 return MulCost /*smulh cost*/ + 2 * AddCost + 2 * AsrCost;
4628 return 2 * MulCost + AddCost /*uzp2 cost*/ + AsrCost + UsraCost;
4629 }
4630 }
4631 }
4632 if (Op2Info.isConstant() && !Op2Info.isUniform() &&
4633 LT.second.isFixedLengthVector()) {
4634 // FIXME: When the constant vector is non-uniform, this may result in
4635 // loading the vector from constant pool or in some cases, may also result
4636 // in scalarization. For now, we are approximating this with the
4637 // scalarization cost.
4638 auto ExtractCost = 2 * getVectorInstrCost(Instruction::ExtractElement, Ty,
4639 CostKind, -1, nullptr, nullptr);
4640 auto InsertCost = getVectorInstrCost(Instruction::InsertElement, Ty,
4641 CostKind, -1, nullptr, nullptr);
4642 unsigned NElts = cast<FixedVectorType>(Ty)->getNumElements();
4643 return ExtractCost + InsertCost +
4644 NElts * getArithmeticInstrCost(Opcode, Ty->getScalarType(),
4645 CostKind, Op1Info.getNoProps(),
4646 Op2Info.getNoProps());
4647 }
4648 [[fallthrough]];
4649 case ISD::UDIV:
4650 case ISD::UREM: {
4651 auto VT = TLI->getValueType(DL, Ty);
4652 if (Op2Info.isConstant()) {
4653 // If the operand is a power of 2 we can use the shift or and cost.
4654 if (ISD == ISD::UDIV && Op2Info.isPowerOf2())
4655 return getArithmeticInstrCost(Instruction::LShr, Ty, CostKind,
4656 Op1Info.getNoProps(),
4657 Op2Info.getNoProps());
4658 if (ISD == ISD::UREM && Op2Info.isPowerOf2())
4659 return getArithmeticInstrCost(Instruction::And, Ty, CostKind,
4660 Op1Info.getNoProps(),
4661 Op2Info.getNoProps());
4662
4663 if (ISD == ISD::UDIV || ISD == ISD::UREM) {
4664 // Divides by a constant are expanded to MULHU + SUB + SRL + ADD + SRL.
4665 // The MULHU will be expanded to UMULL for the types not listed below,
4666 // and will become a pair of UMULL+MULL2 for 128bit vectors.
4667 bool HasMULH = VT == MVT::i64 || LT.second == MVT::nxv2i64 ||
4668 LT.second == MVT::nxv4i32 || LT.second == MVT::nxv8i16 ||
4669 LT.second == MVT::nxv16i8;
4670 bool Is128bit = LT.second.is128BitVector();
4671
4672 InstructionCost MulCost =
4673 getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
4674 Op1Info.getNoProps(), Op2Info.getNoProps());
4675 InstructionCost AddCost =
4676 getArithmeticInstrCost(Instruction::Add, Ty, CostKind,
4677 Op1Info.getNoProps(), Op2Info.getNoProps());
4678 InstructionCost ShrCost =
4679 getArithmeticInstrCost(Instruction::AShr, Ty, CostKind,
4680 Op1Info.getNoProps(), Op2Info.getNoProps());
4681 InstructionCost DivCost = MulCost * (Is128bit ? 2 : 1) + // UMULL/UMULH
4682 (HasMULH ? 0 : ShrCost) + // UMULL shift
4683 AddCost * 2 + ShrCost;
4684 return DivCost + (ISD == ISD::UREM ? MulCost + AddCost : 0);
4685 }
4686 }
4687
4688 // div i128's are lowered as libcalls. Pass nullptr as (u)divti3 calls are
4689 // emitted by the backend even when those functions are not declared in the
4690 // module.
4691 if (!VT.isVector() && VT.getSizeInBits() > 64)
4692 return getCallInstrCost(/*Function*/ nullptr, Ty, {Ty, Ty}, CostKind);
4693
4695 Opcode, Ty, CostKind, Op1Info, Op2Info);
4696 if (Ty->isVectorTy() && (ISD == ISD::SDIV || ISD == ISD::UDIV)) {
4697 if (TLI->isOperationLegalOrCustom(ISD, LT.second) && ST->hasSVE()) {
4698 // SDIV/UDIV operations are lowered using SVE, then we can have less
4699 // costs.
4700 if (VT.isSimple() && isa<FixedVectorType>(Ty) &&
4701 Ty->getPrimitiveSizeInBits().getFixedValue() < 128) {
4702 static const CostTblEntry DivTbl[]{
4703 {ISD::SDIV, MVT::v2i8, 5}, {ISD::SDIV, MVT::v4i8, 8},
4704 {ISD::SDIV, MVT::v8i8, 8}, {ISD::SDIV, MVT::v2i16, 5},
4705 {ISD::SDIV, MVT::v4i16, 5}, {ISD::SDIV, MVT::v2i32, 1},
4706 {ISD::UDIV, MVT::v2i8, 5}, {ISD::UDIV, MVT::v4i8, 8},
4707 {ISD::UDIV, MVT::v8i8, 8}, {ISD::UDIV, MVT::v2i16, 5},
4708 {ISD::UDIV, MVT::v4i16, 5}, {ISD::UDIV, MVT::v2i32, 1}};
4709
4710 const auto *Entry = CostTableLookup(DivTbl, ISD, VT.getSimpleVT());
4711 if (nullptr != Entry)
4712 return Entry->Cost;
4713 }
4714 // For 8/16-bit elements, the cost is higher because the type
4715 // requires promotion and possibly splitting:
4716 if (LT.second.getScalarType() == MVT::i8)
4717 Cost *= 8;
4718 else if (LT.second.getScalarType() == MVT::i16)
4719 Cost *= 4;
4720 return Cost;
4721 } else {
4722 // If one of the operands is a uniform constant then the cost for each
4723 // element is Cost for insertion, extraction and division.
4724 // Insertion cost = 2, Extraction Cost = 2, Division = cost for the
4725 // operation with scalar type
4726 if ((Op1Info.isConstant() && Op1Info.isUniform()) ||
4727 (Op2Info.isConstant() && Op2Info.isUniform())) {
4728 if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
4730 Opcode, Ty->getScalarType(), CostKind, Op1Info, Op2Info);
4731 return (4 + DivCost) * VTy->getNumElements();
4732 }
4733 }
4734 // On AArch64, without SVE, vector divisions are expanded
4735 // into scalar divisions of each pair of elements.
4736 Cost += getVectorInstrCost(Instruction::ExtractElement, Ty, CostKind,
4737 -1, nullptr, nullptr);
4738 Cost += getVectorInstrCost(Instruction::InsertElement, Ty, CostKind, -1,
4739 nullptr, nullptr);
4740 }
4741
4742 // TODO: if one of the arguments is scalar, then it's not necessary to
4743 // double the cost of handling the vector elements.
4744 Cost += Cost;
4745 }
4746 return Cost;
4747 }
4748 case ISD::XOR:
4749 case ISD::OR:
4750 case ISD::AND:
4751 case ISD::SRL:
4752 case ISD::SRA:
4753 case ISD::SHL:
4754 // These nodes are marked as 'custom' for combining purposes only.
4755 // We know that they are legal. See LowerAdd in ISelLowering.
4756 return LT.first;
4757
4758 case ISD::FNEG:
4759 // Scalar fmul(fneg) or fneg(fmul) can be converted to fnmul
4760 if ((Ty->isFloatTy() || Ty->isDoubleTy() ||
4761 (Ty->isHalfTy() && ST->hasFullFP16())) &&
4762 CxtI &&
4763 ((CxtI->hasOneUse() &&
4764 match(*CxtI->user_begin(), m_FMul(m_Value(), m_Value()))) ||
4765 match(CxtI->getOperand(0), m_FMul(m_Value(), m_Value()))))
4766 return 0;
4767 [[fallthrough]];
4768 case ISD::FADD:
4769 case ISD::FSUB:
4770 if (!Ty->getScalarType()->isFP128Ty())
4771 return LT.first;
4772 [[fallthrough]];
4773 case ISD::FMUL:
4774 case ISD::FDIV:
4775 // These nodes are marked as 'custom' just to lower them to SVE.
4776 // We know said lowering will incur no additional cost.
4777 if (!Ty->getScalarType()->isFP128Ty())
4778 return 2 * LT.first;
4779
4780 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
4781 Op2Info);
4782 case ISD::FREM:
4783 // Pass nullptr as fmod/fmodf calls are emitted by the backend even when
4784 // those functions are not declared in the module.
4785 if (!Ty->isVectorTy())
4786 return getCallInstrCost(/*Function*/ nullptr, Ty, {Ty, Ty}, CostKind);
4787 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
4788 Op2Info);
4789 }
4790}
4791
4794 const SCEV *Ptr,
4796 // Address computations in vectorized code with non-consecutive addresses will
4797 // likely result in more instructions compared to scalar code where the
4798 // computation can more often be merged into the index mode. The resulting
4799 // extra micro-ops can significantly decrease throughput.
4800 unsigned NumVectorInstToHideOverhead = NeonNonConstStrideOverhead;
4801 int MaxMergeDistance = 64;
4802
4803 if (PtrTy->isVectorTy() && SE &&
4804 !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
4805 return NumVectorInstToHideOverhead;
4806
4807 // In many cases the address computation is not merged into the instruction
4808 // addressing mode.
4809 return 1;
4810}
4811
4812/// Check whether Opcode1 has less throughput according to the scheduling
4813/// model than Opcode2.
4815 unsigned Opcode1, unsigned Opcode2) const {
4816 const MCSchedModel &Sched = ST->getSchedModel();
4817 const TargetInstrInfo *TII = ST->getInstrInfo();
4818 if (!Sched.hasInstrSchedModel())
4819 return false;
4820
4821 const MCSchedClassDesc *SCD1 =
4822 Sched.getSchedClassDesc(TII->get(Opcode1).getSchedClass());
4823 const MCSchedClassDesc *SCD2 =
4824 Sched.getSchedClassDesc(TII->get(Opcode2).getSchedClass());
4825 // We cannot handle variant scheduling classes without an MI. If we need to
4826 // support them for any of the instructions we query the information of we
4827 // might need to add a way to resolve them without a MI or not use the
4828 // scheduling info.
4829 assert(!SCD1->isVariant() && !SCD2->isVariant() &&
4830 "Cannot handle variant scheduling classes without an MI");
4831 if (!SCD1->isValid() || !SCD2->isValid())
4832 return false;
4833
4834 return MCSchedModel::getReciprocalThroughput(*ST, *SCD1) >
4836}
4837
4839 unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred,
4841 TTI::OperandValueInfo Op2Info, const Instruction *I) const {
4842 // We don't lower some vector selects well that are wider than the register
4843 // width. TODO: Improve this with different cost kinds.
4844 if (isa<FixedVectorType>(ValTy) && Opcode == Instruction::Select) {
4845 // We would need this many instructions to hide the scalarization happening.
4846 const int AmortizationCost = 20;
4847
4848 // If VecPred is not set, check if we can get a predicate from the context
4849 // instruction, if its type matches the requested ValTy.
4850 if (VecPred == CmpInst::BAD_ICMP_PREDICATE && I && I->getType() == ValTy) {
4851 CmpPredicate CurrentPred;
4852 if (match(I, m_Select(m_Cmp(CurrentPred, m_Value(), m_Value()), m_Value(),
4853 m_Value())))
4854 VecPred = CurrentPred;
4855 }
4856 // Check if we have a compare/select chain that can be lowered using
4857 // a (F)CMxx & BFI pair.
4858 if (CmpInst::isIntPredicate(VecPred) || VecPred == CmpInst::FCMP_OLE ||
4859 VecPred == CmpInst::FCMP_OLT || VecPred == CmpInst::FCMP_OGT ||
4860 VecPred == CmpInst::FCMP_OGE || VecPred == CmpInst::FCMP_OEQ ||
4861 VecPred == CmpInst::FCMP_UNE) {
4862 static const auto ValidMinMaxTys = {
4863 MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16, MVT::v2i32,
4864 MVT::v4i32, MVT::v2i64, MVT::v2f32, MVT::v4f32, MVT::v2f64};
4865 static const auto ValidFP16MinMaxTys = {MVT::v4f16, MVT::v8f16};
4866
4867 auto LT = getTypeLegalizationCost(ValTy);
4868 if (any_of(ValidMinMaxTys, equal_to(LT.second)) ||
4869 (ST->hasFullFP16() &&
4870 any_of(ValidFP16MinMaxTys, equal_to(LT.second))))
4871 return LT.first;
4872 }
4873
4874 static const TypeConversionCostTblEntry VectorSelectTbl[] = {
4875 {Instruction::Select, MVT::v2i1, MVT::v2f32, 2},
4876 {Instruction::Select, MVT::v2i1, MVT::v2f64, 2},
4877 {Instruction::Select, MVT::v4i1, MVT::v4f32, 2},
4878 {Instruction::Select, MVT::v4i1, MVT::v4f16, 2},
4879 {Instruction::Select, MVT::v8i1, MVT::v8f16, 2},
4880 {Instruction::Select, MVT::v16i1, MVT::v16i16, 16},
4881 {Instruction::Select, MVT::v8i1, MVT::v8i32, 8},
4882 {Instruction::Select, MVT::v16i1, MVT::v16i32, 16},
4883 {Instruction::Select, MVT::v4i1, MVT::v4i64, 4 * AmortizationCost},
4884 {Instruction::Select, MVT::v8i1, MVT::v8i64, 8 * AmortizationCost},
4885 {Instruction::Select, MVT::v16i1, MVT::v16i64, 16 * AmortizationCost}};
4886
4887 EVT SelCondTy = TLI->getValueType(DL, CondTy);
4888 EVT SelValTy = TLI->getValueType(DL, ValTy);
4889 if (SelCondTy.isSimple() && SelValTy.isSimple()) {
4890 if (const auto *Entry = ConvertCostTableLookup(VectorSelectTbl, Opcode,
4891 SelCondTy.getSimpleVT(),
4892 SelValTy.getSimpleVT()))
4893 return Entry->Cost;
4894 }
4895 }
4896
4897 if (Opcode == Instruction::FCmp) {
4898 if (auto PromotedCost = getFP16BF16PromoteCost(
4899 ValTy, CostKind, Op1Info, Op2Info, /*IncludeTrunc=*/false,
4900 // TODO: Consider costing SVE FCMPs.
4901 /*CanUseSVE=*/false, [&](Type *PromotedTy) {
4903 getCmpSelInstrCost(Opcode, PromotedTy, CondTy, VecPred,
4904 CostKind, Op1Info, Op2Info);
4905 if (isa<VectorType>(PromotedTy))
4907 Instruction::Trunc,
4911 return Cost;
4912 }))
4913 return *PromotedCost;
4914
4915 auto LT = getTypeLegalizationCost(ValTy);
4916 // Model unknown fp compares as a libcall.
4917 if (LT.second.getScalarType() != MVT::f64 &&
4918 LT.second.getScalarType() != MVT::f32 &&
4919 LT.second.getScalarType() != MVT::f16)
4920 return LT.first * getCallInstrCost(/*Function*/ nullptr, ValTy,
4921 {ValTy, ValTy}, CostKind);
4922
4923 // Some comparison operators require expanding to multiple compares + or.
4924 unsigned Factor = 1;
4925 if (!CondTy->isVectorTy() &&
4926 (VecPred == FCmpInst::FCMP_ONE || VecPred == FCmpInst::FCMP_UEQ))
4927 Factor = 2; // fcmp with 2 selects
4928 else if (isa<FixedVectorType>(ValTy) &&
4929 (VecPred == FCmpInst::FCMP_ONE || VecPred == FCmpInst::FCMP_UEQ ||
4930 VecPred == FCmpInst::FCMP_ORD || VecPred == FCmpInst::FCMP_UNO))
4931 Factor = 3; // fcmxx+fcmyy+or
4932 else if (isa<ScalableVectorType>(ValTy) &&
4933 (VecPred == FCmpInst::FCMP_ONE || VecPred == FCmpInst::FCMP_UEQ))
4934 Factor = 3; // fcmxx+fcmyy+or
4935
4936 if (isa<ScalableVectorType>(ValTy) &&
4938 hasKnownLowerThroughputFromSchedulingModel(AArch64::FCMEQ_PPzZZ_S,
4939 AArch64::FCMEQv4f32))
4940 Factor *= 2;
4941
4942 return Factor * (CostKind == TTI::TCK_Latency ? 2 : LT.first);
4943 }
4944
4945 // Treat the icmp in icmp(and, 0) or icmp(and, -1/1) when it can be folded to
4946 // icmp(and, 0) as free, as we can make use of ands, but only if the
4947 // comparison is not unsigned. FIXME: Enable for non-throughput cost kinds
4948 // providing it will not cause performance regressions.
4949 if (CostKind == TTI::TCK_RecipThroughput && ValTy->isIntegerTy() &&
4950 Opcode == Instruction::ICmp && I && !CmpInst::isUnsigned(VecPred) &&
4951 TLI->isTypeLegal(TLI->getValueType(DL, ValTy)) &&
4952 match(I->getOperand(0), m_And(m_Value(), m_Value()))) {
4953 if (match(I->getOperand(1), m_Zero()))
4954 return 0;
4955
4956 // x >= 1 / x < 1 -> x > 0 / x <= 0
4957 if (match(I->getOperand(1), m_One()) &&
4958 (VecPred == CmpInst::ICMP_SLT || VecPred == CmpInst::ICMP_SGE))
4959 return 0;
4960
4961 // x <= -1 / x > -1 -> x > 0 / x <= 0
4962 if (match(I->getOperand(1), m_AllOnes()) &&
4963 (VecPred == CmpInst::ICMP_SLE || VecPred == CmpInst::ICMP_SGT))
4964 return 0;
4965 }
4966
4967 // The base case handles scalable vectors fine for now, since it treats the
4968 // cost as 1 * legalization cost.
4969 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
4970 Op1Info, Op2Info, I);
4971}
4972
4974AArch64TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
4976 if (ST->requiresStrictAlign()) {
4977 // TODO: Add cost modeling for strict align. Misaligned loads expand to
4978 // a bunch of instructions when strict align is enabled.
4979 return Options;
4980 }
4981 Options.AllowOverlappingLoads = true;
4982 Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
4983 Options.NumLoadsPerBlock = Options.MaxNumLoads;
4984 // TODO: Though vector loads usually perform well on AArch64, in some targets
4985 // they may wake up the FP unit, which raises the power consumption. Perhaps
4986 // they could be used with no holds barred (-O3).
4987 Options.LoadSizes = {8, 4, 2, 1};
4988 Options.AllowedTailExpansions = {3, 5, 6};
4989 return Options;
4990}
4991
4993 return ST->hasSVE();
4994}
4995
4999 switch (MICA.getID()) {
5000 case Intrinsic::masked_scatter:
5001 case Intrinsic::masked_gather:
5002 return getGatherScatterOpCost(MICA, CostKind);
5003 case Intrinsic::masked_load:
5004 case Intrinsic::masked_expandload:
5005 case Intrinsic::masked_store:
5006 return getMaskedMemoryOpCost(MICA, CostKind);
5007 }
5009}
5010
5014 Type *Src = MICA.getDataType();
5015
5016 if (useNeonVector(Src))
5018 auto LT = getTypeLegalizationCost(Src);
5019 if (!LT.first.isValid())
5021
5022 // Return an invalid cost for element types that we are unable to lower.
5023 auto *VT = cast<VectorType>(Src);
5024 if (VT->getElementType()->isIntegerTy(1))
5026
5027 // The code-generator is currently not able to handle scalable vectors
5028 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
5029 // it. This change will be removed when code-generation for these types is
5030 // sufficiently reliable.
5031 if (VT->getElementCount() == ElementCount::getScalable(1))
5033
5034 InstructionCost MemOpCost = LT.first;
5035 if (MICA.getID() == Intrinsic::masked_expandload) {
5036 if (!isLegalMaskedExpandLoad(Src, MICA.getAlignment()))
5038
5039 // Operation will be split into expand of masked.load
5040 MemOpCost *= 2;
5041 }
5042
5043 // If we need to split the memory operation, we will also need to split the
5044 // mask. This will likely lead to overestimating the cost in some cases if
5045 // multiple memory operations use the same mask, but we often don't have
5046 // enough context to figure that out here.
5047 //
5048 // If the elements being loaded are bytes then the mask will already be split,
5049 // since the number of bits in a P register matches the number of bytes in a
5050 // Z register.
5051 if (LT.first > 1 && LT.second.getScalarSizeInBits() > 8)
5052 return MemOpCost * 2;
5053
5054 return MemOpCost;
5055}
5056
5057// This function returns gather/scatter overhead either from
5058// user-provided value or specialized values per-target from \p ST.
5059static unsigned getSVEGatherScatterOverhead(unsigned Opcode,
5060 const AArch64Subtarget *ST) {
5061 assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
5062 "Should be called on only load or stores.");
5063 switch (Opcode) {
5064 case Instruction::Load:
5065 if (SVEGatherOverhead.getNumOccurrences() > 0)
5066 return SVEGatherOverhead;
5067 return ST->getGatherOverhead();
5068 break;
5069 case Instruction::Store:
5070 if (SVEScatterOverhead.getNumOccurrences() > 0)
5071 return SVEScatterOverhead;
5072 return ST->getScatterOverhead();
5073 break;
5074 default:
5075 llvm_unreachable("Shouldn't have reached here");
5076 }
5077}
5078
5082
5083 unsigned Opcode = (MICA.getID() == Intrinsic::masked_gather ||
5084 MICA.getID() == Intrinsic::vp_gather)
5085 ? Instruction::Load
5086 : Instruction::Store;
5087
5088 Type *DataTy = MICA.getDataType();
5089 Align Alignment = MICA.getAlignment();
5090 const Instruction *I = MICA.getInst();
5091
5092 if (useNeonVector(DataTy) || !isLegalMaskedGatherScatter(DataTy))
5094 auto *VT = cast<VectorType>(DataTy);
5095 auto LT = getTypeLegalizationCost(DataTy);
5096 if (!LT.first.isValid())
5098
5099 // Return an invalid cost for element types that we are unable to lower.
5100 if (!LT.second.isVector() ||
5101 !isElementTypeLegalForScalableVector(VT->getElementType()) ||
5102 VT->getElementType()->isIntegerTy(1))
5104
5105 // The code-generator is currently not able to handle scalable vectors
5106 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
5107 // it. This change will be removed when code-generation for these types is
5108 // sufficiently reliable.
5109 if (VT->getElementCount() == ElementCount::getScalable(1))
5111
5112 ElementCount LegalVF = LT.second.getVectorElementCount();
5113 InstructionCost MemOpCost =
5114 getMemoryOpCost(Opcode, VT->getElementType(), Alignment, 0, CostKind,
5115 {TTI::OK_AnyValue, TTI::OP_None}, I);
5116 // Add on an overhead cost for using gathers/scatters.
5117 MemOpCost *= getSVEGatherScatterOverhead(Opcode, ST);
5118 return LT.first * MemOpCost * getMaxNumElements(LegalVF);
5119}
5120
5122 return isa<FixedVectorType>(Ty) && !ST->useSVEForFixedLengthVectors();
5123}
5124
5126 Align Alignment,
5127 unsigned AddressSpace,
5129 TTI::OperandValueInfo OpInfo,
5130 const Instruction *I) const {
5131 EVT VT = TLI->getValueType(DL, Ty, true);
5132 // Type legalization can't handle structs
5133 if (VT == MVT::Other)
5134 return BaseT::getMemoryOpCost(Opcode, Ty, Alignment, AddressSpace,
5135 CostKind);
5136
5137 auto LT = getTypeLegalizationCost(Ty);
5138 if (!LT.first.isValid())
5140
5141 // The code-generator is currently not able to handle scalable vectors
5142 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
5143 // it. This change will be removed when code-generation for these types is
5144 // sufficiently reliable.
5145 // We also only support full register predicate loads and stores.
5146 if (auto *VTy = dyn_cast<ScalableVectorType>(Ty))
5147 if (VTy->getElementCount() == ElementCount::getScalable(1) ||
5148 (VTy->getElementType()->isIntegerTy(1) &&
5149 !VTy->getElementCount().isKnownMultipleOf(
5152
5153 // TODO: consider latency as well for TCK_SizeAndLatency.
5155 return LT.first;
5156
5157 if (CostKind == TTI::TCK_Latency) {
5158 // Latency doesn't make much sense for stores, so just return 1
5159 if (Opcode == Instruction::Store)
5160 return 1;
5161 // If the subtarget has overridden the load latency then use that instead of
5162 // querying the SchedModel.
5163 if (ST->getFixedLoadLatency())
5164 return (LT.first - 1) + ST->getFixedLoadLatency();
5165 // We expect the load to become LT.first loads of type LT.second. The
5166 // latency will be the latency of the last load plus the time it gets to get
5167 // there, which will be the amount of other loads before that (i.e. total
5168 // loads - 1) multiplied by how long it takes to get through them (the
5169 // reciprocal of the throughput). We get the latency and reciprocal
5170 // throughput from the SchedModel, and assume that the loads become the
5171 // variant with unsigned integer offset.
5172 unsigned Inst = 0;
5173 if (LT.second.isScalableVector() ||
5174 ST->useSVEForFixedLengthVectors(LT.second)) {
5175 Inst = AArch64::LDR_ZXI;
5176 } else if (LT.second.isVector() || LT.second.isFloatingPoint()) {
5177 switch (LT.second.getSizeInBits()) {
5178 case 8:
5179 Inst = AArch64::LDRBui;
5180 break;
5181 case 16:
5182 Inst = AArch64::LDRHui;
5183 break;
5184 case 32:
5185 Inst = AArch64::LDRSui;
5186 break;
5187 case 64:
5188 Inst = AArch64::LDRDui;
5189 break;
5190 case 128:
5191 Inst = AArch64::LDRQui;
5192 break;
5193 default:
5194 llvm_unreachable("Unexpected float or vector type");
5195 }
5196 } else {
5197 switch (LT.second.getSizeInBits()) {
5198 case 8:
5199 Inst = AArch64::LDRBBui;
5200 break;
5201 case 16:
5202 Inst = AArch64::LDRHHui;
5203 break;
5204 case 32:
5205 Inst = AArch64::LDRWui;
5206 break;
5207 case 64:
5208 Inst = AArch64::LDRXui;
5209 break;
5210 default:
5211 llvm_unreachable("Unexpected integer type");
5212 }
5213 }
5214 const MCSchedModel &Sched = ST->getSchedModel();
5215 const TargetInstrInfo *TII = ST->getInstrInfo();
5216 unsigned SchedClass = TII->get(Inst).getSchedClass();
5217 const MCSchedClassDesc *SCD = Sched.getSchedClassDesc(SchedClass);
5218 // We need to convert the number of loads before the last to a float here,
5219 // as the reciprocal throughput may be fractional.
5220 float NumLoads = (LT.first - 1).getValue();
5221 return NumLoads * Sched.getReciprocalThroughput(*ST, *SCD) +
5222 Sched.computeInstrLatency(*ST, *SCD);
5223 }
5224
5225 if (ST->isMisaligned128StoreSlow() && Opcode == Instruction::Store &&
5226 LT.second.is128BitVector() && Alignment < Align(16)) {
5227 // Unaligned stores are extremely inefficient. We don't split all
5228 // unaligned 128-bit stores because the negative impact that has shown in
5229 // practice on inlined block copy code.
5230 // We make such stores expensive so that we will only vectorize if there
5231 // are 6 other instructions getting vectorized.
5232 const int AmortizationCost = 6;
5233
5234 return LT.first * 2 * AmortizationCost;
5235 }
5236
5237 // Opaque ptr or ptr vector types are i64s and can be lowered to STP/LDPs.
5238 if (Ty->isPtrOrPtrVectorTy())
5239 return LT.first;
5240
5241 if (useNeonVector(Ty)) {
5242 // Check truncating stores and extending loads.
5243 if (Ty->getScalarSizeInBits() != LT.second.getScalarSizeInBits()) {
5244 // v4i8 types are lowered to scalar a load/store and sshll/xtn.
5245 if (VT == MVT::v4i8)
5246 return 2;
5247 // Otherwise we need to scalarize.
5248 return cast<FixedVectorType>(Ty)->getNumElements() * 2;
5249 }
5250 EVT EltVT = VT.getVectorElementType();
5251 unsigned EltSize = EltVT.getScalarSizeInBits();
5252 if (!isPowerOf2_32(EltSize) || EltSize < 8 || EltSize > 64 ||
5253 VT.getVectorNumElements() >= (128 / EltSize) || Alignment != Align(1))
5254 return LT.first;
5255 // FIXME: v3i8 lowering currently is very inefficient, due to automatic
5256 // widening to v4i8, which produces suboptimal results.
5257 if (VT.getVectorNumElements() == 3 && EltVT == MVT::i8)
5258 return LT.first;
5259
5260 // Check non-power-of-2 loads/stores for legal vector element types with
5261 // NEON. Non-power-of-2 memory ops will get broken down to a set of
5262 // operations on smaller power-of-2 ops, including ld1/st1.
5263 LLVMContext &C = Ty->getContext();
5265 SmallVector<EVT> TypeWorklist;
5266 TypeWorklist.push_back(VT);
5267 while (!TypeWorklist.empty()) {
5268 EVT CurrVT = TypeWorklist.pop_back_val();
5269 unsigned CurrNumElements = CurrVT.getVectorNumElements();
5270 if (isPowerOf2_32(CurrNumElements)) {
5271 Cost += 1;
5272 continue;
5273 }
5274
5275 unsigned PrevPow2 = NextPowerOf2(CurrNumElements) / 2;
5276 TypeWorklist.push_back(EVT::getVectorVT(C, EltVT, PrevPow2));
5277 TypeWorklist.push_back(
5278 EVT::getVectorVT(C, EltVT, CurrNumElements - PrevPow2));
5279 }
5280 return Cost;
5281 }
5282
5283 return LT.first;
5284}
5285
5287 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
5288 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
5289 bool UseMaskForCond, bool UseMaskForGaps) const {
5290 assert(Factor >= 2 && "Invalid interleave factor");
5291 auto *VecVTy = cast<VectorType>(VecTy);
5292
5293 if (VecTy->isScalableTy() && !ST->hasSVE())
5295
5296 // Scalable VFs will emit vector.[de]interleave intrinsics, and currently we
5297 // only have lowering for power-of-2 factors.
5298 // TODO: Add lowering for vector.[de]interleave3 intrinsics and support in
5299 // InterleavedAccessPass for ld3/st3
5300 if (VecTy->isScalableTy() && !isPowerOf2_32(Factor))
5302
5303 // Vectorization for masked interleaved accesses is only enabled for scalable
5304 // VF.
5305 if (!VecTy->isScalableTy() && (UseMaskForCond || UseMaskForGaps))
5307
5308 if (!UseMaskForGaps && Factor <= TLI->getMaxSupportedInterleaveFactor()) {
5309 unsigned MinElts = VecVTy->getElementCount().getKnownMinValue();
5310 auto *SubVecTy =
5311 VectorType::get(VecVTy->getElementType(),
5312 VecVTy->getElementCount().divideCoefficientBy(Factor));
5313
5314 // ldN/stN only support legal vector types of size 64 or 128 in bits.
5315 // Accesses having vector types that are a multiple of 128 bits can be
5316 // matched to more than one ldN/stN instruction.
5317 bool UseScalable;
5318 if (MinElts % Factor == 0 &&
5319 TLI->isLegalInterleavedAccessType(SubVecTy, DL, UseScalable))
5320 return Factor * TLI->getNumInterleavedAccesses(SubVecTy, DL, UseScalable);
5321 }
5322
5323 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5324 Alignment, AddressSpace, CostKind,
5325 UseMaskForCond, UseMaskForGaps);
5326}
5327
5332 for (auto *I : Tys) {
5333 if (!I->isVectorTy())
5334 continue;
5335 if (I->getScalarSizeInBits() * cast<FixedVectorType>(I)->getNumElements() ==
5336 128)
5337 Cost += getMemoryOpCost(Instruction::Store, I, Align(128), 0, CostKind) +
5338 getMemoryOpCost(Instruction::Load, I, Align(128), 0, CostKind);
5339 }
5340 return Cost;
5341}
5342
5344 Align Alignment) const {
5345 // Neon types should be scalarised when we are not choosing to use SVE.
5346 if (useNeonVector(DataTy))
5347 return false;
5348
5349 // Return true only if we are able to lower using the SVE2p2/SME2p2
5350 // expand instruction.
5351 return (ST->isSVEAvailable() && ST->hasSVE2p2()) ||
5352 (ST->isSVEorStreamingSVEAvailable() && ST->hasSME2p2());
5353}
5354
5355unsigned
5357 bool HasUnorderedReductions) const {
5358 if (VF.isScalar() || (HasUnorderedReductions && VF.getKnownMinValue() <= 4))
5359 return 4;
5360 return ST->getMaxInterleaveFactor();
5361}
5362
5363// For Falkor, we want to avoid having too many strided loads in a loop since
5364// that can exhaust the HW prefetcher resources. We adjust the unroller
5365// MaxCount preference below to attempt to ensure unrolling doesn't create too
5366// many strided loads.
5367static void
5370 enum { MaxStridedLoads = 7 };
5371 auto countStridedLoads = [](Loop *L, ScalarEvolution &SE) {
5372 int StridedLoads = 0;
5373 // FIXME? We could make this more precise by looking at the CFG and
5374 // e.g. not counting loads in each side of an if-then-else diamond.
5375 for (const auto BB : L->blocks()) {
5376 for (auto &I : *BB) {
5377 LoadInst *LMemI = dyn_cast<LoadInst>(&I);
5378 if (!LMemI)
5379 continue;
5380
5381 Value *PtrValue = LMemI->getPointerOperand();
5382 if (L->isLoopInvariant(PtrValue))
5383 continue;
5384
5385 const SCEV *LSCEV = SE.getSCEV(PtrValue);
5386 const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
5387 if (!LSCEVAddRec || !LSCEVAddRec->isAffine())
5388 continue;
5389
5390 // FIXME? We could take pairing of unrolled load copies into account
5391 // by looking at the AddRec, but we would probably have to limit this
5392 // to loops with no stores or other memory optimization barriers.
5393 ++StridedLoads;
5394 // We've seen enough strided loads that seeing more won't make a
5395 // difference.
5396 if (StridedLoads > MaxStridedLoads / 2)
5397 return StridedLoads;
5398 }
5399 }
5400 return StridedLoads;
5401 };
5402
5403 int StridedLoads = countStridedLoads(L, SE);
5404 LLVM_DEBUG(dbgs() << "falkor-hwpf: detected " << StridedLoads
5405 << " strided loads\n");
5406 // Pick the largest power of 2 unroll count that won't result in too many
5407 // strided loads.
5408 if (StridedLoads) {
5409 UP.MaxCount = 1 << Log2_32(MaxStridedLoads / StridedLoads);
5410 LLVM_DEBUG(dbgs() << "falkor-hwpf: setting unroll MaxCount to "
5411 << UP.MaxCount << '\n');
5412 }
5413}
5414
5415// This function returns true if the loop:
5416// 1. Has a valid cost, and
5417// 2. Has a cost within the supplied budget.
5418// Otherwise it returns false.
5420 InstructionCost Budget,
5421 unsigned *FinalSize) {
5422 // Estimate the size of the loop.
5423 InstructionCost LoopCost = 0;
5424
5425 for (auto *BB : L->getBlocks()) {
5426 for (auto &I : *BB) {
5427 SmallVector<const Value *, 4> Operands(I.operand_values());
5428 InstructionCost Cost =
5429 TTI.getInstructionCost(&I, Operands, TTI::TCK_CodeSize);
5430 // This can happen with intrinsics that don't currently have a cost model
5431 // or for some operations that require SVE.
5432 if (!Cost.isValid())
5433 return false;
5434
5435 LoopCost += Cost;
5436 if (LoopCost > Budget)
5437 return false;
5438 }
5439 }
5440
5441 if (FinalSize)
5442 *FinalSize = LoopCost.getValue();
5443 return true;
5444}
5445
5447 const AArch64TTIImpl &TTI) {
5448 // Only consider loops with unknown trip counts for which we can determine
5449 // a symbolic expression. Multi-exit loops with small known trip counts will
5450 // likely be unrolled anyway.
5451 const SCEV *BTC = SE.getSymbolicMaxBackedgeTakenCount(L);
5453 return false;
5454
5455 // It might not be worth unrolling loops with low max trip counts. Restrict
5456 // this to max trip counts > 32 for now.
5457 unsigned MaxTC = SE.getSmallConstantMaxTripCount(L);
5458 if (MaxTC > 0 && MaxTC <= 32)
5459 return false;
5460
5461 // Make sure the loop size is <= 5.
5462 if (!isLoopSizeWithinBudget(L, TTI, 5, nullptr))
5463 return false;
5464
5465 // Small search loops with multiple exits can be highly beneficial to unroll.
5466 // We only care about loops with exactly two exiting blocks, although each
5467 // block could jump to the same exit block.
5468 ArrayRef<BasicBlock *> Blocks = L->getBlocks();
5469 if (Blocks.size() != 2)
5470 return false;
5471
5472 if (any_of(Blocks, [](BasicBlock *BB) {
5474 }))
5475 return false;
5476
5477 return true;
5478}
5479
5480/// For Apple CPUs, we want to runtime-unroll loops to make better use if the
5481/// OOO engine's wide instruction window and various predictors.
5482static void
5485 const AArch64TTIImpl &TTI) {
5486 // Limit loops with structure that is highly likely to benefit from runtime
5487 // unrolling; that is we exclude outer loops and loops with many blocks (i.e.
5488 // likely with complex control flow). Note that the heuristics here may be
5489 // overly conservative and we err on the side of avoiding runtime unrolling
5490 // rather than unroll excessively. They are all subject to further refinement.
5491 if (!L->isInnermost() || L->getNumBlocks() > 8)
5492 return;
5493
5494 // Loops with multiple exits are handled by common code.
5495 if (!L->getExitBlock())
5496 return;
5497
5498 // Check if the loop contains any reductions that could be parallelized when
5499 // unrolling. If so, enable partial unrolling, if the trip count is know to be
5500 // a multiple of 2.
5501 bool HasParellelizableReductions =
5502 L->getNumBlocks() == 1 &&
5503 any_of(L->getHeader()->phis(),
5504 [&SE, L](PHINode &Phi) {
5505 return canParallelizeReductionWhenUnrolling(Phi, L, &SE);
5506 }) &&
5507 isLoopSizeWithinBudget(L, TTI, 12, nullptr);
5508 if (HasParellelizableReductions &&
5509 SE.getSmallConstantTripMultiple(L, L->getExitingBlock()) % 2 == 0) {
5510 UP.Partial = true;
5511 UP.MaxCount = 4;
5512 UP.AddAdditionalAccumulators = true;
5513 }
5514
5515 const SCEV *BTC = SE.getSymbolicMaxBackedgeTakenCount(L);
5517 (SE.getSmallConstantMaxTripCount(L) > 0 &&
5518 SE.getSmallConstantMaxTripCount(L) <= 32))
5519 return;
5520
5521 if (findStringMetadataForLoop(L, "llvm.loop.isvectorized"))
5522 return;
5523
5525 return;
5526
5527 // Limit to loops with trip counts that are cheap to expand.
5528 UP.SCEVExpansionBudget = 1;
5529
5530 if (HasParellelizableReductions) {
5531 UP.Runtime = true;
5533 UP.AddAdditionalAccumulators = true;
5534 }
5535
5536 // Try to unroll small loops, of few-blocks with low budget, if they have
5537 // load/store dependencies, to expose more parallel memory access streams,
5538 // or if they do little work inside a block (i.e. load -> X -> store pattern).
5539 BasicBlock *Header = L->getHeader();
5540 BasicBlock *Latch = L->getLoopLatch();
5541 if (Header == Latch) {
5542 // Estimate the size of the loop.
5543 unsigned Size;
5544 unsigned Width = 10;
5545 if (!isLoopSizeWithinBudget(L, TTI, Width, &Size))
5546 return;
5547
5548 // Try to find an unroll count that maximizes the use of the instruction
5549 // window, i.e. trying to fetch as many instructions per cycle as possible.
5550 unsigned MaxInstsPerLine = 16;
5551 unsigned UC = 1;
5552 unsigned BestUC = 1;
5553 unsigned SizeWithBestUC = BestUC * Size;
5554 while (UC <= 8) {
5555 unsigned SizeWithUC = UC * Size;
5556 if (SizeWithUC > 48)
5557 break;
5558 if ((SizeWithUC % MaxInstsPerLine) == 0 ||
5559 (SizeWithBestUC % MaxInstsPerLine) < (SizeWithUC % MaxInstsPerLine)) {
5560 BestUC = UC;
5561 SizeWithBestUC = BestUC * Size;
5562 }
5563 UC++;
5564 }
5565
5566 if (BestUC == 1)
5567 return;
5568
5569 SmallPtrSet<Value *, 8> LoadedValuesPlus;
5571 for (auto *BB : L->blocks()) {
5572 for (auto &I : *BB) {
5574 if (!Ptr)
5575 continue;
5576 const SCEV *PtrSCEV = SE.getSCEV(Ptr);
5577 if (SE.isLoopInvariant(PtrSCEV, L))
5578 continue;
5579 if (isa<LoadInst>(&I)) {
5580 LoadedValuesPlus.insert(&I);
5581 // Include in-loop 1st users of loaded values.
5582 for (auto *U : I.users())
5583 if (L->contains(cast<Instruction>(U)))
5584 LoadedValuesPlus.insert(U);
5585 } else
5586 Stores.push_back(cast<StoreInst>(&I));
5587 }
5588 }
5589
5590 if (none_of(Stores, [&LoadedValuesPlus](StoreInst *SI) {
5591 return LoadedValuesPlus.contains(SI->getOperand(0));
5592 }))
5593 return;
5594
5595 UP.Runtime = true;
5596 UP.DefaultUnrollRuntimeCount = BestUC;
5597 return;
5598 }
5599
5600 // Try to runtime-unroll loops with early-continues depending on loop-varying
5601 // loads; this helps with branch-prediction for the early-continues.
5602 auto *Term = dyn_cast<CondBrInst>(Header->getTerminator());
5604 if (!Term || Preds.size() == 1 || !llvm::is_contained(Preds, Header) ||
5605 none_of(Preds, [L](BasicBlock *Pred) { return L->contains(Pred); }))
5606 return;
5607
5608 std::function<bool(Instruction *, unsigned)> DependsOnLoopLoad =
5609 [&](Instruction *I, unsigned Depth) -> bool {
5610 if (isa<PHINode>(I) || L->isLoopInvariant(I) || Depth > 8)
5611 return false;
5612
5613 if (isa<LoadInst>(I))
5614 return true;
5615
5616 return any_of(I->operands(), [&](Value *V) {
5617 auto *I = dyn_cast<Instruction>(V);
5618 return I && DependsOnLoopLoad(I, Depth + 1);
5619 });
5620 };
5621 CmpPredicate Pred;
5622 Instruction *I;
5623 if (match(Term, m_Br(m_ICmp(Pred, m_Instruction(I), m_Value()), m_Value(),
5624 m_Value())) &&
5625 DependsOnLoopLoad(I, 0)) {
5626 UP.Runtime = true;
5627 }
5628}
5629
5632 OptimizationRemarkEmitter *ORE) const {
5633 // Enable partial unrolling and runtime unrolling.
5634 BaseT::getUnrollingPreferences(L, SE, UP, ORE);
5635
5636 UP.UpperBound = true;
5637
5638 // For inner loop, it is more likely to be a hot one, and the runtime check
5639 // can be promoted out from LICM pass, so the overhead is less, let's try
5640 // a larger threshold to unroll more loops.
5641 if (L->getLoopDepth() > 1)
5642 UP.PartialThreshold *= 2;
5643
5644 // Disable partial & runtime unrolling on -Os.
5646
5647 // Scan the loop: don't unroll loops with calls as this could prevent
5648 // inlining. Don't unroll auto-vectorized loops either, though do allow
5649 // unrolling of the scalar remainder.
5650 bool IsVectorized = getBooleanLoopAttribute(L, "llvm.loop.isvectorized");
5652 for (auto *BB : L->getBlocks()) {
5653 for (auto &I : *BB) {
5654 // Both auto-vectorized loops and the scalar remainder have the
5655 // isvectorized attribute, so differentiate between them by the presence
5656 // of vector instructions.
5657 if (IsVectorized && I.getType()->isVectorTy())
5658 return;
5659 if (isa<CallBase>(I)) {
5662 if (!isLoweredToCall(F))
5663 continue;
5664 return;
5665 }
5666
5667 SmallVector<const Value *, 4> Operands(I.operand_values());
5668 Cost += getInstructionCost(&I, Operands,
5670 }
5671 }
5672
5673 // Apply subtarget-specific unrolling preferences.
5674 if (ST->isAppleMLike())
5675 getAppleRuntimeUnrollPreferences(L, SE, UP, *this);
5676 else if (ST->getProcFamily() == AArch64Subtarget::Falkor &&
5679
5680 // If this is a small, multi-exit loop similar to something like std::find,
5681 // then there is typically a performance improvement achieved by unrolling.
5682 if (!L->getExitBlock() && shouldUnrollMultiExitLoop(L, SE, *this)) {
5683 UP.RuntimeUnrollMultiExit = true;
5684 UP.Runtime = true;
5685 // Limit unroll count.
5687 // Allow slightly more costly trip-count expansion to catch search loops
5688 // with pointer inductions.
5689 UP.SCEVExpansionBudget = 5;
5690 return;
5691 }
5692
5693 // Enable runtime unrolling for in-order models
5694 // If mcpu is omitted, getProcFamily() returns AArch64Subtarget::Others, so by
5695 // checking for that case, we can ensure that the default behaviour is
5696 // unchanged
5697 if (ST->getProcFamily() != AArch64Subtarget::Generic &&
5698 !ST->getSchedModel().isOutOfOrder()) {
5699 UP.Runtime = true;
5700 UP.Partial = true;
5701 UP.UnrollRemainder = true;
5703
5704 UP.UnrollAndJam = true;
5706 }
5707
5708 // Force unrolling small loops can be very useful because of the branch
5709 // taken cost of the backedge.
5711 UP.Force = true;
5712}
5713
5718
5720 Type *ExpectedType,
5721 bool CanCreate) const {
5722 switch (Inst->getIntrinsicID()) {
5723 default:
5724 return nullptr;
5725 case Intrinsic::aarch64_neon_st1x2:
5726 case Intrinsic::aarch64_neon_st1x3:
5727 case Intrinsic::aarch64_neon_st1x4:
5728 case Intrinsic::aarch64_neon_st2:
5729 case Intrinsic::aarch64_neon_st3:
5730 case Intrinsic::aarch64_neon_st4: {
5731 // Create a struct type
5732 StructType *ST = dyn_cast<StructType>(ExpectedType);
5733 if (!CanCreate || !ST)
5734 return nullptr;
5735 unsigned NumElts = Inst->arg_size() - 1;
5736 if (ST->getNumElements() != NumElts)
5737 return nullptr;
5738 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5739 if (Inst->getArgOperand(i)->getType() != ST->getElementType(i))
5740 return nullptr;
5741 }
5742 Value *Res = PoisonValue::get(ExpectedType);
5743 IRBuilder<> Builder(Inst);
5744 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5745 Value *L = Inst->getArgOperand(i);
5746 Res = Builder.CreateInsertValue(Res, L, i);
5747 }
5748 return Res;
5749 }
5750 case Intrinsic::aarch64_neon_ld1x2:
5751 case Intrinsic::aarch64_neon_ld1x3:
5752 case Intrinsic::aarch64_neon_ld1x4:
5753 case Intrinsic::aarch64_neon_ld2:
5754 case Intrinsic::aarch64_neon_ld3:
5755 case Intrinsic::aarch64_neon_ld4:
5756 if (Inst->getType() == ExpectedType)
5757 return Inst;
5758 return nullptr;
5759 }
5760}
5761
5763 MemIntrinsicInfo &Info) const {
5764 switch (Inst->getIntrinsicID()) {
5765 default:
5766 break;
5767 case Intrinsic::aarch64_neon_ld1x2:
5768 case Intrinsic::aarch64_neon_ld1x3:
5769 case Intrinsic::aarch64_neon_ld1x4:
5770 case Intrinsic::aarch64_neon_ld2:
5771 case Intrinsic::aarch64_neon_ld3:
5772 case Intrinsic::aarch64_neon_ld4:
5773 Info.ReadMem = true;
5774 Info.WriteMem = false;
5775 Info.PtrVal = Inst->getArgOperand(0);
5776 break;
5777 case Intrinsic::aarch64_neon_st1x2:
5778 case Intrinsic::aarch64_neon_st1x3:
5779 case Intrinsic::aarch64_neon_st1x4:
5780 case Intrinsic::aarch64_neon_st2:
5781 case Intrinsic::aarch64_neon_st3:
5782 case Intrinsic::aarch64_neon_st4:
5783 Info.ReadMem = false;
5784 Info.WriteMem = true;
5785 Info.PtrVal = Inst->getArgOperand(Inst->arg_size() - 1);
5786 break;
5787 }
5788
5789 // Use the ID of neon load as the "matching id".
5790 switch (Inst->getIntrinsicID()) {
5791 default:
5792 return false;
5793 case Intrinsic::aarch64_neon_ld1x2:
5794 case Intrinsic::aarch64_neon_st1x2:
5795 Info.MatchingId = Intrinsic::aarch64_neon_ld1x2;
5796 break;
5797 case Intrinsic::aarch64_neon_ld1x3:
5798 case Intrinsic::aarch64_neon_st1x3:
5799 Info.MatchingId = Intrinsic::aarch64_neon_ld1x3;
5800 break;
5801 case Intrinsic::aarch64_neon_ld1x4:
5802 case Intrinsic::aarch64_neon_st1x4:
5803 Info.MatchingId = Intrinsic::aarch64_neon_ld1x4;
5804 break;
5805 case Intrinsic::aarch64_neon_ld2:
5806 case Intrinsic::aarch64_neon_st2:
5807 Info.MatchingId = Intrinsic::aarch64_neon_ld2;
5808 break;
5809 case Intrinsic::aarch64_neon_ld3:
5810 case Intrinsic::aarch64_neon_st3:
5811 Info.MatchingId = Intrinsic::aarch64_neon_ld3;
5812 break;
5813 case Intrinsic::aarch64_neon_ld4:
5814 case Intrinsic::aarch64_neon_st4:
5815 Info.MatchingId = Intrinsic::aarch64_neon_ld4;
5816 break;
5817 }
5818 return true;
5819}
5820
5821/// See if \p I should be considered for address type promotion. We check if \p
5822/// I is a sext with right type and used in memory accesses. If it used in a
5823/// "complex" getelementptr, we allow it to be promoted without finding other
5824/// sext instructions that sign extended the same initial value. A getelementptr
5825/// is considered as "complex" if it has more than 2 operands.
5827 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const {
5828 bool Considerable = false;
5829 AllowPromotionWithoutCommonHeader = false;
5830 if (!isa<SExtInst>(&I))
5831 return false;
5832 Type *ConsideredSExtType =
5833 Type::getInt64Ty(I.getParent()->getParent()->getContext());
5834 if (I.getType() != ConsideredSExtType)
5835 return false;
5836 // See if the sext is the one with the right type and used in at least one
5837 // GetElementPtrInst.
5838 for (const User *U : I.users()) {
5839 if (const GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
5840 Considerable = true;
5841 // A getelementptr is considered as "complex" if it has more than 2
5842 // operands. We will promote a SExt used in such complex GEP as we
5843 // expect some computation to be merged if they are done on 64 bits.
5844 if (GEPInst->getNumOperands() > 2) {
5845 AllowPromotionWithoutCommonHeader = true;
5846 break;
5847 }
5848 }
5849 }
5850 return Considerable;
5851}
5852
5854 const RecurrenceDescriptor &RdxDesc, ElementCount VF) const {
5855 if (!VF.isScalable())
5856 return true;
5857
5858 Type *Ty = RdxDesc.getRecurrenceType();
5859 if (Ty->isBFloatTy() || !isElementTypeLegalForScalableVector(Ty))
5860 return false;
5861
5862 switch (RdxDesc.getRecurrenceKind()) {
5863 case RecurKind::Sub:
5864 case RecurKind::FSub:
5867 case RecurKind::Add:
5868 case RecurKind::FAdd:
5869 case RecurKind::And:
5870 case RecurKind::Or:
5871 case RecurKind::Xor:
5872 case RecurKind::SMin:
5873 case RecurKind::SMax:
5874 case RecurKind::UMin:
5875 case RecurKind::UMax:
5876 case RecurKind::FMin:
5877 case RecurKind::FMax:
5878 case RecurKind::FMulAdd:
5879 case RecurKind::AnyOf:
5881 return true;
5882 default:
5883 return false;
5884 }
5885}
5886
5889 FastMathFlags FMF,
5891 // The code-generator is currently not able to handle scalable vectors
5892 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
5893 // it. This change will be removed when code-generation for these types is
5894 // sufficiently reliable.
5895 if (auto *VTy = dyn_cast<ScalableVectorType>(Ty))
5896 if (VTy->getElementCount() == ElementCount::getScalable(1))
5898
5899 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
5900
5901 if (LT.second.getScalarType() == MVT::f16 && !ST->hasFullFP16())
5902 return BaseT::getMinMaxReductionCost(IID, Ty, FMF, CostKind);
5903
5904 InstructionCost LegalizationCost = 0;
5905 if (LT.first > 1) {
5906 Type *LegalVTy = EVT(LT.second).getTypeForEVT(Ty->getContext());
5907 IntrinsicCostAttributes Attrs(IID, LegalVTy, {LegalVTy, LegalVTy}, FMF);
5908 LegalizationCost = getIntrinsicInstrCost(Attrs, CostKind) * (LT.first - 1);
5909 }
5910
5911 return LegalizationCost + /*Cost of horizontal reduction*/ 2;
5912}
5913
5915 unsigned Opcode, VectorType *ValTy, TTI::TargetCostKind CostKind) const {
5916 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
5917 InstructionCost LegalizationCost = 0;
5918 if (LT.first > 1) {
5919 Type *LegalVTy = EVT(LT.second).getTypeForEVT(ValTy->getContext());
5920 LegalizationCost = getArithmeticInstrCost(Opcode, LegalVTy, CostKind);
5921 LegalizationCost *= LT.first - 1;
5922 }
5923
5924 int ISD = TLI->InstructionOpcodeToISD(Opcode);
5925 assert(ISD && "Invalid opcode");
5926 // Add the final reduction cost for the legal horizontal reduction
5927 switch (ISD) {
5928 case ISD::ADD:
5929 case ISD::AND:
5930 case ISD::OR:
5931 case ISD::XOR:
5932 case ISD::FADD:
5933 return LegalizationCost + 2;
5934 default:
5936 }
5937}
5938
5941 std::optional<FastMathFlags> FMF,
5943 // The code-generator is currently not able to handle scalable vectors
5944 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
5945 // it. This change will be removed when code-generation for these types is
5946 // sufficiently reliable.
5947 if (auto *VTy = dyn_cast<ScalableVectorType>(ValTy))
5948 if (VTy->getElementCount() == ElementCount::getScalable(1))
5950
5952 if (auto *FixedVTy = dyn_cast<FixedVectorType>(ValTy)) {
5953 InstructionCost BaseCost =
5954 BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
5955 // Add on extra cost to reflect the extra overhead on some CPUs. We still
5956 // end up vectorizing for more computationally intensive loops.
5957 return BaseCost + FixedVTy->getNumElements();
5958 }
5959
5960 if (Opcode != Instruction::FAdd || ValTy->getElementType()->isBFloatTy())
5962
5963 auto *VTy = cast<ScalableVectorType>(ValTy);
5965 getArithmeticInstrCost(Opcode, VTy->getScalarType(), CostKind);
5966 Cost *= getMaxNumElements(VTy->getElementCount());
5967 return Cost;
5968 }
5969
5970 if (isa<ScalableVectorType>(ValTy))
5971 return getArithmeticReductionCostSVE(Opcode, ValTy, CostKind);
5972
5973 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
5974 MVT MTy = LT.second;
5975 int ISD = TLI->InstructionOpcodeToISD(Opcode);
5976 assert(ISD && "Invalid opcode");
5977
5978 // Horizontal adds can use the 'addv' instruction. We model the cost of these
5979 // instructions as twice a normal vector add, plus 1 for each legalization
5980 // step (LT.first). This is the only arithmetic vector reduction operation for
5981 // which we have an instruction.
5982 // OR, XOR and AND costs should match the codegen from:
5983 // OR: llvm/test/CodeGen/AArch64/reduce-or.ll
5984 // XOR: llvm/test/CodeGen/AArch64/reduce-xor.ll
5985 // AND: llvm/test/CodeGen/AArch64/reduce-and.ll
5986 static const CostTblEntry CostTblNoPairwise[]{
5987 {ISD::ADD, MVT::v8i8, 2},
5988 {ISD::ADD, MVT::v16i8, 2},
5989 {ISD::ADD, MVT::v4i16, 2},
5990 {ISD::ADD, MVT::v8i16, 2},
5991 {ISD::ADD, MVT::v2i32, 2},
5992 {ISD::ADD, MVT::v4i32, 2},
5993 {ISD::ADD, MVT::v2i64, 2},
5994 {ISD::OR, MVT::v8i8, 5}, // fmov + orr_lsr + orr_lsr + lsr + orr
5995 {ISD::OR, MVT::v16i8, 7}, // ext + orr + same as v8i8
5996 {ISD::OR, MVT::v4i16, 4}, // fmov + orr_lsr + lsr + orr
5997 {ISD::OR, MVT::v8i16, 6}, // ext + orr + same as v4i16
5998 {ISD::OR, MVT::v2i32, 3}, // fmov + lsr + orr
5999 {ISD::OR, MVT::v4i32, 5}, // ext + orr + same as v2i32
6000 {ISD::OR, MVT::v2i64, 3}, // ext + orr + fmov
6001 {ISD::XOR, MVT::v8i8, 5}, // Same as above for or...
6002 {ISD::XOR, MVT::v16i8, 7},
6003 {ISD::XOR, MVT::v4i16, 4},
6004 {ISD::XOR, MVT::v8i16, 6},
6005 {ISD::XOR, MVT::v2i32, 3},
6006 {ISD::XOR, MVT::v4i32, 5},
6007 {ISD::XOR, MVT::v2i64, 3},
6008 {ISD::AND, MVT::v8i8, 5}, // Same as above for or...
6009 {ISD::AND, MVT::v16i8, 7},
6010 {ISD::AND, MVT::v4i16, 4},
6011 {ISD::AND, MVT::v8i16, 6},
6012 {ISD::AND, MVT::v2i32, 3},
6013 {ISD::AND, MVT::v4i32, 5},
6014 {ISD::AND, MVT::v2i64, 3},
6015 };
6016 switch (ISD) {
6017 default:
6018 break;
6019 case ISD::FADD:
6020 if (Type *EltTy = ValTy->getScalarType();
6021 // FIXME: For half types without fullfp16 support, this could extend and
6022 // use a fp32 faddp reduction but current codegen unrolls.
6023 MTy.isVector() && (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
6024 (EltTy->isHalfTy() && ST->hasFullFP16()))) {
6025 const unsigned NElts = MTy.getVectorNumElements();
6026 if (ValTy->getElementCount().getFixedValue() >= 2 && NElts >= 2 &&
6027 isPowerOf2_32(NElts))
6028 // Reduction corresponding to series of fadd instructions is lowered to
6029 // series of faddp instructions. faddp has latency/throughput that
6030 // matches fadd instruction and hence, every faddp instruction can be
6031 // considered to have a relative cost = 1 with
6032 // CostKind = TCK_RecipThroughput.
6033 // An faddp will pairwise add vector elements, so the size of input
6034 // vector reduces by half every time, requiring
6035 // #(faddp instructions) = log2_32(NElts).
6036 return (LT.first - 1) + /*No of faddp instructions*/ Log2_32(NElts);
6037 }
6038 break;
6039 case ISD::ADD:
6040 if (const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy))
6041 return (LT.first - 1) + Entry->Cost;
6042 break;
6043 case ISD::XOR:
6044 case ISD::AND:
6045 case ISD::OR:
6046 const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy);
6047 if (!Entry)
6048 break;
6049 auto *ValVTy = cast<FixedVectorType>(ValTy);
6050 if (MTy.getVectorNumElements() <= ValVTy->getNumElements() &&
6051 isPowerOf2_32(ValVTy->getNumElements())) {
6052 InstructionCost ExtraCost = 0;
6053 if (LT.first != 1) {
6054 // Type needs to be split, so there is an extra cost of LT.first - 1
6055 // arithmetic ops.
6056 auto *Ty = FixedVectorType::get(ValTy->getElementType(),
6057 MTy.getVectorNumElements());
6058 ExtraCost = getArithmeticInstrCost(Opcode, Ty, CostKind);
6059 ExtraCost *= LT.first - 1;
6060 }
6061 // All and/or/xor of i1 will be lowered with maxv/minv/addv + fmov
6062 auto Cost = ValVTy->getElementType()->isIntegerTy(1) ? 2 : Entry->Cost;
6063 return Cost + ExtraCost;
6064 }
6065 break;
6066 }
6067 return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
6068}
6069
6071 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *VecTy,
6072 std::optional<FastMathFlags> FMF, TTI::TargetCostKind CostKind) const {
6073 EVT VecVT = TLI->getValueType(DL, VecTy);
6074 EVT ResVT = TLI->getValueType(DL, ResTy);
6075
6076 if (Opcode == Instruction::Add && VecVT.isSimple() && ResVT.isSimple() &&
6077 VecVT.getSizeInBits() >= 64) {
6078 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(VecTy);
6079
6080 // The legal cases are:
6081 // UADDLV 8/16/32->32
6082 // UADDLP 32->64
6083 unsigned RevVTSize = ResVT.getSizeInBits();
6084 if (((LT.second == MVT::v8i8 || LT.second == MVT::v16i8) &&
6085 RevVTSize <= 32) ||
6086 ((LT.second == MVT::v4i16 || LT.second == MVT::v8i16) &&
6087 RevVTSize <= 32) ||
6088 ((LT.second == MVT::v2i32 || LT.second == MVT::v4i32) &&
6089 RevVTSize <= 64))
6090 return (LT.first - 1) * 2 + 2;
6091 }
6092
6093 return BaseT::getExtendedReductionCost(Opcode, IsUnsigned, ResTy, VecTy, FMF,
6094 CostKind);
6095}
6096
6098AArch64TTIImpl::getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode,
6099 Type *ResTy, VectorType *VecTy,
6101 EVT VecVT = TLI->getValueType(DL, VecTy);
6102 EVT ResVT = TLI->getValueType(DL, ResTy);
6103
6104 if (ST->hasDotProd() && VecVT.isSimple() && ResVT.isSimple() &&
6105 RedOpcode == Instruction::Add) {
6106 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(VecTy);
6107
6108 // The legal cases with dotprod are
6109 // UDOT 8->32
6110 // Which requires an additional uaddv to sum the i32 values.
6111 if ((LT.second == MVT::v8i8 || LT.second == MVT::v16i8) &&
6112 ResVT == MVT::i32)
6113 return LT.first + 2;
6114 }
6115
6116 return BaseT::getMulAccReductionCost(IsUnsigned, RedOpcode, ResTy, VecTy,
6117 CostKind);
6118}
6119
6123 static const CostTblEntry ShuffleTbl[] = {
6124 { TTI::SK_Splice, MVT::nxv16i8, 1 },
6125 { TTI::SK_Splice, MVT::nxv8i16, 1 },
6126 { TTI::SK_Splice, MVT::nxv4i32, 1 },
6127 { TTI::SK_Splice, MVT::nxv2i64, 1 },
6128 { TTI::SK_Splice, MVT::nxv2f16, 1 },
6129 { TTI::SK_Splice, MVT::nxv4f16, 1 },
6130 { TTI::SK_Splice, MVT::nxv8f16, 1 },
6131 { TTI::SK_Splice, MVT::nxv2bf16, 1 },
6132 { TTI::SK_Splice, MVT::nxv4bf16, 1 },
6133 { TTI::SK_Splice, MVT::nxv8bf16, 1 },
6134 { TTI::SK_Splice, MVT::nxv2f32, 1 },
6135 { TTI::SK_Splice, MVT::nxv4f32, 1 },
6136 { TTI::SK_Splice, MVT::nxv2f64, 1 },
6137 };
6138
6139 // The code-generator is currently not able to handle scalable vectors
6140 // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
6141 // it. This change will be removed when code-generation for these types is
6142 // sufficiently reliable.
6145
6146 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Tp);
6147 Type *LegalVTy = EVT(LT.second).getTypeForEVT(Tp->getContext());
6148 EVT PromotedVT = LT.second.getScalarType() == MVT::i1
6149 ? TLI->getPromotedVTForPredicate(EVT(LT.second))
6150 : LT.second;
6151 Type *PromotedVTy = EVT(PromotedVT).getTypeForEVT(Tp->getContext());
6152 InstructionCost LegalizationCost = 0;
6153 if (Index < 0) {
6154 LegalizationCost =
6155 getCmpSelInstrCost(Instruction::ICmp, PromotedVTy, PromotedVTy,
6157 getCmpSelInstrCost(Instruction::Select, PromotedVTy, LegalVTy,
6159 }
6160
6161 // Predicated splice are promoted when lowering. See AArch64ISelLowering.cpp
6162 // Cost performed on a promoted type.
6163 if (LT.second.getScalarType() == MVT::i1) {
6164 LegalizationCost +=
6165 getCastInstrCost(Instruction::ZExt, PromotedVTy, LegalVTy,
6167 getCastInstrCost(Instruction::Trunc, LegalVTy, PromotedVTy,
6169 }
6170 const auto *Entry =
6171 CostTableLookup(ShuffleTbl, TTI::SK_Splice, PromotedVT.getSimpleVT());
6172 assert(Entry && "Illegal Type for Splice");
6173 LegalizationCost += Entry->Cost;
6174 return LegalizationCost * LT.first;
6175}
6176
6178 unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType,
6180 TTI::PartialReductionExtendKind OpBExtend, std::optional<unsigned> BinOp,
6181 TTI::TargetCostKind CostKind, std::optional<FastMathFlags> FMF) const {
6183
6185 return Invalid;
6186
6187 if ((Opcode != Instruction::Add && Opcode != Instruction::Sub &&
6188 Opcode != Instruction::FAdd && Opcode != Instruction::FSub) ||
6189 OpAExtend == TTI::PR_None)
6190 return Invalid;
6191
6192 // Floating-point partial reductions are invalid if `reassoc` and `contract`
6193 // are not allowed.
6194 if (AccumType->isFloatingPointTy()) {
6195 assert(FMF && "Missing FastMathFlags for floating-point partial reduction");
6196 if (!FMF->allowReassoc() || !FMF->allowContract())
6197 return Invalid;
6198 } else {
6199 assert(!FMF &&
6200 "FastMathFlags only apply to floating-point partial reductions");
6201 }
6202
6203 assert((BinOp || (OpBExtend == TTI::PR_None && !InputTypeB)) &&
6204 (!BinOp || (OpBExtend != TTI::PR_None && InputTypeB)) &&
6205 "Unexpected values for OpBExtend or InputTypeB");
6206
6207 // We only support multiply binary operations for now, and for muls we
6208 // require the types being extended to be the same.
6209 if (BinOp && ((*BinOp != Instruction::Mul && *BinOp != Instruction::FMul) ||
6210 InputTypeA != InputTypeB))
6211 return Invalid;
6212
6213 bool IsUSDot = OpBExtend != TTI::PR_None && OpAExtend != OpBExtend;
6214 // USDot is natively supported with +i8mm. With plain +dotprod, SUMLA is
6215 // lowered to two udots plus an eor and a sub.
6216 if (IsUSDot && !ST->hasMatMulInt8() && !ST->hasDotProd())
6217 // FIXME: Remove this early bailout in favour of expand cost.
6218 return Invalid;
6219
6220 unsigned Ratio =
6221 AccumType->getScalarSizeInBits() / InputTypeA->getScalarSizeInBits();
6222 if (VF.getKnownMinValue() <= Ratio)
6223 return Invalid;
6224
6225 VectorType *InputVectorType = VectorType::get(InputTypeA, VF);
6226 VectorType *AccumVectorType =
6227 VectorType::get(AccumType, VF.divideCoefficientBy(Ratio));
6228 // We don't yet support all kinds of legalization.
6229 auto TC = TLI->getTypeConversion(AccumVectorType->getContext(),
6230 EVT::getEVT(AccumVectorType));
6231 switch (TC.first) {
6232 default:
6233 return Invalid;
6237 // The legalised type (e.g. after splitting) must be legal too.
6238 if (TLI->getTypeAction(AccumVectorType->getContext(), TC.second) !=
6240 return Invalid;
6241 break;
6242 }
6243
6244 std::pair<InstructionCost, MVT> AccumLT =
6245 getTypeLegalizationCost(AccumVectorType);
6246 std::pair<InstructionCost, MVT> InputLT =
6247 getTypeLegalizationCost(InputVectorType);
6248
6249 // Returns true if the subtarget supports the operation for a given type.
6250 auto IsSupported = [&](bool SVEPred, bool NEONPred) -> bool {
6251 return (ST->isSVEorStreamingSVEAvailable() && SVEPred) ||
6252 (AccumLT.second.isFixedLengthVector() &&
6253 AccumLT.second.getSizeInBits() <= 128 && ST->isNeonAvailable() &&
6254 NEONPred);
6255 };
6256
6257 bool IsSub = Opcode == Instruction::Sub || Opcode == Instruction::FSub;
6258 InstructionCost Cost = InputLT.first * TTI::TCC_Basic;
6259 // Integer partial sub-reductions that don't map to a specific instruction,
6260 // carry an extra cost for implementing a double negation:
6261 // partial_reduce_umls acc, lhs, rhs
6262 // <=> -partial_reduce_umla -acc, lhs, rhs
6263 InstructionCost INegCost = IsSub ? 2 * InputLT.first * TTI::TCC_Basic : 0;
6264
6265 if (AccumLT.second.getScalarType() == MVT::i32 &&
6266 InputLT.second.getScalarType() == MVT::i8) {
6267 // i8 -> i32 is natively supported with udot/sdot for both NEON and SVE.
6268 if (!IsUSDot && IsSupported(true, ST->hasDotProd()))
6269 return Cost + INegCost;
6270 // i8 -> i32 usdot requires +i8mm
6271 if (IsUSDot && IsSupported(ST->hasMatMulInt8(), ST->hasMatMulInt8()))
6272 return Cost + INegCost;
6273 // Without +i8mm, lower SUMLA via two udots plus an eor and a sub on plain
6274 // +dotprod targets. Note that this is only implemented for NEON, as all
6275 // modern CPUs with SVE also have +i8mm. Charge an extra factor for the
6276 // expansion.
6277 if (IsUSDot && IsSupported(false, ST->hasDotProd()))
6278 return Cost * 3 + INegCost;
6279 }
6280
6281 if (ST->isSVEorStreamingSVEAvailable() && !IsUSDot) {
6282 // i16 -> i64 is natively supported for udot/sdot
6283 if (AccumLT.second.getScalarType() == MVT::i64 &&
6284 InputLT.second.getScalarType() == MVT::i16)
6285 return Cost + INegCost;
6286 // i16 -> i32 is natively supported with SVE2p1 udot/sdot.
6287 // For sub-reductions, we prefer using the *mlslb/t instructions.
6288 if (AccumLT.second.getScalarType() == MVT::i32 &&
6289 InputLT.second.getScalarType() == MVT::i16 &&
6290 (ST->hasSVE2p1() || ST->hasSME2()) && !IsSub)
6291 return Cost;
6292 // i8 -> i64 is supported with an extra level of extends
6293 if (AccumLT.second.getScalarType() == MVT::i64 &&
6294 InputLT.second.getScalarType() == MVT::i8)
6295 // FIXME: This cost should probably be a little higher, e.g. Cost + 2
6296 // because it requires two extra extends on the inputs. But if we'd change
6297 // that now, a regular reduction would be cheaper because the costs of
6298 // the extends in the IR are still counted. This can be fixed
6299 // after https://github.com/llvm/llvm-project/pull/147302 has landed.
6300 return Cost + INegCost;
6301 // i8 -> i16 is natively supported with SVE2p3 udot/sdot
6302 // For sub-reductions, we prefer using the *mlslb/t instructions.
6303 if (AccumLT.second.getScalarType() == MVT::i16 &&
6304 InputLT.second.getScalarType() == MVT::i8 &&
6305 (ST->hasSVE2p3() || ST->hasSME2p3()) && !IsSub)
6306 return Cost;
6307 }
6308
6309 // f16 -> f32 is natively supported for fdot using either
6310 // SVE or NEON instruction.
6311 if (Opcode == Instruction::FAdd && !IsSub &&
6312 IsSupported(ST->hasSME2() || ST->hasSVE2p1(), ST->hasF16F32DOT()) &&
6313 AccumLT.second.getScalarType() == MVT::f32 &&
6314 InputLT.second.getScalarType() == MVT::f16)
6315 return Cost;
6316
6317 // For a ratio of 2, we can use *mlal and *mlsl top/bottom instructions.
6318 if (Ratio == 2 && !IsUSDot) {
6319 MVT InVT = InputLT.second.getScalarType();
6320
6321 // SVE2 [us]ml[as]lb/t and NEON [us]ml[as]l(2)
6322 if (IsSupported(ST->hasSVE2() || ST->hasSME(), true) &&
6323 llvm::is_contained({MVT::i8, MVT::i16, MVT::i32}, InVT.SimpleTy))
6324 return Cost * 2;
6325
6326 // SVE2 fml[as]lb/t and NEON fml[as]l(2)
6327 if (IsSupported(ST->hasSVE2(), ST->hasFP16FML()) && InVT == MVT::f16)
6328 return Cost * 2;
6329
6330 // SME2/SVE2p1 bfmlslb/t
6331 if (IsSupported(ST->hasSVE2p1() || ST->hasSME2(), false) &&
6332 InVT == MVT::bf16 && IsSub)
6333 return Cost * 2;
6334
6335 // FP partial sub-reductions that don't map to a specific instruction,
6336 // carry an extra cost for implementing an extra negation:
6337 // partial_reduce_fmls acc, lhs, rhs
6338 // <=> partial_reduce_fmla acc, lhs, -rhs
6339 InstructionCost FNegCost = IsSub ? InputLT.first * TTI::TCC_Basic : 0;
6340
6341 // SVE and NEON bfmlalb/t
6342 if (IsSupported(ST->hasBF16(), ST->hasBF16()) && InVT == MVT::bf16)
6343 return Cost * 2 + FNegCost;
6344 }
6345
6346 return BaseT::getPartialReductionCost(Opcode, InputTypeA, InputTypeB,
6347 AccumType, VF, OpAExtend, OpBExtend,
6348 BinOp, CostKind, FMF);
6349}
6350
6353 VectorType *SrcTy, ArrayRef<int> Mask,
6354 TTI::TargetCostKind CostKind, int Index,
6356 const Instruction *CxtI) const {
6357 assert((Mask.empty() || DstTy->isScalableTy() ||
6358 Mask.size() == DstTy->getElementCount().getKnownMinValue()) &&
6359 "Expected the Mask to match the return size if given");
6360 assert(SrcTy->getScalarType() == DstTy->getScalarType() &&
6361 "Expected the same scalar types");
6362 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(SrcTy);
6363
6364 // If we have a Mask, and the LT is being legalized somehow, split the Mask
6365 // into smaller vectors and sum the cost of each shuffle.
6366 if (!Mask.empty() && isa<FixedVectorType>(SrcTy) && LT.second.isVector() &&
6367 LT.second.getScalarSizeInBits() * Mask.size() > 128 &&
6368 SrcTy->getScalarSizeInBits() == LT.second.getScalarSizeInBits() &&
6369 Mask.size() > LT.second.getVectorNumElements() && !Index && !SubTp) {
6370 // Check for LD3/LD4 instructions, which are represented in llvm IR as
6371 // deinterleaving-shuffle(load). The shuffle cost could potentially be free,
6372 // but we model it with a cost of LT.first so that LD3/LD4 have a higher
6373 // cost than just the load.
6374 if (Args.size() >= 1 && isa<LoadInst>(Args[0]) &&
6377 return std::max<InstructionCost>(1, LT.first / 4);
6378
6379 // Check for ST3/ST4 instructions, which are represented in llvm IR as
6380 // store(interleaving-shuffle). The shuffle cost could potentially be free,
6381 // but we model it with a cost of LT.first so that ST3/ST4 have a higher
6382 // cost than just the store.
6383 if (CxtI && CxtI->hasOneUse() && isa<StoreInst>(*CxtI->user_begin()) &&
6385 Mask, 4, SrcTy->getElementCount().getKnownMinValue() * 2) ||
6387 Mask, 3, SrcTy->getElementCount().getKnownMinValue() * 2)))
6388 return LT.first;
6389
6390 unsigned TpNumElts = Mask.size();
6391 unsigned LTNumElts = LT.second.getVectorNumElements();
6392 unsigned NumVecs = (TpNumElts + LTNumElts - 1) / LTNumElts;
6393 VectorType *NTp = VectorType::get(SrcTy->getScalarType(),
6394 LT.second.getVectorElementCount());
6396 std::map<std::tuple<unsigned, unsigned, SmallVector<int>>, InstructionCost>
6397 PreviousCosts;
6398 for (unsigned N = 0; N < NumVecs; N++) {
6399 SmallVector<int> NMask;
6400 // Split the existing mask into chunks of size LTNumElts. Track the source
6401 // sub-vectors to ensure the result has at most 2 inputs.
6402 unsigned Source1 = -1U, Source2 = -1U;
6403 unsigned NumSources = 0;
6404 for (unsigned E = 0; E < LTNumElts; E++) {
6405 int MaskElt = (N * LTNumElts + E < TpNumElts) ? Mask[N * LTNumElts + E]
6407 if (MaskElt < 0) {
6409 continue;
6410 }
6411
6412 // Calculate which source from the input this comes from and whether it
6413 // is new to us.
6414 unsigned Source = MaskElt / LTNumElts;
6415 if (NumSources == 0) {
6416 Source1 = Source;
6417 NumSources = 1;
6418 } else if (NumSources == 1 && Source != Source1) {
6419 Source2 = Source;
6420 NumSources = 2;
6421 } else if (NumSources >= 2 && Source != Source1 && Source != Source2) {
6422 NumSources++;
6423 }
6424
6425 // Add to the new mask. For the NumSources>2 case these are not correct,
6426 // but are only used for the modular lane number.
6427 if (Source == Source1)
6428 NMask.push_back(MaskElt % LTNumElts);
6429 else if (Source == Source2)
6430 NMask.push_back(MaskElt % LTNumElts + LTNumElts);
6431 else
6432 NMask.push_back(MaskElt % LTNumElts);
6433 }
6434 // Check if we have already generated this sub-shuffle, which means we
6435 // will have already generated the output. For example a <16 x i32> splat
6436 // will be the same sub-splat 4 times, which only needs to be generated
6437 // once and reused.
6438 auto Result =
6439 PreviousCosts.insert({std::make_tuple(Source1, Source2, NMask), 0});
6440 // Check if it was already in the map (already costed).
6441 if (!Result.second)
6442 continue;
6443 // If the sub-mask has at most 2 input sub-vectors then re-cost it using
6444 // getShuffleCost. If not then cost it using the worst case as the number
6445 // of element moves into a new vector.
6446 InstructionCost NCost =
6447 NumSources <= 2
6448 ? getShuffleCost(NumSources <= 1 ? TTI::SK_PermuteSingleSrc
6450 NTp, NTp, NMask, CostKind, 0, nullptr, Args,
6451 CxtI)
6452 : LTNumElts;
6453 Result.first->second = NCost;
6454 Cost += NCost;
6455 }
6456 return Cost;
6457 }
6458
6459 Kind = improveShuffleKindFromMask(Kind, Mask, SrcTy, Index, SubTp);
6460 bool IsExtractSubvector = Kind == TTI::SK_ExtractSubvector;
6461 // A subvector extract can be implemented with a NEON/SVE ext (or trivial
6462 // extract, if from lane 0) for 128-bit NEON vectors or legal SVE vectors.
6463 // This currently only handles low or high extracts to prevent SLP vectorizer
6464 // regressions.
6465 // Note that SVE's ext instruction is destructive, but it can be fused with
6466 // a movprfx to act like a constructive instruction.
6467 if (IsExtractSubvector && LT.second.isFixedLengthVector()) {
6468 if (LT.second.getFixedSizeInBits() >= 128 &&
6469 cast<FixedVectorType>(SubTp)->getNumElements() ==
6470 LT.second.getVectorNumElements() / 2) {
6471 if (Index == 0)
6472 return 0;
6473 if (Index == (int)LT.second.getVectorNumElements() / 2)
6474 return 1;
6475 }
6477 }
6478 // FIXME: This was added to keep the costs equal when adding DstTys. Update
6479 // the code to handle length-changing shuffles.
6480 if (Kind == TTI::SK_InsertSubvector) {
6481 LT = getTypeLegalizationCost(DstTy);
6482 SrcTy = DstTy;
6483 }
6484
6485 // Check for identity masks, which we can treat as free for both fixed and
6486 // scalable vector paths.
6487 if (!Mask.empty() && LT.second.isFixedLengthVector() &&
6488 (Kind == TTI::SK_PermuteTwoSrc || Kind == TTI::SK_PermuteSingleSrc) &&
6489 all_of(enumerate(Mask), [](const auto &M) {
6490 return M.value() < 0 || M.value() == (int)M.index();
6491 }))
6492 return 0;
6493
6494 // Segmented shuffle matching.
6495 if (Kind == TTI::SK_PermuteSingleSrc && isa<FixedVectorType>(SrcTy) &&
6496 !Mask.empty() && SrcTy->getPrimitiveSizeInBits().isNonZero() &&
6497 SrcTy->getPrimitiveSizeInBits().isKnownMultipleOf(
6499
6501 unsigned Segments =
6503 unsigned SegmentElts = VTy->getNumElements() / Segments;
6504
6505 // dupq zd.t, zn.t[idx]
6506 if ((ST->hasSVE2p1() || ST->hasSME2p1()) &&
6507 ST->isSVEorStreamingSVEAvailable() &&
6508 isDUPQMask(Mask, Segments, SegmentElts))
6509 return LT.first;
6510
6511 // mov zd.q, vn
6512 if (ST->isSVEorStreamingSVEAvailable() &&
6513 isDUPFirstSegmentMask(Mask, Segments, SegmentElts))
6514 return LT.first;
6515 }
6516
6517 // Check for broadcast loads, which are supported by the LD1R instruction.
6518 // In terms of code-size, the shuffle vector is free when a load + dup get
6519 // folded into a LD1R. That's what we check and return here. For performance
6520 // and reciprocal throughput, a LD1R is not completely free. In this case, we
6521 // return the cost for the broadcast below (i.e. 1 for most/all types), so
6522 // that we model the load + dup sequence slightly higher because LD1R is a
6523 // high latency instruction.
6524 if (CostKind == TTI::TCK_CodeSize && Kind == TTI::SK_Broadcast) {
6525 bool IsLoad = !Args.empty() && isa<LoadInst>(Args[0]);
6526 if (IsLoad && LT.second.isVector() &&
6527 isLegalBroadcastLoad(SrcTy->getElementType(),
6528 LT.second.getVectorElementCount()))
6529 return 0;
6530 }
6531
6532 // If we have 4 elements for the shuffle and a Mask, get the cost straight
6533 // from the perfect shuffle tables.
6534 if (Mask.size() == 4 &&
6535 SrcTy->getElementCount() == ElementCount::getFixed(4) &&
6536 (SrcTy->getScalarSizeInBits() == 16 ||
6537 SrcTy->getScalarSizeInBits() == 32) &&
6538 all_of(Mask, [](int E) { return E < 8; }))
6539 return getPerfectShuffleCost(Mask);
6540
6541 // Check for other shuffles that are not SK_ kinds but we have native
6542 // instructions for, for example ZIP and UZP.
6543 unsigned Unused;
6544 if (LT.second.isFixedLengthVector() &&
6545 LT.second.getVectorNumElements() == Mask.size() &&
6546 (Kind == TTI::SK_PermuteTwoSrc || Kind == TTI::SK_PermuteSingleSrc ||
6547 // Discrepancies between isTRNMask and ShuffleVectorInst::isTransposeMask
6548 // mean that we can end up with shuffles that satisfy isTRNMask, but end
6549 // up labelled as TTI::SK_InsertSubvector. (e.g. {2, 0}).
6550 Kind == TTI::SK_InsertSubvector) &&
6551 (isZIPMask(Mask, LT.second.getVectorNumElements(), Unused, Unused) ||
6552 isTRNMask(Mask, LT.second.getVectorNumElements(), Unused, Unused) ||
6553 isUZPMask(Mask, LT.second.getVectorNumElements(), Unused) ||
6554 isREVMask(Mask, LT.second.getScalarSizeInBits(),
6555 LT.second.getVectorNumElements(), 16) ||
6556 isREVMask(Mask, LT.second.getScalarSizeInBits(),
6557 LT.second.getVectorNumElements(), 32) ||
6558 isREVMask(Mask, LT.second.getScalarSizeInBits(),
6559 LT.second.getVectorNumElements(), 64) ||
6560 // Check for non-zero lane splats
6561 all_of(drop_begin(Mask),
6562 [&Mask](int M) { return M < 0 || M == Mask[0]; })))
6563 return 1;
6564
6565 if (Kind == TTI::SK_Broadcast || Kind == TTI::SK_Transpose ||
6566 Kind == TTI::SK_Select || Kind == TTI::SK_PermuteSingleSrc ||
6567 Kind == TTI::SK_Reverse || Kind == TTI::SK_Splice) {
6568 static const CostTblEntry ShuffleTbl[] = {
6569 // Broadcast shuffle kinds can be performed with 'dup'.
6570 {TTI::SK_Broadcast, MVT::v8i8, 1},
6571 {TTI::SK_Broadcast, MVT::v16i8, 1},
6572 {TTI::SK_Broadcast, MVT::v4i16, 1},
6573 {TTI::SK_Broadcast, MVT::v8i16, 1},
6574 {TTI::SK_Broadcast, MVT::v2i32, 1},
6575 {TTI::SK_Broadcast, MVT::v4i32, 1},
6576 {TTI::SK_Broadcast, MVT::v2i64, 1},
6577 {TTI::SK_Broadcast, MVT::v4f16, 1},
6578 {TTI::SK_Broadcast, MVT::v8f16, 1},
6579 {TTI::SK_Broadcast, MVT::v4bf16, 1},
6580 {TTI::SK_Broadcast, MVT::v8bf16, 1},
6581 {TTI::SK_Broadcast, MVT::v2f32, 1},
6582 {TTI::SK_Broadcast, MVT::v4f32, 1},
6583 {TTI::SK_Broadcast, MVT::v2f64, 1},
6584 // Transpose shuffle kinds can be performed with 'trn1/trn2' and
6585 // 'zip1/zip2' instructions.
6586 {TTI::SK_Transpose, MVT::v8i8, 1},
6587 {TTI::SK_Transpose, MVT::v16i8, 1},
6588 {TTI::SK_Transpose, MVT::v4i16, 1},
6589 {TTI::SK_Transpose, MVT::v8i16, 1},
6590 {TTI::SK_Transpose, MVT::v2i32, 1},
6591 {TTI::SK_Transpose, MVT::v4i32, 1},
6592 {TTI::SK_Transpose, MVT::v2i64, 1},
6593 {TTI::SK_Transpose, MVT::v4f16, 1},
6594 {TTI::SK_Transpose, MVT::v8f16, 1},
6595 {TTI::SK_Transpose, MVT::v4bf16, 1},
6596 {TTI::SK_Transpose, MVT::v8bf16, 1},
6597 {TTI::SK_Transpose, MVT::v2f32, 1},
6598 {TTI::SK_Transpose, MVT::v4f32, 1},
6599 {TTI::SK_Transpose, MVT::v2f64, 1},
6600 // Select shuffle kinds.
6601 // TODO: handle vXi8/vXi16.
6602 {TTI::SK_Select, MVT::v2i32, 1}, // mov.
6603 {TTI::SK_Select, MVT::v4i32, 2}, // rev+trn (or similar).
6604 {TTI::SK_Select, MVT::v2i64, 1}, // mov.
6605 {TTI::SK_Select, MVT::v2f32, 1}, // mov.
6606 {TTI::SK_Select, MVT::v4f32, 2}, // rev+trn (or similar).
6607 {TTI::SK_Select, MVT::v2f64, 1}, // mov.
6608 // PermuteSingleSrc shuffle kinds.
6609 {TTI::SK_PermuteSingleSrc, MVT::v2i32, 1}, // mov.
6610 {TTI::SK_PermuteSingleSrc, MVT::v4i32, 3}, // perfectshuffle worst case.
6611 {TTI::SK_PermuteSingleSrc, MVT::v2i64, 1}, // mov.
6612 {TTI::SK_PermuteSingleSrc, MVT::v2f32, 1}, // mov.
6613 {TTI::SK_PermuteSingleSrc, MVT::v4f32, 3}, // perfectshuffle worst case.
6614 {TTI::SK_PermuteSingleSrc, MVT::v2f64, 1}, // mov.
6615 {TTI::SK_PermuteSingleSrc, MVT::v4i16, 3}, // perfectshuffle worst case.
6616 {TTI::SK_PermuteSingleSrc, MVT::v4f16, 3}, // perfectshuffle worst case.
6617 {TTI::SK_PermuteSingleSrc, MVT::v4bf16, 3}, // same
6618 {TTI::SK_PermuteSingleSrc, MVT::v8i16, 8}, // constpool + load + tbl
6619 {TTI::SK_PermuteSingleSrc, MVT::v8f16, 8}, // constpool + load + tbl
6620 {TTI::SK_PermuteSingleSrc, MVT::v8bf16, 8}, // constpool + load + tbl
6621 {TTI::SK_PermuteSingleSrc, MVT::v8i8, 8}, // constpool + load + tbl
6622 {TTI::SK_PermuteSingleSrc, MVT::v16i8, 8}, // constpool + load + tbl
6623 // Reverse can be lowered with `rev`.
6624 {TTI::SK_Reverse, MVT::v2i32, 1}, // REV64
6625 {TTI::SK_Reverse, MVT::v4i32, 2}, // REV64; EXT
6626 {TTI::SK_Reverse, MVT::v2i64, 1}, // EXT
6627 {TTI::SK_Reverse, MVT::v2f32, 1}, // REV64
6628 {TTI::SK_Reverse, MVT::v4f32, 2}, // REV64; EXT
6629 {TTI::SK_Reverse, MVT::v2f64, 1}, // EXT
6630 {TTI::SK_Reverse, MVT::v8f16, 2}, // REV64; EXT
6631 {TTI::SK_Reverse, MVT::v8bf16, 2}, // REV64; EXT
6632 {TTI::SK_Reverse, MVT::v8i16, 2}, // REV64; EXT
6633 {TTI::SK_Reverse, MVT::v16i8, 2}, // REV64; EXT
6634 {TTI::SK_Reverse, MVT::v4f16, 1}, // REV64
6635 {TTI::SK_Reverse, MVT::v4bf16, 1}, // REV64
6636 {TTI::SK_Reverse, MVT::v4i16, 1}, // REV64
6637 {TTI::SK_Reverse, MVT::v8i8, 1}, // REV64
6638 // Splice can all be lowered as `ext`.
6639 {TTI::SK_Splice, MVT::v2i32, 1},
6640 {TTI::SK_Splice, MVT::v4i32, 1},
6641 {TTI::SK_Splice, MVT::v2i64, 1},
6642 {TTI::SK_Splice, MVT::v2f32, 1},
6643 {TTI::SK_Splice, MVT::v4f32, 1},
6644 {TTI::SK_Splice, MVT::v2f64, 1},
6645 {TTI::SK_Splice, MVT::v8f16, 1},
6646 {TTI::SK_Splice, MVT::v8bf16, 1},
6647 {TTI::SK_Splice, MVT::v8i16, 1},
6648 {TTI::SK_Splice, MVT::v16i8, 1},
6649 {TTI::SK_Splice, MVT::v4f16, 1},
6650 {TTI::SK_Splice, MVT::v4bf16, 1},
6651 {TTI::SK_Splice, MVT::v4i16, 1},
6652 {TTI::SK_Splice, MVT::v8i8, 1},
6653 // Broadcast shuffle kinds for scalable vectors
6654 {TTI::SK_Broadcast, MVT::nxv16i8, 1},
6655 {TTI::SK_Broadcast, MVT::nxv8i16, 1},
6656 {TTI::SK_Broadcast, MVT::nxv4i32, 1},
6657 {TTI::SK_Broadcast, MVT::nxv2i64, 1},
6658 {TTI::SK_Broadcast, MVT::nxv2f16, 1},
6659 {TTI::SK_Broadcast, MVT::nxv4f16, 1},
6660 {TTI::SK_Broadcast, MVT::nxv8f16, 1},
6661 {TTI::SK_Broadcast, MVT::nxv2bf16, 1},
6662 {TTI::SK_Broadcast, MVT::nxv4bf16, 1},
6663 {TTI::SK_Broadcast, MVT::nxv8bf16, 1},
6664 {TTI::SK_Broadcast, MVT::nxv2f32, 1},
6665 {TTI::SK_Broadcast, MVT::nxv4f32, 1},
6666 {TTI::SK_Broadcast, MVT::nxv2f64, 1},
6667 {TTI::SK_Broadcast, MVT::nxv16i1, 1},
6668 {TTI::SK_Broadcast, MVT::nxv8i1, 1},
6669 {TTI::SK_Broadcast, MVT::nxv4i1, 1},
6670 {TTI::SK_Broadcast, MVT::nxv2i1, 1},
6671 // Handle the cases for vector.reverse with scalable vectors
6672 {TTI::SK_Reverse, MVT::nxv16i8, 1},
6673 {TTI::SK_Reverse, MVT::nxv8i16, 1},
6674 {TTI::SK_Reverse, MVT::nxv4i32, 1},
6675 {TTI::SK_Reverse, MVT::nxv2i64, 1},
6676 {TTI::SK_Reverse, MVT::nxv2f16, 1},
6677 {TTI::SK_Reverse, MVT::nxv4f16, 1},
6678 {TTI::SK_Reverse, MVT::nxv8f16, 1},
6679 {TTI::SK_Reverse, MVT::nxv2bf16, 1},
6680 {TTI::SK_Reverse, MVT::nxv4bf16, 1},
6681 {TTI::SK_Reverse, MVT::nxv8bf16, 1},
6682 {TTI::SK_Reverse, MVT::nxv2f32, 1},
6683 {TTI::SK_Reverse, MVT::nxv4f32, 1},
6684 {TTI::SK_Reverse, MVT::nxv2f64, 1},
6685 {TTI::SK_Reverse, MVT::nxv16i1, 1},
6686 {TTI::SK_Reverse, MVT::nxv8i1, 1},
6687 {TTI::SK_Reverse, MVT::nxv4i1, 1},
6688 {TTI::SK_Reverse, MVT::nxv2i1, 1},
6689 };
6690 if (const auto *Entry = CostTableLookup(ShuffleTbl, Kind, LT.second))
6691 return LT.first * Entry->Cost;
6692 }
6693
6694 if (Kind == TTI::SK_Splice && isa<ScalableVectorType>(SrcTy))
6695 return getSpliceCost(SrcTy, Index, CostKind);
6696
6697 // Inserting a subvector can often be done with either a D, S or H register
6698 // move, so long as the inserted vector is "aligned".
6699 if (Kind == TTI::SK_InsertSubvector && LT.second.isFixedLengthVector() &&
6700 LT.second.getSizeInBits() <= 128 && SubTp) {
6701 std::pair<InstructionCost, MVT> SubLT = getTypeLegalizationCost(SubTp);
6702 if (SubLT.second.isVector()) {
6703 int NumElts = LT.second.getVectorNumElements();
6704 int NumSubElts = SubLT.second.getVectorNumElements();
6705 if ((Index % NumSubElts) == 0 && (NumElts % NumSubElts) == 0)
6706 return SubLT.first;
6707 }
6708 }
6709
6710 // Restore optimal kind.
6711 if (IsExtractSubvector)
6713 return BaseT::getShuffleCost(Kind, DstTy, SrcTy, Mask, CostKind, Index, SubTp,
6714 Args, CxtI);
6715}
6716
6719 const DominatorTree &DT) {
6720 const auto &Strides = DenseMap<Value *, const SCEV *>();
6721 for (BasicBlock *BB : TheLoop->blocks()) {
6722 // Scan the instructions in the block and look for addresses that are
6723 // consecutive and decreasing.
6724 for (Instruction &I : *BB) {
6725 if (isa<LoadInst>(&I) || isa<StoreInst>(&I)) {
6727 Type *AccessTy = getLoadStoreType(&I);
6728 if (getPtrStride(*PSE, AccessTy, Ptr, TheLoop, DT, Strides,
6729 /*Assume=*/true, /*ShouldCheckWrap=*/false)
6730 .value_or(0) < 0)
6731 return true;
6732 }
6733 }
6734 }
6735 return false;
6736}
6737
6739 if (SVEPreferFixedOverScalableIfEqualCost.getNumOccurrences())
6741 // For cases like post-LTO vectorization, when we eventually know the trip
6742 // count, epilogue with fixed-width vectorization can be deleted if the trip
6743 // count is less than the epilogue iterations. That's why we prefer
6744 // fixed-width vectorization in epilogue in case of equal costs.
6745 if (IsEpilogue)
6746 return true;
6747 return ST->useFixedOverScalableIfEqualCost();
6748}
6749
6751 return ST->getEpilogueVectorizationMinVF();
6752}
6753
6755 if (!ST->hasSVE())
6756 return false;
6757
6758 // We don't currently support vectorisation with interleaving for SVE - with
6759 // such loops we're better off not using tail-folding. This gives us a chance
6760 // to fall back on fixed-width vectorisation using NEON's ld2/st2/etc.
6761 if (TFI->IAI->hasGroups())
6762 return false;
6763
6765 if (TFI->LVL->getReductionVars().size())
6766 Required |= TailFoldingOpts::Reductions;
6767 if (TFI->LVL->getFixedOrderRecurrences().size())
6768 Required |= TailFoldingOpts::Recurrences;
6769
6770 // We call this to discover whether any load/store pointers in the loop have
6771 // negative strides. This will require extra work to reverse the loop
6772 // predicate, which may be expensive.
6775 *TFI->LVL->getDominatorTree()))
6776 Required |= TailFoldingOpts::Reverse;
6777 if (Required == TailFoldingOpts::Disabled)
6778 Required |= TailFoldingOpts::Simple;
6779
6780 if (!TailFoldingOptionLoc.satisfies(ST->getSVETailFoldingDefaultOpts(),
6781 Required))
6782 return false;
6783
6784 // Don't tail-fold for tight loops where we would be better off interleaving
6785 // with an unpredicated loop.
6786 unsigned NumInsns = 0;
6787 for (BasicBlock *BB : TFI->LVL->getLoop()->blocks()) {
6788 NumInsns += BB->size();
6789 }
6790
6791 // We expect 4 of these to be a IV PHI, IV add, IV compare and branch.
6792 return NumInsns >= SVETailFoldInsnThreshold;
6793}
6794
6797 StackOffset BaseOffset, bool HasBaseReg,
6798 int64_t Scale, unsigned AddrSpace) const {
6799 // Scaling factors are not free at all.
6800 // Operands | Rt Latency
6801 // -------------------------------------------
6802 // Rt, [Xn, Xm] | 4
6803 // -------------------------------------------
6804 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
6805 // Rt, [Xn, Wm, <extend> #imm] |
6807 AM.BaseGV = BaseGV;
6808 AM.BaseOffs = BaseOffset.getFixed();
6809 AM.HasBaseReg = HasBaseReg;
6810 AM.Scale = Scale;
6811 AM.ScalableOffset = BaseOffset.getScalable();
6812 if (getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace))
6813 // Scale represents reg2 * scale, thus account for 1 if
6814 // it is not equal to 0 or 1.
6815 return AM.Scale != 0 && AM.Scale != 1;
6817}
6818
6820 const Instruction *I) const {
6822 // For the binary operators (e.g. or) we need to be more careful than
6823 // selects, here we only transform them if they are already at a natural
6824 // break point in the code - the end of a block with an unconditional
6825 // terminator.
6826 if (I->getOpcode() == Instruction::Or &&
6827 isa<UncondBrInst>(I->getNextNode()))
6828 return true;
6829
6830 if (I->getOpcode() == Instruction::Add ||
6831 I->getOpcode() == Instruction::Sub)
6832 return true;
6833 }
6835}
6836
6839 const TargetTransformInfo::LSRCost &C2) const {
6840 // AArch64 specific here is adding the number of instructions to the
6841 // comparison (though not as the first consideration, as some targets do)
6842 // along with changing the priority of the base additions.
6843 // TODO: Maybe a more nuanced tradeoff between instruction count
6844 // and number of registers? To be investigated at a later date.
6845 if (EnableLSRCostOpt)
6846 return std::tie(C1.NumRegs, C1.Insns, C1.NumBaseAdds, C1.AddRecCost,
6847 C1.NumIVMuls, C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
6848 std::tie(C2.NumRegs, C2.Insns, C2.NumBaseAdds, C2.AddRecCost,
6849 C2.NumIVMuls, C2.ScaleCost, C2.ImmCost, C2.SetupCost);
6850
6852}
6853
6854static bool isSplatShuffle(Value *V) {
6855 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V))
6856 return all_equal(Shuf->getShuffleMask());
6857 return false;
6858}
6859
6860/// Check if both Op1 and Op2 are shufflevector extracts of either the lower
6861/// or upper half of the vector elements.
6862static bool areExtractShuffleVectors(Value *Op1, Value *Op2,
6863 bool AllowSplat = false) {
6864 // Scalable types can't be extract shuffle vectors.
6865 if (Op1->getType()->isScalableTy() || Op2->getType()->isScalableTy())
6866 return false;
6867
6868 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
6869 auto *FullTy = FullV->getType();
6870 auto *HalfTy = HalfV->getType();
6871 return FullTy->getPrimitiveSizeInBits().getFixedValue() ==
6872 2 * HalfTy->getPrimitiveSizeInBits().getFixedValue();
6873 };
6874
6875 auto extractHalf = [](Value *FullV, Value *HalfV) {
6876 auto *FullVT = cast<FixedVectorType>(FullV->getType());
6877 auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
6878 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
6879 };
6880
6881 ArrayRef<int> M1, M2;
6882 Value *S1Op1 = nullptr, *S2Op1 = nullptr;
6883 if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
6884 !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
6885 return false;
6886
6887 // If we allow splats, set S1Op1/S2Op1 to nullptr for the relevant arg so that
6888 // it is not checked as an extract below.
6889 if (AllowSplat && isSplatShuffle(Op1))
6890 S1Op1 = nullptr;
6891 if (AllowSplat && isSplatShuffle(Op2))
6892 S2Op1 = nullptr;
6893
6894 // Check that the operands are half as wide as the result and we extract
6895 // half of the elements of the input vectors.
6896 if ((S1Op1 && (!areTypesHalfed(S1Op1, Op1) || !extractHalf(S1Op1, Op1))) ||
6897 (S2Op1 && (!areTypesHalfed(S2Op1, Op2) || !extractHalf(S2Op1, Op2))))
6898 return false;
6899
6900 // Check the mask extracts either the lower or upper half of vector
6901 // elements.
6902 int M1Start = 0;
6903 int M2Start = 0;
6904 int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
6905 if ((S1Op1 &&
6906 !ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start)) ||
6907 (S2Op1 &&
6908 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start)))
6909 return false;
6910
6911 if ((M1Start != 0 && M1Start != (NumElements / 2)) ||
6912 (M2Start != 0 && M2Start != (NumElements / 2)))
6913 return false;
6914 if (S1Op1 && S2Op1 && M1Start != M2Start)
6915 return false;
6916
6917 return true;
6918}
6919
6920/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
6921/// of the vector elements.
6922static bool areExtractExts(Value *Ext1, Value *Ext2) {
6923 auto areExtDoubled = [](Instruction *Ext) {
6924 return Ext->getType()->getScalarSizeInBits() ==
6925 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
6926 };
6927
6928 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
6929 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
6930 !areExtDoubled(cast<Instruction>(Ext1)) ||
6931 !areExtDoubled(cast<Instruction>(Ext2)))
6932 return false;
6933
6934 return true;
6935}
6936
6937/// Check if Op could be used with vmull_high_p64 intrinsic.
6939 Value *VectorOperand = nullptr;
6940 ConstantInt *ElementIndex = nullptr;
6941 return match(Op, m_ExtractElt(m_Value(VectorOperand),
6942 m_ConstantInt(ElementIndex))) &&
6943 ElementIndex->getValue() == 1 &&
6944 isa<FixedVectorType>(VectorOperand->getType()) &&
6945 cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
6946}
6947
6948/// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
6949static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
6951}
6952
6954 // Restrict ourselves to the form CodeGenPrepare typically constructs.
6955 auto *GEP = dyn_cast<GetElementPtrInst>(Ptrs);
6956 if (!GEP || GEP->getNumOperands() != 2)
6957 return false;
6958
6959 Value *Base = GEP->getOperand(0);
6960 Value *Offsets = GEP->getOperand(1);
6961
6962 // We only care about scalar_base+vector_offsets.
6963 if (Base->getType()->isVectorTy() || !Offsets->getType()->isVectorTy())
6964 return false;
6965
6966 // Sink extends that would allow us to use 32-bit offset vectors.
6967 if (isa<SExtInst>(Offsets) || isa<ZExtInst>(Offsets)) {
6968 auto *OffsetsInst = cast<Instruction>(Offsets);
6969 if (OffsetsInst->getType()->getScalarSizeInBits() > 32 &&
6970 OffsetsInst->getOperand(0)->getType()->getScalarSizeInBits() <= 32)
6971 Ops.push_back(&GEP->getOperandUse(1));
6972 }
6973
6974 // Sink the GEP.
6975 return true;
6976}
6977
6978/// We want to sink following cases:
6979/// (add|sub|gep) A, ((mul|shl) vscale, imm); (add|sub|gep) A, vscale;
6980/// (add|sub|gep) A, ((mul|shl) zext(vscale), imm);
6982 if (match(Op, m_VScale()))
6983 return true;
6984 if (match(Op, m_Shl(m_VScale(), m_ConstantInt())) ||
6986 Ops.push_back(&cast<Instruction>(Op)->getOperandUse(0));
6987 return true;
6988 }
6989 if (match(Op, m_Shl(m_ZExt(m_VScale()), m_ConstantInt())) ||
6991 Value *ZExtOp = cast<Instruction>(Op)->getOperand(0);
6992 Ops.push_back(&cast<Instruction>(ZExtOp)->getOperandUse(0));
6993 Ops.push_back(&cast<Instruction>(Op)->getOperandUse(0));
6994 return true;
6995 }
6996 return false;
6997}
6998
6999static bool isFNeg(Value *Op) { return match(Op, m_FNeg(m_Value())); }
7000
7001/// Check if sinking \p I's operands to I's basic block is profitable, because
7002/// the operands can be folded into a target instruction, e.g.
7003/// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
7007 switch (II->getIntrinsicID()) {
7008 case Intrinsic::aarch64_neon_smull:
7009 case Intrinsic::aarch64_neon_umull:
7010 if (areExtractShuffleVectors(II->getOperand(0), II->getOperand(1),
7011 /*AllowSplat=*/true)) {
7012 Ops.push_back(&II->getOperandUse(0));
7013 Ops.push_back(&II->getOperandUse(1));
7014 return true;
7015 }
7016 [[fallthrough]];
7017
7018 case Intrinsic::fma:
7019 case Intrinsic::fmuladd:
7020 if (isa<VectorType>(I->getType()) &&
7021 cast<VectorType>(I->getType())->getElementType()->isHalfTy() &&
7022 !ST->hasFullFP16())
7023 return false;
7024
7025 if (isFNeg(II->getOperand(0)))
7026 Ops.push_back(&II->getOperandUse(0));
7027 if (isFNeg(II->getOperand(1)))
7028 Ops.push_back(&II->getOperandUse(1));
7029
7030 [[fallthrough]];
7031 case Intrinsic::aarch64_neon_sqdmull:
7032 case Intrinsic::aarch64_neon_sqdmulh:
7033 case Intrinsic::aarch64_neon_sqrdmulh:
7034 // Sink splats for index lane variants
7035 if (isSplatShuffle(II->getOperand(0)))
7036 Ops.push_back(&II->getOperandUse(0));
7037 if (isSplatShuffle(II->getOperand(1)))
7038 Ops.push_back(&II->getOperandUse(1));
7039 return !Ops.empty();
7040 case Intrinsic::aarch64_neon_fmlal:
7041 case Intrinsic::aarch64_neon_fmlal2:
7042 case Intrinsic::aarch64_neon_fmlsl:
7043 case Intrinsic::aarch64_neon_fmlsl2:
7044 // Sink splats for index lane variants
7045 if (isSplatShuffle(II->getOperand(1)))
7046 Ops.push_back(&II->getOperandUse(1));
7047 if (isSplatShuffle(II->getOperand(2)))
7048 Ops.push_back(&II->getOperandUse(2));
7049 return !Ops.empty();
7050 case Intrinsic::aarch64_sve_ptest_first:
7051 case Intrinsic::aarch64_sve_ptest_last:
7052 if (auto *IIOp = dyn_cast<IntrinsicInst>(II->getOperand(0)))
7053 if (IIOp->getIntrinsicID() == Intrinsic::aarch64_sve_ptrue)
7054 Ops.push_back(&II->getOperandUse(0));
7055 return !Ops.empty();
7056 case Intrinsic::aarch64_sme_write_horiz:
7057 case Intrinsic::aarch64_sme_write_vert:
7058 case Intrinsic::aarch64_sme_writeq_horiz:
7059 case Intrinsic::aarch64_sme_writeq_vert: {
7060 auto *Idx = dyn_cast<Instruction>(II->getOperand(1));
7061 if (!Idx || Idx->getOpcode() != Instruction::Add)
7062 return false;
7063 Ops.push_back(&II->getOperandUse(1));
7064 return true;
7065 }
7066 case Intrinsic::aarch64_sme_read_horiz:
7067 case Intrinsic::aarch64_sme_read_vert:
7068 case Intrinsic::aarch64_sme_readq_horiz:
7069 case Intrinsic::aarch64_sme_readq_vert:
7070 case Intrinsic::aarch64_sme_ld1b_vert:
7071 case Intrinsic::aarch64_sme_ld1h_vert:
7072 case Intrinsic::aarch64_sme_ld1w_vert:
7073 case Intrinsic::aarch64_sme_ld1d_vert:
7074 case Intrinsic::aarch64_sme_ld1q_vert:
7075 case Intrinsic::aarch64_sme_st1b_vert:
7076 case Intrinsic::aarch64_sme_st1h_vert:
7077 case Intrinsic::aarch64_sme_st1w_vert:
7078 case Intrinsic::aarch64_sme_st1d_vert:
7079 case Intrinsic::aarch64_sme_st1q_vert:
7080 case Intrinsic::aarch64_sme_ld1b_horiz:
7081 case Intrinsic::aarch64_sme_ld1h_horiz:
7082 case Intrinsic::aarch64_sme_ld1w_horiz:
7083 case Intrinsic::aarch64_sme_ld1d_horiz:
7084 case Intrinsic::aarch64_sme_ld1q_horiz:
7085 case Intrinsic::aarch64_sme_st1b_horiz:
7086 case Intrinsic::aarch64_sme_st1h_horiz:
7087 case Intrinsic::aarch64_sme_st1w_horiz:
7088 case Intrinsic::aarch64_sme_st1d_horiz:
7089 case Intrinsic::aarch64_sme_st1q_horiz: {
7090 auto *Idx = dyn_cast<Instruction>(II->getOperand(3));
7091 if (!Idx || Idx->getOpcode() != Instruction::Add)
7092 return false;
7093 Ops.push_back(&II->getOperandUse(3));
7094 return true;
7095 }
7096 case Intrinsic::aarch64_neon_pmull:
7097 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
7098 return false;
7099 Ops.push_back(&II->getOperandUse(0));
7100 Ops.push_back(&II->getOperandUse(1));
7101 return true;
7102 case Intrinsic::aarch64_neon_pmull64:
7103 if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
7104 II->getArgOperand(1)))
7105 return false;
7106 Ops.push_back(&II->getArgOperandUse(0));
7107 Ops.push_back(&II->getArgOperandUse(1));
7108 return true;
7109 case Intrinsic::masked_gather:
7110 if (!shouldSinkVectorOfPtrs(II->getArgOperand(0), Ops))
7111 return false;
7112 Ops.push_back(&II->getArgOperandUse(0));
7113 return true;
7114 case Intrinsic::masked_scatter:
7115 if (!shouldSinkVectorOfPtrs(II->getArgOperand(1), Ops))
7116 return false;
7117 Ops.push_back(&II->getArgOperandUse(1));
7118 return true;
7119 default:
7120 return false;
7121 }
7122 }
7123
7124 auto ShouldSinkCondition = [](Value *Cond,
7125 SmallVectorImpl<Use *> &Ops) -> bool {
7127 return false;
7129 if (II->getIntrinsicID() != Intrinsic::vector_reduce_or ||
7130 !isa<ScalableVectorType>(II->getOperand(0)->getType()))
7131 return false;
7132 if (isa<CmpInst>(II->getOperand(0)))
7133 Ops.push_back(&II->getOperandUse(0));
7134 return true;
7135 };
7136
7137 switch (I->getOpcode()) {
7138 case Instruction::GetElementPtr:
7139 case Instruction::Add:
7140 case Instruction::Sub:
7141 // Sink vscales closer to uses for better isel
7142 for (unsigned Op = 0; Op < I->getNumOperands(); ++Op) {
7143 if (shouldSinkVScale(I->getOperand(Op), Ops)) {
7144 Ops.push_back(&I->getOperandUse(Op));
7145 return true;
7146 }
7147 }
7148 break;
7149 case Instruction::Select: {
7150 if (!ShouldSinkCondition(I->getOperand(0), Ops))
7151 return false;
7152
7153 Ops.push_back(&I->getOperandUse(0));
7154 return true;
7155 }
7156 case Instruction::UncondBr:
7157 return false;
7158 case Instruction::CondBr: {
7159 if (!ShouldSinkCondition(cast<CondBrInst>(I)->getCondition(), Ops))
7160 return false;
7161
7162 Ops.push_back(&I->getOperandUse(0));
7163 return true;
7164 }
7165 case Instruction::FMul:
7166 // fmul with contract flag can be combined with fadd into fma.
7167 // Sinking fneg into this block enables fmls pattern.
7168 if (cast<FPMathOperator>(I)->hasAllowContract()) {
7169 if (isFNeg(I->getOperand(0)))
7170 Ops.push_back(&I->getOperandUse(0));
7171 if (isFNeg(I->getOperand(1)))
7172 Ops.push_back(&I->getOperandUse(1));
7173 }
7174 break;
7175
7176 // Type | BIC | ORN | EON
7177 // ----------------+-----------+-----------+-----------
7178 // scalar | Base | Base | Base
7179 // scalar w/shift | - | - | -
7180 // fixed vector | NEON/Base | NEON/Base | BSL2N/Base
7181 // scalable vector | SVE | - | BSL2N
7182 case Instruction::Xor:
7183 // EON only for scalars (possibly expanded fixed vectors)
7184 // and vectors using the SVE2/SME BSL2N instruction.
7185 if (I->getType()->isVectorTy() && ST->isNeonAvailable()) {
7186 bool HasBSL2N =
7187 ST->isSVEorStreamingSVEAvailable() && (ST->hasSVE2() || ST->hasSME());
7188 if (!HasBSL2N)
7189 break;
7190 }
7191 [[fallthrough]];
7192 case Instruction::And:
7193 case Instruction::Or:
7194 // Even though we could use the SVE2/SME BSL2N instruction,
7195 // it might pessimize with an extra MOV depending on register allocation.
7196 if (I->getOpcode() == Instruction::Or &&
7197 isa<ScalableVectorType>(I->getType()))
7198 break;
7199 // Shift can be fold into scalar AND/ORR/EOR,
7200 // but not the non-negated operand of BIC/ORN/EON.
7201 if (!(I->getType()->isVectorTy() && ST->hasNEON()) &&
7203 break;
7204 for (auto &Op : I->operands()) {
7205 // (and/or/xor X, (not Y)) -> (bic/orn/eon X, Y)
7206 if (match(Op.get(), m_Not(m_Value()))) {
7207 Ops.push_back(&Op);
7208 return true;
7209 }
7210 // (and/or/xor X, (splat (not Y))) -> (bic/orn/eon X, (splat Y))
7211 if (match(Op.get(),
7213 m_Value(), m_ZeroMask()))) {
7214 Use &InsertElt = cast<Instruction>(Op)->getOperandUse(0);
7215 Use &Not = cast<Instruction>(InsertElt)->getOperandUse(1);
7216 Ops.push_back(&Not);
7217 Ops.push_back(&InsertElt);
7218 Ops.push_back(&Op);
7219 return true;
7220 }
7221 }
7222 break;
7223 default:
7224 break;
7225 }
7226
7227 if (!I->getType()->isVectorTy())
7228 return !Ops.empty();
7229
7230 switch (I->getOpcode()) {
7231 case Instruction::Sub:
7232 case Instruction::Add: {
7233 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
7234 return false;
7235
7236 // If the exts' operands extract either the lower or upper elements, we
7237 // can sink them too.
7238 auto Ext1 = cast<Instruction>(I->getOperand(0));
7239 auto Ext2 = cast<Instruction>(I->getOperand(1));
7240 if (areExtractShuffleVectors(Ext1->getOperand(0), Ext2->getOperand(0))) {
7241 Ops.push_back(&Ext1->getOperandUse(0));
7242 Ops.push_back(&Ext2->getOperandUse(0));
7243 }
7244
7245 Ops.push_back(&I->getOperandUse(0));
7246 Ops.push_back(&I->getOperandUse(1));
7247
7248 return true;
7249 }
7250 case Instruction::Or: {
7251 // Pattern: Or(And(MaskValue, A), And(Not(MaskValue), B)) ->
7252 // bitselect(MaskValue, A, B) where Not(MaskValue) = Xor(MaskValue, -1)
7253 if (ST->hasNEON()) {
7254 Instruction *OtherAnd, *IA, *IB;
7255 Value *MaskValue;
7256 // MainAnd refers to And instruction that has 'Not' as one of its operands
7257 if (match(I, m_c_Or(m_OneUse(m_Instruction(OtherAnd)),
7258 m_OneUse(m_c_And(m_OneUse(m_Not(m_Value(MaskValue))),
7259 m_Instruction(IA)))))) {
7260 if (match(OtherAnd,
7261 m_c_And(m_Specific(MaskValue), m_Instruction(IB)))) {
7262 Instruction *MainAnd = I->getOperand(0) == OtherAnd
7263 ? cast<Instruction>(I->getOperand(1))
7264 : cast<Instruction>(I->getOperand(0));
7265
7266 // Both Ands should be in same basic block as Or
7267 if (I->getParent() != MainAnd->getParent() ||
7268 I->getParent() != OtherAnd->getParent())
7269 return false;
7270
7271 // Non-mask operands of both Ands should also be in same basic block
7272 if (I->getParent() != IA->getParent() ||
7273 I->getParent() != IB->getParent())
7274 return false;
7275
7276 Ops.push_back(
7277 &MainAnd->getOperandUse(MainAnd->getOperand(0) == IA ? 1 : 0));
7278 Ops.push_back(&I->getOperandUse(0));
7279 Ops.push_back(&I->getOperandUse(1));
7280
7281 return true;
7282 }
7283 }
7284 }
7285
7286 return false;
7287 }
7288 case Instruction::Mul: {
7289 auto ShouldSinkSplatForIndexedVariant = [](Value *V) {
7290 auto *Ty = cast<VectorType>(V->getType());
7291 // For SVE the lane-indexing is within 128-bits, so we can't fold splats.
7292 if (Ty->isScalableTy())
7293 return false;
7294
7295 // Indexed variants of Mul exist for i16 and i32 element types only.
7296 return Ty->getScalarSizeInBits() == 16 || Ty->getScalarSizeInBits() == 32;
7297 };
7298
7299 int NumZExts = 0, NumSExts = 0;
7300 for (auto &Op : I->operands()) {
7301 // Make sure we are not already sinking this operand
7302 if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
7303 continue;
7304
7305 if (match(&Op, m_ZExtOrSExt(m_Value()))) {
7306 auto *Ext = cast<Instruction>(Op);
7307 auto *ExtOp = Ext->getOperand(0);
7308 if (isSplatShuffle(ExtOp) && ShouldSinkSplatForIndexedVariant(ExtOp))
7309 Ops.push_back(&Ext->getOperandUse(0));
7310 Ops.push_back(&Op);
7311
7312 if (isa<SExtInst>(Ext)) {
7313 NumSExts++;
7314 } else {
7315 NumZExts++;
7316 // A zext(a) is also a sext(zext(a)), if we take more than 2 steps.
7317 if (Ext->getOperand(0)->getType()->getScalarSizeInBits() * 2 <
7318 I->getType()->getScalarSizeInBits())
7319 NumSExts++;
7320 }
7321
7322 continue;
7323 }
7324
7326 if (!Shuffle)
7327 continue;
7328
7329 // If the Shuffle is a splat and the operand is a zext/sext, sinking the
7330 // operand and the s/zext can help create indexed s/umull. This is
7331 // especially useful to prevent i64 mul being scalarized.
7332 if (isSplatShuffle(Shuffle) &&
7333 match(Shuffle->getOperand(0), m_ZExtOrSExt(m_Value()))) {
7334 Ops.push_back(&Shuffle->getOperandUse(0));
7335 Ops.push_back(&Op);
7336 if (match(Shuffle->getOperand(0), m_SExt(m_Value())))
7337 NumSExts++;
7338 else
7339 NumZExts++;
7340 continue;
7341 }
7342
7343 Value *ShuffleOperand = Shuffle->getOperand(0);
7344 InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand);
7345 if (!Insert)
7346 continue;
7347
7348 Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1));
7349 if (!OperandInstr)
7350 continue;
7351
7352 ConstantInt *ElementConstant =
7353 dyn_cast<ConstantInt>(Insert->getOperand(2));
7354 // Check that the insertelement is inserting into element 0
7355 if (!ElementConstant || !ElementConstant->isZero())
7356 continue;
7357
7358 unsigned Opcode = OperandInstr->getOpcode();
7359 if (Opcode == Instruction::SExt)
7360 NumSExts++;
7361 else if (Opcode == Instruction::ZExt)
7362 NumZExts++;
7363 else {
7364 // If we find that the top bits are known 0, then we can sink and allow
7365 // the backend to generate a umull.
7366 unsigned Bitwidth = I->getType()->getScalarSizeInBits();
7367 APInt UpperMask = APInt::getHighBitsSet(Bitwidth, Bitwidth / 2);
7368 if (!MaskedValueIsZero(OperandInstr, UpperMask, DL))
7369 continue;
7370 NumZExts++;
7371 }
7372
7373 // And(Load) is excluded to prevent CGP getting stuck in a loop of sinking
7374 // the And, just to hoist it again back to the load.
7375 if (!match(OperandInstr, m_And(m_Load(m_Value()), m_Value())))
7376 Ops.push_back(&Insert->getOperandUse(1));
7377 Ops.push_back(&Shuffle->getOperandUse(0));
7378 Ops.push_back(&Op);
7379 }
7380
7381 // It is profitable to sink if we found two of the same type of extends.
7382 if (!Ops.empty() && (NumSExts == 2 || NumZExts == 2))
7383 return true;
7384
7385 // Otherwise, see if we should sink splats for indexed variants.
7386 if (!ShouldSinkSplatForIndexedVariant(I))
7387 return false;
7388
7389 Ops.clear();
7390 if (isSplatShuffle(I->getOperand(0)))
7391 Ops.push_back(&I->getOperandUse(0));
7392 if (isSplatShuffle(I->getOperand(1)))
7393 Ops.push_back(&I->getOperandUse(1));
7394
7395 return !Ops.empty();
7396 }
7397 case Instruction::FMul: {
7398 // For SVE the lane-indexing is within 128-bits, so we can't fold splats.
7399 if (I->getType()->isScalableTy())
7400 return !Ops.empty();
7401
7402 if (cast<VectorType>(I->getType())->getElementType()->isHalfTy() &&
7403 !ST->hasFullFP16())
7404 return !Ops.empty();
7405
7406 // Sink splats for index lane variants
7407 if (isSplatShuffle(I->getOperand(0)))
7408 Ops.push_back(&I->getOperandUse(0));
7409 if (isSplatShuffle(I->getOperand(1)))
7410 Ops.push_back(&I->getOperandUse(1));
7411 return !Ops.empty();
7412 }
7413 default:
7414 return false;
7415 }
7416 return false;
7417}
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 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 hasPossibleIncompatibleOps(const Function *F, const AArch64TargetLowering &TLI)
Returns true if the function has explicit operations that can only be lowered using incompatible inst...
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 InstructionCost getHistogramCost(const AArch64Subtarget *ST, const IntrinsicCostAttributes &ICA)
static std::optional< Instruction * > tryCombineFromSVBoolBinOp(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEUnpack(InstCombiner &IC, IntrinsicInst &II)
static cl::opt< unsigned > SVETailFoldInsnThreshold("sve-tail-folding-insn-threshold", cl::init(15), cl::Hidden)
static cl::opt< bool > EnableFixedwidthAutovecInStreamingMode("enable-fixedwidth-autovec-in-streaming-mode", cl::init(false), cl::Hidden)
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 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 cl::opt< bool > EnableLSRCostOpt("enable-aarch64-lsr-cost-opt", cl::init(true), cl::Hidden)
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 bool isSMEABIRoutineCall(const CallInst &CI, const AArch64TargetLowering &TLI)
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 cl::opt< bool > SVEPreferFixedOverScalableIfEqualCost("sve-prefer-fixed-over-scalable-if-equal", cl::Hidden)
static bool isUnpackedVectorVT(EVT VecVT)
static std::optional< Instruction * > instCombineSVEDupX(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVECmpNE(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineDMB(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 cl::opt< unsigned > SVEGatherOverhead("sve-gather-overhead", cl::init(10), cl::Hidden)
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 cl::opt< int > Aarch64ForceUnrollThreshold("aarch64-force-unroll-threshold", cl::init(0), cl::Hidden, cl::desc("Threshold for forced unrolling of small loops in AArch64"))
static std::optional< Instruction * > instCombineSVEDup(InstCombiner &IC, IntrinsicInst &II)
static cl::opt< unsigned > BaseHistCntCost("aarch64-base-histcnt-cost", cl::init(8), cl::Hidden, cl::desc("The cost of a histcnt instruction"))
static std::optional< Instruction * > instCombineConvertFromSVBool(InstCombiner &IC, IntrinsicInst &II)
static cl::opt< unsigned > CallPenaltyChangeSM("call-penalty-sm-change", cl::init(5), cl::Hidden, cl::desc("Penalty of calling a function that requires a change to PSTATE.SM"))
static std::optional< Instruction * > instCombineSVEUzp1(InstCombiner &IC, IntrinsicInst &II)
static std::optional< Instruction * > instCombineSVEVectorBinOp(InstCombiner &IC, IntrinsicInst &II)
static cl::opt< bool > EnableScalableAutovecInStreamingMode("enable-scalable-autovec-in-streaming-mode", cl::init(false), cl::Hidden)
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 bool isSplatShuffle(Value *V)
static cl::opt< unsigned > InlineCallPenaltyChangeSM("inline-call-penalty-sm-change", cl::init(10), cl::Hidden, cl::desc("Penalty of inlining a call that requires a change to PSTATE.SM"))
static std::optional< Instruction * > instCombineSVELD1(InstCombiner &IC, IntrinsicInst &II, const DataLayout &DL)
static std::optional< Instruction * > instCombineSVESrshl(InstCombiner &IC, IntrinsicInst &II)
static cl::opt< unsigned > DMBLookaheadThreshold("dmb-lookahead-threshold", cl::init(10), cl::Hidden, cl::desc("The number of instructions to search for a redundant dmb"))
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 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 cl::opt< unsigned > NeonNonConstStrideOverhead("neon-nonconst-stride-overhead", cl::init(10), cl::Hidden)
static cl::opt< bool > EnableFalkorHWPFUnrollFix("enable-falkor-hwpf-unroll-fix", cl::init(true), cl::Hidden)
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 cl::opt< bool > EnableOrLikeSelectOpt("enable-aarch64-or-like-select", cl::init(true), cl::Hidden)
static cl::opt< unsigned > SVEScatterOverhead("sve-scatter-overhead", cl::init(10), cl::Hidden)
static std::optional< Instruction * > instCombineSVEDupqLane(InstCombiner &IC, IntrinsicInst &II)
This file a TargetTransformInfoImplBase conforming object specific to the AArch64 target machine.
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< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
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.
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
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 Value *V)
#define T
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
static uint64_t getBits(uint64_t Val, int Start, int End)
#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
unsigned getVectorInsertExtractBaseCost() 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 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 *CxtI=nullptr) 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 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 getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index, const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getIntImmCost(int64_t Val) const
Calculate the cost of materializing a 64-bit value.
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
InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const override
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const override
InstructionCost getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode, Type *ResTy, VectorType *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) 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
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
bool shouldMaximizeVectorBandwidth(TargetTransformInfo::RegisterKind K) 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
bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops) const override
Check if sinking I's operands to I's basic block is profitable, because the operands can be folded in...
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 getShuffleCost(TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, ArrayRef< int > Mask, TTI::TargetCostKind CostKind, int Index, VectorType *SubTp, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr) const override
InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *ValTy, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
bool isLegalMaskedExpandLoad(Type *DataTy, Align Alignment) const override
TTI::PopcntSupportKind getPopcntSupport(unsigned TyWidth) const override
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
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
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
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,...
bool preferFixedOverScalableIfEqualCost(bool IsEpilogue) const override
unsigned getMaxInterleaveFactor(ElementCount VF, bool HasUnorderedReductions) const override
Class for arbitrary precision integers.
Definition APInt.h:78
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:450
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1693
unsigned countLeadingOnes() const
Definition APInt.h:1647
void negate()
Negate this APInt in place.
Definition APInt.h:1491
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1084
unsigned logBase2() const
Definition APInt.h:1784
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:297
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1585
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
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 getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr) 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 getShuffleCost(TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, ArrayRef< int > Mask, TTI::TargetCostKind CostKind, int Index, VectorType *SubTp, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr) 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 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...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
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_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
@ 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_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
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
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:43
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:64
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
bool empty() const
Definition DenseMap.h:173
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:216
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:312
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:320
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This provides a helper for copying FMF from an instruction or setting specified flags.
Definition IRBuilder.h:93
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:867
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2617
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2605
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition IRBuilder.h:547
Type * getDoubleTy()
Fetch the type representing a 64-bit floating point value.
Definition IRBuilder.h:567
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:534
Type * getHalfTy()
Fetch the type representing a 16-bit floating point value.
Definition IRBuilder.h:552
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition IRBuilder.h:2000
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:482
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2314
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2529
Value * CreateBinOpFMF(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1737
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1439
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2232
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:1906
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2639
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:1919
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:1422
Type * getFloatTy()
Fetch the type representing a 32-bit floating point value.
Definition IRBuilder.h:562
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2305
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
Value * CreateInsertVector(Type *DstType, Value *SrcVec, Value *SubVec, Value *Idx, const Twine &Name="")
Create a call to the vector.insert intrinsic.
Definition IRBuilder.h:1126
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:2848
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
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
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:68
An instruction for reading from memory.
Value * getPointerOperand()
iterator_range< block_iterator > blocks() const
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.
static MVT getScalableVectorVT(MVT VT, unsigned NumElements)
bool isFixedLengthVector() const
MVT getVectorElementType() const
size_type size() const
Definition MapVector.h:58
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 hasNonStreamingInterfaceAndBody() const
bool hasStreamingCompatibleInterface() const
bool hasStreamingInterfaceOrBody() const
bool isSMEABIRoutine() const
bool hasStreamingBody() const
void set(unsigned M, bool Enable=true)
SMECallAttrs is a utility class to hold the SMEAttrs for a callsite.
bool requiresPreservingZT0() const
bool requiresPreservingAllZAState() const
static LLVM_ABI ScalableVectorType * get(Type *ElementType, unsigned MinNumElts)
Definition Type.cpp:889
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 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 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
Definition SmallPtrSet.h:99
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)
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:30
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:40
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:39
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:736
Class to represent struct types.
TargetInstrInfo - Interface to description of machine instruction set.
std::pair< LegalizeTypeAction, EVT > LegalizeKind
LegalizeKind holds the legalization kind that needs to happen to EVT in order to type-legalize it.
const RTLIB::RuntimeLibcallsInfo & getRuntimeLibcallsInfo() const
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
VectorInstrContext
Represents a hint about the context in which an insert/extract is used.
@ None
The insert/extract is not used with a load/store.
@ Load
The value being inserted comes from a load (InsertElement only).
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...
PopcntSupportKind
Flags indicating the kind of support for population count.
@ 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:343
static constexpr TypeSize getScalable(ScalarTy MinimumSize)
Definition TypeSize.h:346
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:310
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
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
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
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
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
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:306
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:286
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:255
user_iterator user_begin()
Definition Value.h:402
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:993
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
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 ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
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:252
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.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:24
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:888
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:417
@ 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:852
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:769
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:858
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:986
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:934
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:739
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:967
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:864
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.
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)
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
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.
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.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
IntrinsicID_match m_VScale()
Matches a call to llvm.vscale().
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::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.
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
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.
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)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
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.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
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.
LLVM_ABI Libcall getPOW(EVT RetVT)
getPOW - Return the POW_* value for the given types, or UNKNOWN_LIBCALL if there is none.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
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:315
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:1739
const CostTblEntryT< CostType > * CostTableLookup(ArrayRef< CostTblEntryT< CostType > > Tbl, int ISD, MVT Ty)
Find in cost table.
Definition CostTable.h:35
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:165
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:2554
bool isDUPFirstSegmentMask(ArrayRef< int > Mask, unsigned Segments, unsigned SegmentSize)
isDUPFirstSegmentMask - matches a splat of the first 128b segment.
TypeConversionCostTblEntryT< unsigned > TypeConversionCostTblEntry
Definition CostTable.h:61
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
LLVM_ABI std::optional< const MDOperand * > findStringMetadataForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for loop.
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
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:2173
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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:377
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:1746
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:331
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=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...
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:1753
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,...
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.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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.
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(cmp(),x,y) where one of (x,y) is loop invariant, and both x and y are int...
@ Xor
Bitwise or logical XOR of integers.
@ FindLast
FindLast reduction with select(cmp(),x,y) where x and y.
@ FMax
FP max implemented in terms of select(cmp()).
@ 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 implemented in terms of select(cmp()).
@ 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
CostTblEntryT< unsigned > CostTblEntry
Definition CostTable.h:30
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:1947
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
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:2166
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
LLVM_ABI std::optional< int64_t > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DominatorTree &DT, const DenseMap< Value *, const SCEV * > &StridesMap=DenseMap< Value *, const SCEV * >(), bool ShouldCheckWrap=true, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
If the pointer has a constant stride return it in units of the access type size.
const TypeConversionCostTblEntryT< CostType > * ConvertCostTableLookup(ArrayRef< TypeConversionCostTblEntryT< CostType > > Tbl, int ISD, MVT Dst, MVT Src)
Find in type conversion cost table.
Definition CostTable.h:66
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:373
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
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 & 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 isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:382
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
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:339
bool isFixedLengthVector() const
Definition ValueTypes.h:199
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
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:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition MCSchedule.h:129
bool isVariant() const
Definition MCSchedule.h:150
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:264
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*...
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...