LLVM 24.0.0git
SLPCostAnalysis.cpp
Go to the documentation of this file.
1//===- SLPCostAnalysis.cpp - SLP Vectorizer free cost helpers -------------===//
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#include "SLPCostAnalysis.h"
10#include "SLPTypeUtils.h"
11#include "SLPUtils.h"
12
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/Sequence.h"
20#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/Operator.h"
27#include "llvm/IR/Type.h"
28#include "llvm/IR/Value.h"
32
33#include <cassert>
34#include <utility>
35
36using namespace llvm;
37using namespace llvm::PatternMatch;
38
39namespace llvm::slpvectorizer {
40
42 const DataLayout &DL, bool IsReverse) {
43 assert(Stride && "Expected a valid Stride");
44 uint64_t ElementSize = DL.getTypeAllocSize(ScalarTy).getFixedValue();
45 APInt Bytes = Stride->getValue() * ElementSize;
46 return ConstantInt::get(Stride->getContext(), IsReverse ? -Bytes : Bytes);
47}
48
51 const TTI::TargetCostKind CostKind,
52 ArrayRef<int> Mask, int Index, VectorType *SubTp,
55 VectorType *DstTy = Tp;
56 if (!Mask.empty())
57 DstTy = FixedVectorType::get(Tp->getScalarType(), Mask.size());
58
59 if (Kind != TTI::SK_PermuteTwoSrc)
60 return TTI.getShuffleCost(Kind, DstTy, Tp, CostKind, Mask, Index, SubTp,
61 Args, /*CtxI=*/nullptr, VIC);
62 int NumSrcElts = Tp->getElementCount().getKnownMinValue();
63 int NumSubElts;
64 if (Mask.size() > 2 && ShuffleVectorInst::isInsertSubvectorMask(
65 Mask, NumSrcElts, NumSubElts, Index)) {
66 if (Index + NumSubElts > NumSrcElts &&
67 Index + NumSrcElts <= static_cast<int>(Mask.size()))
68 return TTI.getShuffleCost(TTI::SK_InsertSubvector, DstTy, Tp, CostKind,
69 Mask, Index, Tp);
70 }
71 return TTI.getShuffleCost(Kind, DstTy, Tp, CostKind, Mask, Index, SubTp, Args,
72 /*CtxI=*/nullptr, VIC);
73}
74
76 const TargetTransformInfo &TTI, const DataLayout &DL, Value *StrideVal,
77 Type *StridedLoadTy, Type *VecTy, Type *ScalarTy, Value *Ptr,
79 TargetTransformInfo::TargetCostKind CostKind, bool IsReverse) {
80 Value *Stride = nullptr;
81 if (auto *ConstStrideVal = dyn_cast_if_present<ConstantInt>(StrideVal))
82 Stride = getStrideBytesForConstant(ConstStrideVal, ScalarTy, DL, IsReverse);
83 InstructionCost StridedCost = TTI.getMemIntrinsicInstrCost(
84 MemIntrinsicCostAttributes(Intrinsic::experimental_vp_strided_load,
85 StridedLoadTy, Ptr,
86 /*VariableMask=*/false, CommonAlignment,
87 /*I=*/nullptr, Stride),
88 CostKind);
89 if (StridedLoadTy != VecTy)
90 StridedCost +=
91 getWidenedStridedCastCost(TTI, StridedLoadTy, VecTy, DL, Ctx, CostKind);
92 return StridedCost;
93}
94
97 const CompressedLoadInfo &Info,
99 if (Info.InterleaveFactor) {
100 assert(!Info.IsMasked && "Masked interleaved loads are not supported");
101 return TTI.getInterleavedMemoryOpCost(
102 Instruction::Load, Info.LoadVecTy, Info.InterleaveFactor, {},
103 LI0->getAlign(), LI0->getPointerAddressSpace(), CostKind);
104 }
105
107 if (Info.IsMasked) {
108 Cost = TTI.getMemIntrinsicInstrCost(
109 MemIntrinsicCostAttributes(Intrinsic::masked_load, Info.LoadVecTy,
110 LI0->getAlign(),
112 CostKind);
113 } else {
114 Cost = TTI.getMemoryOpCost(
115 Instruction::Load, Info.LoadVecTy, LI0->getAlign(),
116 LI0->getPointerAddressSpace(), CostKind,
118 }
119 // For REVEC the emitted shuffle uses the compress mask expanded to the
120 // individual elements of the vector scalars.
121 SmallVector<int> CompressCostMask(Info.CompressMask);
123 CompressCostMask);
124 // TODO: include this cost into CommonCost.
126 CostKind, CompressCostMask);
127 return Cost;
128}
129
130std::pair<InstructionCost, InstructionCost>
132 Value *BasePtr, unsigned Opcode, const TTI::TargetCostKind CostKind,
133 Type *ScalarTy, VectorType *VecTy) {
134 InstructionCost ScalarCost = 0;
135 InstructionCost VecCost = 0;
136 // Here we differentiate two cases: (1) when Ptrs represent a regular
137 // vectorization tree node (as they are pointer arguments of scattered
138 // loads) or (2) when Ptrs are the arguments of loads or stores being
139 // vectorized as plane wide unit-stride load/store since all the
140 // loads/stores are known to be from/to adjacent locations.
141 if (Opcode == Instruction::Load || Opcode == Instruction::Store) {
142 // Case 2: estimate costs for pointer related costs when vectorizing to
143 // a wide load/store.
144 // Scalar cost is estimated as a set of pointers with known relationship
145 // between them.
146 // For vector code we will use BasePtr as argument for the wide load/store
147 // but we also need to account all the instructions which are going to
148 // stay in vectorized code due to uses outside of these scalar
149 // loads/stores.
150 ScalarCost = TTI.getPointersChainCost(
151 Ptrs, BasePtr, TTI::PointersChainInfo::getUnitStride(), ScalarTy,
152 CostKind);
153
154 SmallVector<const Value *> PtrsRetainedInVecCode;
155 for (Value *V : Ptrs) {
156 if (V == BasePtr) {
157 PtrsRetainedInVecCode.push_back(V);
158 continue;
159 }
160 auto *Ptr = dyn_cast<GetElementPtrInst>(V);
161 // For simplicity assume Ptr to stay in vectorized code if it's not a
162 // GEP instruction. We don't care since it's cost considered free.
163 // TODO: We should check for any uses outside of vectorizable tree
164 // rather than just single use.
165 if (!Ptr || !Ptr->hasOneUse())
166 PtrsRetainedInVecCode.push_back(V);
167 }
168
169 if (PtrsRetainedInVecCode.size() == Ptrs.size()) {
170 // If all pointers stay in vectorized code then we don't have
171 // any savings on that.
172 return std::make_pair(TTI::TCC_Free, TTI::TCC_Free);
173 }
174 VecCost = TTI.getPointersChainCost(PtrsRetainedInVecCode, BasePtr,
175 TTI::PointersChainInfo::getKnownStride(),
176 VecTy, CostKind);
177 } else {
178 // Case 1: Ptrs are the arguments of loads that we are going to transform
179 // into masked gather load intrinsic.
180 // All the scalar GEPs will be removed as a result of vectorization.
181 // For any external uses of some lanes extract element instructions will
182 // be generated (which cost is estimated separately).
183 TTI::PointersChainInfo PtrsInfo =
184 all_of(Ptrs,
185 [](const Value *V) {
186 auto *Ptr = dyn_cast<GetElementPtrInst>(V);
187 return Ptr && !Ptr->hasAllConstantIndices();
188 })
189 ? TTI::PointersChainInfo::getUnknownStride()
190 : TTI::PointersChainInfo::getKnownStride();
191
192 const bool IsSameBase =
194 all_equal(map_range(Ptrs, [](Value *V) {
195 return cast<GetElementPtrInst>(V)->getPointerOperand();
196 }));
197 // The GEPs of the masked gather loads are accessed with the loaded type
198 // and form a chain only if the lanes share the base.
199 Type *AccessTy = ScalarTy;
200 if (all_of(Ptrs, [](const Value *V) {
201 auto *Ptr = dyn_cast<GetElementPtrInst>(V);
202 return Ptr && Ptr->hasOneUse() && isa<LoadInst>(Ptr->user_back());
203 })) {
204 PtrsInfo.IsSameBaseAddress = IsSameBase;
205 AccessTy = Ptrs.front()->user_back()->getType();
206 }
207 ScalarCost =
208 TTI.getPointersChainCost(Ptrs, BasePtr, PtrsInfo, AccessTy, CostKind);
209 auto *BaseGEP = dyn_cast<GEPOperator>(BasePtr);
210 if (!BaseGEP) {
211 auto *It = find_if(Ptrs, IsaPred<GEPOperator>);
212 if (It != Ptrs.end())
213 BaseGEP = cast<GEPOperator>(*It);
214 }
215 if (!IsSameBase) {
216 // The different bases are not folded into the addressing of the vector
217 // access, the scaled indices are added to them.
218 const DataLayout &DL = cast<Instruction>(Ptrs.front())->getDataLayout();
219 Type *IdxTy = DL.getIndexType(VecTy);
220 VecCost = TTI.getArithmeticInstrCost(Instruction::Add, IdxTy, CostKind);
221 uint64_t Stride = DL.getTypeAllocSize(BaseGEP->getSourceElementType())
222 .getKnownMinValue();
223 if (Stride != 1 && !all_of(Ptrs, [](Value *V) {
224 return isa<Constant>(cast<GetElementPtrInst>(V)->getOperand(1));
225 }))
226 VecCost += TTI.getArithmeticInstrCost(
227 isPowerOf2_64(Stride) ? Instruction::Shl : Instruction::Mul, IdxTy,
229 } else if (BaseGEP) {
230 SmallVector<const Value *> Indices(BaseGEP->indices());
231 VecCost = TTI.getGEPCost(BaseGEP->getSourceElementType(),
232 BaseGEP->getPointerOperand(), Indices, CostKind,
233 VecTy);
234 }
235 }
236
237 return std::make_pair(ScalarCost, VecCost);
238}
239
241 Align Alignment, unsigned AddressSpace,
242 const TTI::TargetCostKind CostKind) {
243 Type *CmpTy = CmpInst::makeCmpResultType(VecTy);
244 return 2 * TTI.getMemIntrinsicInstrCost(
245 MemIntrinsicCostAttributes(Intrinsic::masked_load, VecTy,
246 Alignment, AddressSpace),
247 CostKind) +
248 TTI.getArithmeticInstrCost(Instruction::Xor, CmpTy, CostKind) +
249 TTI.getCmpSelInstrCost(Instruction::Select, VecTy, CmpTy,
251}
252
254 Type *SrcTy, Type *DstTy,
255 const DataLayout &DL,
257 TTI::TargetCostKind CostKind) {
258 bool ToPtr = cast<VectorType>(DstTy)->getElementType()->isPointerTy();
259 if (ToPtr == cast<VectorType>(SrcTy)->getElementType()->isPointerTy())
260 return TTI.getCastInstrCost(Instruction::BitCast, DstTy, SrcTy, CCH,
261 CostKind);
262 // The ptr/int conversion keeps the vector shape, the bitcast transforms the
263 // resulting integer vector.
264 if (ToPtr) {
265 Type *IntVecTy = DL.getIntPtrType(DstTy);
266 return TTI.getCastInstrCost(Instruction::IntToPtr, DstTy, IntVecTy, CCH,
267 CostKind) +
268 TTI.getCastInstrCost(Instruction::BitCast, IntVecTy, SrcTy, CCH,
269 CostKind);
270 }
271 Type *IntVecTy = DL.getIntPtrType(SrcTy);
272 return TTI.getCastInstrCost(Instruction::PtrToInt, IntVecTy, SrcTy, CCH,
273 CostKind) +
274 TTI.getCastInstrCost(Instruction::BitCast, DstTy, IntVecTy, CCH,
275 CostKind);
276}
277
279 VectorType *VecTy,
280 const std::pair<uint64_t, bool> &MinBW,
282 TTI::TargetCostKind CostKind) {
283 unsigned BWSz = MinBW.first;
284 unsigned DstBWSz = VecTy->getScalarSizeInBits();
285 unsigned VecOpcode;
286 if (DstBWSz < BWSz)
287 VecOpcode = Instruction::Trunc;
288 else
289 VecOpcode = MinBW.second ? Instruction::SExt : Instruction::ZExt;
290 return TTI.getCastInstrCost(VecOpcode, VecTy, VecTy->getWithNewBitWidth(BWSz),
291 CCH, CostKind);
292}
293
295 unsigned Opcode, Type *ScalarTy,
296 unsigned NumElts,
297 const TTI::TargetCostKind CostKind,
298 FixedVectorType **PaddedTy) {
299 FixedVectorType *PaddedVecTy =
300 getMaskedDivRemType(TTI, Opcode, ScalarTy, NumElts, ReVec);
301 if (!PaddedVecTy)
303 // One mask bit per element of the padded vector, not per padded lane.
304 auto *MaskTy =
306 PaddedVecTy->getNumElements());
307 InstructionCost DirectCost = TTI.getArithmeticInstrCost(
308 Opcode, getWidenedType(ScalarTy, NumElts), CostKind);
309 IntrinsicCostAttributes ICA(getMaskedDivRemIntrinsic(Opcode), PaddedVecTy,
310 {PaddedVecTy, PaddedVecTy, MaskTy});
311 InstructionCost MaskedCost = TTI.getIntrinsicInstrCost(ICA, CostKind);
312 if (!MaskedCost.isValid() || MaskedCost >= DirectCost)
314 if (PaddedTy)
315 *PaddedTy = PaddedVecTy;
316 return MaskedCost;
317}
318
321 Type *ScalarTy, VectorType *Ty,
322 const APInt &DemandedElts, bool Insert, bool Extract,
323 const TTI::TargetCostKind CostKind, bool ForPoisonSrc,
326 "ScalableVectorType is not supported.");
327 assert(getNumElements(ScalarTy) * DemandedElts.getBitWidth() ==
328 getNumElements(Ty) &&
329 "Incorrect usage.");
330 if (auto *VecTy = dyn_cast<FixedVectorType>(ScalarTy)) {
331 assert(ReVec && "Only supported by REVEC.");
332 // If ScalarTy is FixedVectorType, we should use CreateInsertVector instead
333 // of CreateInsertElement.
334 unsigned ScalarTyNumElements = VecTy->getNumElements();
336 for (unsigned I : seq(DemandedElts.getBitWidth())) {
337 if (!DemandedElts[I])
338 continue;
339 if (Insert)
340 Cost += getShuffleCost(TTI, TTI::SK_InsertSubvector, Ty, CostKind, {},
341 I * ScalarTyNumElements, VecTy);
342 if (Extract)
343 Cost += getShuffleCost(TTI, TTI::SK_ExtractSubvector, Ty, CostKind, {},
344 I * ScalarTyNumElements, VecTy);
345 }
346 return Cost;
347 }
348 return TTI.getScalarizationOverhead(Ty, DemandedElts, Insert, Extract,
349 CostKind, ForPoisonSrc, VL, VIC);
350}
351
353 const TargetTransformInfo &TTI, bool ReVec, Type *ScalarTy, unsigned Opcode,
354 Type *Val, const TTI::TargetCostKind CostKind, unsigned Index,
355 Value *Scalar, ArrayRef<std::tuple<Value *, User *, int>> ScalarUserAndIdx,
357 if (Opcode == Instruction::ExtractElement) {
358 if (auto *VecTy = dyn_cast<FixedVectorType>(ScalarTy)) {
359 assert(ReVec && "Only supported by REVEC.");
360 assert(isa<VectorType>(Val) && "Val must be a vector type.");
362 cast<VectorType>(Val), CostKind, {},
363 Index * VecTy->getNumElements(), VecTy);
364 }
365 }
366 return TTI.getVectorInstrCost(Opcode, Val, CostKind, Index, Scalar,
367 ScalarUserAndIdx, VIC);
368}
369
371 bool ReVec, unsigned Opcode, Type *Dst,
372 VectorType *VecTy, unsigned Index,
373 const TTI::TargetCostKind CostKind) {
374 if (isVectorizedTy(Dst)) {
375 assert(ReVec && "Only supported by REVEC.");
376 auto *SubTp = cast<FixedVectorType>(
378 return getShuffleCost(TTI, TTI::SK_ExtractSubvector, VecTy, CostKind, {},
379 Index * getNumElements(Dst), SubTp) +
380 TTI.getCastInstrCost(Opcode, Dst, SubTp, TTI::CastContextHint::None,
381 CostKind);
382 }
383 return TTI.getExtractWithExtendCost(Opcode, Dst, VecTy, Index, CostKind);
384}
385
386/// Returns the cast context hint for the trunc of the booleanized reduction
387/// result, which inherits the uses of the reduction root \p Root.
400
402 RecurKind RdxKind,
403 FixedVectorType *VecTy,
404 const Value *Root, FastMathFlags FMF,
405 const TTI::TargetCostKind CostKind) {
406 Type *I1Ty = Type::getInt1Ty(VecTy->getContext());
407 return TTI.getArithmeticReductionCost(
408 RecurrenceDescriptor::getOpcode(RdxKind), VecTy, FMF, CostKind) +
409 TTI.getCastInstrCost(Instruction::Trunc, I1Ty, VecTy->getScalarType(),
410 getBoolReduxResultCCH(Root), CostKind);
411}
412
414 RecurKind RdxKind,
415 FixedVectorType *VecTy,
416 const Value *Root,
417 ArrayRef<Instruction *> ChainInsts,
418 const TTI::TargetCostKind CostKind) {
419 // The new instructions are costed in the context of the replaced cast chain
420 // instructions.
421 auto TruncIt =
422 find_if(ChainInsts, [](Instruction *I) { return isa<TruncInst>(I); });
423 const Instruction *TruncI = TruncIt == ChainInsts.end() ? nullptr : *TruncIt;
424 auto CmpIt =
425 find_if(ChainInsts, [](Instruction *I) { return isa<ICmpInst>(I); });
426 const Instruction *CmpI = CmpIt == ChainInsts.end() ? nullptr : *CmpIt;
427 unsigned VF = VecTy->getNumElements();
428 auto *I1VecTy =
430 Type *IntTy = IntegerType::get(VecTy->getContext(), VF);
431 Constant *CmpRHS = RdxKind == RecurKind::And
433 : Constant::getNullValue(IntTy);
434 return TTI.getCastInstrCost(Instruction::Trunc, I1VecTy, VecTy,
435 TTI.getCastContextHint(TruncI), CostKind,
436 TruncI) +
437 TTI.getCastInstrCost(Instruction::BitCast, IntTy, I1VecTy,
438 TTI.getCastContextHint(TruncI), CostKind) +
439 TTI.getCmpSelInstrCost(
440 Instruction::ICmp, IntTy, CmpInst::makeCmpResultType(IntTy),
442 CostKind, TTI.getOperandInfo(Root), TTI.getOperandInfo(CmpRHS),
443 CmpI);
444}
445
446static InstructionCost
449 TTI::TargetCostKind CostKind) {
450 assert((Kind == RecurKind::And || Kind == RecurKind::Or) &&
451 VectorTy->getElementType()->isIntegerTy(1) &&
452 "Expected and/or reduction of i1");
453 auto *IntTy =
454 IntegerType::get(VectorTy->getContext(), getNumElements(VectorTy));
455 CmpInst::Predicate Pred =
457 // The compare is against the all-ones (and) or zero (or) constant.
458 return TTI.getCastInstrCost(Instruction::BitCast, IntTy, VectorTy, Ctx,
459 CostKind) +
460 TTI.getCmpSelInstrCost(Instruction::ICmp, IntTy,
461 CmpInst::makeCmpResultType(IntTy), Pred,
462 CostKind, /*Op1Info=*/{},
464}
465
466std::pair<InstructionCost, bool>
468 FixedVectorType *VectorTy, Type *ScalarTy,
470 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
471 if (Kind == RecurKind::And || Kind == RecurKind::Or) {
472 InstructionCost RdxCost = TTI.getArithmeticReductionCost(
473 RdxOpcode, VectorTy, std::nullopt, CostKind);
474 InstructionCost BitcastCost =
475 getBoolLogicRdxBitcastCost(Kind, TTI, VectorTy, Ctx, CostKind);
476 return {std::min(RdxCost, BitcastCost), BitcastCost < RdxCost};
477 }
478 assert(Kind == RecurKind::Add && !ScalarTy->isIntegerTy(1) &&
479 "Expected add reduction of zexted i1 values");
480 // The bitcast+ctpop form is estimated as the cheaper of the extended
481 // reduction cost, which models it for the zexted i1 add reduction, and the
482 // explicitly priced components, including the cast of the ctpop result to
483 // the destination type.
484 auto *IntTy =
485 IntegerType::get(VectorTy->getContext(), getNumElements(VectorTy));
486 InstructionCost ExplicitCost =
487 TTI.getCastInstrCost(Instruction::BitCast, IntTy, VectorTy, Ctx,
488 CostKind) +
489 TTI.getIntrinsicInstrCost(
490 IntrinsicCostAttributes(Intrinsic::ctpop, IntTy, {IntTy}), CostKind);
491 if (IntTy != ScalarTy)
492 ExplicitCost += TTI.getCastInstrCost(IntTy->getBitWidth() <
493 ScalarTy->getIntegerBitWidth()
494 ? Instruction::ZExt
495 : Instruction::Trunc,
496 ScalarTy, IntTy, Ctx, CostKind);
497 InstructionCost CtpopCost = std::min(
498 TTI.getExtendedReductionCost(RdxOpcode, /*IsUnsigned=*/true, ScalarTy,
499 VectorTy, std::nullopt, CostKind),
500 ExplicitCost);
501 // The plain form is the zext to the wide vector type plus the reduction.
502 auto *ExtTy = VectorType::get(ScalarTy, VectorTy);
503 InstructionCost ExtRdxCost =
504 TTI.getCastInstrCost(Instruction::ZExt, ExtTy, VectorTy, Ctx, CostKind) +
505 TTI.getArithmeticReductionCost(RdxOpcode, ExtTy, std::nullopt, CostKind);
506 return {std::min(ExtRdxCost, CtpopCost), CtpopCost <= ExtRdxCost};
507}
508
510 FixedVectorType *SrcTy, Type *ResultTy,
511 const BitPackInfo &Info, unsigned ZExtSrcWidth,
513 TTI::TargetCostKind CostKind,
514 const TargetLibraryInfo *TLI,
515 const Instruction *CtxI, unsigned &ShiftWidth) {
516 unsigned BitWidth = SrcTy->getScalarSizeInBits();
517 unsigned NumElts = SrcTy->getNumElements();
518 uint64_t MaxAmt = *max_element(Info.LShrAmts);
519 // The shift amounts form a constant vector.
520 TTI::OperandValueInfo ShiftAmtInfo = {
523 all_of(Info.LShrAmts,
524 [](uint64_t A) { return A == 0 || isPowerOf2_64(A); })
526 : TTI::OP_None};
527 // After the shift the field content of each lane sits in the low bits of
528 // the lane, so the packing is a single byte shuffle of the shifted lanes.
529 // Pick the cheapest shift width: the narrowest type still holding the field
530 // content is not always the cheapest (e.g. missing narrow variable shifts).
531 Type *Int8Ty = Type::getInt8Ty(SrcTy->getContext());
532 assert(BitWidth % 8 == 0 &&
533 "The byte-multiple field width divides the result bit width.");
534 unsigned OutBytes = ResultTy->getScalarSizeInBits() / 8;
535 auto *PackTy = FixedVectorType::get(Int8Ty, OutBytes);
536 unsigned MinShiftWidth = 8;
537 while (MinShiftWidth < MaxAmt + Info.FieldWidth)
538 MinShiftWidth *= 2;
539 bool IsReversed = equal(Info.LaneOfField, reverse(seq<unsigned>(NumElts)));
540 bool IsTrunc = IsReversed || equal(Info.LaneOfField, seq<unsigned>(NumElts));
541 auto *FieldTy = FixedVectorType::get(
542 IntegerType::get(SrcTy->getContext(), Info.FieldWidth), NumElts);
544 ShiftWidth = 0;
545 for (unsigned W2 = MinShiftWidth; W2 <= BitWidth; W2 *= 2) {
546 auto *ShiftTy = FixedVectorType::get(
547 IntegerType::get(SrcTy->getContext(), W2), NumElts);
548 unsigned BytesPerLane = W2 / 8;
549 unsigned InBytes = NumElts * BytesPerLane;
550 SmallVector<int> Mask =
551 getBitPackMask(Info, OutBytes, NumElts, BytesPerLane);
552 InstructionCost C = TTI.getCastInstrCost(Instruction::BitCast, ResultTy,
553 PackTy, CCH, CostKind);
554 if (IsTrunc) {
555 // Fields in lane order, possibly reversed, are a truncation of the
556 // shifted lanes. A reversal of byte fields is a bswap.
557 if (Info.FieldWidth < W2)
558 C += TTI.getCastInstrCost(Instruction::Trunc, FieldTy, ShiftTy,
560 if (IsReversed && Info.FieldWidth == 8) {
561 IntrinsicCostAttributes CostAttrs(Intrinsic::bswap, ResultTy,
562 {ResultTy});
563 C += TTI.getIntrinsicInstrCost(CostAttrs, CostKind);
564 } else if (IsReversed) {
565 C += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, FieldTy,
566 FieldTy, CostKind);
567 }
568 } else {
569 // A narrowing shuffle is a shuffle at the source width followed by an
570 // extract of the low elements.
571 auto *SrcByteTy = FixedVectorType::get(Int8Ty, InBytes);
572 SmallVector<int> WideMask(Mask);
573 WideMask.resize(std::max(InBytes, OutBytes), PoisonMaskElem);
574 C += TTI.getShuffleCost(
575 is_contained(Info.LaneOfField, BitPackInfo::NoLane)
578 FixedVectorType::get(Int8Ty, WideMask.size()), SrcByteTy, CostKind,
579 WideMask, /*Index=*/0, /*SubTp=*/nullptr, /*Args=*/{}, CtxI);
580 if (InBytes > OutBytes)
582 PackTy, SrcByteTy, CostKind, /*Mask=*/{},
583 /*Index=*/0, PackTy, /*Args=*/{}, CtxI);
584 }
585 if (W2 != BitWidth && W2 != ZExtSrcWidth)
586 C += TTI.getCastInstrCost(Instruction::Trunc, ShiftTy, SrcTy, CCH,
587 CostKind);
588 if (Info.needsShift())
589 C += TTI.getArithmeticInstrCost(Instruction::LShr, ShiftTy, CostKind,
590 /*Opd1Info=*/{}, ShiftAmtInfo,
591 /*Args=*/{}, CtxI, TLI);
592 if (C.isValid() && (!NewCost.isValid() || C < NewCost)) {
593 NewCost = C;
594 ShiftWidth = W2;
595 }
596 }
597 return NewCost;
598}
599
601 bool NeedMask, Type *NarrowScalarTy,
602 Type *WideTy, unsigned VF,
603 ArrayRef<int> PermMask, const Value *Root,
604 const TTI::TargetCostKind CostKind) {
605 auto *NarrowVecTy = cast<VectorType>(getWidenedType(NarrowScalarTy, VF));
606 Type *CmpTy = CmpInst::makeCmpResultType(NarrowVecTy);
607 auto *MaskTy = IntegerType::get(WideTy->getContext(), VF);
608 // The result cast inherits the uses of the reduction root.
610 const auto *CtxI = cast<Instruction>(Root);
612 if (NeedMask)
613 Cost += TTI.getArithmeticInstrCost(
614 Instruction::And, NarrowVecTy, CostKind,
617 if (!ShuffleVectorInst::isIdentityMask(PermMask, VF))
618 Cost += getShuffleCost(TTI, TTI::SK_PermuteSingleSrc, NarrowVecTy, CostKind,
619 PermMask);
620 if (!NarrowScalarTy->isIntegerTy(1))
621 Cost += TTI.getCmpSelInstrCost(
622 Instruction::ICmp, NarrowVecTy, CmpTy, CmpInst::ICMP_NE, CostKind,
625 // Only the final cast inherits the uses of the reduction root.
626 Cost += TTI.getCastInstrCost(
627 Instruction::BitCast, MaskTy, CmpTy,
628 MaskTy == WideTy ? CCH : TTI::CastContextHint::None, CostKind);
629 if (MaskTy != WideTy)
630 Cost +=
631 TTI.getCastInstrCost(Instruction::ZExt, WideTy, MaskTy, CCH, CostKind);
632 return Cost;
633}
634
637 const SmallDenseMap<Value *, NarrowedLeafInfo> &NarrowedLeafShifts,
638 VectorType *NarrowVecTy, VectorType *WideVecTy, const Instruction *CtxI,
639 const TTI::TargetCostKind CostKind) {
641 if (any_of(NarrowedLeafShifts,
642 [](const auto &P) { return P.second.Shift != 0; }))
643 Cost += TTI.getArithmeticInstrCost(
644 Instruction::Shl, WideVecTy, CostKind, {TTI::OK_AnyValue, TTI::OP_None},
645 {TTI::OK_NonUniformConstantValue, TTI::OP_None}, {}, CtxI);
646 if (any_of(NarrowedLeafShifts,
647 [](const auto &P) { return !P.second.Mask.isAllOnes(); }))
648 Cost += TTI.getArithmeticInstrCost(
649 Instruction::And, NarrowVecTy, CostKind,
650 {TTI::OK_AnyValue, TTI::OP_None},
651 {TTI::OK_NonUniformConstantValue, TTI::OP_None}, {}, CtxI);
652 return Cost;
653}
654
656 const Intrinsic::ID ID,
657 const unsigned VF, unsigned MinBW,
658 const TargetTransformInfo &TTI) {
659 SmallVector<Type *> ArgTys;
660 for (auto [Idx, Arg] : enumerate(CI->args())) {
661 if (ID != Intrinsic::not_intrinsic) {
663 ArgTys.push_back(Arg->getType());
664 continue;
665 }
666 if (MinBW > 0) {
667 ArgTys.push_back(
668 getWidenedType(IntegerType::get(CI->getContext(), MinBW), VF));
669 continue;
670 }
671 }
672 ArgTys.push_back(getWidenedType(Arg->getType(), VF));
673 }
674 return ArgTys;
675}
676
677std::pair<InstructionCost, InstructionCost>
680 const TTI::TargetCostKind CostKind) {
681 auto Shape = VFShape::get(CI->getFunctionType(),
683 false /*HasGlobalPred*/);
684 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
685 auto LibCost = InstructionCost::getInvalid();
686 if (!CI->isNoBuiltin() && VecFunc) {
687 // Calculate the cost of the vector library call.
688 // If the corresponding vector call is cheaper, return its cost.
689 LibCost = TTI.getCallInstrCost(nullptr, VecTy, ArgTys, CostKind);
690 }
692
693 // Calculate the cost of the vector intrinsic call.
694 FastMathFlags FMF;
695 if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
696 FMF = FPCI->getFastMathFlags();
697 const InstructionCost ScalarLimit = 10000;
698 IntrinsicCostAttributes CostAttrs(ID, VecTy, ArgTys, FMF,
700 LibCost.isValid() ? LibCost : ScalarLimit);
701 auto IntrinsicCost = TTI.getIntrinsicInstrCost(CostAttrs, CostKind);
702 if (LibCost.isValid()) {
703 if (IntrinsicCost > LibCost)
705 } else if (IntrinsicCost > ScalarLimit) {
706 // A type-based query always scalarizes struct-returning intrinsics (e.g.
707 // llvm.sincos), which do not have a VFDatabase name mapping. Retry with an
708 // argument-aware query (as the loop vectorizer does) so such lowerings are
709 // taken into account.
711 IntrinsicCostAttributes ArgAwareAttrs(
712 ID, VecTy, Args, ArgTys, FMF, dyn_cast<IntrinsicInst>(CI), ScalarLimit);
713 IntrinsicCost = TTI.getIntrinsicInstrCost(ArgAwareAttrs, CostKind);
714 if (IntrinsicCost > ScalarLimit)
716 }
717 if (ID == Intrinsic::sincos &&
720 Shape.VF, CI->getModule()))
722 2 * TTI.getCallInstrCost(nullptr, ArgTys.front(), ArgTys, CostKind);
723
724 return {IntrinsicCost, LibCost};
725}
726
727/// \returns the reciprocal-throughput cost of \p I widened to \p VF lanes (an
728/// arithmetic op or a vectorizable call).
731 const TargetLibraryInfo &TLI,
732 const TTI::TargetCostKind CostKind) {
734 "getVectorOpCost expects an arithmetic op or a vectorizable call.");
735 Type *VecTy = getWidenedType(I->getType(), VF);
736 if (auto *CI = dyn_cast<CallInst>(I)) {
738 SmallVector<Type *> ArgTys = buildIntrinsicArgTypes(CI, ID, VF, 0, TTI);
739 auto [IntrCost, LibCost] =
740 getVectorCallCosts(CI, VecTy, TTI, TLI, ArgTys, CostKind);
741 return std::min(IntrCost, LibCost);
742 }
743 SmallVector<const Value *, 2> Args{I->getOperand(0), I->getOperand(1)};
744 return TTI.getArithmeticInstrCost(
745 I->getOpcode(), VecTy, CostKind, TTI::getOperandInfo(I->getOperand(0)),
746 TTI::getOperandInfo(I->getOperand(1)), Args, I);
747}
748
749/// Packs a type's kind and scalar width into one key, so an opcode/intrinsic
750/// id reused across scalar widths (e.g. fdiv float vs. fdiv double) is cached
751/// per width instead of sharing one verdict.
752static unsigned getPoorThroughputTypeKey(Type *Ty) {
753 return (static_cast<unsigned>(Ty->getTypeID()) << 16) |
754 Ty->getScalarSizeInBits();
755}
756
759 const TargetLibraryInfo &TLI,
761 const TTI::TargetCostKind CostKind,
762 unsigned MaxVecRegSize) {
764 return false;
765 Type *Ty = I->getType();
766 if ((Ty->isVectorTy() && !ReVec) || Ty->isAggregateType() ||
767 !isValidElementType(Ty, ReVec))
768 return false;
769 auto Analyze = [&]() {
770 InstructionCost ScalarCost = TTI.getInstructionCost(I, CostKind);
771 if (ScalarCost < TTI::TCC_Expensive)
772 return false;
773 constexpr unsigned MinVF = 2;
774 if (getVectorOpCost(I, MinVF, TTI, TLI, CostKind) < ScalarCost * MinVF)
775 return true;
776 // Some ops (e.g. div by constant) scalarize at VF=2 but have a cheap
777 // vector form at the full register width.
778 unsigned TyBits = Ty->getPrimitiveSizeInBits().getFixedValue();
779 unsigned MaxVF = TyBits ? llvm::bit_floor(MaxVecRegSize / TyBits) : 0;
780 return MaxVF > MinVF &&
781 getVectorOpCost(I, MaxVF, TTI, TLI, CostKind) < ScalarCost * MaxVF;
782 };
783 auto CheckCached = [&](bool IsCheap, llvm::function_ref<void()> MarkCheap) {
784 if (IsCheap)
785 return false;
786 if (Analyze())
787 return true;
788 MarkCheap();
789 return false;
790 };
791 if (auto *CI = dyn_cast<CallInst>(I)) {
792 if (any_of(CI->args(), [&](const Value *Arg) {
793 return !isValidElementType(Arg->getType(), ReVec);
794 }))
795 return false;
796 // A call, used only as a select operand, may get the values rejected by the
797 // select condition, which the vector library call handles on its slow path.
798 if (!CI->use_empty() && !CI->hasNUsesOrMore(UsesLimit) &&
799 all_of(CI->users(), [&](User *U) {
800 return match(
801 U, m_Select(m_Unless(m_Specific(CI)), m_Value(), m_Value()));
802 }))
803 return false;
805 auto Key = std::make_pair(ID, getPoorThroughputTypeKey(Ty));
806 return CheckCached(Cache.CheapIntrinsics.contains(Key),
807 [&] { Cache.CheapIntrinsics.insert(Key); });
808 }
809 // A call without the vector variants is never vectorized.
810 if (VFDatabase::getMappings(*CI).empty())
811 return false;
812 const Function *Callee = CI->getCalledFunction();
813 if (!Callee)
814 return Analyze();
815 return CheckCached(Cache.CheapCallees.contains(Callee),
816 [&] { Cache.CheapCallees.insert(Callee); });
817 }
818 auto Key = std::make_pair(I->getOpcode(), getPoorThroughputTypeKey(Ty));
819 return CheckCached(Cache.CheapOpcodes.contains(Key),
820 [&] { Cache.CheapOpcodes.insert(Key); });
821}
822
824 const TargetTransformInfo &TTI) {
827 m_FMul(m_Value(), m_Value()))))))
828 return false;
829 if (FMul->getParent() == I->getParent())
830 return true;
831 SmallVector<Use *> OpsToSink;
832 return TTI.isProfitableToSinkOperands(I, OpsToSink) &&
833 any_of(OpsToSink, [&](const Use *U) { return U->get() == FMul; });
834}
835
836bool hasHighRegisterPressure(unsigned ScheduleBudget, const BasicBlock &BB,
837 Type *Ty, const TargetTransformInfo &TTI) {
838 if (hasNItemsOrMore(BB, ScheduleBudget))
839 return false;
840 const unsigned NumRegs = TTI.getNumberOfRegisters(
841 TTI.getRegisterClassForType(/*Vector=*/false, Ty));
842 auto IsLiveCandidate = [&](const Value *V) {
843 return isa<Instruction, Argument>(V) && V->getType()->getScalarType() == Ty;
844 };
846 for (const Instruction &I : reverse(BB)) {
847 // The operands of the PHIs are live in the predecessors.
848 if (isa<PHINode>(I))
849 break;
850 Live.erase(&I);
851 Live.insert_range(make_filter_range(I.operand_values(), IsLiveCandidate));
852 if (Live.size() > NumRegs)
853 return true;
854 }
855 return false;
856}
857
859 ArrayRef<SmallVector<Value *>> GatheredScalars, const DataLayout &DL,
860 const TargetTransformInfo &TTI, bool ReVec,
862 function_ref<std::optional<
863 std::tuple<const void *, FixedVectorType *, unsigned>>(Value *)>
864 GetVectorizedSource) {
865 struct SourceVector {
866 FixedVectorType *VecTy = nullptr;
867 APInt DemandedElts;
869 SmallVector<unsigned> Gathers;
870 };
872 SmallBitVector BSwapGathers(GatheredScalars.size());
873 for (auto [Idx, VL] : enumerate(GatheredScalars)) {
874 std::optional<std::tuple<Value *, unsigned, SmallVector<int>>> Fields =
876 if (!Fields)
877 continue;
878 auto &[Src, FieldWidth, Mask] = *Fields;
879 Type *SrcTy = Src->getType();
880 unsigned NumFields = SrcTy->getIntegerBitWidth() / FieldWidth;
881 if (FieldWidth != 8 || NumFields % 2 != 0 ||
882 !ShuffleVectorInst::isReverseMask(Mask, NumFields))
883 continue;
884 Type *ByteTy = Type::getInt8Ty(SrcTy->getContext());
885 auto *FieldVecTy = cast<VectorType>(getWidenedType(ByteTy, NumFields));
886 IntrinsicCostAttributes CostAttrs(Intrinsic::bswap, SrcTy, {SrcTy});
887 InstructionCost BSwapCost = TTI.getIntrinsicInstrCost(CostAttrs, CostKind);
889 FieldVecTy, CostKind, Mask);
890 std::optional<std::tuple<const void *, FixedVectorType *, unsigned>>
891 Source = GetVectorizedSource(Src);
892 if (!Source)
893 if (std::optional<unsigned> Lane = getElementIndex(Src)) {
894 auto *EE = cast<ExtractElementInst>(Src);
895 Source = std::make_tuple(
896 EE->getVectorOperand(),
897 cast<FixedVectorType>(EE->getVectorOperandType()), *Lane);
898 }
899 if (!Source) {
900 if (BSwapCost <= PermuteCost)
901 BSwapGathers.set(Idx);
902 continue;
903 }
904 auto &[Vec, VecTy, Lane] = *Source;
905 // The bytes of the scalar are either extracted from the vector as a
906 // subvector and permuted, or permuted from the whole vector directly.
907 auto *VecBytesTy = cast<VectorType>(
908 getWidenedType(ByteTy, NumFields * VecTy->getNumElements()));
909 for (int &I : Mask)
910 if (I != PoisonMaskElem)
911 I += Lane * NumFields;
912 PermuteCost =
913 std::min(PermuteCost + getShuffleCost(TTI, TTI::SK_ExtractSubvector,
914 VecBytesTy, CostKind, {},
915 Lane * NumFields, FieldVecTy),
917 CostKind, Mask));
918 auto [It, Inserted] = SourceVectors.try_emplace(Vec);
919 SourceVector &Info = It->second;
920 if (Inserted) {
921 Info.VecTy = VecTy;
922 Info.DemandedElts = APInt::getZero(VecTy->getNumElements());
923 }
924 Info.DemandedElts.setBit(Lane);
925 Info.Cost += BSwapCost - PermuteCost;
926 Info.Gathers.push_back(Idx);
927 }
928 for (const SourceVector &Info : make_second_range(SourceVectors)) {
930 TTI, ReVec, Info.VecTy->getElementType(), Info.VecTy, Info.DemandedElts,
931 /*Insert=*/false, /*Extract=*/true, CostKind);
932 if (Info.Cost + ExtractCost <= 0)
933 for (unsigned Idx : Info.Gathers)
934 BSwapGathers.set(Idx);
935 }
936 return BSwapGathers;
937}
938} // namespace llvm::slpvectorizer
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define I(x, y, z)
Definition MD5.cpp:57
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
iterator end() const
Definition ArrayRef.h:130
LLVM Basic Block Representation.
Definition BasicBlock.h:61
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
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_NE
not equal
Definition InstrTypes.h:762
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
static InstructionCost getInvalid(CostType Val=0)
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
Information for memory intrinsic cost model.
static LLVM_ABI unsigned getOpcode(RecurKind Kind)
Returns the opcode corresponding to the RecurrenceKind.
static LLVM_ABI bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
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 isInsertSubvectorMask(ArrayRef< int > Mask, int NumSrcElts, int &NumSubElts, int &Index)
Return true if this shuffle mask is an insert subvector mask.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
size_type size() const
bool erase(PtrType Ptr)
Remove pointer from the set.
void insert_range(Range &&R)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Provides information about what library functions are available for the current target.
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.
llvm::VectorInstrContext VectorInstrContext
@ TCC_Expensive
The cost of a 'div' instruction on x86.
@ TCC_Free
Expected to fold away in lowering.
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_InsertSubvector
InsertSubvector. Index indicates start offset.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_PermuteTwoSrc
Merge elements from two source vectors into one with any shuffle mask.
@ SK_Reverse
Reverse the order of the vector.
@ SK_ExtractSubvector
ExtractSubvector Index indicates start offset.
CastContextHint
Represents a hint about the context in which a cast is used.
@ Masked
The cast is used with a masked load/store.
@ Normal
The cast is used with a normal load/store.
@ GatherScatter
The cast is used with a gather/scatter.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
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...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
The Vector Function Database.
Definition VectorUtils.h:35
static SmallVector< VFInfo, 8 > getMappings(const CallInst &CI)
Retrieve all the VFInfo instances associated to the CallInst CI.
Definition VectorUtils.h:76
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
Function * getVectorizedFunction(const VFShape &Shape) const
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
AllowFmf_match< T, FastMathFlags::AllowContract > m_AllowContract(const T &SubPattern)
A private "module" namespace for types and utilities used by this pass.
std::pair< InstructionCost, bool > getI1ReductionCost(RecurKind Kind, const TargetTransformInfo &TTI, FixedVectorType *VectorTy, Type *ScalarTy, TTI::CastContextHint Ctx, TTI::TargetCostKind CostKind)
i1 reductions can be emitted as the plain target reduction or in the bitcast-based form (bitcast to a...
std::pair< InstructionCost, InstructionCost > getVectorCallCosts(CallInst *CI, Type *VecTy, const TargetTransformInfo &TTI, const TargetLibraryInfo &TLI, ArrayRef< Type * > ArgTys, const TTI::TargetCostKind CostKind)
Calculates the costs of vectorized intrinsic (if possible) and vectorized function (if possible) call...
InstructionCost getShuffleCost(const TargetTransformInfo &TTI, TTI::ShuffleKind Kind, VectorType *Tp, const TTI::TargetCostKind CostKind, ArrayRef< int > Mask, int Index, VectorType *SubTp, ArrayRef< const Value * > Args, TTI::VectorInstrContext VIC)
Returns the cost of the shuffle instructions with the given Kind, vector type Tp and optional Mask.
std::optional< unsigned > getElementIndex(const Value *Inst, unsigned Offset)
Definition SLPUtils.cpp:264
InstructionCost getNarrowedLeafOpsCost(const TargetTransformInfo &TTI, const SmallDenseMap< Value *, NarrowedLeafInfo > &NarrowedLeafShifts, VectorType *NarrowVecTy, VectorType *WideVecTy, const Instruction *CtxI, const TTI::TargetCostKind CostKind)
Returns the cost of the per-lane operations on the narrowed leaves NarrowedLeafShifts: the shl in the...
std::optional< std::tuple< Value *, unsigned, SmallVector< int > > > matchGatheredExtractedFields(ArrayRef< Value * > VL, const DataLayout &DL)
Checks if the values in VL are zero-extended sub-fields of the same wider integer scalar.
InstructionCost getBoolReduxBitcastCmpCost(const TargetTransformInfo &TTI, RecurKind RdxKind, FixedVectorType *VecTy, const Value *Root, ArrayRef< Instruction * > ChainInsts, const TTI::TargetCostKind CostKind)
Returns the cost of the booleanized logical and/or reduction of a vector of type VecTy with the i1 ro...
std::pair< InstructionCost, InstructionCost > getGEPCosts(const TargetTransformInfo &TTI, ArrayRef< Value * > Ptrs, Value *BasePtr, unsigned Opcode, const TTI::TargetCostKind CostKind, Type *ScalarTy, VectorType *VecTy)
Calculate the scalar and the vector costs from vectorizing set of GEPs.
Intrinsic::ID getMaskedDivRemIntrinsic(unsigned Opcode)
SmallVector< int > getBitPackMask(const BitPackInfo &Info, unsigned NumBytes, unsigned NumElts, unsigned BytesPerLane)
Returns the byte shuffle mask packing the per-lane fields of the shifted lanes (BytesPerLane bytes ea...
SmallVector< Type * > buildIntrinsicArgTypes(const CallInst *CI, const Intrinsic::ID ID, const unsigned VF, unsigned MinBW, const TargetTransformInfo &TTI)
Builds the arguments types vector for the given call instruction with the given ID for the specified ...
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:118
Type * getWidenedType(Type *ScalarTy, unsigned VF)
static unsigned getPoorThroughputTypeKey(Type *Ty)
Packs a type's kind and scalar width into one key, so an opcode/intrinsic id reused across scalar wid...
bool isPoorThroughputOp(bool ReVec, Instruction *I, const TargetTransformInfo &TTI, const TargetLibraryInfo &TLI, PoorThroughputOpCache &Cache, const TTI::TargetCostKind CostKind, unsigned MaxVecRegSize)
Returns true if I is an expensive scalar op whose vector form is cheaper per lane (e....
ConstantInt * getStrideBytesForConstant(ConstantInt *Stride, Type *ScalarTy, const DataLayout &DL, bool IsReverse)
Returns Stride scaled by the allocation size of ScalarTy, negated if IsReverse is set.
static TTI::CastContextHint getBoolReduxResultCCH(const Value *Root)
Returns the cast context hint for the trunc of the booleanized reduction result, which inherits the u...
void transformScalarShuffleIndiciesToVector(unsigned VecTyNumElements, SmallVectorImpl< int > &Mask)
Definition SLPUtils.cpp:512
InstructionCost getBlendedLoadCost(const TargetTransformInfo &TTI, Type *VecTy, Align Alignment, unsigned AddressSpace, const TTI::TargetCostKind CostKind)
Returns the cost of a BlendedLoadVectorize node loading VecTy: two masked loads (one per candidate ba...
FixedVectorType * getMaskedDivRemType(const TargetTransformInfo &TTI, unsigned Opcode, Type *ScalarTy, unsigned NumElts, bool ReVec)
For a non-power-of-2 NumElts-wide integer div/rem Opcode, returns the padded full-register vector typ...
InstructionCost getBoolBitmaskCost(const TargetTransformInfo &TTI, bool NeedMask, Type *NarrowScalarTy, Type *WideTy, unsigned VF, ArrayRef< int > PermMask, const Value *Root, const TTI::TargetCostKind CostKind)
Returns the cost of the boolean bitmask reduction of a vector of boolean leaves of type NarrowScalarT...
InstructionCost getDemotedTypeCastCost(const TargetTransformInfo &TTI, VectorType *VecTy, const std::pair< uint64_t, bool > &MinBW, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind)
Returns the cost of casting a vector of the demoted type to VecTy.
bool isFusableFMulOperand(Value *Op, Instruction *I, const TargetTransformInfo &TTI)
InstructionCost getBoolReduxWideRdxCost(const TargetTransformInfo &TTI, RecurKind RdxKind, FixedVectorType *VecTy, const Value *Root, FastMathFlags FMF, const TTI::TargetCostKind CostKind)
Returns the cost of the booleanized logical and/or reduction of a vector of type VecTy with the i1 ro...
InstructionCost getCompressedLoadCost(const TargetTransformInfo &TTI, const LoadInst *LI0, const CompressedLoadInfo &Info, TargetTransformInfo::TargetCostKind CostKind)
Return the cost of a compressed load and accompanying shuffle.
InstructionCost getWidenedStridedCastCost(const TargetTransformInfo &TTI, Type *SrcTy, Type *DstTy, const DataLayout &DL, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind)
Returns the cost of the cast between the widened strided access type and the entry vector type.
bool isValidElementType(Type *Ty, bool ReVec)
Predicate for the element types that the SLP vectorizer supports.
InstructionCost getScalarizationOverhead(const TargetTransformInfo &TTI, bool ReVec, Type *ScalarTy, VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, const TTI::TargetCostKind CostKind, bool ForPoisonSrc, ArrayRef< Value * > VL, TTI::VectorInstrContext VIC)
This is similar to TargetTransformInfo::getScalarizationOverhead, but if ScalarTy is a FixedVectorTyp...
InstructionCost getStridedLoadCost(const TargetTransformInfo &TTI, const DataLayout &DL, Value *StrideVal, Type *StridedLoadTy, Type *VecTy, Type *ScalarTy, Value *Ptr, Align CommonAlignment, TargetTransformInfo::CastContextHint Ctx, TargetTransformInfo::TargetCostKind CostKind, bool IsReverse)
Return the cost of a strided load and accompanying bitcast.
bool hasHighRegisterPressure(unsigned ScheduleBudget, const BasicBlock &BB, Type *Ty, const TargetTransformInfo &TTI)
SmallBitVector selectBSwapGathers(ArrayRef< SmallVector< Value * > > GatheredScalars, const DataLayout &DL, const TargetTransformInfo &TTI, bool ReVec, TargetTransformInfo::TargetCostKind CostKind, function_ref< std::optional< std::tuple< const void *, FixedVectorType *, unsigned > >(Value *)> GetVectorizedSource)
Selects the gathers of GatheredScalars, which fully reverse the bytes of a scalar and are emitted as ...
InstructionCost getExtractWithExtendCost(const TargetTransformInfo &TTI, bool ReVec, unsigned Opcode, Type *Dst, VectorType *VecTy, unsigned Index, const TTI::TargetCostKind CostKind)
This is similar to TargetTransformInfo::getExtractWithExtendCost, but if Dst is a FixedVectorType,...
static InstructionCost getVectorOpCost(Instruction *I, unsigned VF, const TargetTransformInfo &TTI, const TargetLibraryInfo &TLI, const TTI::TargetCostKind CostKind)
static InstructionCost getBoolLogicRdxBitcastCost(RecurKind Kind, const TargetTransformInfo &TTI, FixedVectorType *VectorTy, TTI::CastContextHint Ctx, TTI::TargetCostKind CostKind)
constexpr int UsesLimit
Limit of the number of uses for potentially transformed instructions/values, used in checks to avoid ...
Definition SLPUtils.h:61
InstructionCost getVectorInstrCost(const TargetTransformInfo &TTI, bool ReVec, Type *ScalarTy, unsigned Opcode, Type *Val, const TTI::TargetCostKind CostKind, unsigned Index, Value *Scalar, ArrayRef< std::tuple< Value *, User *, int > > ScalarUserAndIdx, TTI::VectorInstrContext VIC)
This is similar to TargetTransformInfo::getVectorInstrCost, but if ScalarTy is a FixedVectorType,...
InstructionCost getMaskedDivRemCost(const TargetTransformInfo &TTI, bool ReVec, unsigned Opcode, Type *ScalarTy, unsigned NumElts, const TTI::TargetCostKind CostKind, FixedVectorType **PaddedTy)
For a non-power-of-2 NumElts-wide integer div/rem Opcode, checks if padding to a full register and us...
InstructionCost getBitPackCost(const TargetTransformInfo &TTI, FixedVectorType *SrcTy, Type *ResultTy, const BitPackInfo &Info, unsigned ZExtSrcWidth, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const TargetLibraryInfo *TLI, const Instruction *CtxI, unsigned &ShiftWidth)
Returns the cost of the bitfield packing of SrcTy into ResultTy, picking the cheapest shift width.
This is an optimization pass for GlobalISel generic memory operations.
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 getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
InstructionCost Cost
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
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...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
bool hasNItemsOrMore(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has N or more items.
Definition STLExtras.h:2659
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
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:376
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
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
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
constexpr int PoisonMaskElem
TargetTransformInfo TTI
RecurKind
These are the kinds of recurrences that we support.
@ Or
Bitwise or logical OR of integers.
@ FMul
Product of floats.
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1425
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
LLVM_ABI bool shouldSplitVectorSinCos(const TargetLibraryInfo &TLI, Type *ScalarTy, ElementCount EC, Module *M)
Returns true if the vector llvm.sincos with ScalarTy elements and EC element count has no vector libr...
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Describe known properties for a set of pointers.
unsigned IsSameBaseAddress
All the GEPs in a set have same base address.
static VFShape get(const FunctionType *FTy, ElementCount EC, bool HasGlobalPred)
Retrieve the basic vectorization shape of the function, where all parameters are mapped to VFParamKin...
Description of a bitfield packing of vector lanes into a scalar value: every lane contributes a disjo...
Definition SLPUtils.h:514
static constexpr unsigned NoLane
Definition SLPUtils.h:515
Describe a single compressed load for costing and generating the vector instruction.
Memoizes opcode / intrinsic / callee kinds already ruled out as seeds.