LLVM 24.0.0git
BasicTTIImpl.h
Go to the documentation of this file.
1//===- BasicTTIImpl.h -------------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This file provides a helper that implements much of the TTI interface in
11/// terms of the target-independent code generator and TargetLowering
12/// interfaces.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CODEGEN_BASICTTIIMPL_H
17#define LLVM_CODEGEN_BASICTTIIMPL_H
18
19#include "llvm/ADT/APInt.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/STLExtras.h"
35#include "llvm/IR/BasicBlock.h"
36#include "llvm/IR/Constant.h"
37#include "llvm/IR/Constants.h"
38#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/InstrTypes.h"
41#include "llvm/IR/Instruction.h"
43#include "llvm/IR/Intrinsics.h"
44#include "llvm/IR/Operator.h"
45#include "llvm/IR/Type.h"
46#include "llvm/IR/Value.h"
55#include <algorithm>
56#include <cassert>
57#include <cstdint>
58#include <limits>
59#include <optional>
60#include <utility>
61
62namespace llvm {
63
64class Function;
65class GlobalValue;
66class LLVMContext;
67class ScalarEvolution;
68class SCEV;
69class TargetMachine;
70
71/// Returns -partial-unrolling-threshold if specified.
72LLVM_ABI std::optional<unsigned> getPartialUnrollingThreshold();
73
74/// Base class which can be used to help build a TTI implementation.
75///
76/// This class provides as much implementation of the TTI interface as is
77/// possible using the target independent parts of the code generator.
78///
79/// In order to subclass it, your class must implement a getST() method to
80/// return the subtarget, and a getTLI() method to return the target lowering.
81/// We need these methods implemented in the derived class so that this class
82/// doesn't have to duplicate storage for them.
83template <typename T>
85private:
87 using TTI = TargetTransformInfo;
88
89 /// Helper function to access this as a T.
90 const T *thisT() const { return static_cast<const T *>(this); }
91
92 /// Estimate a cost of Broadcast as an extract and sequence of insert
93 /// operations.
95 getBroadcastShuffleOverhead(FixedVectorType *VTy,
96 TTI::TargetCostKind CostKind) const {
98 // Broadcast cost is equal to the cost of extracting the zero'th element
99 // plus the cost of inserting it into every element of the result vector.
100 Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, VTy,
101 CostKind, 0, nullptr, nullptr);
102
103 for (int i = 0, e = VTy->getNumElements(); i < e; ++i) {
104 Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, VTy,
105 CostKind, i, nullptr, nullptr);
106 }
107 return Cost;
108 }
109
110 /// Estimate a cost of shuffle as a sequence of extract and insert
111 /// operations.
113 getPermuteShuffleOverhead(FixedVectorType *VTy,
114 TTI::TargetCostKind CostKind) const {
116 // Shuffle cost is equal to the cost of extracting element from its argument
117 // plus the cost of inserting them onto the result vector.
118
119 // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
120 // index 0 of first vector, index 1 of second vector,index 2 of first
121 // vector and finally index 3 of second vector and insert them at index
122 // <0,1,2,3> of result vector.
123 for (int i = 0, e = VTy->getNumElements(); i < e; ++i) {
124 Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, VTy,
125 CostKind, i, nullptr, nullptr);
126 Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, VTy,
127 CostKind, i, nullptr, nullptr);
128 }
129 return Cost;
130 }
131
132 /// Estimate a cost of subvector extraction as a sequence of extract and
133 /// insert operations.
134 InstructionCost getExtractSubvectorOverhead(VectorType *VTy,
135 TTI::TargetCostKind CostKind,
136 int Index,
137 FixedVectorType *SubVTy) const {
138 assert(VTy && SubVTy &&
139 "Can only extract subvectors from vectors");
140 int NumSubElts = SubVTy->getNumElements();
142 (Index + NumSubElts) <=
143 (int)cast<FixedVectorType>(VTy)->getNumElements()) &&
144 "SK_ExtractSubvector index out of range");
145
147 // Subvector extraction cost is equal to the cost of extracting element from
148 // the source type plus the cost of inserting them into the result vector
149 // type.
150 for (int i = 0; i != NumSubElts; ++i) {
151 Cost +=
152 thisT()->getVectorInstrCost(Instruction::ExtractElement, VTy,
153 CostKind, i + Index, nullptr, nullptr);
154 Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, SubVTy,
155 CostKind, i, nullptr, nullptr);
156 }
157 return Cost;
158 }
159
160 /// Estimate a cost of subvector insertion as a sequence of extract and
161 /// insert operations.
162 InstructionCost getInsertSubvectorOverhead(VectorType *VTy,
163 TTI::TargetCostKind CostKind,
164 int Index,
165 FixedVectorType *SubVTy) const {
166 assert(VTy && SubVTy &&
167 "Can only insert subvectors into vectors");
168 int NumSubElts = SubVTy->getNumElements();
170 (Index + NumSubElts) <=
171 (int)cast<FixedVectorType>(VTy)->getNumElements()) &&
172 "SK_InsertSubvector index out of range");
173
175 // Subvector insertion cost is equal to the cost of extracting element from
176 // the source type plus the cost of inserting them into the result vector
177 // type.
178 for (int i = 0; i != NumSubElts; ++i) {
179 Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, SubVTy,
180 CostKind, i, nullptr, nullptr);
181 Cost +=
182 thisT()->getVectorInstrCost(Instruction::InsertElement, VTy, CostKind,
183 i + Index, nullptr, nullptr);
184 }
185 return Cost;
186 }
187
188 /// Estimate the cost of casting the offset of a bitinsert or bitextract on
189 /// \p IntTy to the shift amount type.
191 getBitOffsetCastOverhead(Type *IntTy, TTI::TargetCostKind CostKind,
192 TTI::OperandValueInfo OffsetInfo) const {
193 // The i32 offset needs a zext or a trunc to the shift type.
194 unsigned BitWidth = IntTy->getScalarSizeInBits();
195 if (!IntTy->isVectorTy() || BitWidth == 32 || OffsetInfo.isConstant() ||
196 OffsetInfo.isUniform())
197 return TTI::TCC_Free;
198 return thisT()->getCastInstrCost(
199 BitWidth > 32 ? Instruction::ZExt : Instruction::Trunc, IntTy,
200 IntTy->getWithNewBitWidth(32), TTI::CastContextHint::None, CostKind);
201 }
202
203 /// Local query method delegates up to T which *must* implement this!
204 const TargetSubtargetInfo *getST() const {
205 return static_cast<const T *>(this)->getST();
206 }
207
208 /// Local query method delegates up to T which *must* implement this!
209 const TargetLoweringBase *getTLI() const {
210 return static_cast<const T *>(this)->getTLI();
211 }
212
213 static ISD::MemIndexedMode getISDIndexedMode(TTI::MemIndexedMode M) {
214 switch (M) {
216 return ISD::UNINDEXED;
217 case TTI::MIM_PreInc:
218 return ISD::PRE_INC;
219 case TTI::MIM_PreDec:
220 return ISD::PRE_DEC;
221 case TTI::MIM_PostInc:
222 return ISD::POST_INC;
223 case TTI::MIM_PostDec:
224 return ISD::POST_DEC;
225 }
226 llvm_unreachable("Unexpected MemIndexedMode");
227 }
228
229 InstructionCost getCommonMaskedMemoryOpCost(unsigned Opcode, Type *DataTy,
230 Align Alignment,
231 bool VariableMask,
232 bool IsGatherScatter,
233 TTI::TargetCostKind CostKind,
234 unsigned AddressSpace = 0) const {
235 // We cannot scalarize scalable vectors, so return Invalid.
236 if (isa<ScalableVectorType>(DataTy))
238
239 auto *VT = cast<FixedVectorType>(DataTy);
240 unsigned VF = VT->getNumElements();
241
242 // Assume the target does not have support for gather/scatter operations
243 // and provide a rough estimate.
244 //
245 // First, compute the cost of the individual memory operations.
246 InstructionCost AddrExtractCost =
247 IsGatherScatter ? getScalarizationOverhead(
249 PointerType::get(VT->getContext(), 0), VF),
250 /*Insert=*/false, /*Extract=*/true, CostKind)
251 : 0;
252
253 // The cost of the scalar loads/stores.
254 InstructionCost MemoryOpCost =
255 VF * thisT()->getMemoryOpCost(Opcode, VT->getElementType(), Alignment,
256 AddressSpace, CostKind);
257
258 // Next, compute the cost of packing the result in a vector.
259 InstructionCost PackingCost =
260 getScalarizationOverhead(VT, Opcode != Instruction::Store,
261 Opcode == Instruction::Store, CostKind);
262
263 InstructionCost ConditionalCost = 0;
264 if (VariableMask) {
265 // Compute the cost of conditionally executing the memory operations with
266 // variable masks. This includes extracting the individual conditions, a
267 // branches and PHIs to combine the results.
268 // NOTE: Estimating the cost of conditionally executing the memory
269 // operations accurately is quite difficult and the current solution
270 // provides a very rough estimate only.
271 ConditionalCost =
274 /*Insert=*/false, /*Extract=*/true, CostKind) +
275 VF * (thisT()->getCFInstrCost(Instruction::CondBr, CostKind) +
276 thisT()->getCFInstrCost(Instruction::PHI, CostKind));
277 }
278
279 return AddrExtractCost + MemoryOpCost + PackingCost + ConditionalCost;
280 }
281
282 /// Checks if the provided mask \p is a splat mask, i.e. it contains only -1
283 /// or same non -1 index value and this index value contained at least twice.
284 /// So, mask <0, -1,-1, -1> is not considered splat (it is just identity),
285 /// same for <-1, 0, -1, -1> (just a slide), while <2, -1, 2, -1> is a splat
286 /// with \p Index=2.
287 static bool isSplatMask(ArrayRef<int> Mask, unsigned NumSrcElts, int &Index) {
288 // Check that the broadcast index meets at least twice.
289 bool IsCompared = false;
290 if (int SplatIdx = PoisonMaskElem;
291 all_of(enumerate(Mask), [&](const auto &P) {
292 if (P.value() == PoisonMaskElem)
293 return P.index() != Mask.size() - 1 || IsCompared;
294 if (static_cast<unsigned>(P.value()) >= NumSrcElts * 2)
295 return false;
296 if (SplatIdx == PoisonMaskElem) {
297 SplatIdx = P.value();
298 return P.index() != Mask.size() - 1;
299 }
300 IsCompared = true;
301 return SplatIdx == P.value();
302 })) {
303 Index = SplatIdx;
304 return true;
305 }
306 return false;
307 }
308
309 /// Several intrinsics that return structs (including llvm.sincos[pi] and
310 /// llvm.modf) can be lowered to a vector library call (for certain VFs). The
311 /// vector library functions correspond to the scalar calls (e.g. sincos or
312 /// modf), which unlike the intrinsic return values via output pointers. This
313 /// helper checks if a vector call exists for the given intrinsic, and returns
314 /// the cost, which includes the cost of the mask (if required), and the loads
315 /// for values returned via output pointers. \p LC is the scalar libcall and
316 /// \p CallRetElementIndex (optional) is the struct element which is mapped to
317 /// the call return value. If std::nullopt is returned, then no vector library
318 /// call is available, so the intrinsic should be assigned the default cost
319 /// (e.g. scalarization).
320 std::optional<InstructionCost> getMultipleResultIntrinsicVectorLibCallCost(
321 const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind,
322 std::optional<unsigned> CallRetElementIndex = {}) const {
323 Type *RetTy = ICA.getReturnType();
324 // Vector variants of the intrinsic can be mapped to a vector library call.
325 if (!isa<StructType>(RetTy) ||
327 return std::nullopt;
328
329 Type *Ty = getContainedTypes(RetTy).front();
330 EVT VT = getTLI()->getValueType(DL, Ty);
331
332 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
333
334 switch (ICA.getID()) {
335 case Intrinsic::modf:
336 LC = RTLIB::getMODF(VT);
337 break;
338 case Intrinsic::sincospi:
339 LC = RTLIB::getSINCOSPI(VT);
340 break;
341 case Intrinsic::sincos:
342 LC = RTLIB::getSINCOS(VT);
343 break;
344 default:
345 return std::nullopt;
346 }
347
348 // Find associated libcall.
349 RTLIB::LibcallImpl LibcallImpl =
350 getTLI()->getLibcallLoweringInfo().getVectorLibcallImplOrMasked(LC);
351 if (LibcallImpl == RTLIB::Unsupported)
352 return std::nullopt;
353
354 LLVMContext &Ctx = RetTy->getContext();
355
356 // Cost the call + mask.
357 auto Cost =
358 thisT()->getCallInstrCost(nullptr, RetTy, ICA.getArgTypes(), CostKind);
359
362 auto VecTy = VectorType::get(IntegerType::getInt1Ty(Ctx), VF);
363 Cost += thisT()->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
364 VecTy, CostKind, {}, 0, nullptr, {});
365 }
366
367 // Lowering to a library call (with output pointers) may require us to emit
368 // reloads for the results.
369 for (auto [Idx, VectorTy] : enumerate(getContainedTypes(RetTy))) {
370 if (Idx == CallRetElementIndex)
371 continue;
372 Cost += thisT()->getMemoryOpCost(
373 Instruction::Load, VectorTy,
374 thisT()->getDataLayout().getABITypeAlign(VectorTy), 0, CostKind);
375 }
376 return Cost;
377 }
378
379 /// Filter out constant and duplicated entries in \p Ops and return a vector
380 /// containing the types from \p Tys corresponding to the remaining operands.
382 filterConstantAndDuplicatedOperands(ArrayRef<const Value *> Ops,
383 ArrayRef<Type *> Tys) {
384 SmallPtrSet<const Value *, 4> UniqueOperands;
385 SmallVector<Type *, 4> FilteredTys;
386 for (const auto &[Op, Ty] : zip_equal(Ops, Tys)) {
387 if (isa<Constant>(Op) || !UniqueOperands.insert(Op).second)
388 continue;
389 FilteredTys.push_back(Ty);
390 }
391 return FilteredTys;
392 }
393
394protected:
395 explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
396 : BaseT(DL) {}
397 ~BasicTTIImplBase() override = default;
398
401
402public:
403 /// \name Scalar TTI Implementations
404 /// @{
406 unsigned AddressSpace, Align Alignment,
407 unsigned *Fast) const override {
409 return getTLI()->allowsMisalignedMemoryAccesses(
411 }
412
413 bool areInlineCompatible(const Function *Caller,
414 const Function *Callee) const override {
415 const TargetMachine &TM = getTLI()->getTargetMachine();
416
417 const TargetSubtargetInfo *CallerSTI = TM.getSubtargetImpl(*Caller);
418 const TargetSubtargetInfo *CalleeSTI = TM.getSubtargetImpl(*Callee);
419 FeatureBitset InlineIgnoreFeatures = CallerSTI->getInlineIgnoreFeatures();
420 FeatureBitset InlineInverseFeatures = CallerSTI->getInlineInverseFeatures();
421 FeatureBitset InlineMustMatchFeatures =
422 CallerSTI->getInlineMustMatchFeatures();
423
424 FeatureBitset CallerBits =
425 (CallerSTI->getFeatureBits() ^ InlineInverseFeatures) &
426 ~InlineIgnoreFeatures;
427 FeatureBitset CalleeBits =
428 (CalleeSTI->getFeatureBits() ^ InlineInverseFeatures) &
429 ~InlineIgnoreFeatures;
430
431 if ((CallerBits & InlineMustMatchFeatures) !=
432 (CalleeBits & InlineMustMatchFeatures))
433 return false;
434
435 // Inline a callee if its target-features are a subset of the callers
436 // target-features.
437 return (CallerBits & CalleeBits) == CalleeBits;
438 }
439
440 bool hasBranchDivergence(const Function *F = nullptr) const override {
441 return false;
442 }
443
444 bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const override {
445 return false;
446 }
447
448 bool addrspacesMayAlias(unsigned AS0, unsigned AS1) const override {
449 return true;
450 }
451
452 unsigned getFlatAddressSpace() const override {
453 // Return an invalid address space.
454 return -1;
455 }
456
458 Intrinsic::ID IID) const override {
459 return false;
460 }
461
462 bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const override {
463 return getTLI()->getTargetMachine().isNoopAddrSpaceCast(DL, FromAS, ToAS);
464 }
465
466 unsigned getAssumedAddrSpace(const Value *V) const override {
467 return getTLI()->getTargetMachine().getAssumedAddrSpace(V);
468 }
469
470 std::pair<const Value *, unsigned>
471 getPredicatedAddrSpace(const Value *V) const override {
472 return getTLI()->getTargetMachine().getPredicatedAddrSpace(V);
473 }
474
476 Value *NewV) const override {
477 return nullptr;
478 }
479
480 bool isLegalAddImmediate(int64_t imm) const override {
481 return getTLI()->isLegalAddImmediate(imm);
482 }
483
484 bool isLegalAddScalableImmediate(int64_t Imm) const override {
485 return getTLI()->isLegalAddScalableImmediate(Imm);
486 }
487
488 bool isLegalICmpImmediate(int64_t imm) const override {
489 return getTLI()->isLegalICmpImmediate(imm);
490 }
491
492 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
493 bool HasBaseReg, int64_t Scale, unsigned AddrSpace,
494 Instruction *I = nullptr,
495 int64_t ScalableOffset = 0) const override {
497 AM.BaseGV = BaseGV;
498 AM.BaseOffs = BaseOffset;
499 AM.HasBaseReg = HasBaseReg;
500 AM.Scale = Scale;
501 AM.ScalableOffset = ScalableOffset;
502 return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace, I);
503 }
504
505 int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset, int64_t MaxOffset) {
506 return getTLI()->getPreferredLargeGEPBaseOffset(MinOffset, MaxOffset);
507 }
508
509 unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy, Type *ScalarValTy,
510 Align Alignment,
511 unsigned AddrSpace) const override {
512 auto &&IsSupportedByTarget = [this, ScalarMemTy, ScalarValTy, Alignment,
513 AddrSpace](unsigned VF) {
514 auto *SrcTy = FixedVectorType::get(ScalarMemTy, VF / 2);
515 EVT VT = getTLI()->getValueType(DL, SrcTy);
516 if (getTLI()->isOperationLegal(ISD::STORE, VT) ||
517 getTLI()->isOperationCustom(ISD::STORE, VT))
518 return true;
519
520 EVT ValVT =
521 getTLI()->getValueType(DL, FixedVectorType::get(ScalarValTy, VF / 2));
522 EVT LegalizedVT =
523 getTLI()->getTypeToTransformTo(ScalarMemTy->getContext(), VT);
524 return getTLI()->isTruncStoreLegal(LegalizedVT, ValVT, Alignment,
525 AddrSpace);
526 };
527 while (VF > 2 && IsSupportedByTarget(VF))
528 VF /= 2;
529 return VF;
530 }
531
532 bool isIndexedLoadLegal(TTI::MemIndexedMode M, Type *Ty) const override {
533 EVT VT = getTLI()->getValueType(DL, Ty, /*AllowUnknown=*/true);
534 return getTLI()->isIndexedLoadLegal(getISDIndexedMode(M), VT);
535 }
536
537 bool isIndexedStoreLegal(TTI::MemIndexedMode M, Type *Ty) const override {
538 EVT VT = getTLI()->getValueType(DL, Ty, /*AllowUnknown=*/true);
539 return getTLI()->isIndexedStoreLegal(getISDIndexedMode(M), VT);
540 }
541
543 const TTI::LSRCost &C2) const override {
545 }
546
550
554
558
560 StackOffset BaseOffset, bool HasBaseReg,
561 int64_t Scale,
562 unsigned AddrSpace) const override {
564 AM.BaseGV = BaseGV;
565 AM.BaseOffs = BaseOffset.getFixed();
566 AM.HasBaseReg = HasBaseReg;
567 AM.Scale = Scale;
568 AM.ScalableOffset = BaseOffset.getScalable();
569 if (getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace))
570 return 0;
572 }
573
574 bool isTruncateFree(Type *Ty1, Type *Ty2) const override {
575 return getTLI()->isTruncateFree(Ty1, Ty2);
576 }
577
578 bool isProfitableToHoist(Instruction *I) const override {
579 return getTLI()->isProfitableToHoist(I);
580 }
581
582 bool useAA() const override { return getST()->useAA(); }
583
584 bool isTypeLegal(Type *Ty) const override {
585 EVT VT = getTLI()->getValueType(DL, Ty, /*AllowUnknown=*/true);
586 return getTLI()->isTypeLegal(VT);
587 }
588
589 unsigned getRegUsageForType(Type *Ty) const override {
590 if (!getTypeLegalizationCost(Ty).first.isValid())
591 return 0;
592 EVT ETy = getTLI()->getValueType(DL, Ty);
593 return getTLI()->getNumRegisters(Ty->getContext(), ETy);
594 }
595
596 InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr,
598 TTI::TargetCostKind CostKind,
599 Type *AccessType) const override {
600 return BaseT::getGEPCost(PointeeType, Ptr, Operands, CostKind, AccessType);
601 }
602
604 const SwitchInst &SI, unsigned &JumpTableSize, ProfileSummaryInfo *PSI,
605 BlockFrequencyInfo *BFI) const override {
606 /// Try to find the estimated number of clusters. Note that the number of
607 /// clusters identified in this function could be different from the actual
608 /// numbers found in lowering. This function ignore switches that are
609 /// lowered with a mix of jump table / bit test / BTree. This function was
610 /// initially intended to be used when estimating the cost of switch in
611 /// inline cost heuristic, but it's a generic cost model to be used in other
612 /// places (e.g., in loop unrolling).
613 unsigned N = SI.getNumCases();
614 const TargetLoweringBase *TLI = getTLI();
615 const DataLayout &DL = this->getDataLayout();
616
617 JumpTableSize = 0;
618 bool IsJTAllowed = TLI->areJTsAllowed(SI.getParent()->getParent());
619
620 // Early exit if both a jump table and bit test are not allowed.
621 if (N < 1 || (!IsJTAllowed && DL.getIndexSizeInBits(0u) < N))
622 return N;
623
624 APInt MaxCaseVal = SI.case_begin()->getCaseValue()->getValue();
625 APInt MinCaseVal = MaxCaseVal;
626 for (auto CI : SI.cases()) {
627 const APInt &CaseVal = CI.getCaseValue()->getValue();
628 if (CaseVal.sgt(MaxCaseVal))
629 MaxCaseVal = CaseVal;
630 if (CaseVal.slt(MinCaseVal))
631 MinCaseVal = CaseVal;
632 }
633
634 // Check if suitable for a bit test
635 if (N <= DL.getIndexSizeInBits(0u)) {
637 for (auto I : SI.cases()) {
638 const BasicBlock *BB = I.getCaseSuccessor();
639 ++DestMap[BB];
640 }
641
642 if (TLI->isSuitableForBitTests(DestMap, MinCaseVal, MaxCaseVal, DL))
643 return 1;
644 }
645
646 // Check if suitable for a jump table.
647 if (IsJTAllowed) {
648 if (N < 2 || N < TLI->getMinimumJumpTableEntries())
649 return N;
651 (MaxCaseVal - MinCaseVal)
652 .getLimitedValue(std::numeric_limits<uint64_t>::max() - 1) + 1;
653 // Check whether a range of clusters is dense enough for a jump table
654 if (TLI->isSuitableForJumpTable(&SI, N, Range, PSI, BFI)) {
655 JumpTableSize = Range;
656 return 1;
657 }
658 }
659 return N;
660 }
661
662 bool shouldBuildLookupTables() const override {
663 const TargetLoweringBase *TLI = getTLI();
664 return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
665 TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
666 }
667
668 bool shouldBuildRelLookupTables() const override {
669 const TargetMachine &TM = getTLI()->getTargetMachine();
670 // If non-PIC mode, do not generate a relative lookup table.
671 if (!TM.isPositionIndependent())
672 return false;
673
674 /// Relative lookup table entries consist of 32-bit offsets.
675 /// Do not generate relative lookup tables for large code models
676 /// in 64-bit achitectures where 32-bit offsets might not be enough.
677 if (TM.getCodeModel() == CodeModel::Medium ||
679 return false;
680
681 const Triple &TargetTriple = TM.getTargetTriple();
682 if (!TargetTriple.isArch64Bit())
683 return false;
684
685 // TODO: Triggers issues on aarch64 on darwin, so temporarily disable it
686 // there.
687 if (TargetTriple.getArch() == Triple::aarch64 && TargetTriple.isOSDarwin())
688 return false;
689
690 return true;
691 }
692
693 bool haveFastSqrt(Type *Ty) const override {
694 const TargetLoweringBase *TLI = getTLI();
695 EVT VT = TLI->getValueType(DL, Ty);
696 return TLI->isTypeLegal(VT) &&
697 TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
698 }
699
700 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) const override { return true; }
701
702 InstructionCost getFPOpCost(Type *Ty) const override {
703 // Check whether FADD is available, as a proxy for floating-point in
704 // general.
705 const TargetLoweringBase *TLI = getTLI();
706 EVT VT = TLI->getValueType(DL, Ty);
707 if (TLI->isOperationLegalOrCustomOrPromote(ISD::FADD, VT))
710 }
711
713 const Function &Fn) const override {
714 switch (Inst.getOpcode()) {
715 default:
716 break;
717 case Instruction::SDiv:
718 case Instruction::SRem:
719 case Instruction::UDiv:
720 case Instruction::URem: {
721 if (!isa<ConstantInt>(Inst.getOperand(1)))
722 return false;
723 EVT VT = getTLI()->getValueType(DL, Inst.getType());
724 return !getTLI()->isIntDivCheap(VT, Fn.getAttributes());
725 }
726 };
727
728 return false;
729 }
730
731 unsigned getInliningThresholdMultiplier() const override { return 1; }
732 unsigned adjustInliningThreshold(const CallBase *CB) const override {
733 return 0;
734 }
735 unsigned getCallerAllocaCost(const CallBase *CB,
736 const AllocaInst *AI) const override {
737 return 0;
738 }
739
740 int getInlinerVectorBonusPercent() const override { return 150; }
741
744 OptimizationRemarkEmitter *ORE) const override {
745 // This unrolling functionality is target independent, but to provide some
746 // motivation for its intended use, for x86:
747
748 // According to the Intel 64 and IA-32 Architectures Optimization Reference
749 // Manual, Intel Core models and later have a loop stream detector (and
750 // associated uop queue) that can benefit from partial unrolling.
751 // The relevant requirements are:
752 // - The loop must have no more than 4 (8 for Nehalem and later) branches
753 // taken, and none of them may be calls.
754 // - The loop can have no more than 18 (28 for Nehalem and later) uops.
755
756 // According to the Software Optimization Guide for AMD Family 15h
757 // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
758 // and loop buffer which can benefit from partial unrolling.
759 // The relevant requirements are:
760 // - The loop must have fewer than 16 branches
761 // - The loop must have less than 40 uops in all executed loop branches
762
763 // The number of taken branches in a loop is hard to estimate here, and
764 // benchmarking has revealed that it is better not to be conservative when
765 // estimating the branch count. As a result, we'll ignore the branch limits
766 // until someone finds a case where it matters in practice.
767
768 unsigned MaxOps;
769 const TargetSubtargetInfo *ST = getST();
770 if (std::optional<unsigned> Threshold = getPartialUnrollingThreshold())
771 MaxOps = *Threshold;
772 else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
773 MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
774 else
775 return;
776
777 // Scan the loop: don't unroll loops with calls.
778 for (BasicBlock *BB : L->blocks()) {
779 for (Instruction &I : *BB) {
780 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
781 if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
782 if (!thisT()->isLoweredToCall(F))
783 continue;
784 }
785
786 if (ORE) {
787 ORE->emit([&]() {
788 return OptimizationRemark("TTI", "DontUnroll", L->getStartLoc(),
789 L->getHeader())
790 << "advising against unrolling the loop because it "
791 "contains a "
792 << ore::NV("Call", &I);
793 });
794 }
795 return;
796 }
797 }
798 }
799
800 // Enable runtime and partial unrolling up to the specified size.
801 // Enable using trip count upper bound to unroll loops.
802 UP.Partial = UP.Runtime = UP.UpperBound = true;
803 UP.PartialThreshold = MaxOps;
804
805 // Avoid unrolling when optimizing for size.
806 UP.OptSizeThreshold = 0;
808
809 // Set number of instructions optimized when "back edge"
810 // becomes "fall through" to default value of 2.
811 UP.BEInsns = 2;
812 }
813
815 TTI::PeelingPreferences &PP) const override {
816 PP.PeelCount = 0;
817 PP.AllowPeeling = true;
818 PP.AllowLoopNestsPeeling = false;
819 PP.PeelProfiledIterations = true;
820 }
821
824 HardwareLoopInfo &HWLoopInfo) const override {
825 return BaseT::isHardwareLoopProfitable(L, SE, AC, LibInfo, HWLoopInfo);
826 }
827
828 unsigned getEpilogueVectorizationMinVF() const override {
830 }
831
835
839
840 std::optional<Instruction *>
843 }
844
845 std::optional<Value *>
847 APInt DemandedMask, KnownBits &Known,
848 bool &KnownBitsComputed) const override {
849 return BaseT::simplifyDemandedUseBitsIntrinsic(IC, II, DemandedMask, Known,
850 KnownBitsComputed);
851 }
852
854 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
855 APInt &UndefElts2, APInt &UndefElts3,
856 std::function<void(Instruction *, unsigned, APInt, APInt &)>
857 SimplifyAndSetOp) const override {
859 IC, II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
860 SimplifyAndSetOp);
861 }
862
864 return getST()->getMispredictionPenalty();
865 }
866
867 std::optional<unsigned>
869 return std::optional<unsigned>(
870 getST()->getCacheSize(static_cast<unsigned>(Level)));
871 }
872
873 std::optional<unsigned>
875 std::optional<unsigned> TargetResult =
876 getST()->getCacheAssociativity(static_cast<unsigned>(Level));
877
878 if (TargetResult)
879 return TargetResult;
880
881 return BaseT::getCacheAssociativity(Level);
882 }
883
884 unsigned getCacheLineSize() const override {
885 return getST()->getCacheLineSize();
886 }
887
888 unsigned getPrefetchDistance() const override {
889 return getST()->getPrefetchDistance();
890 }
891
892 unsigned getMinPrefetchStride(unsigned NumMemAccesses,
893 unsigned NumStridedMemAccesses,
894 unsigned NumPrefetches,
895 bool HasCall) const override {
896 return getST()->getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses,
897 NumPrefetches, HasCall);
898 }
899
900 unsigned getMaxPrefetchIterationsAhead() const override {
901 return getST()->getMaxPrefetchIterationsAhead();
902 }
903
904 bool enableWritePrefetching() const override {
905 return getST()->enableWritePrefetching();
906 }
907
908 bool shouldPrefetchAddressSpace(unsigned AS) const override {
909 return getST()->shouldPrefetchAddressSpace(AS);
910 }
911
912 /// @}
913
914 /// \name Vector TTI Implementations
915 /// @{
916
921
922 std::optional<unsigned> getVScaleForTuning() const override {
923 return std::nullopt;
924 }
925
926 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
927 /// are set if the demanded result elements need to be inserted and/or
928 /// extracted from vectors.
930 getScalarizationOverhead(VectorType *InTy, const APInt &DemandedElts,
931 bool Insert, bool Extract,
932 TTI::TargetCostKind CostKind,
933 bool ForPoisonSrc = true, ArrayRef<Value *> VL = {},
935 TTI::VectorInstrContext::None) const override {
936 /// FIXME: a bitfield is not a reasonable abstraction for talking about
937 /// which elements are needed from a scalable vector
938 if (isa<ScalableVectorType>(InTy))
940 auto *Ty = cast<FixedVectorType>(InTy);
941
942 assert(DemandedElts.getBitWidth() == Ty->getNumElements() &&
943 (VL.empty() || VL.size() == Ty->getNumElements()) &&
944 "Vector size mismatch");
945
947
948 for (int i = 0, e = Ty->getNumElements(); i < e; ++i) {
949 if (!DemandedElts[i])
950 continue;
951 if (Insert) {
952 Value *InsertedVal = VL.empty() ? nullptr : VL[i];
953 Cost +=
954 thisT()->getVectorInstrCost(Instruction::InsertElement, Ty,
955 CostKind, i, nullptr, InsertedVal, VIC);
956 }
957 if (Extract)
958 Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, Ty,
959 CostKind, i, nullptr, nullptr, VIC);
960 }
961
962 return Cost;
963 }
964
965 bool
967 unsigned ScalarOpdIdx) const override {
968 return false;
969 }
970
972 int OpdIdx) const override {
973 return OpdIdx == -1;
974 }
975
976 bool
978 int RetIdx) const override {
979 return RetIdx == 0;
980 }
981
982 /// Helper wrapper for the DemandedElts variant of getScalarizationOverhead.
984 VectorType *InTy, bool Insert, bool Extract, TTI::TargetCostKind CostKind,
985 bool ForPoisonSrc = true, ArrayRef<Value *> VL = {},
987 if (isa<ScalableVectorType>(InTy))
989 auto *Ty = cast<FixedVectorType>(InTy);
990
991 APInt DemandedElts = APInt::getAllOnes(Ty->getNumElements());
992 // Use CRTP to allow target overrides
993 return thisT()->getScalarizationOverhead(Ty, DemandedElts, Insert, Extract,
994 CostKind, ForPoisonSrc, VL, VIC);
995 }
996
997 /// Estimate the overhead of scalarizing an instruction's
998 /// operands. The (potentially vector) types to use for each of
999 /// argument are passes via Tys.
1003 TTI::VectorInstrContext::None) const override {
1005 for (Type *Ty : Tys) {
1006 // Disregard things like metadata arguments.
1007 if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy() &&
1008 !Ty->isPtrOrPtrVectorTy())
1009 continue;
1010
1011 if (auto *VecTy = dyn_cast<VectorType>(Ty))
1012 Cost += getScalarizationOverhead(VecTy, /*Insert*/ false,
1013 /*Extract*/ true, CostKind,
1014 /*ForPoisonSrc=*/true, {}, VIC);
1015 }
1016
1017 return Cost;
1018 }
1019
1020 /// Estimate the overhead of scalarizing the inputs and outputs of an
1021 /// instruction, with return type RetTy and arguments Args of type Tys. If
1022 /// Args are unknown (empty), then the cost associated with one argument is
1023 /// added as a heuristic.
1026 ArrayRef<Type *> Tys,
1027 TTI::TargetCostKind CostKind) const {
1029 RetTy, /*Insert*/ true, /*Extract*/ false, CostKind);
1030 if (!Args.empty())
1032 filterConstantAndDuplicatedOperands(Args, Tys), CostKind);
1033 else
1034 // When no information on arguments is provided, we add the cost
1035 // associated with one argument as a heuristic.
1036 Cost += getScalarizationOverhead(RetTy, /*Insert*/ false,
1037 /*Extract*/ true, CostKind);
1038
1039 return Cost;
1040 }
1041
1042 /// Estimate the cost of type-legalization and the legalized type.
1043 std::pair<InstructionCost, MVT> getTypeLegalizationCost(Type *Ty) const {
1044 auto [It, Inserted] = TypeLegalizationCostCache.try_emplace(Ty);
1045 if (Inserted)
1046 It->second = computeTypeLegalizationCost(Ty);
1047 return It->second;
1048 }
1049
1050private:
1051 std::pair<InstructionCost, MVT> computeTypeLegalizationCost(Type *Ty) const {
1052 LLVMContext &C = Ty->getContext();
1053 EVT MTy = getTLI()->getValueType(DL, Ty);
1054
1056 // We keep legalizing the type until we find a legal kind. We assume that
1057 // the only operation that costs anything is the split. After splitting
1058 // we need to handle two types.
1059 while (true) {
1061
1063 // Ensure we return a sensible simple VT here, since many callers of
1064 // this function require it.
1065 MVT VT = MTy.isSimple() ? MTy.getSimpleVT() : MVT::i64;
1066 return std::make_pair(InstructionCost::getInvalid(), VT);
1067 }
1068
1069 if (LK.first == TargetLoweringBase::TypeLegal)
1070 return std::make_pair(Cost, MTy.getSimpleVT());
1071
1072 if (LK.first == TargetLoweringBase::TypeSplitVector ||
1074 Cost *= 2;
1075
1076 // Do not loop with f128 type.
1077 if (MTy == LK.second)
1078 return std::make_pair(Cost, MTy.getSimpleVT());
1079
1080 // Keep legalizing the type.
1081 MTy = LK.second;
1082 }
1083 }
1084
1085 /// Memoizes type legalization cost. The mapping does not depend on the IR, so
1086 /// entries stay valid for the lifetime of this object.
1087 mutable DenseMap<Type *, std::pair<InstructionCost, MVT>>
1088 TypeLegalizationCostCache;
1089
1090public:
1092 bool HasUnorderedReductions) const override {
1093 return 1;
1094 }
1095
1097 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
1100 ArrayRef<const Value *> Args = {}, const Instruction *CtxI = nullptr,
1101 const TargetLibraryInfo *TLibInfo = nullptr,
1102 ArrayRef<const Value *> Scalars = {}) const override {
1103 // Check if any of the operands are vector operands.
1104 const TargetLoweringBase *TLI = getTLI();
1105 int ISD = TLI->InstructionOpcodeToISD(Opcode);
1106 assert(ISD && "Invalid opcode");
1107
1108 // TODO: Handle more cost kinds.
1109 if (CostKind != TTI::TCK_RecipThroughput)
1110 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
1111 Opd2Info, Args, CtxI, TLibInfo,
1112 Scalars);
1113
1114 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
1115
1116 bool IsFloat = Ty->isFPOrFPVectorTy();
1117 // Assume that floating point arithmetic operations cost twice as much as
1118 // integer operations.
1119 InstructionCost OpCost = (IsFloat ? 2 : 1);
1120
1121 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
1122 // The operation is legal. Assume it costs 1.
1123 // TODO: Once we have extract/insert subvector cost we need to use them.
1124 return LT.first * OpCost;
1125 }
1126
1127 if (!TLI->isOperationExpand(ISD, LT.second)) {
1128 // If the operation is custom lowered, then assume that the code is twice
1129 // as expensive.
1130 return LT.first * 2 * OpCost;
1131 }
1132
1133 // An 'Expand' of URem and SRem is special because it may default
1134 // to expanding the operation into a sequence of sub-operations
1135 // i.e. X % Y -> X-(X/Y)*Y.
1136 if (ISD == ISD::UREM || ISD == ISD::SREM) {
1137 bool IsSigned = ISD == ISD::SREM;
1138 if (TLI->isOperationLegalOrCustom(IsSigned ? ISD::SDIVREM : ISD::UDIVREM,
1139 LT.second) ||
1140 TLI->isOperationLegalOrCustom(IsSigned ? ISD::SDIV : ISD::UDIV,
1141 LT.second)) {
1142 unsigned DivOpc = IsSigned ? Instruction::SDiv : Instruction::UDiv;
1143 InstructionCost DivCost = thisT()->getArithmeticInstrCost(
1144 DivOpc, Ty, CostKind, Opd1Info, Opd2Info);
1145 InstructionCost MulCost =
1146 thisT()->getArithmeticInstrCost(Instruction::Mul, Ty, CostKind);
1147 InstructionCost SubCost =
1148 thisT()->getArithmeticInstrCost(Instruction::Sub, Ty, CostKind);
1149 return DivCost + MulCost + SubCost;
1150 }
1151 }
1152
1153 // We cannot scalarize scalable vectors, so return Invalid.
1156
1157 // Else, assume that we need to scalarize this op.
1158 // TODO: If one of the types get legalized by splitting, handle this
1159 // similarly to what getCastInstrCost() does.
1160 if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
1161 InstructionCost Cost = thisT()->getArithmeticInstrCost(
1162 Opcode, VTy->getScalarType(), CostKind, Opd1Info, Opd2Info, Args,
1163 CtxI, TLibInfo, Scalars);
1164 // Return the cost of multiple scalar invocation plus the cost of
1165 // inserting and extracting the values.
1166 SmallVector<Type *> Tys(Args.size(), Ty);
1167 return getScalarizationOverhead(VTy, Args, Tys, CostKind) +
1168 VTy->getNumElements() * Cost;
1169 }
1170
1171 // We don't know anything about this scalar instruction.
1172 return OpCost;
1173 }
1174
1176 ArrayRef<int> Mask,
1177 VectorType *SrcTy, int &Index,
1178 VectorType *&SubTy) const {
1179 if (Mask.empty())
1180 return Kind;
1181 int NumDstElts = Mask.size();
1182 int NumSrcElts = SrcTy->getElementCount().getKnownMinValue();
1183 switch (Kind) {
1185 if (ShuffleVectorInst::isReverseMask(Mask, NumSrcElts))
1186 return TTI::SK_Reverse;
1187 if (ShuffleVectorInst::isZeroEltSplatMask(Mask, NumSrcElts))
1188 return TTI::SK_Broadcast;
1189 if (isSplatMask(Mask, NumSrcElts, Index))
1190 return TTI::SK_Broadcast;
1191 if (ShuffleVectorInst::isExtractSubvectorMask(Mask, NumSrcElts, Index) &&
1192 (Index + NumDstElts) <= NumSrcElts) {
1193 SubTy = FixedVectorType::get(SrcTy->getElementType(), NumDstElts);
1195 }
1196 break;
1197 }
1198 case TTI::SK_PermuteTwoSrc: {
1199 if (all_of(Mask, [NumSrcElts](int M) { return M < NumSrcElts; }))
1201 Index, SubTy);
1202 int NumSubElts;
1203 if (NumDstElts > 2 && ShuffleVectorInst::isInsertSubvectorMask(
1204 Mask, NumSrcElts, NumSubElts, Index)) {
1205 if (Index + NumSubElts > NumSrcElts)
1206 return Kind;
1207 SubTy = FixedVectorType::get(SrcTy->getElementType(), NumSubElts);
1209 }
1210 if (ShuffleVectorInst::isSelectMask(Mask, NumSrcElts))
1211 return TTI::SK_Select;
1212 if (ShuffleVectorInst::isTransposeMask(Mask, NumSrcElts))
1213 return TTI::SK_Transpose;
1214 if (ShuffleVectorInst::isSpliceMask(Mask, NumSrcElts, Index))
1215 return TTI::SK_Splice;
1216 break;
1217 }
1218 case TTI::SK_Select:
1219 case TTI::SK_Reverse:
1220 case TTI::SK_Broadcast:
1221 case TTI::SK_Transpose:
1224 case TTI::SK_Splice:
1225 break;
1226 }
1227 return Kind;
1228 }
1229
1232 TTI::TargetCostKind CostKind, ArrayRef<int> Mask, int Index,
1233 VectorType *SubTp, ArrayRef<const Value *> Args = {},
1234 const Instruction *CtxI = nullptr,
1236 TTI::VectorInstrContext::None) const override {
1237 switch (improveShuffleKindFromMask(Kind, Mask, SrcTy, Index, SubTp)) {
1238 case TTI::SK_Broadcast:
1239 if (auto *FVT = dyn_cast<FixedVectorType>(SrcTy))
1240 return getBroadcastShuffleOverhead(FVT, CostKind);
1242 case TTI::SK_Select:
1243 case TTI::SK_Splice:
1244 case TTI::SK_Reverse:
1245 case TTI::SK_Transpose:
1248 if (auto *FVT = dyn_cast<FixedVectorType>(SrcTy))
1249 return getPermuteShuffleOverhead(FVT, CostKind);
1252 return getExtractSubvectorOverhead(SrcTy, CostKind, Index,
1253 cast<FixedVectorType>(SubTp));
1255 return getInsertSubvectorOverhead(DstTy, CostKind, Index,
1256 cast<FixedVectorType>(SubTp));
1257 }
1258 llvm_unreachable("Unknown TTI::ShuffleKind");
1259 }
1260
1262 getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
1264 const Instruction *I = nullptr) const override {
1265 if (BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I) == 0)
1266 return 0;
1267
1268 const TargetLoweringBase *TLI = getTLI();
1269 int ISD = TLI->InstructionOpcodeToISD(Opcode);
1270 assert(ISD && "Invalid opcode");
1271 std::pair<InstructionCost, MVT> SrcLT = getTypeLegalizationCost(Src);
1272 std::pair<InstructionCost, MVT> DstLT = getTypeLegalizationCost(Dst);
1273
1274 TypeSize SrcSize = SrcLT.second.getSizeInBits();
1275 TypeSize DstSize = DstLT.second.getSizeInBits();
1276 bool IntOrPtrSrc = Src->isIntegerTy() || Src->isPointerTy();
1277 bool IntOrPtrDst = Dst->isIntegerTy() || Dst->isPointerTy();
1278
1279 switch (Opcode) {
1280 default:
1281 break;
1282 case Instruction::Trunc:
1283 // Check for NOOP conversions.
1284 if (TLI->isTruncateFree(SrcLT.second, DstLT.second))
1285 return 0;
1286 [[fallthrough]];
1287 case Instruction::BitCast:
1288 // Bitcast between types that are legalized to the same type are free and
1289 // assume int to/from ptr of the same size is also free.
1290 if (SrcLT.first == DstLT.first && IntOrPtrSrc == IntOrPtrDst &&
1291 SrcSize == DstSize)
1292 return 0;
1293 break;
1294 case Instruction::FPExt:
1295 if (I && getTLI()->isExtFree(I))
1296 return 0;
1297 break;
1298 case Instruction::ZExt:
1299 if (TLI->isZExtFree(SrcLT.second, DstLT.second))
1300 return 0;
1301 [[fallthrough]];
1302 case Instruction::SExt:
1303 if (I && getTLI()->isExtFree(I))
1304 return 0;
1305
1306 // If this is a zext/sext of a load, return 0 if the corresponding
1307 // extending load exists on target and the result type is legal.
1308 if (CCH == TTI::CastContextHint::Normal) {
1309 EVT ExtVT = EVT::getEVT(Dst);
1310 EVT LoadVT = EVT::getEVT(Src);
1311 unsigned LType =
1312 Opcode == Instruction::ZExt ? ISD::ZEXTLOAD : ISD::SEXTLOAD;
1313 if (I) {
1314 if (auto *LI = dyn_cast<LoadInst>(I->getOperand(0))) {
1315 if (DstLT.first == SrcLT.first &&
1316 TLI->isLoadLegal(ExtVT, LoadVT, LI->getAlign(),
1317 LI->getPointerAddressSpace(), LType, false))
1318 return 0;
1319 } else if (auto *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1320 switch (II->getIntrinsicID()) {
1321 case Intrinsic::masked_load: {
1322 Type *PtrType = II->getArgOperand(0)->getType();
1323 assert(PtrType->isPointerTy());
1324
1325 if (DstLT.first == SrcLT.first &&
1326 TLI->isLoadLegal(
1327 ExtVT, LoadVT, II->getParamAlign(0).valueOrOne(),
1328 PtrType->getPointerAddressSpace(), LType, false))
1329 return 0;
1330
1331 break;
1332 }
1333 default:
1334 break;
1335 }
1336 }
1337 }
1338 }
1339 break;
1340 case Instruction::AddrSpaceCast:
1341 if (TLI->isFreeAddrSpaceCast(DL, Src->getPointerAddressSpace(),
1342 Dst->getPointerAddressSpace()))
1343 return 0;
1344 break;
1345 }
1346
1347 auto *SrcVTy = dyn_cast<VectorType>(Src);
1348 auto *DstVTy = dyn_cast<VectorType>(Dst);
1349
1350 // If the cast is marked as legal (or promote) then assume low cost.
1351 if (SrcLT.first == DstLT.first &&
1352 TLI->isOperationLegalOrPromote(ISD, DstLT.second))
1353 return SrcLT.first;
1354
1355 // Handle scalar conversions.
1356 if (!SrcVTy && !DstVTy) {
1357 // Just check the op cost. If the operation is legal then assume it costs
1358 // 1.
1359 if (!TLI->isOperationExpand(ISD, DstLT.second))
1360 return 1;
1361
1362 // Assume that illegal scalar instruction are expensive.
1363 return 4;
1364 }
1365
1366 // Check vector-to-vector casts.
1367 if (DstVTy && SrcVTy) {
1368 // If the cast is between same-sized registers, then the check is simple.
1369 if (SrcLT.first == DstLT.first && SrcSize == DstSize) {
1370
1371 // Assume that Zext is done using AND.
1372 if (Opcode == Instruction::ZExt)
1373 return SrcLT.first;
1374
1375 // Assume that sext is done using SHL and SRA.
1376 if (Opcode == Instruction::SExt)
1377 return SrcLT.first * 2;
1378
1379 // Just check the op cost. If the operation is legal then assume it
1380 // costs
1381 // 1 and multiply by the type-legalization overhead.
1382 if (!TLI->isOperationExpand(ISD, DstLT.second))
1383 return SrcLT.first * 1;
1384 }
1385
1386 // If we are legalizing by splitting, query the concrete TTI for the cost
1387 // of casting the original vector twice. We also need to factor in the
1388 // cost of the split itself. Count that as 1, to be consistent with
1389 // getTypeLegalizationCost().
1390 bool SplitSrc =
1391 TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
1393 bool SplitDst =
1394 TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
1396 if ((SplitSrc || SplitDst) && SrcVTy->getElementCount().isKnownEven() &&
1397 DstVTy->getElementCount().isKnownEven()) {
1398 Type *SplitDstTy = VectorType::getHalfElementsVectorType(DstVTy);
1399 Type *SplitSrcTy = VectorType::getHalfElementsVectorType(SrcVTy);
1400 const T *TTI = thisT();
1401 // If both types need to be split then the split is free.
1402 InstructionCost SplitCost =
1403 (!SplitSrc || !SplitDst) ? TTI->getVectorSplitCost() : 0;
1404 return SplitCost +
1405 (2 * TTI->getCastInstrCost(Opcode, SplitDstTy, SplitSrcTy, CCH,
1406 CostKind, I));
1407 }
1408
1409 // Scalarization cost is Invalid, can't assume any num elements.
1410 if (isa<ScalableVectorType>(DstVTy))
1412
1413 // In other cases where the source or destination are illegal, assume
1414 // the operation will get scalarized.
1415 unsigned Num = cast<FixedVectorType>(DstVTy)->getNumElements();
1416 InstructionCost Cost = thisT()->getCastInstrCost(
1417 Opcode, Dst->getScalarType(), Src->getScalarType(), CCH, CostKind, I);
1418
1419 // Return the cost of multiple scalar invocation plus the cost of
1420 // inserting and extracting the values.
1421 return getScalarizationOverhead(DstVTy, /*Insert*/ true, /*Extract*/ true,
1422 CostKind) +
1423 Num * Cost;
1424 }
1425
1426 // We already handled vector-to-vector and scalar-to-scalar conversions.
1427 // This
1428 // is where we handle bitcast between vectors and scalars. We need to assume
1429 // that the conversion is scalarized in one way or another.
1430 if (Opcode == Instruction::BitCast) {
1431 // Illegal bitcasts are done by storing and loading from a stack slot.
1432 return (SrcVTy ? getScalarizationOverhead(SrcVTy, /*Insert*/ false,
1433 /*Extract*/ true, CostKind)
1434 : 0) +
1435 (DstVTy ? getScalarizationOverhead(DstVTy, /*Insert*/ true,
1436 /*Extract*/ false, CostKind)
1437 : 0);
1438 }
1439
1440 llvm_unreachable("Unhandled cast");
1441 }
1442
1444 getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
1445 unsigned Index,
1446 TTI::TargetCostKind CostKind) const override {
1447 return thisT()->getVectorInstrCost(Instruction::ExtractElement, VecTy,
1448 CostKind, Index, nullptr, nullptr) +
1449 thisT()->getCastInstrCost(Opcode, Dst, VecTy->getElementType(),
1450 TTI::CastContextHint::None, CostKind);
1451 }
1452
1454 getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind,
1455 const Instruction *I = nullptr) const override {
1456 return BaseT::getCFInstrCost(Opcode, CostKind, I);
1457 }
1458
1460 unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred,
1461 TTI::TargetCostKind CostKind,
1464 const Instruction *I = nullptr) const override {
1465 const TargetLoweringBase *TLI = getTLI();
1466 int ISD = TLI->InstructionOpcodeToISD(Opcode);
1467 assert(ISD && "Invalid opcode");
1468
1469 if (getTLI()->getValueType(DL, ValTy, true) == MVT::Other)
1470 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
1471 Op1Info, Op2Info, I);
1472
1473 // Selects on vectors are actually vector selects.
1474 if (ISD == ISD::SELECT) {
1475 assert(CondTy && "CondTy must exist");
1476 if (CondTy->isVectorTy())
1477 ISD = ISD::VSELECT;
1478 }
1479 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
1480
1481 if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
1482 !TLI->isOperationExpand(ISD, LT.second)) {
1483 // The operation is legal. Assume it costs 1. Multiply
1484 // by the type-legalization overhead.
1485 return LT.first * 1;
1486 }
1487
1488 // Otherwise, assume that the cast is scalarized.
1489 // TODO: If one of the types get legalized by splitting, handle this
1490 // similarly to what getCastInstrCost() does.
1491 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
1492 if (isa<ScalableVectorType>(ValTy))
1494
1495 unsigned Num = cast<FixedVectorType>(ValVTy)->getNumElements();
1496 InstructionCost Cost = thisT()->getCmpSelInstrCost(
1497 Opcode, ValVTy->getScalarType(), CondTy->getScalarType(), VecPred,
1498 CostKind, Op1Info, Op2Info, I);
1499
1500 // Return the cost of multiple scalar invocation plus the cost of
1501 // inserting and extracting the values.
1502 return getScalarizationOverhead(ValVTy, /*Insert*/ true,
1503 /*Extract*/ false, CostKind) +
1504 Num * Cost;
1505 }
1506
1507 // Unknown scalar opcode.
1508 return 1;
1509 }
1510
1512 getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind,
1513 unsigned Index, const Value *Op0, const Value *Op1,
1515 TTI::VectorInstrContext::None) const override {
1516 return getRegUsageForType(Val->getScalarType());
1517 }
1518
1519 /// \param ScalarUserAndIdx encodes the information about extracts from a
1520 /// vector with 'Scalar' being the value being extracted,'User' being the user
1521 /// of the extract(nullptr if user is not known before vectorization) and
1522 /// 'Idx' being the extract lane.
1524 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index,
1525 Value *Scalar,
1526 ArrayRef<std::tuple<Value *, User *, int>> ScalarUserAndIdx,
1528 TTI::VectorInstrContext::None) const override {
1529 return getVectorInstrCost(Opcode, Val, CostKind, Index, nullptr, nullptr,
1530 VIC);
1531 }
1532
1535 TTI::TargetCostKind CostKind, unsigned Index,
1537 TTI::VectorInstrContext::None) const override {
1538 Value *Op0 = nullptr;
1539 Value *Op1 = nullptr;
1540 if (auto *IE = dyn_cast<InsertElementInst>(&I)) {
1541 Op0 = IE->getOperand(0);
1542 Op1 = IE->getOperand(1);
1543 }
1544 // If VIC is None, compute it from the instruction
1547 return thisT()->getVectorInstrCost(I.getOpcode(), Val, CostKind, Index, Op0,
1548 Op1, VIC);
1549 }
1550
1553 TTI::TargetCostKind CostKind,
1554 unsigned Index) const override {
1555 unsigned NewIndex = -1;
1556 if (auto *FVTy = dyn_cast<FixedVectorType>(Val)) {
1557 assert(Index < FVTy->getNumElements() &&
1558 "Unexpected index from end of vector");
1559 NewIndex = FVTy->getNumElements() - 1 - Index;
1560 }
1561 return thisT()->getVectorInstrCost(Opcode, Val, CostKind, NewIndex, nullptr,
1562 nullptr);
1563 }
1564
1566 getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF,
1567 const APInt &DemandedDstElts,
1568 TTI::TargetCostKind CostKind) const override {
1569 assert(DemandedDstElts.getBitWidth() == (unsigned)VF * ReplicationFactor &&
1570 "Unexpected size of DemandedDstElts.");
1571
1573
1574 auto *SrcVT = FixedVectorType::get(EltTy, VF);
1575 auto *ReplicatedVT = FixedVectorType::get(EltTy, VF * ReplicationFactor);
1576
1577 // The Mask shuffling cost is extract all the elements of the Mask
1578 // and insert each of them Factor times into the wide vector:
1579 //
1580 // E.g. an interleaved group with factor 3:
1581 // %mask = icmp ult <8 x i32> %vec1, %vec2
1582 // %interleaved.mask = shufflevector <8 x i1> %mask, <8 x i1> undef,
1583 // <24 x i32> <0,0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7>
1584 // The cost is estimated as extract all mask elements from the <8xi1> mask
1585 // vector and insert them factor times into the <24xi1> shuffled mask
1586 // vector.
1587 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedDstElts, VF);
1588 Cost += thisT()->getScalarizationOverhead(SrcVT, DemandedSrcElts,
1589 /*Insert*/ false,
1590 /*Extract*/ true, CostKind);
1591 Cost += thisT()->getScalarizationOverhead(ReplicatedVT, DemandedDstElts,
1592 /*Insert*/ true,
1593 /*Extract*/ false, CostKind);
1594
1595 return Cost;
1596 }
1597
1599 TTI::TargetCostKind CostKind,
1600 TTI::OperandValueInfo OffsetInfo,
1602 const Instruction *CtxI) const override {
1603 const DataLayout &DL = this->getDataLayout();
1605 Type *IntValTy = IntTy->getWithNewBitWidth(
1606 DL.getTypeSizeInBits(Val->getScalarType()).getFixedValue());
1607
1608 // bitinsert: (Base & ~(Mask << Offset)) | (zext(Val) << Offset)
1610 Cost += thisT()->getArithmeticInstrCost(Instruction::And, IntTy, CostKind);
1611 Cost += thisT()->getArithmeticInstrCost(Instruction::Shl, IntTy, CostKind,
1612 {}, OffsetInfo);
1613 Cost += thisT()->getArithmeticInstrCost(Instruction::Or, IntTy, CostKind);
1614 Cost += getBitOffsetCastOverhead(IntTy, CostKind, OffsetInfo);
1615 if (IntValTy != IntTy)
1616 Cost += thisT()->getCastInstrCost(Instruction::ZExt, IntTy, IntValTy,
1617 TTI::CastContextHint::None, CostKind);
1618
1619 // A variable offset shifts and inverts the mask at run time.
1620 if (!OffsetInfo.isConstant()) {
1621 Cost += thisT()->getArithmeticInstrCost(Instruction::Shl, IntTy, CostKind,
1622 {}, OffsetInfo);
1623 Cost +=
1624 thisT()->getArithmeticInstrCost(Instruction::Xor, IntTy, CostKind);
1625 }
1626 return Cost;
1627 }
1628
1630 TTI::TargetCostKind CostKind,
1631 TTI::OperandValueInfo OffsetInfo,
1633 const Instruction *CtxI) const override {
1634 const DataLayout &DL = this->getDataLayout();
1635 Type *IntTy = Type::getIntFromByteType(Src);
1636 Type *IntDstTy = IntTy->getWithNewBitWidth(
1637 DL.getTypeSizeInBits(Dst->getScalarType()).getFixedValue());
1638
1639 // bitextract: trunc(Src >> Offset)
1641 Cost += thisT()->getArithmeticInstrCost(Instruction::LShr, IntTy, CostKind,
1642 {}, OffsetInfo);
1643 Cost += getBitOffsetCastOverhead(IntTy, CostKind, OffsetInfo);
1644 if (IntDstTy != IntTy)
1645 Cost += thisT()->getCastInstrCost(Instruction::Trunc, IntDstTy, IntTy,
1646 TTI::CastContextHint::None, CostKind);
1647 return Cost;
1648 }
1649
1651 unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace,
1652 TTI::TargetCostKind CostKind,
1654 const Instruction *I = nullptr) const override {
1655 assert(!Src->isVoidTy() && "Invalid type");
1656 // Assume types, such as structs, are expensive.
1657 if (getTLI()->getValueType(DL, Src, true) == MVT::Other)
1658 return 4;
1659 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Src);
1660
1661 // FIXME: Arbitrary cost
1662 if (Opcode == Instruction::Load && CostKind == TTI::TCK_Latency)
1663 return 4;
1664
1665 // Assuming that all loads of legal types cost 1.
1666 InstructionCost Cost = LT.first;
1667 if (CostKind != TTI::TCK_RecipThroughput)
1668 return Cost;
1669
1670 const DataLayout &DL = this->getDataLayout();
1671 if (Src->isVectorTy() &&
1672 // In practice it's not currently possible to have a change in lane
1673 // length for extending loads or truncating stores so both types should
1674 // have the same scalable property.
1675 TypeSize::isKnownLT(DL.getTypeStoreSizeInBits(Src),
1676 LT.second.getSizeInBits())) {
1677 // This is a vector load that legalizes to a larger type than the vector
1678 // itself. Unless the corresponding extending load or truncating store is
1679 // legal, then this will scalarize.
1681 EVT MemVT = getTLI()->getValueType(DL, Src);
1682 if (Opcode == Instruction::Store)
1683 LA = getTLI()->getTruncStoreAction(LT.second, MemVT, Alignment,
1684 AddressSpace);
1685 else
1686 LA = getTLI()->getLoadAction(LT.second, MemVT, Alignment, AddressSpace,
1687 ISD::EXTLOAD, false);
1688
1689 if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
1690 // This is a vector load/store for some illegal type that is scalarized.
1691 // We must account for the cost of building or decomposing the vector.
1693 cast<VectorType>(Src), Opcode != Instruction::Store,
1694 Opcode == Instruction::Store, CostKind);
1695 }
1696 }
1697
1698 return Cost;
1699 }
1700
1702 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1703 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1704 bool UseMaskForCond = false, bool UseMaskForGaps = false) const override {
1705
1706 // We cannot scalarize scalable vectors, so return Invalid.
1707 if (isa<ScalableVectorType>(VecTy))
1709
1710 auto *VT = cast<FixedVectorType>(VecTy);
1711
1712 unsigned NumElts = VT->getNumElements();
1713 assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
1714
1715 unsigned NumSubElts = NumElts / Factor;
1716 auto *SubVT = FixedVectorType::get(VT->getElementType(), NumSubElts);
1717
1718 // Firstly, the cost of load/store operation.
1720 if (UseMaskForCond || UseMaskForGaps) {
1721 unsigned IID = Opcode == Instruction::Load ? Intrinsic::masked_load
1722 : Intrinsic::masked_store;
1723 Cost = thisT()->getMemIntrinsicInstrCost(
1724 MemIntrinsicCostAttributes(IID, VecTy, Alignment, AddressSpace),
1725 CostKind);
1726 } else
1727 Cost = thisT()->getMemoryOpCost(Opcode, VecTy, Alignment, AddressSpace,
1728 CostKind);
1729
1730 // Legalize the vector type, and get the legalized and unlegalized type
1731 // sizes.
1732 MVT VecTyLT = getTypeLegalizationCost(VecTy).second;
1733 unsigned VecTySize = thisT()->getDataLayout().getTypeStoreSize(VecTy);
1734 unsigned VecTyLTSize = VecTyLT.getStoreSize();
1735
1736 // Scale the cost of the memory operation by the fraction of legalized
1737 // instructions that will actually be used. We shouldn't account for the
1738 // cost of dead instructions since they will be removed.
1739 //
1740 // E.g., An interleaved load of factor 8:
1741 // %vec = load <16 x i64>, <16 x i64>* %ptr
1742 // %v0 = shufflevector %vec, undef, <0, 8>
1743 //
1744 // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
1745 // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
1746 // type). The other loads are unused.
1747 //
1748 // TODO: Note that legalization can turn masked loads/stores into unmasked
1749 // (legalized) loads/stores. This can be reflected in the cost.
1750 if (Cost.isValid() && VecTySize > VecTyLTSize) {
1751 // The number of loads of a legal type it will take to represent a load
1752 // of the unlegalized vector type.
1753 unsigned NumLegalInsts = divideCeil(VecTySize, VecTyLTSize);
1754
1755 // The number of elements of the unlegalized type that correspond to a
1756 // single legal instruction.
1757 unsigned NumEltsPerLegalInst = divideCeil(NumElts, NumLegalInsts);
1758
1759 // Determine which legal instructions will be used.
1760 BitVector UsedInsts(NumLegalInsts, false);
1761 for (unsigned Index : Indices)
1762 for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
1763 UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
1764
1765 // Scale the cost of the load by the fraction of legal instructions that
1766 // will be used.
1767 Cost = divideCeil(UsedInsts.count() * Cost.getValue(), NumLegalInsts);
1768 }
1769
1770 // Then plus the cost of interleave operation.
1771 assert(Indices.size() <= Factor &&
1772 "Interleaved memory op has too many members");
1773
1774 const APInt DemandedAllSubElts = APInt::getAllOnes(NumSubElts);
1775 const APInt DemandedAllResultElts = APInt::getAllOnes(NumElts);
1776
1777 APInt DemandedLoadStoreElts = APInt::getZero(NumElts);
1778 for (unsigned Index : Indices) {
1779 assert(Index < Factor && "Invalid index for interleaved memory op");
1780 for (unsigned Elm = 0; Elm < NumSubElts; Elm++)
1781 DemandedLoadStoreElts.setBit(Index + Elm * Factor);
1782 }
1783
1784 if (Opcode == Instruction::Load) {
1785 // The interleave cost is similar to extract sub vectors' elements
1786 // from the wide vector, and insert them into sub vectors.
1787 //
1788 // E.g. An interleaved load of factor 2 (with one member of index 0):
1789 // %vec = load <8 x i32>, <8 x i32>* %ptr
1790 // %v0 = shuffle %vec, undef, <0, 2, 4, 6> ; Index 0
1791 // The cost is estimated as extract elements at 0, 2, 4, 6 from the
1792 // <8 x i32> vector and insert them into a <4 x i32> vector.
1793 InstructionCost InsSubCost = thisT()->getScalarizationOverhead(
1794 SubVT, DemandedAllSubElts,
1795 /*Insert*/ true, /*Extract*/ false, CostKind);
1796 Cost += Indices.size() * InsSubCost;
1797 Cost += thisT()->getScalarizationOverhead(VT, DemandedLoadStoreElts,
1798 /*Insert*/ false,
1799 /*Extract*/ true, CostKind);
1800 } else {
1801 // The interleave cost is extract elements from sub vectors, and
1802 // insert them into the wide vector.
1803 //
1804 // E.g. An interleaved store of factor 3 with 2 members at indices 0,1:
1805 // (using VF=4):
1806 // %v0_v1 = shuffle %v0, %v1, <0,4,undef,1,5,undef,2,6,undef,3,7,undef>
1807 // %gaps.mask = <true, true, false, true, true, false,
1808 // true, true, false, true, true, false>
1809 // call llvm.masked.store <12 x i32> %v0_v1, <12 x i32>* %ptr,
1810 // i32 Align, <12 x i1> %gaps.mask
1811 // The cost is estimated as extract all elements (of actual members,
1812 // excluding gaps) from both <4 x i32> vectors and insert into the <12 x
1813 // i32> vector.
1814 InstructionCost ExtSubCost = thisT()->getScalarizationOverhead(
1815 SubVT, DemandedAllSubElts,
1816 /*Insert*/ false, /*Extract*/ true, CostKind);
1817 Cost += ExtSubCost * Indices.size();
1818 Cost += thisT()->getScalarizationOverhead(VT, DemandedLoadStoreElts,
1819 /*Insert*/ true,
1820 /*Extract*/ false, CostKind);
1821 }
1822
1823 if (!UseMaskForCond)
1824 return Cost;
1825
1826 Type *I8Type = Type::getInt8Ty(VT->getContext());
1827
1828 Cost += thisT()->getReplicationShuffleCost(
1829 I8Type, Factor, NumSubElts,
1830 UseMaskForGaps ? DemandedLoadStoreElts : DemandedAllResultElts,
1831 CostKind);
1832
1833 // The Gaps mask is invariant and created outside the loop, therefore the
1834 // cost of creating it is not accounted for here. However if we have both
1835 // a MaskForGaps and some other mask that guards the execution of the
1836 // memory access, we need to account for the cost of And-ing the two masks
1837 // inside the loop.
1838 if (UseMaskForGaps) {
1839 auto *MaskVT = FixedVectorType::get(I8Type, NumElts);
1840 Cost += thisT()->getArithmeticInstrCost(BinaryOperator::And, MaskVT,
1841 CostKind);
1842 }
1843
1844 return Cost;
1845 }
1846
1847 /// Get intrinsic cost based on arguments.
1850 TTI::TargetCostKind CostKind) const override {
1851 // Check for generically free intrinsics.
1852 if (BaseT::getIntrinsicInstrCost(ICA, CostKind) == 0)
1853 return 0;
1854
1855 // Assume that target intrinsics are cheap.
1856 Intrinsic::ID IID = ICA.getID();
1859
1860 // VP Intrinsics should have the same cost as their non-vp counterpart.
1861 // TODO: Adjust the cost to make the vp intrinsic cheaper than its non-vp
1862 // counterpart when the vector length argument is smaller than the maximum
1863 // vector length.
1864 // TODO: Support other kinds of VPIntrinsics
1865 if (VPIntrinsic::isVPIntrinsic(ICA.getID())) {
1866 std::optional<unsigned> FOp =
1868 if (FOp) {
1869 if (ICA.getID() == Intrinsic::vp_load) {
1870 Align Alignment;
1871 if (auto *VPI = dyn_cast_or_null<VPIntrinsic>(ICA.getInst()))
1872 Alignment = VPI->getPointerAlignment().valueOrOne();
1873 unsigned AS = 0;
1874 if (ICA.getArgTypes().size() > 1)
1875 if (auto *PtrTy = dyn_cast<PointerType>(ICA.getArgTypes()[0]))
1876 AS = PtrTy->getAddressSpace();
1877 return thisT()->getMemoryOpCost(*FOp, ICA.getReturnType(), Alignment,
1878 AS, CostKind);
1879 }
1880 if (ICA.getID() == Intrinsic::vp_store) {
1881 Align Alignment;
1882 if (auto *VPI = dyn_cast_or_null<VPIntrinsic>(ICA.getInst()))
1883 Alignment = VPI->getPointerAlignment().valueOrOne();
1884 unsigned AS = 0;
1885 if (ICA.getArgTypes().size() >= 2)
1886 if (auto *PtrTy = dyn_cast<PointerType>(ICA.getArgTypes()[1]))
1887 AS = PtrTy->getAddressSpace();
1888 return thisT()->getMemoryOpCost(*FOp, ICA.getArgTypes()[0], Alignment,
1889 AS, CostKind);
1890 }
1891 if (ICA.getID() == Intrinsic::vp_udiv ||
1892 ICA.getID() == Intrinsic::vp_sdiv ||
1893 ICA.getID() == Intrinsic::vp_urem ||
1894 ICA.getID() == Intrinsic::vp_srem) {
1895 return thisT()->getArithmeticInstrCost(*FOp, ICA.getReturnType(),
1896 CostKind);
1897 }
1898 }
1899 if (ICA.getID() == Intrinsic::vp_load_ff) {
1900 Type *RetTy = ICA.getReturnType();
1901 Type *DataTy = cast<StructType>(RetTy)->getElementType(0);
1902 Align Alignment;
1903 if (auto *VPI = dyn_cast_or_null<VPIntrinsic>(ICA.getInst()))
1904 Alignment = VPI->getPointerAlignment().valueOrOne();
1905 return thisT()->getMemIntrinsicInstrCost(
1906 MemIntrinsicCostAttributes(ICA.getID(), DataTy, Alignment),
1907 CostKind);
1908 }
1909 if (ICA.getID() == Intrinsic::vp_scatter) {
1910 if (ICA.isTypeBasedOnly()) {
1911 IntrinsicCostAttributes MaskedScatter(
1914 ICA.getFlags());
1915 return getTypeBasedIntrinsicInstrCost(MaskedScatter, CostKind);
1916 }
1917 Align Alignment;
1918 if (auto *VPI = dyn_cast_or_null<VPIntrinsic>(ICA.getInst()))
1919 Alignment = VPI->getPointerAlignment().valueOrOne();
1920 bool VarMask = isa<Constant>(ICA.getArgs()[2]);
1921 return thisT()->getMemIntrinsicInstrCost(
1922 MemIntrinsicCostAttributes(Intrinsic::vp_scatter,
1923 ICA.getArgTypes()[0], ICA.getArgs()[1],
1924 VarMask, Alignment, nullptr),
1925 CostKind);
1926 }
1927 if (ICA.getID() == Intrinsic::vp_gather) {
1928 if (ICA.isTypeBasedOnly()) {
1929 IntrinsicCostAttributes MaskedGather(
1932 ICA.getFlags());
1933 return getTypeBasedIntrinsicInstrCost(MaskedGather, CostKind);
1934 }
1935 Align Alignment;
1936 if (auto *VPI = dyn_cast_or_null<VPIntrinsic>(ICA.getInst()))
1937 Alignment = VPI->getPointerAlignment().valueOrOne();
1938 bool VarMask = isa<Constant>(ICA.getArgs()[1]);
1939 return thisT()->getMemIntrinsicInstrCost(
1940 MemIntrinsicCostAttributes(Intrinsic::vp_gather,
1941 ICA.getReturnType(), ICA.getArgs()[0],
1942 VarMask, Alignment, nullptr),
1943 CostKind);
1944 }
1945
1946 if (ICA.getID() == Intrinsic::vp_merge) {
1947 TTI::OperandValueInfo OpInfoX, OpInfoY;
1948 if (!ICA.isTypeBasedOnly()) {
1949 OpInfoX = TTI::getOperandInfo(ICA.getArgs()[0]);
1950 OpInfoY = TTI::getOperandInfo(ICA.getArgs()[1]);
1951 }
1952 return getCmpSelInstrCost(
1953 Instruction::Select, ICA.getReturnType(), ICA.getArgTypes()[0],
1954 CmpInst::BAD_ICMP_PREDICATE, CostKind, OpInfoX, OpInfoY);
1955 }
1956
1957 std::optional<Intrinsic::ID> FID =
1959
1960 // Not functionally equivalent but close enough for cost modelling.
1961 if (ICA.getID() == Intrinsic::experimental_vp_reverse)
1962 FID = Intrinsic::vector_reverse;
1963
1964 if (FID) {
1965 // Non-vp version will have same arg types except mask and vector
1966 // length.
1967 assert(ICA.getArgTypes().size() >= 2 &&
1968 "Expected VPIntrinsic to have Mask and Vector Length args and "
1969 "types");
1970
1971 ArrayRef<const Value *> NewArgs = ArrayRef(ICA.getArgs());
1972 if (!ICA.isTypeBasedOnly())
1973 NewArgs = NewArgs.drop_back(2);
1975
1976 // VPReduction intrinsics have a start value argument that their non-vp
1977 // counterparts do not have, except for the fadd and fmul non-vp
1978 // counterpart.
1980 *FID != Intrinsic::vector_reduce_fadd &&
1981 *FID != Intrinsic::vector_reduce_fmul) {
1982 if (!ICA.isTypeBasedOnly())
1983 NewArgs = NewArgs.drop_front();
1984 NewTys = NewTys.drop_front();
1985 }
1986
1987 IntrinsicCostAttributes NewICA(*FID, ICA.getReturnType(), NewArgs,
1988 NewTys, ICA.getFlags());
1989 return thisT()->getIntrinsicInstrCost(NewICA, CostKind);
1990 }
1991 }
1992
1993 if (ICA.isTypeBasedOnly())
1994 return getTypeBasedIntrinsicInstrCost(ICA, CostKind);
1995
1996 Type *RetTy = ICA.getReturnType();
1997
1998 ElementCount RetVF = isVectorizedTy(RetTy) ? getVectorizedTypeVF(RetTy)
2000
2001 const IntrinsicInst *I = ICA.getInst();
2002 const SmallVectorImpl<const Value *> &Args = ICA.getArgs();
2003 FastMathFlags FMF = ICA.getFlags();
2004 switch (IID) {
2005 default:
2006 break;
2007
2008 case Intrinsic::powi:
2009 if (auto *RHSC = dyn_cast<ConstantInt>(Args[1])) {
2010 bool ShouldOptForSize = I->getParent()->getParent()->hasOptSize();
2011 if (getTLI()->isBeneficialToExpandPowI(RHSC->getSExtValue(),
2012 ShouldOptForSize)) {
2013 // The cost is modeled on the expansion performed by ExpandPowI in
2014 // SelectionDAGBuilder.
2015 APInt Exponent = RHSC->getValue().abs();
2016 unsigned ActiveBits = Exponent.getActiveBits();
2017 unsigned PopCount = Exponent.popcount();
2018 InstructionCost Cost = (ActiveBits + PopCount - 2) *
2019 thisT()->getArithmeticInstrCost(
2020 Instruction::FMul, RetTy, CostKind);
2021 if (RHSC->isNegative())
2022 Cost += thisT()->getArithmeticInstrCost(Instruction::FDiv, RetTy,
2023 CostKind);
2024 return Cost;
2025 }
2026 }
2027 break;
2028 case Intrinsic::cttz:
2029 // FIXME: If necessary, this should go in target-specific overrides.
2030 if (RetVF.isScalar() && getTLI()->isCheapToSpeculateCttz(RetTy))
2032 break;
2033
2034 case Intrinsic::ctlz:
2035 // FIXME: If necessary, this should go in target-specific overrides.
2036 if (RetVF.isScalar() && getTLI()->isCheapToSpeculateCtlz(RetTy))
2038 break;
2039
2040 case Intrinsic::memcpy:
2041 return thisT()->getMemcpyCost(ICA.getInst());
2042
2043 case Intrinsic::masked_scatter: {
2044 const Value *Mask = Args[2];
2045 bool VarMask = !isa<Constant>(Mask);
2046 Align Alignment = I->getParamAlign(1).valueOrOne();
2047 return thisT()->getMemIntrinsicInstrCost(
2048 MemIntrinsicCostAttributes(Intrinsic::masked_scatter,
2049 ICA.getArgTypes()[0], Args[1], VarMask,
2050 Alignment, I),
2051 CostKind);
2052 }
2053 case Intrinsic::masked_gather: {
2054 const Value *Mask = Args[1];
2055 bool VarMask = !isa<Constant>(Mask);
2056 Align Alignment = I->getParamAlign(0).valueOrOne();
2057 return thisT()->getMemIntrinsicInstrCost(
2058 MemIntrinsicCostAttributes(Intrinsic::masked_gather, RetTy, Args[0],
2059 VarMask, Alignment, I),
2060 CostKind);
2061 }
2062 case Intrinsic::masked_compressstore: {
2063 const Value *Data = Args[0];
2064 const Value *Mask = Args[2];
2065 Align Alignment = I->getParamAlign(1).valueOrOne();
2066 return thisT()->getMemIntrinsicInstrCost(
2067 MemIntrinsicCostAttributes(IID, Data->getType(), !isa<Constant>(Mask),
2068 Alignment, I),
2069 CostKind);
2070 }
2071 case Intrinsic::masked_expandload: {
2072 const Value *Mask = Args[1];
2073 Align Alignment = I->getParamAlign(0).valueOrOne();
2074 return thisT()->getMemIntrinsicInstrCost(
2075 MemIntrinsicCostAttributes(IID, RetTy, !isa<Constant>(Mask),
2076 Alignment, I),
2077 CostKind);
2078 }
2079 case Intrinsic::experimental_vp_strided_store: {
2080 const Value *Data = Args[0];
2081 const Value *Ptr = Args[1];
2082 const Value *Stride = Args[2];
2083 const Value *Mask = Args[3];
2084 const Value *EVL = Args[4];
2085 bool VarMask = !isa<Constant>(Mask) || !isa<Constant>(EVL);
2086 Type *EltTy = cast<VectorType>(Data->getType())->getElementType();
2087 Align Alignment =
2088 I->getParamAlign(1).value_or(thisT()->DL.getABITypeAlign(EltTy));
2089 return thisT()->getMemIntrinsicInstrCost(
2090 MemIntrinsicCostAttributes(IID, Data->getType(), Ptr, VarMask,
2091 Alignment, I, Stride),
2092 CostKind);
2093 }
2094 case Intrinsic::experimental_vp_strided_load: {
2095 const Value *Ptr = Args[0];
2096 const Value *Stride = Args[1];
2097 const Value *Mask = Args[2];
2098 const Value *EVL = Args[3];
2099 bool VarMask = !isa<Constant>(Mask) || !isa<Constant>(EVL);
2100 Type *EltTy = cast<VectorType>(RetTy)->getElementType();
2101 Align Alignment =
2102 I->getParamAlign(0).value_or(thisT()->DL.getABITypeAlign(EltTy));
2103 return thisT()->getMemIntrinsicInstrCost(
2104 MemIntrinsicCostAttributes(IID, RetTy, Ptr, VarMask, Alignment, I,
2105 Stride),
2106 CostKind);
2107 }
2108 case Intrinsic::stepvector: {
2109 if (isa<ScalableVectorType>(RetTy))
2110 return BaseT::getIntrinsicInstrCost(ICA, CostKind);
2111 // The cost of materialising a constant integer vector.
2113 }
2114 case Intrinsic::vector_extract: {
2115 // FIXME: Handle case where a scalable vector is extracted from a scalable
2116 // vector
2117 if (isa<ScalableVectorType>(RetTy))
2118 return BaseT::getIntrinsicInstrCost(ICA, CostKind);
2119 unsigned Index = cast<ConstantInt>(Args[1])->getZExtValue();
2120 return thisT()->getShuffleCost(
2122 cast<VectorType>(Args[0]->getType()), CostKind, {}, Index,
2123 cast<VectorType>(RetTy));
2124 }
2125 case Intrinsic::vector_insert: {
2126 // FIXME: Handle case where a scalable vector is inserted into a scalable
2127 // vector
2128 if (isa<ScalableVectorType>(Args[1]->getType()))
2129 return BaseT::getIntrinsicInstrCost(ICA, CostKind);
2130 unsigned Index = cast<ConstantInt>(Args[2])->getZExtValue();
2131 return thisT()->getShuffleCost(
2133 cast<VectorType>(Args[0]->getType()), CostKind, {}, Index,
2134 cast<VectorType>(Args[1]->getType()));
2135 }
2136 case Intrinsic::vector_splice_left:
2137 case Intrinsic::vector_splice_right: {
2138 auto *COffset = dyn_cast<ConstantInt>(Args[2]);
2139 if (!COffset)
2140 break;
2141 unsigned Index = COffset->getZExtValue();
2142 return thisT()->getShuffleCost(
2144 cast<VectorType>(Args[0]->getType()), CostKind, {},
2145 IID == Intrinsic::vector_splice_left ? Index : -Index,
2146 cast<VectorType>(RetTy));
2147 }
2148 case Intrinsic::vector_reduce_add:
2149 case Intrinsic::vector_reduce_mul:
2150 case Intrinsic::vector_reduce_and:
2151 case Intrinsic::vector_reduce_or:
2152 case Intrinsic::vector_reduce_xor:
2153 case Intrinsic::vector_reduce_smax:
2154 case Intrinsic::vector_reduce_smin:
2155 case Intrinsic::vector_reduce_fmax:
2156 case Intrinsic::vector_reduce_fmin:
2157 case Intrinsic::vector_reduce_fmaximum:
2158 case Intrinsic::vector_reduce_fminimum:
2159 case Intrinsic::vector_reduce_fmaximumnum:
2160 case Intrinsic::vector_reduce_fminimumnum:
2161 case Intrinsic::vector_reduce_umax:
2162 case Intrinsic::vector_reduce_umin: {
2163 IntrinsicCostAttributes Attrs(IID, RetTy, Args[0]->getType(), FMF, I, 1);
2164 return getTypeBasedIntrinsicInstrCost(Attrs, CostKind);
2165 }
2166 case Intrinsic::vector_reduce_fadd:
2167 case Intrinsic::vector_reduce_fmul: {
2169 IID, RetTy, {Args[0]->getType(), Args[1]->getType()}, FMF, I, 1);
2170 return getTypeBasedIntrinsicInstrCost(Attrs, CostKind);
2171 }
2172 case Intrinsic::fshl:
2173 case Intrinsic::fshr: {
2174 const Value *X = Args[0];
2175 const Value *Y = Args[1];
2176 const Value *Z = Args[2];
2179 const TTI::OperandValueInfo OpInfoZ = TTI::getOperandInfo(Z);
2180
2181 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
2182 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
2184 Cost +=
2185 thisT()->getArithmeticInstrCost(BinaryOperator::Or, RetTy, CostKind);
2186 Cost += thisT()->getArithmeticInstrCost(
2187 BinaryOperator::Shl, RetTy, CostKind, OpInfoX,
2188 {OpInfoZ.Kind, TTI::OP_None});
2189 Cost += thisT()->getArithmeticInstrCost(
2190 BinaryOperator::LShr, RetTy, CostKind, OpInfoY,
2191 {OpInfoZ.Kind, TTI::OP_None});
2192
2193 if (!OpInfoZ.isConstant()) {
2194 Cost += thisT()->getArithmeticInstrCost(BinaryOperator::Sub, RetTy,
2195 CostKind);
2196 // Non-constant shift amounts requires a modulo. If the typesize is a
2197 // power-2 then this will be converted to an and, otherwise it will use
2198 // a urem.
2199 Cost += thisT()->getArithmeticInstrCost(
2200 isPowerOf2_32(RetTy->getScalarSizeInBits()) ? BinaryOperator::And
2201 : BinaryOperator::URem,
2202 RetTy, CostKind, OpInfoZ,
2203 {TTI::OK_UniformConstantValue, TTI::OP_None});
2204 // For non-rotates (X != Y) we must add shift-by-zero handling costs.
2205 if (X != Y) {
2206 Type *CondTy = RetTy->getWithNewBitWidth(1);
2207 Cost += thisT()->getCmpSelInstrCost(
2208 BinaryOperator::ICmp, RetTy, CondTy, CmpInst::ICMP_EQ, CostKind);
2209 Cost +=
2210 thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
2211 CmpInst::ICMP_EQ, CostKind);
2212 }
2213 }
2214 return Cost;
2215 }
2216 case Intrinsic::experimental_cttz_elts:
2217 case Intrinsic::get_active_lane_mask:
2218 case Intrinsic::mask_beforefirst:
2219 case Intrinsic::experimental_vector_match:
2220 case Intrinsic::experimental_vector_histogram_add:
2221 case Intrinsic::experimental_vector_histogram_uadd_sat:
2222 case Intrinsic::experimental_vector_histogram_umax:
2223 case Intrinsic::experimental_vector_histogram_umin:
2224 case Intrinsic::masked_udiv:
2225 case Intrinsic::masked_sdiv:
2226 case Intrinsic::masked_urem:
2227 case Intrinsic::masked_srem:
2228 return thisT()->getTypeBasedIntrinsicInstrCost(ICA, CostKind);
2229 case Intrinsic::modf:
2230 case Intrinsic::sincos:
2231 case Intrinsic::sincospi: {
2232 std::optional<unsigned> CallRetElementIndex;
2233 // The first element of the modf result is returned by value in the
2234 // libcall.
2235 if (ICA.getID() == Intrinsic::modf)
2236 CallRetElementIndex = 0;
2237
2238 if (auto Cost = getMultipleResultIntrinsicVectorLibCallCost(
2239 ICA, CostKind, CallRetElementIndex))
2240 return *Cost;
2241 // Otherwise, fallback to default scalarization cost.
2242 break;
2243 }
2244 case Intrinsic::loop_dependence_war_mask:
2245 case Intrinsic::loop_dependence_raw_mask: {
2246 // Compute the cost of the expanded version of these intrinsics:
2247 //
2248 // The possible expansions are...
2249 //
2250 // loop_dependence_war_mask:
2251 // diff = (addrB - addrA) / eltSize
2252 // cmp = icmp sle diff, 0
2253 // upper_bound = select cmp, -1, diff
2254 // mask = get_active_lane_mask 0, upper_bound
2255 //
2256 // loop_dependence_raw_mask:
2257 // diff = (abs(addrB - addrA)) / eltSize
2258 // cmp = icmp eq diff, 0
2259 // upper_bound = select cmp, -1, diff
2260 // mask = get_active_lane_mask 0, upper_bound
2261 //
2262 Type *AddrTy = ICA.getArgTypes()[0];
2263 bool IsReadAfterWrite = IID == Intrinsic::loop_dependence_raw_mask;
2264
2266 thisT()->getArithmeticInstrCost(Instruction::Sub, AddrTy, CostKind);
2267 if (IsReadAfterWrite) {
2268 IntrinsicCostAttributes AbsAttrs(Intrinsic::abs, AddrTy, {AddrTy}, {});
2269 Cost += thisT()->getIntrinsicInstrCost(AbsAttrs, CostKind);
2270 }
2271
2272 TTI::OperandValueInfo EltSizeOpInfo =
2273 TTI::getOperandInfo(ICA.getArgs()[2]);
2274 Cost += thisT()->getArithmeticInstrCost(Instruction::SDiv, AddrTy,
2275 CostKind, {}, EltSizeOpInfo);
2276
2277 Type *CondTy = IntegerType::getInt1Ty(RetTy->getContext());
2279 IsReadAfterWrite ? CmpInst::ICMP_EQ : CmpInst::ICMP_SLE;
2280 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, CondTy, AddrTy,
2281 Pred, CostKind);
2282 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::Select, AddrTy,
2283 CondTy, Pred, CostKind);
2284
2285 IntrinsicCostAttributes Attrs(Intrinsic::get_active_lane_mask, RetTy,
2286 {AddrTy, AddrTy}, FMF);
2287 Cost += thisT()->getIntrinsicInstrCost(Attrs, CostKind);
2288 return Cost;
2289 }
2290 }
2291
2292 // Assume that we need to scalarize this intrinsic.)
2293 // Compute the scalarization overhead based on Args for a vector
2294 // intrinsic.
2295 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
2296 if (RetVF.isVector() && !RetVF.isScalable()) {
2297 ScalarizationCost = 0;
2298 if (!RetTy->isVoidTy()) {
2299 for (Type *VectorTy : getContainedTypes(RetTy)) {
2300 ScalarizationCost += getScalarizationOverhead(
2301 cast<VectorType>(VectorTy),
2302 /*Insert=*/true, /*Extract=*/false, CostKind);
2303 }
2304 }
2305 ScalarizationCost += getOperandsScalarizationOverhead(
2306 filterConstantAndDuplicatedOperands(Args, ICA.getArgTypes()),
2307 CostKind);
2308 }
2309
2310 IntrinsicCostAttributes Attrs(IID, RetTy, ICA.getArgTypes(), FMF, I,
2311 ScalarizationCost);
2312 return thisT()->getTypeBasedIntrinsicInstrCost(Attrs, CostKind);
2313 }
2314
2315 /// Get intrinsic cost based on argument types.
2316 /// If ScalarizationCostPassed is std::numeric_limits<unsigned>::max(), the
2317 /// cost of scalarizing the arguments and the return value will be computed
2318 /// based on types.
2321 TTI::TargetCostKind CostKind) const {
2322 Intrinsic::ID IID = ICA.getID();
2323 Type *RetTy = ICA.getReturnType();
2324 const SmallVectorImpl<Type *> &Tys = ICA.getArgTypes();
2325 FastMathFlags FMF = ICA.getFlags();
2326 InstructionCost ScalarizationCostPassed = ICA.getScalarizationCost();
2327 bool SkipScalarizationCost = ICA.skipScalarizationCost();
2328
2329 VectorType *VecOpTy = nullptr;
2330 if (!Tys.empty()) {
2331 // The vector reduction operand is operand 0 except for fadd/fmul.
2332 // Their operand 0 is a scalar start value, so the vector op is operand 1.
2333 unsigned VecTyIndex = 0;
2334 if (IID == Intrinsic::vector_reduce_fadd ||
2335 IID == Intrinsic::vector_reduce_fmul)
2336 VecTyIndex = 1;
2337 assert(Tys.size() > VecTyIndex && "Unexpected IntrinsicCostAttributes");
2338 VecOpTy = dyn_cast<VectorType>(Tys[VecTyIndex]);
2339 }
2340
2341 // Library call cost - other than size, make it expensive.
2342 unsigned SingleCallCost = CostKind == TTI::TCK_CodeSize ? 1 : 10;
2343 unsigned ISD = 0;
2344 switch (IID) {
2345 default: {
2346 // Scalable vectors cannot be scalarized, so return Invalid.
2347 if (isa<ScalableVectorType>(RetTy) || any_of(Tys, [](const Type *Ty) {
2348 return isa<ScalableVectorType>(Ty);
2349 }))
2351
2352 // Assume that we need to scalarize this intrinsic.
2353 InstructionCost ScalarizationCost =
2354 SkipScalarizationCost ? ScalarizationCostPassed : 0;
2355 unsigned ScalarCalls = 1;
2356 Type *ScalarRetTy = RetTy;
2357 if (auto *RetVTy = dyn_cast<VectorType>(RetTy)) {
2358 if (!SkipScalarizationCost)
2359 ScalarizationCost = getScalarizationOverhead(
2360 RetVTy, /*Insert*/ true, /*Extract*/ false, CostKind);
2361 ScalarCalls = std::max(ScalarCalls,
2362 cast<FixedVectorType>(RetVTy)->getNumElements());
2363 ScalarRetTy = RetTy->getScalarType();
2364 }
2365 SmallVector<Type *, 4> ScalarTys;
2366 for (Type *Ty : Tys) {
2367 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
2368 if (!SkipScalarizationCost)
2369 ScalarizationCost += getScalarizationOverhead(
2370 VTy, /*Insert*/ false, /*Extract*/ true, CostKind);
2371 ScalarCalls = std::max(ScalarCalls,
2372 cast<FixedVectorType>(VTy)->getNumElements());
2373 Ty = Ty->getScalarType();
2374 }
2375 ScalarTys.push_back(Ty);
2376 }
2377 if (ScalarCalls == 1)
2378 return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
2379
2380 IntrinsicCostAttributes ScalarAttrs(IID, ScalarRetTy, ScalarTys, FMF);
2381 InstructionCost ScalarCost =
2382 thisT()->getIntrinsicInstrCost(ScalarAttrs, CostKind);
2383
2384 return ScalarCalls * ScalarCost + ScalarizationCost;
2385 }
2386 // Look for intrinsics that can be lowered directly or turned into a scalar
2387 // intrinsic call.
2388 case Intrinsic::sqrt:
2389 ISD = ISD::FSQRT;
2390 break;
2391 case Intrinsic::sin:
2392 ISD = ISD::FSIN;
2393 break;
2394 case Intrinsic::cos:
2395 ISD = ISD::FCOS;
2396 break;
2397 case Intrinsic::sincos:
2398 ISD = ISD::FSINCOS;
2399 break;
2400 case Intrinsic::sincospi:
2402 break;
2403 case Intrinsic::modf:
2404 ISD = ISD::FMODF;
2405 break;
2406 case Intrinsic::tan:
2407 ISD = ISD::FTAN;
2408 break;
2409 case Intrinsic::asin:
2410 ISD = ISD::FASIN;
2411 break;
2412 case Intrinsic::acos:
2413 ISD = ISD::FACOS;
2414 break;
2415 case Intrinsic::atan:
2416 ISD = ISD::FATAN;
2417 break;
2418 case Intrinsic::atan2:
2419 ISD = ISD::FATAN2;
2420 break;
2421 case Intrinsic::sinh:
2422 ISD = ISD::FSINH;
2423 break;
2424 case Intrinsic::cosh:
2425 ISD = ISD::FCOSH;
2426 break;
2427 case Intrinsic::tanh:
2428 ISD = ISD::FTANH;
2429 break;
2430 case Intrinsic::exp:
2431 ISD = ISD::FEXP;
2432 break;
2433 case Intrinsic::exp2:
2434 ISD = ISD::FEXP2;
2435 break;
2436 case Intrinsic::exp10:
2437 ISD = ISD::FEXP10;
2438 break;
2439 case Intrinsic::log:
2440 ISD = ISD::FLOG;
2441 break;
2442 case Intrinsic::log10:
2443 ISD = ISD::FLOG10;
2444 break;
2445 case Intrinsic::log2:
2446 ISD = ISD::FLOG2;
2447 break;
2448 case Intrinsic::ldexp:
2449 ISD = ISD::FLDEXP;
2450 break;
2451 case Intrinsic::frexp:
2452 ISD = ISD::FFREXP;
2453 break;
2454 case Intrinsic::powi:
2455 ISD = ISD::FPOWI;
2456 break;
2457 case Intrinsic::fabs:
2458 ISD = ISD::FABS;
2459 break;
2460 case Intrinsic::canonicalize:
2462 break;
2463 case Intrinsic::minnum:
2464 ISD = ISD::FMINNUM;
2465 break;
2466 case Intrinsic::maxnum:
2467 ISD = ISD::FMAXNUM;
2468 break;
2469 case Intrinsic::minimum:
2471 break;
2472 case Intrinsic::maximum:
2474 break;
2475 case Intrinsic::minimumnum:
2477 break;
2478 case Intrinsic::maximumnum:
2480 break;
2481 case Intrinsic::copysign:
2483 break;
2484 case Intrinsic::floor:
2485 ISD = ISD::FFLOOR;
2486 break;
2487 case Intrinsic::ceil:
2488 ISD = ISD::FCEIL;
2489 break;
2490 case Intrinsic::trunc:
2491 ISD = ISD::FTRUNC;
2492 break;
2493 case Intrinsic::nearbyint:
2495 break;
2496 case Intrinsic::rint:
2497 ISD = ISD::FRINT;
2498 break;
2499 case Intrinsic::lrint:
2500 ISD = ISD::LRINT;
2501 break;
2502 case Intrinsic::llrint:
2503 ISD = ISD::LLRINT;
2504 break;
2505 case Intrinsic::round:
2506 ISD = ISD::FROUND;
2507 break;
2508 case Intrinsic::roundeven:
2510 break;
2511 case Intrinsic::lround:
2512 ISD = ISD::LROUND;
2513 break;
2514 case Intrinsic::llround:
2515 ISD = ISD::LLROUND;
2516 break;
2517 case Intrinsic::pow:
2518 ISD = ISD::FPOW;
2519 break;
2520 case Intrinsic::fma:
2521 ISD = ISD::FMA;
2522 break;
2523 case Intrinsic::fmuladd:
2524 ISD = ISD::FMA;
2525 break;
2526 case Intrinsic::experimental_constrained_fmuladd:
2528 break;
2529 // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
2530 case Intrinsic::lifetime_start:
2531 case Intrinsic::lifetime_end:
2532 case Intrinsic::sideeffect:
2533 case Intrinsic::pseudoprobe:
2534 case Intrinsic::arithmetic_fence:
2535 return 0;
2536 case Intrinsic::masked_store: {
2537 Type *Ty = Tys[0];
2538 Align TyAlign = thisT()->DL.getABITypeAlign(Ty);
2539 return thisT()->getMemIntrinsicInstrCost(
2540 MemIntrinsicCostAttributes(IID, Ty, TyAlign, 0), CostKind);
2541 }
2542 case Intrinsic::masked_load: {
2543 Type *Ty = RetTy;
2544 Align TyAlign = thisT()->DL.getABITypeAlign(Ty);
2545 return thisT()->getMemIntrinsicInstrCost(
2546 MemIntrinsicCostAttributes(IID, Ty, TyAlign, 0), CostKind);
2547 }
2548 case Intrinsic::speculative_load: {
2549 const IntrinsicInst *I = ICA.getInst();
2550 Align Alignment = I ? I->getParamAlign(0).valueOrOne() : Align(1);
2551 unsigned AS = Tys[0]->getPointerAddressSpace();
2552 return thisT()->getMemIntrinsicInstrCost(
2553 MemIntrinsicCostAttributes(IID, RetTy, Alignment, AS), CostKind);
2554 }
2555 case Intrinsic::experimental_vp_strided_store: {
2556 auto *Ty = cast<VectorType>(ICA.getArgTypes()[0]);
2557 Align Alignment = thisT()->DL.getABITypeAlign(Ty->getElementType());
2558 return thisT()->getMemIntrinsicInstrCost(
2559 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr,
2560 /*VariableMask=*/true, Alignment,
2561 ICA.getInst()),
2562 CostKind);
2563 }
2564 case Intrinsic::experimental_vp_strided_load: {
2565 auto *Ty = cast<VectorType>(ICA.getReturnType());
2566 Align Alignment = thisT()->DL.getABITypeAlign(Ty->getElementType());
2567 return thisT()->getMemIntrinsicInstrCost(
2568 MemIntrinsicCostAttributes(IID, Ty, /*Ptr=*/nullptr,
2569 /*VariableMask=*/true, Alignment,
2570 ICA.getInst()),
2571 CostKind);
2572 }
2573 case Intrinsic::vector_reduce_add:
2574 case Intrinsic::vector_reduce_mul:
2575 case Intrinsic::vector_reduce_and:
2576 case Intrinsic::vector_reduce_or:
2577 case Intrinsic::vector_reduce_xor:
2578 return thisT()->getArithmeticReductionCost(
2579 getArithmeticReductionInstruction(IID), VecOpTy, std::nullopt,
2580 CostKind);
2581 case Intrinsic::vector_reduce_fadd:
2582 case Intrinsic::vector_reduce_fmul:
2583 return thisT()->getArithmeticReductionCost(
2584 getArithmeticReductionInstruction(IID), VecOpTy, FMF, CostKind);
2585 case Intrinsic::vector_reduce_smax:
2586 case Intrinsic::vector_reduce_smin:
2587 case Intrinsic::vector_reduce_umax:
2588 case Intrinsic::vector_reduce_umin:
2589 case Intrinsic::vector_reduce_fmax:
2590 case Intrinsic::vector_reduce_fmin:
2591 case Intrinsic::vector_reduce_fmaximum:
2592 case Intrinsic::vector_reduce_fminimum:
2593 case Intrinsic::vector_reduce_fmaximumnum:
2594 case Intrinsic::vector_reduce_fminimumnum:
2595 return thisT()->getMinMaxReductionCost(getMinMaxReductionIntrinsicOp(IID),
2596 VecOpTy, ICA.getFlags(), CostKind);
2597 case Intrinsic::vector_partial_reduce_add:
2598 case Intrinsic::vector_partial_reduce_fadd: {
2599 VectorType *AccTy = cast<VectorType>(ICA.getArgTypes()[0]);
2600 VectorType *InTy = cast<VectorType>(ICA.getArgTypes()[1]);
2601 // TODO: See if something better can be done for scalable-to-fixed
2602 // partial reductions.
2603 if (AccTy->isScalableTy() != InTy->isScalableTy())
2605
2606 unsigned Opcode = 0;
2607 switch (IID) {
2608 default:
2609 llvm_unreachable("Unexpected partial reduction");
2610 break;
2611 case Intrinsic::vector_partial_reduce_add:
2612 Opcode = Instruction::Add;
2613 break;
2614 case Intrinsic::vector_partial_reduce_fadd:
2615 Opcode = Instruction::FAdd;
2616 break;
2617 }
2618
2619 // TODO: Factor in subvector extract costs if the types are different
2620 // sizes. We get some ridiculously high costs for vector_extract
2621 // at present, so fix that first.
2622 // For a type-only query, model as (possibly multiple) basic instructions
2623 // for the accumulator type.
2625 AccTy->getElementCount()) *
2626 thisT()->getArithmeticInstrCost(Opcode, AccTy, CostKind);
2627 }
2628 case Intrinsic::experimental_vector_match: {
2629 auto *SearchTy = cast<VectorType>(ICA.getArgTypes()[0]);
2630 auto *NeedleTy = cast<FixedVectorType>(ICA.getArgTypes()[1]);
2631 unsigned SearchSize = NeedleTy->getNumElements();
2632
2633 // Approximate the cost based on the expansion code in
2634 // TargetLowering::expandVectorMatch.
2636 Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, NeedleTy,
2637 CostKind, 1, nullptr, nullptr);
2638 Cost += thisT()->getVectorInstrCost(Instruction::InsertElement, SearchTy,
2639 CostKind, 0, nullptr, nullptr);
2640 Cost += thisT()->getShuffleCost(TTI::SK_Broadcast, SearchTy, SearchTy,
2641 CostKind, {}, 0, nullptr);
2642 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, SearchTy, RetTy,
2643 CmpInst::ICMP_EQ, CostKind);
2644 Cost +=
2645 thisT()->getArithmeticInstrCost(BinaryOperator::Or, RetTy, CostKind);
2646 Cost *= SearchSize;
2647 Cost +=
2648 thisT()->getArithmeticInstrCost(BinaryOperator::And, RetTy, CostKind);
2649 return Cost;
2650 }
2651 case Intrinsic::vector_reverse:
2652 return thisT()->getShuffleCost(TTI::SK_Reverse, cast<VectorType>(RetTy),
2653 cast<VectorType>(ICA.getArgTypes()[0]),
2654 CostKind, {}, 0, cast<VectorType>(RetTy));
2655 case Intrinsic::experimental_vector_histogram_add:
2656 case Intrinsic::experimental_vector_histogram_uadd_sat:
2657 case Intrinsic::experimental_vector_histogram_umax:
2658 case Intrinsic::experimental_vector_histogram_umin: {
2660 Type *EltTy = ICA.getArgTypes()[1];
2661
2662 // Targets with scalable vectors must handle this on their own.
2663 if (!PtrsTy)
2665
2667 Type *MaskEltTy = MaskTy->getScalarType();
2668
2669 Align Alignment = thisT()->DL.getABITypeAlign(EltTy);
2671
2672 // Cost the main load->update->store sequence, for one element.
2673 Cost += thisT()->getMemoryOpCost(Instruction::Load, EltTy, Alignment, 0,
2674 CostKind);
2675 switch (IID) {
2676 default:
2677 llvm_unreachable("Unhandled histogram update operation.");
2678 case Intrinsic::experimental_vector_histogram_add:
2679 Cost +=
2680 thisT()->getArithmeticInstrCost(Instruction::Add, EltTy, CostKind);
2681 break;
2682 case Intrinsic::experimental_vector_histogram_uadd_sat: {
2683 IntrinsicCostAttributes UAddSat(Intrinsic::uadd_sat, EltTy, {EltTy});
2684 Cost += thisT()->getIntrinsicInstrCost(UAddSat, CostKind);
2685 break;
2686 }
2687 case Intrinsic::experimental_vector_histogram_umax: {
2688 IntrinsicCostAttributes UMax(Intrinsic::umax, EltTy, {EltTy});
2689 Cost += thisT()->getIntrinsicInstrCost(UMax, CostKind);
2690 break;
2691 }
2692 case Intrinsic::experimental_vector_histogram_umin: {
2693 IntrinsicCostAttributes UMin(Intrinsic::umin, EltTy, {EltTy});
2694 Cost += thisT()->getIntrinsicInstrCost(UMin, CostKind);
2695 break;
2696 }
2697 }
2698 Cost += thisT()->getMemoryOpCost(Instruction::Store, EltTy, Alignment, 0,
2699 CostKind);
2700
2701 // Add the cost of a compare + branch for the mask; for a type-only cost
2702 // we cannot check whether the mask is all-true.
2703 Cost += thisT()->getCmpSelInstrCost(
2704 Instruction::ICmp, MaskEltTy, MaskEltTy, CmpInst::ICMP_EQ, CostKind);
2705 Cost += thisT()->getCFInstrCost(Instruction::CondBr, CostKind);
2706
2707 // Multiply to find the cost for all elements.
2708 Cost *= PtrsTy->getNumElements();
2709
2710 // Add in the cost of the extracts; the lanes may have different costs.
2711 for (unsigned Lane = 0; Lane < PtrsTy->getNumElements(); ++Lane) {
2712 // Pointer extract.
2713 Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, PtrsTy,
2714 CostKind, Lane, nullptr, nullptr);
2715 // Mask extract.
2716 Cost += thisT()->getVectorInstrCost(Instruction::ExtractElement, MaskTy,
2717 CostKind, Lane, nullptr, nullptr);
2718 }
2719
2720 return Cost;
2721 }
2722 case Intrinsic::experimental_cttz_elts: {
2723 EVT ArgType = getTLI()->getValueType(DL, ICA.getArgTypes()[0], true);
2724
2725 // TODO: The costs below reflect the expansion code in
2726 // TargetLowering::expandCttzElts, but we may want to sacrifice some
2727 // accuracy in favour of compile time.
2728
2729 // Find the smallest "sensible" element type to use for the expansion.
2730 const SmallVectorImpl<const Value *> &Args = ICA.getArgs();
2731 bool ZeroIsPoison =
2732 !Args.empty() && !cast<ConstantInt>(Args[1])->isZero();
2733 const IntrinsicInst *I = ICA.getInst();
2734 ConstantRange VScaleRange(APInt(64, 1), APInt::getZero(64));
2735 if (isa<ScalableVectorType>(ICA.getArgTypes()[0]) && I && I->getCaller())
2736 VScaleRange = getVScaleRange(I->getCaller(), 64);
2737
2738 unsigned EltWidth = getTLI()->getBitWidthForCttzElements(
2739 getTLI()->getValueType(DL, RetTy), ArgType.getVectorElementCount(),
2740 ZeroIsPoison, &VScaleRange);
2741 Type *NewEltTy = IntegerType::getIntNTy(RetTy->getContext(), EltWidth);
2742
2743 // Create the new vector type & get the vector length
2744 Type *NewVecTy = VectorType::get(
2745 NewEltTy, cast<VectorType>(ICA.getArgTypes()[0])->getElementCount());
2746
2747 IntrinsicCostAttributes StepVecAttrs(Intrinsic::stepvector, NewVecTy, {},
2748 FMF);
2750 thisT()->getIntrinsicInstrCost(StepVecAttrs, CostKind);
2751
2752 Cost +=
2753 thisT()->getArithmeticInstrCost(Instruction::Sub, NewVecTy, CostKind);
2754 Cost += thisT()->getCastInstrCost(Instruction::SExt, NewVecTy,
2755 ICA.getArgTypes()[0],
2756 TTI::CastContextHint::None, CostKind);
2757 Cost +=
2758 thisT()->getArithmeticInstrCost(Instruction::And, NewVecTy, CostKind);
2759
2760 IntrinsicCostAttributes ReducAttrs(Intrinsic::vector_reduce_umax,
2761 NewEltTy, NewVecTy, FMF, I, 1);
2762 Cost += thisT()->getTypeBasedIntrinsicInstrCost(ReducAttrs, CostKind);
2763 Cost +=
2764 thisT()->getArithmeticInstrCost(Instruction::Sub, NewEltTy, CostKind);
2765
2766 return Cost;
2767 }
2768 case Intrinsic::get_active_lane_mask: {
2769 Type *ArgTy = ICA.getArgTypes()[0];
2770 EVT ResVT = getTLI()->getValueType(DL, RetTy, true);
2771 EVT ArgVT = getTLI()->getValueType(DL, ArgTy, true);
2772
2773 // If we're not expanding the intrinsic then we assume this is cheap
2774 // to implement.
2775 if (!getTLI()->shouldExpandGetActiveLaneMask(ResVT, ArgVT))
2776 return getTypeLegalizationCost(RetTy).first;
2777
2778 // Create the expanded types that will be used to calculate the uadd_sat
2779 // operation.
2780 Type *ExpRetTy =
2781 VectorType::get(ArgTy, cast<VectorType>(RetTy)->getElementCount());
2782 IntrinsicCostAttributes Attrs(Intrinsic::uadd_sat, ExpRetTy, {}, FMF);
2784 thisT()->getTypeBasedIntrinsicInstrCost(Attrs, CostKind);
2785 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, ExpRetTy, RetTy,
2786 CmpInst::ICMP_ULT, CostKind);
2787 return Cost;
2788 }
2789 case Intrinsic::mask_beforefirst: {
2791 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(RetTy);
2792 if (!getTLI()->isOperationExpand(ISD, LT.second))
2793 break;
2794
2795 // Scalar types are lowered as a not.
2796 if (!LT.second.isVector() || LT.second == MVT::v1i1)
2797 return LT.first *
2798 thisT()->getArithmeticInstrCost(
2799 Instruction::Xor, RetTy->getScalarType(), CostKind);
2800
2801 // Expansion via (get_active_lane_mask 0, (cttz.elts mask))
2802 RetTy = VectorType::get(RetTy->getScalarType(),
2803 LT.second.getVectorElementCount());
2804 Type *IdxTy =
2806 getTLI()->getVectorIdxTy(DL).getFixedSizeInBits());
2807 IntrinsicCostAttributes CttzEltsAttrs(Intrinsic::experimental_cttz_elts,
2808 IdxTy, RetTy, FMF);
2810 thisT()->getIntrinsicInstrCost(CttzEltsAttrs, CostKind);
2811
2812 IntrinsicCostAttributes ActiveLaneMaskAttrs(
2813 Intrinsic::get_active_lane_mask, RetTy, {IdxTy, IdxTy}, FMF);
2814 Cost += thisT()->getIntrinsicInstrCost(ActiveLaneMaskAttrs, CostKind);
2815 return Cost * LT.first;
2816 }
2817 case Intrinsic::experimental_memset_pattern:
2818 // This cost is set to match the cost of the memset_pattern16 libcall.
2819 // It should likely be re-evaluated after migration to this intrinsic
2820 // is complete.
2821 return TTI::TCC_Basic * 4;
2822 case Intrinsic::abs:
2823 ISD = ISD::ABS;
2824 break;
2825 case Intrinsic::fshl:
2826 ISD = ISD::FSHL;
2827 break;
2828 case Intrinsic::fshr:
2829 ISD = ISD::FSHR;
2830 break;
2831 case Intrinsic::smax:
2832 ISD = ISD::SMAX;
2833 break;
2834 case Intrinsic::smin:
2835 ISD = ISD::SMIN;
2836 break;
2837 case Intrinsic::umax:
2838 ISD = ISD::UMAX;
2839 break;
2840 case Intrinsic::umin:
2841 ISD = ISD::UMIN;
2842 break;
2843 case Intrinsic::sadd_sat:
2844 ISD = ISD::SADDSAT;
2845 break;
2846 case Intrinsic::ssub_sat:
2847 ISD = ISD::SSUBSAT;
2848 break;
2849 case Intrinsic::uadd_sat:
2850 ISD = ISD::UADDSAT;
2851 break;
2852 case Intrinsic::usub_sat:
2853 ISD = ISD::USUBSAT;
2854 break;
2855 case Intrinsic::sshl_sat:
2856 ISD = ISD::SSHLSAT;
2857 break;
2858 case Intrinsic::ushl_sat:
2859 ISD = ISD::USHLSAT;
2860 break;
2861 case Intrinsic::smul_fix:
2862 ISD = ISD::SMULFIX;
2863 break;
2864 case Intrinsic::umul_fix:
2865 ISD = ISD::UMULFIX;
2866 break;
2867 case Intrinsic::sadd_with_overflow:
2868 ISD = ISD::SADDO;
2869 break;
2870 case Intrinsic::ssub_with_overflow:
2871 ISD = ISD::SSUBO;
2872 break;
2873 case Intrinsic::uadd_with_overflow:
2874 ISD = ISD::UADDO;
2875 break;
2876 case Intrinsic::usub_with_overflow:
2877 ISD = ISD::USUBO;
2878 break;
2879 case Intrinsic::smul_with_overflow:
2880 ISD = ISD::SMULO;
2881 break;
2882 case Intrinsic::umul_with_overflow:
2883 ISD = ISD::UMULO;
2884 break;
2885 case Intrinsic::fptosi_sat:
2886 case Intrinsic::fptoui_sat: {
2887 std::pair<InstructionCost, MVT> SrcLT = getTypeLegalizationCost(Tys[0]);
2888 std::pair<InstructionCost, MVT> RetLT = getTypeLegalizationCost(RetTy);
2889
2890 // For cast instructions, types are different between source and
2891 // destination. Also need to check if the source type can be legalize.
2892 if (!SrcLT.first.isValid() || !RetLT.first.isValid())
2894 ISD = IID == Intrinsic::fptosi_sat ? ISD::FP_TO_SINT_SAT
2896 break;
2897 }
2898 case Intrinsic::ctpop:
2899 ISD = ISD::CTPOP;
2900 break;
2901 case Intrinsic::ctlz:
2902 ISD = ISD::CTLZ;
2903 break;
2904 case Intrinsic::cttz:
2905 ISD = ISD::CTTZ;
2906 break;
2907 case Intrinsic::bswap:
2908 ISD = ISD::BSWAP;
2909 break;
2910 case Intrinsic::bitreverse:
2912 break;
2913 case Intrinsic::pdep:
2914 ISD = ISD::PDEP;
2915 break;
2916 case Intrinsic::pext:
2917 ISD = ISD::PEXT;
2918 break;
2919 case Intrinsic::ucmp:
2920 ISD = ISD::UCMP;
2921 break;
2922 case Intrinsic::scmp:
2923 ISD = ISD::SCMP;
2924 break;
2925 case Intrinsic::clmul:
2926 ISD = ISD::CLMUL;
2927 break;
2928 case Intrinsic::smulh:
2929 ISD = ISD::MULHS;
2930 break;
2931 case Intrinsic::umulh:
2932 ISD = ISD::MULHU;
2933 break;
2934 case Intrinsic::masked_udiv:
2935 case Intrinsic::masked_sdiv:
2936 case Intrinsic::masked_urem:
2937 case Intrinsic::masked_srem: {
2938 unsigned UnmaskedOpc;
2939 switch (IID) {
2940 case Intrinsic::masked_udiv:
2942 UnmaskedOpc = Instruction::UDiv;
2943 break;
2944 case Intrinsic::masked_sdiv:
2946 UnmaskedOpc = Instruction::SDiv;
2947 break;
2948 case Intrinsic::masked_urem:
2950 UnmaskedOpc = Instruction::URem;
2951 break;
2952 case Intrinsic::masked_srem:
2954 UnmaskedOpc = Instruction::SRem;
2955 break;
2956 default:
2957 llvm_unreachable("Unexpected intrinsic ID");
2958 }
2960 thisT()->getArithmeticInstrCost(UnmaskedOpc, RetTy, CostKind);
2961
2962 // Expansion generates a (select %mask, %rhs, 1) for the divisor.
2963 MVT LT = getTypeLegalizationCost(RetTy).second;
2964 if (!getTLI()->isOperationLegalOrCustom(ISD, LT)) {
2965 Type *CondTy = cast<VectorType>(RetTy)->getWithNewType(
2967 Cost += thisT()->getCmpSelInstrCost(
2968 BinaryOperator::Select, RetTy, CondTy, CmpInst::BAD_ICMP_PREDICATE,
2970 }
2971
2972 return Cost;
2973 }
2974 }
2975
2976 auto *ST = dyn_cast<StructType>(RetTy);
2977 Type *LegalizeTy = ST ? ST->getContainedType(0) : RetTy;
2978 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(LegalizeTy);
2979
2980 const TargetLoweringBase *TLI = getTLI();
2981
2982 // pdep/pext span the full scalar width; multi-register scalars can't split
2983 bool BitManipSplit = (ISD == ISD::PDEP || ISD == ISD::PEXT) &&
2984 LT.first > 1 && !LT.second.isVector();
2985
2986 if (!BitManipSplit && TLI->isOperationLegalOrPromote(ISD, LT.second)) {
2987 if (IID == Intrinsic::fabs && LT.second.isFloatingPoint() &&
2988 TLI->isFAbsFree(LT.second)) {
2989 return 0;
2990 }
2991
2992 // The operation is legal. Assume it costs 1.
2993 // If the type is split to multiple registers, assume that there is some
2994 // overhead to this.
2995 // TODO: Once we have extract/insert subvector cost we need to use them.
2996 if (LT.first > 1)
2997 return (LT.first * 2);
2998 else
2999 return (LT.first * 1);
3000 } else if (!BitManipSplit && TLI->isOperationCustom(ISD, LT.second)) {
3001 // If the operation is custom lowered then assume
3002 // that the code is twice as expensive.
3003 return (LT.first * 2);
3004 }
3005
3006 switch (IID) {
3007 case Intrinsic::fmuladd: {
3008 // If we can't lower fmuladd into an FMA estimate the cost as a floating
3009 // point mul followed by an add.
3010
3011 return thisT()->getArithmeticInstrCost(BinaryOperator::FMul, RetTy,
3012 CostKind) +
3013 thisT()->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy,
3014 CostKind);
3015 }
3016 case Intrinsic::experimental_constrained_fmuladd: {
3017 IntrinsicCostAttributes FMulAttrs(
3018 Intrinsic::experimental_constrained_fmul, RetTy, Tys);
3019 IntrinsicCostAttributes FAddAttrs(
3020 Intrinsic::experimental_constrained_fadd, RetTy, Tys);
3021 return thisT()->getIntrinsicInstrCost(FMulAttrs, CostKind) +
3022 thisT()->getIntrinsicInstrCost(FAddAttrs, CostKind);
3023 }
3024 case Intrinsic::smin:
3025 case Intrinsic::smax:
3026 case Intrinsic::umin:
3027 case Intrinsic::umax: {
3028 // minmax(X,Y) = select(icmp(X,Y),X,Y)
3029 Type *CondTy = RetTy->getWithNewBitWidth(1);
3030 bool IsUnsigned = IID == Intrinsic::umax || IID == Intrinsic::umin;
3032 IsUnsigned ? CmpInst::ICMP_UGT : CmpInst::ICMP_SGT;
3034 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy,
3035 Pred, CostKind);
3036 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
3037 Pred, CostKind);
3038 return Cost;
3039 }
3040 case Intrinsic::sadd_with_overflow:
3041 case Intrinsic::ssub_with_overflow: {
3042 Type *SumTy = RetTy->getContainedType(0);
3043 Type *OverflowTy = RetTy->getContainedType(1);
3044 unsigned Opcode = IID == Intrinsic::sadd_with_overflow
3045 ? BinaryOperator::Add
3046 : BinaryOperator::Sub;
3047
3048 // Add:
3049 // Overflow -> (Result < LHS) ^ (RHS < 0)
3050 // Sub:
3051 // Overflow -> (Result < LHS) ^ (RHS > 0)
3053 Cost += thisT()->getArithmeticInstrCost(Opcode, SumTy, CostKind);
3054 Cost +=
3055 2 * thisT()->getCmpSelInstrCost(Instruction::ICmp, SumTy, OverflowTy,
3056 CmpInst::ICMP_SGT, CostKind);
3057 Cost += thisT()->getArithmeticInstrCost(BinaryOperator::Xor, OverflowTy,
3058 CostKind);
3059 return Cost;
3060 }
3061 case Intrinsic::uadd_with_overflow:
3062 case Intrinsic::usub_with_overflow: {
3063 Type *SumTy = RetTy->getContainedType(0);
3064 Type *OverflowTy = RetTy->getContainedType(1);
3065 unsigned Opcode = IID == Intrinsic::uadd_with_overflow
3066 ? BinaryOperator::Add
3067 : BinaryOperator::Sub;
3068 CmpInst::Predicate Pred = IID == Intrinsic::uadd_with_overflow
3071
3073 Cost += thisT()->getArithmeticInstrCost(Opcode, SumTy, CostKind);
3074 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, SumTy,
3075 OverflowTy, Pred, CostKind);
3076 return Cost;
3077 }
3078 case Intrinsic::smul_with_overflow:
3079 case Intrinsic::umul_with_overflow: {
3080 Type *MulTy = RetTy->getContainedType(0);
3081 Type *OverflowTy = RetTy->getContainedType(1);
3082 unsigned ExtSize = MulTy->getScalarSizeInBits() * 2;
3083 Type *ExtTy = MulTy->getWithNewBitWidth(ExtSize);
3084 bool IsSigned = IID == Intrinsic::smul_with_overflow;
3085
3086 unsigned ExtOp = IsSigned ? Instruction::SExt : Instruction::ZExt;
3088
3090 Cost += 2 * thisT()->getCastInstrCost(ExtOp, ExtTy, MulTy, CCH, CostKind);
3091 Cost +=
3092 thisT()->getArithmeticInstrCost(Instruction::Mul, ExtTy, CostKind);
3093 Cost += 2 * thisT()->getCastInstrCost(Instruction::Trunc, MulTy, ExtTy,
3094 CCH, CostKind);
3095 Cost += thisT()->getArithmeticInstrCost(
3096 Instruction::LShr, ExtTy, CostKind, {TTI::OK_AnyValue, TTI::OP_None},
3098
3099 if (IsSigned)
3100 Cost += thisT()->getArithmeticInstrCost(
3101 Instruction::AShr, MulTy, CostKind,
3104
3105 Cost += thisT()->getCmpSelInstrCost(
3106 BinaryOperator::ICmp, MulTy, OverflowTy, CmpInst::ICMP_NE, CostKind);
3107 return Cost;
3108 }
3109 case Intrinsic::sadd_sat:
3110 case Intrinsic::ssub_sat: {
3111 // Assume a default expansion.
3112 Type *CondTy = RetTy->getWithNewBitWidth(1);
3113
3114 Type *OpTy = StructType::create({RetTy, CondTy});
3115 Intrinsic::ID OverflowOp = IID == Intrinsic::sadd_sat
3116 ? Intrinsic::sadd_with_overflow
3117 : Intrinsic::ssub_with_overflow;
3119
3120 // SatMax -> Overflow && SumDiff < 0
3121 // SatMin -> Overflow && SumDiff >= 0
3123 IntrinsicCostAttributes Attrs(OverflowOp, OpTy, {RetTy, RetTy}, FMF,
3124 nullptr, ScalarizationCostPassed);
3125 Cost += thisT()->getIntrinsicInstrCost(Attrs, CostKind);
3126 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy,
3127 Pred, CostKind);
3128 Cost += 2 * thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy,
3129 CondTy, Pred, CostKind);
3130 return Cost;
3131 }
3132 case Intrinsic::uadd_sat:
3133 case Intrinsic::usub_sat: {
3134 Type *CondTy = RetTy->getWithNewBitWidth(1);
3135
3136 Type *OpTy = StructType::create({RetTy, CondTy});
3137 Intrinsic::ID OverflowOp = IID == Intrinsic::uadd_sat
3138 ? Intrinsic::uadd_with_overflow
3139 : Intrinsic::usub_with_overflow;
3140
3142 IntrinsicCostAttributes Attrs(OverflowOp, OpTy, {RetTy, RetTy}, FMF,
3143 nullptr, ScalarizationCostPassed);
3144 Cost += thisT()->getIntrinsicInstrCost(Attrs, CostKind);
3145 Cost +=
3146 thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
3147 CmpInst::BAD_ICMP_PREDICATE, CostKind);
3148 return Cost;
3149 }
3150 case Intrinsic::sshl_sat:
3151 case Intrinsic::ushl_sat: {
3152 Type *CondTy = RetTy->getWithNewBitWidth(1);
3153 bool IsSigned = IID == Intrinsic::sshl_sat;
3155 Cost +=
3156 thisT()->getArithmeticInstrCost(Instruction::Shl, RetTy, CostKind);
3157 Cost += thisT()->getArithmeticInstrCost(
3158 IsSigned ? Instruction::AShr : Instruction::LShr, RetTy, CostKind);
3159 if (IsSigned) {
3160 Cost += thisT()->getCmpSelInstrCost(Instruction::ICmp, RetTy, CondTy,
3161 CmpInst::ICMP_SLT, CostKind);
3162 Cost += thisT()->getCmpSelInstrCost(Instruction::Select, RetTy, CondTy,
3163 CmpInst::ICMP_SLT, CostKind);
3164 }
3165 Cost += thisT()->getCmpSelInstrCost(Instruction::ICmp, RetTy, CondTy,
3166 CmpInst::ICMP_NE, CostKind);
3167 Cost += thisT()->getCmpSelInstrCost(Instruction::Select, RetTy, CondTy,
3168 CmpInst::ICMP_NE, CostKind);
3169 return Cost;
3170 }
3171 case Intrinsic::smul_fix:
3172 case Intrinsic::umul_fix: {
3173 unsigned ExtSize = RetTy->getScalarSizeInBits() * 2;
3174 Type *ExtTy = RetTy->getWithNewBitWidth(ExtSize);
3175
3176 unsigned ExtOp =
3177 IID == Intrinsic::smul_fix ? Instruction::SExt : Instruction::ZExt;
3179
3181 Cost += 2 * thisT()->getCastInstrCost(ExtOp, ExtTy, RetTy, CCH, CostKind);
3182 Cost +=
3183 thisT()->getArithmeticInstrCost(Instruction::Mul, ExtTy, CostKind);
3184 Cost += 2 * thisT()->getCastInstrCost(Instruction::Trunc, RetTy, ExtTy,
3185 CCH, CostKind);
3186 Cost += thisT()->getArithmeticInstrCost(
3187 Instruction::LShr, RetTy, CostKind, {TTI::OK_AnyValue, TTI::OP_None},
3189 Cost += thisT()->getArithmeticInstrCost(
3190 Instruction::Shl, RetTy, CostKind, {TTI::OK_AnyValue, TTI::OP_None},
3192 Cost += thisT()->getArithmeticInstrCost(Instruction::Or, RetTy, CostKind);
3193 return Cost;
3194 }
3195 case Intrinsic::abs: {
3196 // abs(X) = select(icmp(X,0),X,sub(0,X))
3197 Type *CondTy = RetTy->getWithNewBitWidth(1);
3200 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy,
3201 Pred, CostKind);
3202 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
3203 Pred, CostKind);
3204 // TODO: Should we add an OperandValueProperties::OP_Zero property?
3205 Cost += thisT()->getArithmeticInstrCost(
3206 BinaryOperator::Sub, RetTy, CostKind,
3208 return Cost;
3209 }
3210 case Intrinsic::fshl:
3211 case Intrinsic::fshr: {
3212 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3213 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3214 Type *CondTy = RetTy->getWithNewBitWidth(1);
3216 Cost +=
3217 thisT()->getArithmeticInstrCost(BinaryOperator::Or, RetTy, CostKind);
3218 Cost +=
3219 thisT()->getArithmeticInstrCost(BinaryOperator::Sub, RetTy, CostKind);
3220 Cost +=
3221 thisT()->getArithmeticInstrCost(BinaryOperator::Shl, RetTy, CostKind);
3222 Cost += thisT()->getArithmeticInstrCost(BinaryOperator::LShr, RetTy,
3223 CostKind);
3224 // Non-constant shift amounts requires a modulo. If the typesize is a
3225 // power-2 then this will be converted to an and, otherwise it will use a
3226 // urem.
3227 Cost += thisT()->getArithmeticInstrCost(
3228 isPowerOf2_32(RetTy->getScalarSizeInBits()) ? BinaryOperator::And
3229 : BinaryOperator::URem,
3230 RetTy, CostKind, {TTI::OK_AnyValue, TTI::OP_None},
3231 {TTI::OK_UniformConstantValue, TTI::OP_None});
3232 // Shift-by-zero handling.
3233 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy,
3234 CmpInst::ICMP_EQ, CostKind);
3235 Cost += thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
3236 CmpInst::ICMP_EQ, CostKind);
3237 return Cost;
3238 }
3239 case Intrinsic::fptosi_sat:
3240 case Intrinsic::fptoui_sat: {
3241 if (Tys.empty())
3242 break;
3243 Type *FromTy = Tys[0];
3244 bool IsSigned = IID == Intrinsic::fptosi_sat;
3245
3247 IntrinsicCostAttributes Attrs1(Intrinsic::minnum, FromTy,
3248 {FromTy, FromTy});
3249 Cost += thisT()->getIntrinsicInstrCost(Attrs1, CostKind);
3250 IntrinsicCostAttributes Attrs2(Intrinsic::maxnum, FromTy,
3251 {FromTy, FromTy});
3252 Cost += thisT()->getIntrinsicInstrCost(Attrs2, CostKind);
3253 Cost += thisT()->getCastInstrCost(
3254 IsSigned ? Instruction::FPToSI : Instruction::FPToUI, RetTy, FromTy,
3255 TTI::CastContextHint::None, CostKind);
3256 if (IsSigned) {
3257 Type *CondTy = RetTy->getWithNewBitWidth(1);
3258 Cost += thisT()->getCmpSelInstrCost(
3259 BinaryOperator::FCmp, FromTy, CondTy, CmpInst::FCMP_UNO, CostKind);
3260 Cost += thisT()->getCmpSelInstrCost(
3261 BinaryOperator::Select, RetTy, CondTy, CmpInst::FCMP_UNO, CostKind);
3262 }
3263 return Cost;
3264 }
3265 case Intrinsic::ucmp:
3266 case Intrinsic::scmp: {
3267 Type *CmpTy = Tys[0];
3268 Type *CondTy = RetTy->getWithNewBitWidth(1);
3270 thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, CmpTy, CondTy,
3272 CostKind) +
3273 thisT()->getCmpSelInstrCost(BinaryOperator::ICmp, CmpTy, CondTy,
3275 CostKind);
3276
3277 EVT VT = TLI->getValueType(DL, CmpTy, true);
3278 if (TLI->preferSelectsOverBooleanArithmetic(VT)) {
3279 // x < y ? -1 : (x > y ? 1 : 0)
3280 Cost += 2 * thisT()->getCmpSelInstrCost(
3281 BinaryOperator::Select, RetTy, CondTy,
3283 } else {
3284 // zext(x > y) - zext(x < y)
3285 Cost +=
3286 2 * thisT()->getCastInstrCost(CastInst::ZExt, RetTy, CondTy,
3287 TTI::CastContextHint::None, CostKind);
3288 Cost += thisT()->getArithmeticInstrCost(BinaryOperator::Sub, RetTy,
3289 CostKind);
3290 }
3291 return Cost;
3292 }
3293 case Intrinsic::maximumnum:
3294 case Intrinsic::minimumnum: {
3295 // On platform that support FMAXNUM_IEEE/FMINNUM_IEEE, we expand
3296 // maximumnum/minimumnum to
3297 // ARG0 = fcanonicalize ARG0, ARG0 // to quiet ARG0
3298 // ARG1 = fcanonicalize ARG1, ARG1 // to quiet ARG1
3299 // RESULT = MAXNUM_IEEE ARG0, ARG1 // or MINNUM_IEEE
3300 // FIXME: In LangRef, we claimed FMAXNUM has the same behaviour of
3301 // FMAXNUM_IEEE, while the backend hasn't migrated the code yet.
3302 // Finally, we will remove FMAXNUM_IEEE and FMINNUM_IEEE.
3303 int IeeeISD =
3304 IID == Intrinsic::maximumnum ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
3305 if (TLI->isOperationLegal(IeeeISD, LT.second)) {
3306 IntrinsicCostAttributes FCanonicalizeAttrs(Intrinsic::canonicalize,
3307 RetTy, Tys[0]);
3308 InstructionCost FCanonicalizeCost =
3309 thisT()->getIntrinsicInstrCost(FCanonicalizeAttrs, CostKind);
3310 return LT.first + FCanonicalizeCost * 2;
3311 }
3312 break;
3313 }
3314 case Intrinsic::ctpop: {
3315 // This cost model should match the expansion in
3316 // TargetLowering::expandCTPOP. Vectors are scalarized below.
3317 if (RetTy->isVectorTy())
3318 break;
3319 unsigned BW = RetTy->getScalarSizeInBits();
3320 if (BW > 128 || BW % 8 != 0)
3321 break;
3322 InstructionCost AndCost =
3323 thisT()->getArithmeticInstrCost(Instruction::And, RetTy, CostKind);
3324 InstructionCost AddCost =
3325 thisT()->getArithmeticInstrCost(Instruction::Add, RetTy, CostKind);
3326 InstructionCost SubCost =
3327 thisT()->getArithmeticInstrCost(Instruction::Sub, RetTy, CostKind);
3328 InstructionCost LShrCost =
3329 thisT()->getArithmeticInstrCost(Instruction::LShr, RetTy, CostKind);
3330
3331 // v = v - ((v >> 1) & 0x55...)
3332 // v = (v & 0x33...) + ((v >> 2) & 0x33...)
3333 // v = (v + (v >> 4)) & 0x0F...
3334 InstructionCost Cost = 3 * LShrCost + 4 * AndCost + SubCost + 2 * AddCost;
3335 if (BW == 8)
3336 return Cost;
3337 // v = (v + (v >> 8)) & 0xFF
3338 if (BW == 16)
3339 return Cost + LShrCost + AddCost + AndCost;
3340 // v = (v * 0x0101...) >> (BW - 8), with the multiply done as shifts and
3341 // adds if there is no multiply.
3342 InstructionCost MulCost =
3343 thisT()->getArithmeticInstrCost(Instruction::Mul, RetTy, CostKind);
3344 InstructionCost ShlCost =
3345 thisT()->getArithmeticInstrCost(Instruction::Shl, RetTy, CostKind);
3346 if (getTLI()->isOperationLegalOrCustomOrPromote(ISD::MUL, LT.second))
3347 Cost += MulCost;
3348 else
3349 Cost += Log2_32(BW / 8) * (ShlCost + AddCost);
3350 return Cost + LShrCost;
3351 }
3352 case Intrinsic::clmul: {
3353 // This cost model should match the expansion in
3354 // TargetLowering::expandCLMUL.
3355 unsigned BW = RetTy->getScalarSizeInBits();
3356 InstructionCost AndCost =
3357 thisT()->getArithmeticInstrCost(Instruction::And, RetTy, CostKind);
3358 InstructionCost OrCost =
3359 thisT()->getArithmeticInstrCost(Instruction::Or, RetTy, CostKind);
3360 InstructionCost XorCost =
3361 thisT()->getArithmeticInstrCost(Instruction::Xor, RetTy, CostKind);
3362 InstructionCost MulCost =
3363 thisT()->getArithmeticInstrCost(Instruction::Mul, RetTy, CostKind);
3364
3365 // When the multiplication with holes approach is used, it splits the
3366 // operands into S phases (the smallest stride with ceil(BW/S) <= 2^S) and
3367 // emits S*S MULs, 3*S ANDs, S*(S-1) XORs and S-1 ORs.
3368 //
3369 // * BW <= 8 uses S = 2
3370 // * BW <= 24 uses S = 3
3371 // * BW <= 64 uses S = 4
3372 // * BW <= 160 uses S = 5
3373 // * BW <= 384 uses S = 6
3374 unsigned S = 1;
3375 while (S < 32 && divideCeil(BW, S) > (1u << S))
3376 ++S;
3377
3378 // The naive algorithm usually uses AND+MUL+XOR per bit.
3379 unsigned NaiveCost = 3 * BW;
3380 unsigned HolesCost = S * S + 3 * S + S * (S - 1) + (S - 1);
3381
3382 if (HolesCost < NaiveCost &&
3383 TLI->isOperationLegalOrCustom(ISD::MUL,
3384 TLI->getValueType(DL, RetTy))) {
3385 return S * S * MulCost + 3 * S * AndCost + S * (S - 1) * XorCost +
3386 (S - 1) * OrCost;
3387 }
3388
3389 InstructionCost PerBitCostMul = AndCost + MulCost + XorCost;
3390 InstructionCost PerBitCostBittest =
3391 AndCost +
3392 thisT()->getCmpSelInstrCost(BinaryOperator::Select, RetTy, RetTy,
3393 ICmpInst::BAD_ICMP_PREDICATE, CostKind) +
3394 thisT()->getCmpSelInstrCost(Instruction::ICmp, RetTy, RetTy,
3395 ICmpInst::ICMP_NE, CostKind);
3396 InstructionCost PerBitCost = std::min(PerBitCostMul, PerBitCostBittest);
3397 return BW * PerBitCost;
3398 }
3399 case Intrinsic::smulh:
3400 case Intrinsic::umulh: {
3401 unsigned BW = RetTy->getScalarSizeInBits();
3402 Type *WideTy = RetTy->getWithNewBitWidth(BW * 2);
3403 bool IsSigned = IID == Intrinsic::smulh;
3404 unsigned ExtOp = IsSigned ? Instruction::SExt : Instruction::ZExt;
3406 Cost +=
3407 2 * thisT()->getCastInstrCost(ExtOp, WideTy, RetTy,
3408 TTI::CastContextHint::None, CostKind);
3409 Cost +=
3410 thisT()->getArithmeticInstrCost(Instruction::Mul, WideTy, CostKind);
3411 Cost += thisT()->getArithmeticInstrCost(
3412 Instruction::LShr, WideTy, CostKind, {TTI::OK_AnyValue, TTI::OP_None},
3414 Cost += thisT()->getCastInstrCost(Instruction::Trunc, RetTy, WideTy,
3415 TTI::CastContextHint::None, CostKind);
3416 return Cost;
3417 }
3418 case Intrinsic::pdep:
3419 case Intrinsic::pext: {
3420 if (RetTy->isVectorTy())
3421 break;
3422 // Based on Hacker's Delight §7-5: Expand, or Generalized Insert.
3423 // Below cost is accurate for pext, pdep will be similar.
3424 unsigned BW = RetTy->getScalarSizeInBits();
3425 InstructionCost AndCost =
3426 thisT()->getArithmeticInstrCost(Instruction::And, RetTy, CostKind);
3427 InstructionCost ShiftCost =
3428 thisT()->getArithmeticInstrCost(Instruction::Shl, RetTy, CostKind);
3429 InstructionCost OrCost =
3430 thisT()->getArithmeticInstrCost(Instruction::Or, RetTy, CostKind);
3431 InstructionCost XorCost =
3432 thisT()->getArithmeticInstrCost(Instruction::Xor, RetTy, CostKind);
3433 IntrinsicCostAttributes ClmulAttrs(Intrinsic::clmul, RetTy,
3434 {RetTy, RetTy});
3435 int Iterations = Log2_32_Ceil(BW);
3436 // Expansion of CLMUL(Mk, ~0) is lot cheaper
3437 InstructionCost GenericClmulCost =
3438 thisT()->getIntrinsicInstrCost(ClmulAttrs, CostKind);
3439 InstructionCost AllOnesClmulCost = Iterations * (ShiftCost + XorCost);
3440 InstructionCost MulCost = std::min(GenericClmulCost, AllOnesClmulCost);
3441
3442 InstructionCost Cost = AndCost + ShiftCost; // Prefix cost
3443 Cost += Iterations *
3444 (MulCost + 2 * AndCost + 2 * ShiftCost + OrCost + 2 * XorCost);
3445 return Cost;
3446 }
3447 default:
3448 break;
3449 }
3450
3451 // Else, assume that we need to scalarize this intrinsic. For math builtins
3452 // this will emit a costly libcall, adding call overhead and spills. Make it
3453 // very expensive.
3454 if (isVectorizedTy(RetTy)) {
3455 ArrayRef<Type *> RetVTys = getContainedTypes(RetTy);
3456
3457 // Scalable vectors cannot be scalarized, so return Invalid.
3458 if (any_of(concat<Type *const>(RetVTys, Tys),
3459 [](Type *Ty) { return isa<ScalableVectorType>(Ty); }))
3461
3462 InstructionCost ScalarizationCost = ScalarizationCostPassed;
3463 if (!SkipScalarizationCost) {
3464 ScalarizationCost = 0;
3465 for (Type *RetVTy : RetVTys) {
3466 ScalarizationCost += getScalarizationOverhead(
3467 cast<VectorType>(RetVTy), /*Insert=*/true,
3468 /*Extract=*/false, CostKind);
3469 }
3470 }
3471
3472 unsigned ScalarCalls = getVectorizedTypeVF(RetTy).getFixedValue();
3473 SmallVector<Type *, 4> ScalarTys;
3474 for (Type *Ty : Tys) {
3475 if (Ty->isVectorTy())
3476 Ty = Ty->getScalarType();
3477 ScalarTys.push_back(Ty);
3478 }
3479 IntrinsicCostAttributes Attrs(IID, toScalarizedTy(RetTy), ScalarTys, FMF);
3480 InstructionCost ScalarCost =
3481 thisT()->getIntrinsicInstrCost(Attrs, CostKind);
3482 for (Type *Ty : Tys) {
3483 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
3484 if (!ICA.skipScalarizationCost())
3485 ScalarizationCost += getScalarizationOverhead(
3486 VTy, /*Insert*/ false, /*Extract*/ true, CostKind);
3487 ScalarCalls = std::max(ScalarCalls,
3488 cast<FixedVectorType>(VTy)->getNumElements());
3489 }
3490 }
3491 return ScalarCalls * ScalarCost + ScalarizationCost;
3492 }
3493
3494 // This is going to be turned into a library call, make it expensive.
3495 return SingleCallCost;
3496 }
3497
3498 /// Get memory intrinsic cost based on arguments.
3501 TTI::TargetCostKind CostKind) const override {
3502 unsigned Id = MICA.getID();
3503 Type *DataTy = MICA.getDataType();
3504 bool VariableMask = MICA.getVariableMask();
3505 Align Alignment = MICA.getAlignment();
3506
3507 switch (Id) {
3508 case Intrinsic::experimental_vp_strided_load:
3509 case Intrinsic::experimental_vp_strided_store: {
3510 unsigned Opcode = Id == Intrinsic::experimental_vp_strided_load
3511 ? Instruction::Load
3512 : Instruction::Store;
3513 // For a target without strided memory operations (or for an illegal
3514 // operation type on one which does), assume we lower to a gather/scatter
3515 // operation. (Which may in turn be scalarized.)
3516 return getCommonMaskedMemoryOpCost(Opcode, DataTy, Alignment,
3517 VariableMask, true, CostKind);
3518 }
3519 case Intrinsic::masked_scatter:
3520 case Intrinsic::masked_gather:
3521 case Intrinsic::vp_scatter:
3522 case Intrinsic::vp_gather: {
3523 unsigned Opcode = (MICA.getID() == Intrinsic::masked_gather ||
3524 MICA.getID() == Intrinsic::vp_gather)
3525 ? Instruction::Load
3526 : Instruction::Store;
3527
3528 return getCommonMaskedMemoryOpCost(Opcode, DataTy, Alignment,
3529 VariableMask, true, CostKind);
3530 }
3531 case Intrinsic::vp_load:
3532 case Intrinsic::vp_store:
3534 case Intrinsic::masked_load:
3535 case Intrinsic::masked_store: {
3536 unsigned Opcode =
3537 Id == Intrinsic::masked_load ? Instruction::Load : Instruction::Store;
3538 // TODO: Pass on AddressSpace when we have test coverage.
3539 return getCommonMaskedMemoryOpCost(Opcode, DataTy, Alignment, true, false,
3540 CostKind);
3541 }
3542 case Intrinsic::masked_compressstore:
3543 case Intrinsic::masked_expandload: {
3544 unsigned Opcode = MICA.getID() == Intrinsic::masked_expandload
3545 ? Instruction::Load
3546 : Instruction::Store;
3547 // Treat expand load/compress store as gather/scatter operation.
3548 // TODO: implement more precise cost estimation for these intrinsics.
3549 return getCommonMaskedMemoryOpCost(Opcode, DataTy, Alignment,
3550 VariableMask,
3551 /*IsGatherScatter*/ true, CostKind);
3552 }
3553 case Intrinsic::vp_load_ff:
3555 case Intrinsic::speculative_load:
3556 // Speculative loads are lowered to regular loads of the full type.
3557 return thisT()->getMemoryOpCost(Instruction::Load, DataTy, Alignment,
3558 MICA.getAddressSpace(), CostKind);
3559 default:
3560 llvm_unreachable("unexpected intrinsic");
3561 }
3562 }
3563
3564 /// Compute a cost of the given call instruction.
3565 ///
3566 /// Compute the cost of calling function F with return type RetTy and
3567 /// argument types Tys. F might be nullptr, in this case the cost of an
3568 /// arbitrary call with the specified signature will be returned.
3569 /// This is used, for instance, when we estimate call of a vector
3570 /// counterpart of the given function.
3571 /// \param F Called function, might be nullptr.
3572 /// \param RetTy Return value types.
3573 /// \param Tys Argument types.
3574 /// \returns The cost of Call instruction.
3577 TTI::TargetCostKind CostKind) const override {
3578 return 10;
3579 }
3580
3581 unsigned getNumberOfParts(Type *Tp) const override {
3582 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Tp);
3583 if (!LT.first.isValid())
3584 return 0;
3585 // Try to find actual number of parts for non-power-of-2 elements as
3586 // ceil(num-of-elements/num-of-subtype-elements).
3587 if (auto *FTp = dyn_cast<FixedVectorType>(Tp);
3588 FTp && LT.second.isFixedLengthVector() &&
3589 !has_single_bit(FTp->getNumElements())) {
3590 if (auto *SubTp = dyn_cast_if_present<FixedVectorType>(
3591 EVT(LT.second).getTypeForEVT(Tp->getContext()));
3592 SubTp && SubTp->getElementType() == FTp->getElementType())
3593 return divideCeil(FTp->getNumElements(), SubTp->getNumElements());
3594 }
3595 return LT.first.getValue();
3596 }
3597
3600 TTI::TargetCostKind) const override {
3601 return 0;
3602 }
3603
3604 /// Try to calculate arithmetic and shuffle op costs for reduction intrinsics.
3605 /// We're assuming that reduction operation are performing the following way:
3606 ///
3607 /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
3608 /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
3609 /// \----------------v-------------/ \----------v------------/
3610 /// n/2 elements n/2 elements
3611 /// %red1 = op <n x t> %val, <n x t> val1
3612 /// After this operation we have a vector %red1 where only the first n/2
3613 /// elements are meaningful, the second n/2 elements are undefined and can be
3614 /// dropped. All other operations are actually working with the vector of
3615 /// length n/2, not n, though the real vector length is still n.
3616 /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
3617 /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
3618 /// \----------------v-------------/ \----------v------------/
3619 /// n/4 elements 3*n/4 elements
3620 /// %red2 = op <n x t> %red1, <n x t> val2 - working with the vector of
3621 /// length n/2, the resulting vector has length n/4 etc.
3622 ///
3623 /// The cost model should take into account that the actual length of the
3624 /// vector is reduced on each iteration.
3626 TTI::TargetCostKind CostKind) const {
3627 // Targets must implement a default value for the scalable case, since
3628 // we don't know how many lanes the vector has.
3631
3632 Type *ScalarTy = Ty->getElementType();
3633 unsigned NumVecElts = cast<FixedVectorType>(Ty)->getNumElements();
3634 if ((Opcode == Instruction::Or || Opcode == Instruction::And) &&
3635 ScalarTy == IntegerType::getInt1Ty(Ty->getContext()) &&
3636 NumVecElts >= 2) {
3637 // Or reduction for i1 is represented as:
3638 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
3639 // %res = cmp ne iReduxWidth %val, 0
3640 // And reduction for i1 is represented as:
3641 // %val = bitcast <ReduxWidth x i1> to iReduxWidth
3642 // %res = cmp eq iReduxWidth %val, 11111
3643 Type *ValTy = IntegerType::get(Ty->getContext(), NumVecElts);
3644 return thisT()->getCastInstrCost(Instruction::BitCast, ValTy, Ty,
3645 TTI::CastContextHint::None, CostKind) +
3646 thisT()->getCmpSelInstrCost(Instruction::ICmp, ValTy,
3648 CmpInst::BAD_ICMP_PREDICATE, CostKind);
3649 }
3650 unsigned NumReduxLevels = Log2_32(NumVecElts);
3651 InstructionCost ArithCost = 0;
3652 InstructionCost ShuffleCost = 0;
3653 std::pair<InstructionCost, MVT> LT = thisT()->getTypeLegalizationCost(Ty);
3654 unsigned LongVectorCount = 0;
3655 unsigned MVTLen =
3656 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
3657 while (NumVecElts > MVTLen) {
3658 NumVecElts /= 2;
3659 VectorType *SubTy = FixedVectorType::get(ScalarTy, NumVecElts);
3660 ShuffleCost += thisT()->getShuffleCost(
3661 TTI::SK_ExtractSubvector, SubTy, Ty, CostKind, {}, NumVecElts, SubTy);
3662 ArithCost += thisT()->getArithmeticInstrCost(Opcode, SubTy, CostKind);
3663 Ty = SubTy;
3664 ++LongVectorCount;
3665 }
3666
3667 NumReduxLevels -= LongVectorCount;
3668
3669 // The minimal length of the vector is limited by the real length of vector
3670 // operations performed on the current platform. That's why several final
3671 // reduction operations are performed on the vectors with the same
3672 // architecture-dependent length.
3673
3674 // By default reductions need one shuffle per reduction level.
3675 ShuffleCost +=
3676 NumReduxLevels * thisT()->getShuffleCost(TTI::SK_PermuteSingleSrc, Ty,
3677 Ty, CostKind, {}, 0, Ty);
3678 ArithCost +=
3679 NumReduxLevels * thisT()->getArithmeticInstrCost(Opcode, Ty, CostKind);
3680 return ShuffleCost + ArithCost +
3681 thisT()->getVectorInstrCost(Instruction::ExtractElement, Ty,
3682 CostKind, 0, nullptr, nullptr);
3683 }
3684
3685 /// Try to calculate the cost of performing strict (in-order) reductions,
3686 /// which involves doing a sequence of floating point additions in lane
3687 /// order, starting with an initial value. For example, consider a scalar
3688 /// initial value 'InitVal' of type float and a vector of type <4 x float>:
3689 ///
3690 /// Vector = <float %v0, float %v1, float %v2, float %v3>
3691 ///
3692 /// %add1 = %InitVal + %v0
3693 /// %add2 = %add1 + %v1
3694 /// %add3 = %add2 + %v2
3695 /// %add4 = %add3 + %v3
3696 ///
3697 /// As a simple estimate we can say the cost of such a reduction is 4 times
3698 /// the cost of a scalar FP addition. We can only estimate the costs for
3699 /// fixed-width vectors here because for scalable vectors we do not know the
3700 /// runtime number of operations.
3702 TTI::TargetCostKind CostKind) const {
3703 // Targets must implement a default value for the scalable case, since
3704 // we don't know how many lanes the vector has.
3707
3708 auto *VTy = cast<FixedVectorType>(Ty);
3710 VTy, /*Insert=*/false, /*Extract=*/true, CostKind);
3711 InstructionCost ArithCost = thisT()->getArithmeticInstrCost(
3712 Opcode, VTy->getElementType(), CostKind);
3713 ArithCost *= VTy->getNumElements();
3714
3715 return ExtractCost + ArithCost;
3716 }
3717
3720 std::optional<FastMathFlags> FMF,
3721 TTI::TargetCostKind CostKind) const override {
3722 assert(Ty && "Unknown reduction vector type");
3724 return getOrderedReductionCost(Opcode, Ty, CostKind);
3725 return getTreeReductionCost(Opcode, Ty, CostKind);
3726 }
3727
3728 /// Try to calculate op costs for min/max reduction operations.
3729 /// \param CondTy Conditional type for the Select instruction.
3732 TTI::TargetCostKind CostKind) const override {
3733 // Targets must implement a default value for the scalable case, since
3734 // we don't know how many lanes the vector has.
3737
3738 Type *ScalarTy = Ty->getElementType();
3739 unsigned NumVecElts = cast<FixedVectorType>(Ty)->getNumElements();
3740 unsigned NumReduxLevels = Log2_32(NumVecElts);
3741 InstructionCost MinMaxCost = 0;
3742 InstructionCost ShuffleCost = 0;
3743 std::pair<InstructionCost, MVT> LT = thisT()->getTypeLegalizationCost(Ty);
3744 unsigned LongVectorCount = 0;
3745 unsigned MVTLen =
3746 LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
3747 while (NumVecElts > MVTLen) {
3748 NumVecElts /= 2;
3749 auto *SubTy = FixedVectorType::get(ScalarTy, NumVecElts);
3750
3751 ShuffleCost += thisT()->getShuffleCost(
3752 TTI::SK_ExtractSubvector, SubTy, Ty, CostKind, {}, NumVecElts, SubTy);
3753
3754 IntrinsicCostAttributes Attrs(IID, SubTy, {SubTy, SubTy}, FMF);
3755 MinMaxCost += getIntrinsicInstrCost(Attrs, CostKind);
3756 Ty = SubTy;
3757 ++LongVectorCount;
3758 }
3759
3760 NumReduxLevels -= LongVectorCount;
3761
3762 // The minimal length of the vector is limited by the real length of vector
3763 // operations performed on the current platform. That's why several final
3764 // reduction opertions are perfomed on the vectors with the same
3765 // architecture-dependent length.
3766 ShuffleCost +=
3767 NumReduxLevels * thisT()->getShuffleCost(TTI::SK_PermuteSingleSrc, Ty,
3768 Ty, CostKind, {}, 0, Ty);
3769 IntrinsicCostAttributes Attrs(IID, Ty, {Ty, Ty}, FMF);
3770 MinMaxCost += NumReduxLevels * getIntrinsicInstrCost(Attrs, CostKind);
3771 // The last min/max should be in vector registers and we counted it above.
3772 // So just need a single extractelement.
3773 return ShuffleCost + MinMaxCost +
3774 thisT()->getVectorInstrCost(Instruction::ExtractElement, Ty,
3775 CostKind, 0, nullptr, nullptr);
3776 }
3777
3779 getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy,
3780 VectorType *Ty, std::optional<FastMathFlags> FMF,
3781 TTI::TargetCostKind CostKind) const override {
3782 if (auto *FTy = dyn_cast<FixedVectorType>(Ty);
3783 FTy && IsUnsigned && Opcode == Instruction::Add &&
3784 FTy->getElementType() == IntegerType::getInt1Ty(Ty->getContext())) {
3785 // Represent vector_reduce_add(ZExt(<n x i1>)) as
3786 // ZExtOrTrunc(ctpop(bitcast <n x i1> to in)).
3787 auto *IntTy =
3788 IntegerType::get(ResTy->getContext(), FTy->getNumElements());
3789 IntrinsicCostAttributes ICA(Intrinsic::ctpop, IntTy, {IntTy},
3790 FMF ? *FMF : FastMathFlags());
3791 return thisT()->getCastInstrCost(Instruction::BitCast, IntTy, FTy,
3792 TTI::CastContextHint::None, CostKind) +
3793 thisT()->getIntrinsicInstrCost(ICA, CostKind);
3794 }
3795 // Without any native support, this is equivalent to the cost of
3796 // vecreduce.opcode(ext(Ty A)).
3797 VectorType *ExtTy = VectorType::get(ResTy, Ty);
3798 InstructionCost RedCost =
3799 thisT()->getArithmeticReductionCost(Opcode, ExtTy, FMF, CostKind);
3800 InstructionCost ExtCost = thisT()->getCastInstrCost(
3801 IsUnsigned ? Instruction::ZExt : Instruction::SExt, ExtTy, Ty,
3802 TTI::CastContextHint::None, CostKind);
3803
3804 return RedCost + ExtCost;
3805 }
3806
3808 getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode, Type *ResTy,
3809 VectorType *Ty,
3810 TTI::TargetCostKind CostKind) const override {
3811 // Without any native support, this is equivalent to the cost of
3812 // vecreduce.add(mul(ext(Ty A), ext(Ty B))) or
3813 // vecreduce.add(mul(A, B)).
3814 assert((RedOpcode == Instruction::Add || RedOpcode == Instruction::Sub) &&
3815 "The reduction opcode is expected to be Add or Sub.");
3816 VectorType *ExtTy = VectorType::get(ResTy, Ty);
3817 InstructionCost RedCost = thisT()->getArithmeticReductionCost(
3818 RedOpcode, ExtTy, std::nullopt, CostKind);
3819 InstructionCost ExtCost = thisT()->getCastInstrCost(
3820 IsUnsigned ? Instruction::ZExt : Instruction::SExt, ExtTy, Ty,
3821 TTI::CastContextHint::None, CostKind);
3822
3823 InstructionCost MulCost =
3824 thisT()->getArithmeticInstrCost(Instruction::Mul, ExtTy, CostKind);
3825
3826 return RedCost + MulCost + 2 * ExtCost;
3827 }
3828
3830 unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType,
3832 TTI::PartialReductionExtendKind OpBExtend, std::optional<unsigned> BinOp,
3833 TTI::TargetCostKind CostKind,
3834 std::optional<FastMathFlags> FMF) const override {
3835 unsigned EltSizeAcc = AccumType->getScalarSizeInBits();
3836 unsigned EltSizeInA = InputTypeA->getScalarSizeInBits();
3837 unsigned Ratio = EltSizeAcc / EltSizeInA;
3838 if (VF.getKnownMinValue() <= Ratio || VF.getKnownMinValue() % Ratio != 0 ||
3839 EltSizeAcc % EltSizeInA != 0 || (BinOp && InputTypeA != InputTypeB))
3841
3842 Type *InputVectorType = VectorType::get(InputTypeA, VF);
3843 Type *ExtInputVectorType = VectorType::get(AccumType, VF);
3844 Type *AccumVectorType =
3845 VectorType::get(AccumType, VF.divideCoefficientBy(Ratio));
3846
3847 InstructionCost ExtendCostA = 0;
3849 ExtendCostA = getCastInstrCost(
3851 ExtInputVectorType, InputVectorType, TTI::CastContextHint::None,
3852 CostKind);
3853
3854 // TODO: add cost of extracting subvectors from the source vector that
3855 // is to be partially reduced.
3856 InstructionCost ReductionOpCost =
3857 Ratio * getArithmeticInstrCost(Opcode, AccumVectorType, CostKind);
3858
3859 if (!BinOp)
3860 return ExtendCostA + ReductionOpCost;
3861
3862 InstructionCost ExtendCostB = 0;
3864 ExtendCostB = getCastInstrCost(
3866 ExtInputVectorType, InputVectorType, TTI::CastContextHint::None,
3867 CostKind);
3868 return ExtendCostA + ExtendCostB + ReductionOpCost +
3869 getArithmeticInstrCost(*BinOp, ExtInputVectorType, CostKind);
3870 }
3871
3873
3874 /// @}
3875};
3876
3877/// Concrete BasicTTIImpl that can be used if no further customization
3878/// is needed.
3879class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
3880 using BaseT = BasicTTIImplBase<BasicTTIImpl>;
3881
3882 friend class BasicTTIImplBase<BasicTTIImpl>;
3883
3884 const TargetSubtargetInfo *ST;
3885 const TargetLoweringBase *TLI;
3886
3887 const TargetSubtargetInfo *getST() const { return ST; }
3888 const TargetLoweringBase *getTLI() const { return TLI; }
3889
3890public:
3891 LLVM_ABI explicit BasicTTIImpl(const TargetMachine *TM, const Function &F);
3892};
3893
3894} // end namespace llvm
3895
3896#endif // LLVM_CODEGEN_BASICTTIIMPL_H
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const Function * getCalledFunction(const MachineInstr &MI)
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
int64_t C1
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file describes how to lower LLVM code to machine code.
This file provides helpers for the implementation of a TargetTransformInfo-conforming class.
This pass exposes codegen information to IR-level passes.
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:194
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
Definition ArrayRef.h:200
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
InstructionCost getFPOpCost(Type *Ty) const override
bool preferToKeepConstantsAttached(const Instruction &Inst, const Function &Fn) 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
InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) const override
Try to calculate op costs for min/max reduction operations.
bool isIndexedLoadLegal(TTI::MemIndexedMode M, Type *Ty) const override
unsigned getCallerAllocaCost(const CallBase *CB, const AllocaInst *AI) const override
InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
TypeSize getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const override
bool shouldBuildLookupTables() const override
bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const override
bool isProfitableToHoist(Instruction *I) const override
unsigned getNumberOfParts(Type *Tp) const override
unsigned getMinPrefetchStride(unsigned NumMemAccesses, unsigned NumStridedMemAccesses, unsigned NumPrefetches, bool HasCall) const override
InstructionCost getBitInsertCost(Type *Base, Type *Val, TTI::TargetCostKind CostKind, TTI::OperandValueInfo OffsetInfo, ArrayRef< const Value * > Args, const Instruction *CtxI) const override
bool useAA() const override
unsigned getPrefetchDistance() const override
TTI::ShuffleKind improveShuffleKindFromMask(TTI::ShuffleKind Kind, ArrayRef< int > Mask, VectorType *SrcTy, int &Index, VectorType *&SubTy) const
InstructionCost getOperandsScalarizationOverhead(ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
Estimate the overhead of scalarizing an instruction's operands.
bool isLegalAddScalableImmediate(int64_t Imm) const override
unsigned getAssumedAddrSpace(const Value *V) const override
std::optional< Value * > simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed) const override
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 addrspacesMayAlias(unsigned AS0, unsigned AS1) const override
bool areInlineCompatible(const Function *Caller, const Function *Callee) const override
bool isIndexedStoreLegal(TTI::MemIndexedMode M, Type *Ty) const override
bool haveFastSqrt(Type *Ty) const override
bool collectFlatAddressOperands(SmallVectorImpl< int > &OpIndexes, Intrinsic::ID IID) const override
unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JumpTableSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) const override
unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy, Type *ScalarValTy, Align Alignment, unsigned AddrSpace) const override
Value * rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV, Value *NewV) const override
unsigned adjustInliningThreshold(const CallBase *CB) const override
unsigned getInliningThresholdMultiplier() 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
Estimate the overhead of scalarizing an instruction.
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index, Value *Scalar, ArrayRef< std::tuple< Value *, User *, int > > ScalarUserAndIdx, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset, int64_t MaxOffset)
bool shouldBuildRelLookupTables() const override
bool isTargetIntrinsicWithStructReturnOverloadAtField(Intrinsic::ID ID, int RetIdx) 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 getVectorInstrCost(const Instruction &I, Type *Val, TTI::TargetCostKind CostKind, unsigned Index, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, StackOffset BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace) const override
unsigned getEpilogueVectorizationMinVF() const override
InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy, unsigned Index, TTI::TargetCostKind CostKind) const override
InstructionCost getVectorSplitCost() const
bool isTruncateFree(Type *Ty1, Type *Ty2) const override
unsigned getFlatAddressSpace() const override
InstructionCost getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind) const override
Compute a cost of the given call instruction.
void getUnrollingPreferences(Loop *L, ScalarEvolution &SE, TTI::UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const override
InstructionCost getTreeReductionCost(unsigned Opcode, VectorType *Ty, TTI::TargetCostKind CostKind) const
Try to calculate arithmetic and shuffle op costs for reduction intrinsics.
~BasicTTIImplBase() override=default
std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const override
unsigned getMaxPrefetchIterationsAhead() const override
unsigned getMaxInterleaveFactor(ElementCount VF, bool HasUnorderedReductions) const override
void getPeelingPreferences(Loop *L, ScalarEvolution &SE, TTI::PeelingPreferences &PP) const override
InstructionCost getTypeBasedIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
Get intrinsic cost based on argument types.
bool hasBranchDivergence(const Function *F=nullptr) const override
InstructionCost getOrderedReductionCost(unsigned Opcode, VectorType *Ty, TTI::TargetCostKind CostKind) const
Try to calculate the cost of performing strict (in-order) reductions, which involves doing a sequence...
std::optional< unsigned > getCacheAssociativity(TargetTransformInfo::CacheLevel Level) const override
InstructionCost getBitExtractCost(Type *Dst, Type *Src, TTI::TargetCostKind CostKind, TTI::OperandValueInfo OffsetInfo, ArrayRef< const Value * > Args, const Instruction *CtxI) const override
bool shouldPrefetchAddressSpace(unsigned AS) const override
bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth, unsigned AddressSpace, Align Alignment, unsigned *Fast) const override
unsigned getCacheLineSize() const override
std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const override
bool shouldDropLSRSolutionIfLessProfitable() const override
int getInlinerVectorBonusPercent() const override
InstructionCost getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode, Type *ResTy, VectorType *Ty, TTI::TargetCostKind CostKind) const override
InstructionCost getShuffleCost(TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask, int Index, VectorType *SubTp, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const override
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
std::pair< InstructionCost, MVT > getTypeLegalizationCost(Type *Ty) const
Estimate the cost of type-legalization and the legalized type.
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
bool isLegalAddImmediate(int64_t imm) const override
InstructionCost getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF, const APInt &DemandedDstElts, TTI::TargetCostKind CostKind) const override
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
bool isProfitableLSRChainElement(Instruction *I) const override
bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const override
bool isTargetIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx) const override
bool isTargetIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx) const override
std::optional< unsigned > getVScaleForTuning() 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
Get intrinsic cost based on arguments.
bool preferTailFoldingOverEpilogue(TailFoldingInfo *TFI) const override
std::optional< Value * > simplifyDemandedVectorEltsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp) const override
InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *, const SCEV *, TTI::TargetCostKind) const override
bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) const override
InstructionCost getScalarizationOverhead(VectorType *RetTy, ArrayRef< const Value * > Args, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind) const
Estimate the overhead of scalarizing the inputs and outputs of an instruction, with return type RetTy...
TailFoldingStyle getPreferredTailFoldingStyle() const override
std::optional< unsigned > getCacheSize(TargetTransformInfo::CacheLevel Level) const override
bool isLegalICmpImmediate(int64_t imm) const override
InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands, TTI::TargetCostKind CostKind, Type *AccessType) const override
bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE, AssumptionCache &AC, TargetLibraryInfo *LibInfo, HardwareLoopInfo &HWLoopInfo) const override
unsigned getRegUsageForType(Type *Ty) const override
InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const override
Get memory intrinsic cost based on arguments.
BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
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
bool enableWritePrefetching() const override
bool isLSRCostLess(const TTI::LSRCost &C1, const TTI::LSRCost &C2) 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 *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const override
InstructionCost getScalarizationOverhead(VectorType *InTy, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
Helper wrapper for the DemandedElts variant of getScalarizationOverhead.
InstructionCost getBranchMispredictPenalty() const override
bool isNumRegsMajorCostOfLSR() const override
LLVM_ABI BasicTTIImpl(const TargetMachine *TM, const Function &F)
size_type count() const
Returns the number of bits which are set.
Definition BitVector.h:182
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
static CmpInst::Predicate getGTPredicate(Intrinsic::ID ID)
static CmpInst::Predicate getLTPredicate(Intrinsic::ID ID)
This class represents a range of values.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:321
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
Container class for subtarget features.
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
The core instruction combiner logic.
static InstructionCost getInvalid(CostType Val=0)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
const SmallVectorImpl< Type * > & getArgTypes() const
const SmallVectorImpl< const Value * > & getArgs() const
InstructionCost getScalarizationCost() const
const IntrinsicInst * getInst() const
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
const FeatureBitset & getFeatureBits() const
Machine Value Type.
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Information for memory intrinsic cost model.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
Analysis providing profile information.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
static LLVM_ABI bool isZeroEltSplatMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses all elements with the same value as the first element of exa...
static LLVM_ABI bool isSpliceMask(ArrayRef< int > Mask, int NumSrcElts, int &Index)
Return true if this shuffle mask is a splice mask, concatenating the two inputs together and then ext...
static LLVM_ABI bool isSelectMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from its source vectors without lane crossings.
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 isReverseMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask swaps the order of elements from exactly one source vector.
static LLVM_ABI bool isTransposeMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask is a transpose mask.
static LLVM_ABI bool isInsertSubvectorMask(ArrayRef< int > Mask, int NumSrcElts, int &NumSubElts, int &Index)
Return true if this shuffle mask is an insert subvector mask.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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...
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:31
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:40
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:657
Multiway switch.
Provides information about what library functions are available for the current target.
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
LegalizeAction
This enum indicates whether operations are valid for a target, and if not, what action should be used...
LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Return how this store with truncation should be treated: either it is legal, needs to be promoted to ...
LegalizeAction getLoadAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return how this load with extension should be treated: either it is legal, needs to be promoted to a ...
LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const
Return pair that represents the legalization kind (first) that needs to happen to EVT (second) in ord...
std::pair< LegalizeTypeAction, EVT > LegalizeKind
LegalizeKind holds the legalization kind that needs to happen to EVT in order to type-legalize it.
Primary interface to the complete machine description for the target machine.
bool isPositionIndependent() const
const Triple & getTargetTriple() const
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
CodeModel::Model getCodeModel() const
Returns the code model.
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const FeatureBitset & getInlineMustMatchFeatures() const =0
Target features where all mismatches prevent inlining.
virtual const FeatureBitset & getInlineInverseFeatures() const =0
Target features where the callee may have an additional feature, instead of the caller.
virtual const FeatureBitset & getInlineIgnoreFeatures() const =0
Target features to ignore for inline compatibility check.
virtual bool isProfitableLSRChainElement(Instruction *I) const
virtual TailFoldingStyle getPreferredTailFoldingStyle() const
virtual const DataLayout & getDataLayout() const
virtual std::optional< unsigned > getCacheAssociativity(TargetTransformInfo::CacheLevel Level) const
virtual 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
virtual bool shouldDropLSRSolutionIfLessProfitable() const
virtual bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE, AssumptionCache &AC, TargetLibraryInfo *LibInfo, HardwareLoopInfo &HWLoopInfo) const
virtual std::optional< Value * > simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed) const
virtual bool preferTailFoldingOverEpilogue(TailFoldingInfo *TFI) const
virtual InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info, TTI::OperandValueInfo Opd2Info, ArrayRef< const Value * > Args, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const
virtual std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const
virtual unsigned getEpilogueVectorizationMinVF() const
virtual 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
virtual bool isLoweredToCall(const Function *F) const
virtual InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const
virtual bool isLSRCostLess(const TTI::LSRCost &C1, const TTI::LSRCost &C2) const
virtual InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I) const
virtual InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
virtual InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info, TTI::OperandValueInfo Op2Info, const Instruction *I) const
InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands, TTI::TargetCostKind CostKind, Type *AccessType) const override
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
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_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...
llvm::VectorInstrContext VectorInstrContext
@ TCC_Expensive
The cost of a 'div' instruction on x86.
@ TCC_Free
Expected to fold away in lowering.
@ TCC_Basic
The cost of a typical 'add' instruction.
static LLVM_ABI Instruction::CastOps getOpcodeForPartialReductionExtendKind(PartialReductionExtendKind Kind)
Get the cast opcode for an extension kind.
MemIndexedMode
The type of load/store indexing.
static LLVM_ABI VectorInstrContext getVectorInstrContextHint(const Instruction *I)
Calculates a VectorInstrContext from I.
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.
@ Normal
The cast is used with a normal load/store.
CacheLevel
The possible cache levels.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition Triple.h:517
LLVM_ABI bool isArch64Bit() const
Test whether the architecture is 64-bit.
Definition Triple.cpp:1841
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Definition Triple.h:726
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
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
static LLVM_ABI Type * getIntFromByteType(Type *)
Returns an integer (vector of integer) type with the same size of a byte of the given byte (vector of...
Definition Type.cpp:302
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition Type.h:399
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Value * getOperand(unsigned i) const
Definition User.h:207
static LLVM_ABI std::optional< unsigned > getFunctionalOpcodeForVP(Intrinsic::ID ID)
static LLVM_ABI std::optional< Intrinsic::ID > getFunctionalIntrinsicIDForVP(Intrinsic::ID ID)
static LLVM_ABI bool isVPIntrinsic(Intrinsic::ID)
static LLVM_ABI bool isVPReduction(Intrinsic::ID ID)
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
Base class of all SIMD vector types.
static VectorType * getHalfElementsVectorType(VectorType *VTy)
This static method returns a VectorType with half as many elements as the input type and the same ele...
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
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:201
constexpr ScalarTy getKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns a value X where RHS*X will result in a value whose quantity matches our own.
Definition TypeSize.h:274
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:217
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:253
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3052
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:26
@ MASK_BEFOREFIRST
Has one mask vector operand.
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:397
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ FMODF
FMODF - Decomposes the operand into integral and fractional parts, each having the same type and sign...
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ FSINCOSPI
FSINCOSPI - Compute both the sine and cosine times pi more accurately than FSINCOS(pi*x),...
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:802
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ BRIND
BRIND - Indirect branch.
@ BR_JT
BR_JT - Jumptable branch.
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Same as FMINNUM/FMAXNUM, except that a signaling NaN operand deterministi...
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:389
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ MASKED_UDIV
Masked vector arithmetic that returns poison on disabled lanes.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:807
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:759
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:977
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
LLVM_ABI bool isTargetIntrinsic(ID IID)
isTargetIntrinsic - Returns true if IID is an intrinsic specific to a certain target.
DiagnosticInfoOptimizationBase::Argument NV
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
InstructionCost Cost
@ Known
Known to have no common set bits.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
Type * toScalarizedTy(Type *Ty)
A helper for converting vectorized types to scalarized (non-vector) types.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ABI unsigned getArithmeticReductionInstruction(Intrinsic::ID RdxID)
Returns the arithmetic instruction opcode used when expanding a reduction.
bool isVectorizedTy(Type *Ty)
Returns true if Ty is a vector type or a struct of vector types where all vector types share the same...
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1167
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI std::optional< unsigned > getPartialUnrollingThreshold()
Returns -partial-unrolling-threshold if specified.
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
ElementCount getVectorizedTypeVF(Type *Ty)
Returns the number of vector elements for a vectorized type.
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
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
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
@ Fast
Assign the register banks as fast as possible (default).
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
ArrayRef< Type * > getContainedTypes(Type *const &Ty)
Returns the types contained in Ty.
LLVM_ABI bool isVectorizedStructTy(StructType *StructTy)
Returns true if StructTy is an unpacked literal struct where all elements are vectors of matching ele...
#define N
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:160
ElementCount getVectorElementCount() const
Definition ValueTypes.h:388
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
Attributes of a target dependent hardware loop.
static bool hasVectorMaskArgument(RTLIB::LibcallImpl Impl)
Returns true if the function has a vector mask argument, which is assumed to be the last argument.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
bool AllowPeeling
Allow peeling off loop iterations.
bool AllowLoopNestsPeeling
Allow peeling off loop iterations for loop nests.
bool PeelProfiledIterations
Allow peeling basing on profile.
unsigned PeelCount
A forced peeling factor (the number of bodied of the original loop that should be peeled off before t...
Parameters that control the generic loop unrolling transformation.
bool UpperBound
Allow using trip count upper bound to unroll loops.
unsigned PartialOptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size, like OptSizeThreshold,...
unsigned PartialThreshold
The cost threshold for the unrolled loop, like Threshold, but used for partial/runtime unrolling (set...
bool Runtime
Allow runtime unrolling (unrolling of loops to expand the size of the loop body even when the number ...
bool Partial
Allow partial unrolling (unrolling of loops to expand the size of the loop body, not only to eliminat...
unsigned OptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size (set to UINT_MAX to disable).