LLVM 24.0.0git
VectorUtils.cpp
Go to the documentation of this file.
1//===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines vectorizer utilities.
10//
11//===----------------------------------------------------------------------===//
12
14#include "AnalysisOptions.h"
16#include "llvm/ADT/SetVector.h"
26#include "llvm/IR/Constants.h"
28#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/Value.h"
32
33#define DEBUG_TYPE "vectorutils"
34
35using namespace llvm;
36using namespace llvm::PatternMatch;
37
38/// Return true if all of the intrinsic's arguments and return type are scalars
39/// for the scalar form of the intrinsic, and vectors for the vector form of the
40/// intrinsic (except operands that are marked as always being scalar by
41/// isVectorIntrinsicWithScalarOpAtArg).
43 switch (ID) {
44 case Intrinsic::abs: // Begin integer bit-manipulation.
45 case Intrinsic::bswap:
46 case Intrinsic::bitreverse:
47 case Intrinsic::ctpop:
48 case Intrinsic::ctlz:
49 case Intrinsic::cttz:
50 case Intrinsic::fshl:
51 case Intrinsic::fshr:
52 case Intrinsic::smax:
53 case Intrinsic::smin:
54 case Intrinsic::umax:
55 case Intrinsic::umin:
56 case Intrinsic::sadd_sat:
57 case Intrinsic::ssub_sat:
58 case Intrinsic::uadd_sat:
59 case Intrinsic::usub_sat:
60 case Intrinsic::smul_fix:
61 case Intrinsic::smul_fix_sat:
62 case Intrinsic::umul_fix:
63 case Intrinsic::umul_fix_sat:
64 case Intrinsic::uadd_with_overflow:
65 case Intrinsic::sadd_with_overflow:
66 case Intrinsic::usub_with_overflow:
67 case Intrinsic::ssub_with_overflow:
68 case Intrinsic::umul_with_overflow:
69 case Intrinsic::smul_with_overflow:
70 case Intrinsic::sqrt: // Begin floating-point.
71 case Intrinsic::asin:
72 case Intrinsic::acos:
73 case Intrinsic::atan:
74 case Intrinsic::atan2:
75 case Intrinsic::sin:
76 case Intrinsic::cos:
77 case Intrinsic::sincos:
78 case Intrinsic::sincospi:
79 case Intrinsic::tan:
80 case Intrinsic::sinh:
81 case Intrinsic::cosh:
82 case Intrinsic::tanh:
83 case Intrinsic::exp:
84 case Intrinsic::exp10:
85 case Intrinsic::exp2:
86 case Intrinsic::frexp:
87 case Intrinsic::ldexp:
88 case Intrinsic::log:
89 case Intrinsic::log10:
90 case Intrinsic::log2:
91 case Intrinsic::fabs:
92 case Intrinsic::minnum:
93 case Intrinsic::maxnum:
94 case Intrinsic::minimum:
95 case Intrinsic::maximum:
96 case Intrinsic::minimumnum:
97 case Intrinsic::maximumnum:
98 case Intrinsic::modf:
99 case Intrinsic::copysign:
100 case Intrinsic::floor:
101 case Intrinsic::ceil:
102 case Intrinsic::trunc:
103 case Intrinsic::rint:
104 case Intrinsic::nearbyint:
105 case Intrinsic::round:
106 case Intrinsic::roundeven:
107 case Intrinsic::pow:
108 case Intrinsic::fma:
109 case Intrinsic::fmuladd:
110 case Intrinsic::is_fpclass:
111 case Intrinsic::powi:
112 case Intrinsic::canonicalize:
113 case Intrinsic::fptosi_sat:
114 case Intrinsic::fptoui_sat:
115 case Intrinsic::lround:
116 case Intrinsic::llround:
117 case Intrinsic::lrint:
118 case Intrinsic::llrint:
119 case Intrinsic::ucmp:
120 case Intrinsic::scmp:
121 case Intrinsic::clmul:
122 case Intrinsic::pdep:
123 case Intrinsic::pext:
124 case Intrinsic::smulh:
125 case Intrinsic::umulh:
126 return true;
127 default:
128 return false;
129 }
130}
131
134 return true;
135
137}
138
139/// Identifies if the vector form of the intrinsic has a scalar operand.
141 unsigned ScalarOpdIdx,
142 const TargetTransformInfo *TTI) {
143
145 return TTI->isTargetIntrinsicWithScalarOpAtArg(ID, ScalarOpdIdx);
146
147 // Vector predication intrinsics have the EVL as the last operand.
148 if (VPIntrinsic::getVectorLengthParamPos(ID) == ScalarOpdIdx)
149 return true;
150
151 switch (ID) {
152 case Intrinsic::abs:
153 case Intrinsic::ctlz:
154 case Intrinsic::cttz:
155 case Intrinsic::is_fpclass:
156 case Intrinsic::powi:
157 case Intrinsic::vector_extract:
158 case Intrinsic::masked_compressstore:
159 return (ScalarOpdIdx == 1);
160 case Intrinsic::smul_fix:
161 case Intrinsic::smul_fix_sat:
162 case Intrinsic::umul_fix:
163 case Intrinsic::umul_fix_sat:
164 case Intrinsic::vector_splice_left:
165 case Intrinsic::vector_splice_right:
166 return (ScalarOpdIdx == 2);
167 case Intrinsic::experimental_vp_splice:
168 return ScalarOpdIdx == 2 || ScalarOpdIdx == 4;
169 case Intrinsic::experimental_vp_strided_load:
170 return ScalarOpdIdx == 0 || ScalarOpdIdx == 1;
171 case Intrinsic::experimental_vp_strided_store:
172 return ScalarOpdIdx == 1 || ScalarOpdIdx == 2;
173 case Intrinsic::masked_expandload:
174 return ScalarOpdIdx == 0;
175 case Intrinsic::loop_dependence_war_mask:
176 return true;
177 default:
178 return false;
179 }
180}
181
183 Intrinsic::ID ID, int OpdIdx, const TargetTransformInfo *TTI) {
184 assert(ID != Intrinsic::not_intrinsic && "Not an intrinsic!");
185
187 return TTI->isTargetIntrinsicWithOverloadTypeAtArg(ID, OpdIdx);
188
189 switch (ID) {
190 case Intrinsic::fptosi_sat:
191 case Intrinsic::fptoui_sat:
192 case Intrinsic::lround:
193 case Intrinsic::llround:
194 case Intrinsic::lrint:
195 case Intrinsic::llrint:
196 case Intrinsic::ucmp:
197 case Intrinsic::scmp:
198 case Intrinsic::vector_extract:
199 case Intrinsic::loop_dependence_war_mask:
200 case Intrinsic::masked_expandload:
201 return OpdIdx == -1 || OpdIdx == 0;
202 case Intrinsic::modf:
203 case Intrinsic::sincos:
204 case Intrinsic::sincospi:
205 case Intrinsic::is_fpclass:
206 return OpdIdx == 0;
207 case Intrinsic::powi:
208 case Intrinsic::ldexp:
209 return OpdIdx == -1 || OpdIdx == 1;
210 case Intrinsic::experimental_vp_strided_load:
211 return OpdIdx == -1 || OpdIdx == 0 || OpdIdx == 1;
212 case Intrinsic::experimental_vp_strided_store:
213 return OpdIdx == 0 || OpdIdx == 1 || OpdIdx == 2;
214 case Intrinsic::masked_compressstore:
215 return OpdIdx == 0 || OpdIdx == 1;
216 default:
217 return OpdIdx == -1;
218 }
219}
220
221std::optional<unsigned>
223 switch (ID) {
224 case Intrinsic::experimental_vp_strided_store:
225 case Intrinsic::masked_compressstore:
226 return 1;
227 case Intrinsic::experimental_vp_strided_load:
228 case Intrinsic::masked_expandload:
229 return 0;
230 default:
231 return std::nullopt;
232 }
233}
234
235std::optional<unsigned>
237 switch (ID) {
238 case Intrinsic::experimental_vp_strided_store:
239 case Intrinsic::masked_compressstore:
240 return 0;
241 default:
242 return std::nullopt;
243 }
244}
245
247 if (auto MaskPos = VPIntrinsic::getMaskParamPos(ID))
248 return MaskPos;
249 switch (ID) {
250 case Intrinsic::masked_compressstore:
251 return 2;
252 case Intrinsic::masked_expandload:
253 return 1;
254 default:
255 return std::nullopt;
256 }
257}
258
260 Intrinsic::ID ID, int RetIdx, const TargetTransformInfo *TTI) {
261
263 return TTI->isTargetIntrinsicWithStructReturnOverloadAtField(ID, RetIdx);
264
265 switch (ID) {
266 case Intrinsic::frexp:
267 return RetIdx == 0 || RetIdx == 1;
268 default:
269 return RetIdx == 0;
270 }
271}
272
273/// Returns intrinsic ID for call.
274/// For the input call instruction it finds mapping intrinsic and returns
275/// its ID, in case it does not found it return not_intrinsic.
277 const TargetLibraryInfo *TLI) {
279 if (ID == Intrinsic::not_intrinsic)
281
282 if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
283 ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
284 ID == Intrinsic::experimental_noalias_scope_decl ||
285 ID == Intrinsic::sideeffect || ID == Intrinsic::pseudoprobe)
286 return ID;
288}
289
291 ElementCount EC, Module *M) {
292 auto HasIntrinsicMapping = [&](Intrinsic::ID ID) {
293 return TLI.isFunctionVectorizable(Intrinsic::getName(ID, ScalarTy, M), EC);
294 };
295 // If a vector sincos mapping exists for the intrinsic name (e.g.
296 // "llvm.sincos.f32") or for the scalar libcall name ("sincos"/"sincosf"),
297 // SelectionDAG legalization handles it via expandMultipleResultFPLibCall
298 // when the runtime libcall impl is enabled.
299 if (HasIntrinsicMapping(Intrinsic::sincos))
300 return false;
301 LibFunc LF = NotLibFunc;
302 if (ScalarTy->isFloatTy())
303 LF = LibFunc_sincosf;
304 else if (ScalarTy->isDoubleTy())
305 LF = LibFunc_sincos;
306 if (LF != NotLibFunc && TLI.isFunctionVectorizable(TLI.getName(LF), EC))
307 return false;
308 return HasIntrinsicMapping(Intrinsic::sin) &&
309 HasIntrinsicMapping(Intrinsic::cos);
310}
311
313 switch (ID) {
314 case Intrinsic::vector_interleave2:
315 return 2;
316 case Intrinsic::vector_interleave3:
317 return 3;
318 case Intrinsic::vector_interleave4:
319 return 4;
320 case Intrinsic::vector_interleave5:
321 return 5;
322 case Intrinsic::vector_interleave6:
323 return 6;
324 case Intrinsic::vector_interleave7:
325 return 7;
326 case Intrinsic::vector_interleave8:
327 return 8;
328 default:
329 return 0;
330 }
331}
332
334 switch (ID) {
335 case Intrinsic::vector_deinterleave2:
336 return 2;
337 case Intrinsic::vector_deinterleave3:
338 return 3;
339 case Intrinsic::vector_deinterleave4:
340 return 4;
341 case Intrinsic::vector_deinterleave5:
342 return 5;
343 case Intrinsic::vector_deinterleave6:
344 return 6;
345 case Intrinsic::vector_deinterleave7:
346 return 7;
347 case Intrinsic::vector_deinterleave8:
348 return 8;
349 default:
350 return 0;
351 }
352}
353
355 [[maybe_unused]] unsigned Factor =
357 ArrayRef<Type *> DISubtypes = DI->getType()->subtypes();
358 assert(Factor && Factor == DISubtypes.size() &&
359 "unexpected deinterleave factor or result type");
360 return cast<VectorType>(DISubtypes[0]);
361}
362
363/// Given a vector and an element number, see if the scalar value is
364/// already around as a register, for example if it were inserted then extracted
365/// from the vector.
366Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
367 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
368 VectorType *VTy = cast<VectorType>(V->getType());
369 // For fixed-length vector, return poison for out of range access.
370 if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
371 unsigned Width = FVTy->getNumElements();
372 if (EltNo >= Width)
373 return PoisonValue::get(FVTy->getElementType());
374 }
375
376 if (Constant *C = dyn_cast<Constant>(V))
377 return C->getAggregateElement(EltNo);
378
380 // If this is an insert to a variable element, we don't know what it is.
381 uint64_t IIElt;
382 if (!match(III->getOperand(2), m_ConstantInt(IIElt)))
383 return nullptr;
384
385 // If this is an insert to the element we are looking for, return the
386 // inserted value.
387 if (EltNo == IIElt)
388 return III->getOperand(1);
389
390 // Guard against infinite loop on malformed, unreachable IR.
391 if (III == III->getOperand(0))
392 return nullptr;
393
394 // Otherwise, the insertelement doesn't modify the value, recurse on its
395 // vector input.
396 return findScalarElement(III->getOperand(0), EltNo);
397 }
398
400 // Restrict the following transformation to fixed-length vector.
401 if (SVI && isa<FixedVectorType>(SVI->getType())) {
402 unsigned LHSWidth =
403 cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements();
404 int InEl = SVI->getMaskValue(EltNo);
405 if (InEl < 0)
406 return PoisonValue::get(VTy->getElementType());
407 if (InEl < (int)LHSWidth)
408 return findScalarElement(SVI->getOperand(0), InEl);
409 return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
410 }
411
412 // Extract a value from a vector add operation with a constant zero.
413 // TODO: Use getBinOpIdentity() to generalize this.
414 Value *Val; Constant *C;
415 if (match(V, m_Add(m_Value(Val), m_Constant(C))))
416 if (Constant *Elt = C->getAggregateElement(EltNo))
417 if (Elt->isNullValue())
418 return findScalarElement(Val, EltNo);
419
420 // If the vector is a splat then we can trivially find the scalar element.
422 if (Value *Splat = getSplatValue(V))
423 if (EltNo < VTy->getElementCount().getKnownMinValue())
424 return Splat;
425
426 // Otherwise, we don't know.
427 return nullptr;
428}
429
431 int SplatIndex = -1;
432 for (int M : Mask) {
433 // Ignore invalid (undefined) mask elements.
434 if (M < 0)
435 continue;
436
437 // There can be only 1 non-negative mask element value if this is a splat.
438 if (SplatIndex != -1 && SplatIndex != M)
439 return -1;
440
441 // Initialize the splat index to the 1st non-negative mask element.
442 SplatIndex = M;
443 }
444 assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?");
445 return SplatIndex;
446}
447
448/// Get splat value if the input is a splat vector or return nullptr.
449/// This function is not fully general. It checks only 2 cases:
450/// the input value is (1) a splat constant vector or (2) a sequence
451/// of instructions that broadcasts a scalar at element 0.
453 if (isa<VectorType>(V->getType()))
454 if (auto *C = dyn_cast<Constant>(V))
455 return C->getSplatValue();
456
457 // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
458 Value *Splat;
459 if (match(V,
461 m_Value(), m_ZeroMask())))
462 return Splat;
463
464 return nullptr;
465}
466
467bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) {
468 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
469
470 if (isa<VectorType>(V->getType())) {
471 if (isa<UndefValue>(V))
472 return true;
473 // FIXME: We can allow undefs, but if Index was specified, we may want to
474 // check that the constant is defined at that index.
475 if (auto *C = dyn_cast<Constant>(V))
476 return C->getSplatValue() != nullptr;
477 }
478
479 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) {
480 // FIXME: We can safely allow undefs here. If Index was specified, we will
481 // check that the mask elt is defined at the required index.
482 if (!all_equal(Shuf->getShuffleMask()))
483 return false;
484
485 // Match any index.
486 if (Index == -1)
487 return true;
488
489 // Match a specific element. The mask should be defined at and match the
490 // specified index.
491 return Shuf->getMaskValue(Index) == Index;
492 }
493
494 // The remaining tests are all recursive, so bail out if we hit the limit.
496 return false;
497
498 // If both operands of a binop are splats, the result is a splat.
499 Value *X, *Y, *Z;
500 if (match(V, m_BinOp(m_Value(X), m_Value(Y))))
501 return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth);
502
503 // If all operands of a select are splats, the result is a splat.
504 if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z))))
505 return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) &&
506 isSplatValue(Z, Index, Depth);
507
508 // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
509
510 return false;
511}
512
514 const APInt &DemandedElts, APInt &DemandedLHS,
515 APInt &DemandedRHS, bool AllowUndefElts) {
516 DemandedLHS = DemandedRHS = APInt::getZero(SrcWidth);
517
518 // Early out if we don't demand any elements.
519 if (DemandedElts.isZero())
520 return true;
521
522 // Simple case of a shuffle with zeroinitializer.
523 if (all_of(Mask, equal_to(0))) {
524 DemandedLHS.setBit(0);
525 return true;
526 }
527
528 for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
529 int M = Mask[I];
530 assert((-1 <= M) && (M < (SrcWidth * 2)) &&
531 "Invalid shuffle mask constant");
532
533 if (!DemandedElts[I] || (AllowUndefElts && (M < 0)))
534 continue;
535
536 // For undef elements, we don't know anything about the common state of
537 // the shuffle result.
538 if (M < 0)
539 return false;
540
541 if (M < SrcWidth)
542 DemandedLHS.setBit(M);
543 else
544 DemandedRHS.setBit(M - SrcWidth);
545 }
546
547 return true;
548}
549
551 std::array<std::pair<int, int>, 2> &SrcInfo) {
552 const int SignalValue = NumElts * 2;
553 SrcInfo[0] = {-1, SignalValue};
554 SrcInfo[1] = {-1, SignalValue};
555 for (auto [i, M] : enumerate(Mask)) {
556 if (M < 0)
557 continue;
558 int Src = M >= NumElts;
559 int Diff = (int)i - (M % NumElts);
560 bool Match = false;
561 for (int j = 0; j < 2; j++) {
562 auto &[SrcE, DiffE] = SrcInfo[j];
563 if (SrcE == -1) {
564 assert(DiffE == SignalValue);
565 SrcE = Src;
566 DiffE = Diff;
567 }
568 if (SrcE == Src && DiffE == Diff) {
569 Match = true;
570 break;
571 }
572 }
573 if (!Match)
574 return false;
575 }
576 // Avoid all undef masks
577 return SrcInfo[0].first != -1;
578}
579
581 SmallVectorImpl<int> &ScaledMask) {
582 assert(Scale > 0 && "Unexpected scaling factor");
583
584 // Fast-path: if no scaling, then it is just a copy.
585 if (Scale == 1) {
586 ScaledMask.assign(Mask.begin(), Mask.end());
587 return;
588 }
589
590 ScaledMask.clear();
591 for (int MaskElt : Mask) {
592 if (MaskElt >= 0) {
593 assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= INT32_MAX &&
594 "Overflowed 32-bits");
595 }
596 for (int SliceElt = 0; SliceElt != Scale; ++SliceElt)
597 ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt);
598 }
599}
600
602 SmallVectorImpl<int> &ScaledMask) {
603 assert(Scale > 0 && "Unexpected scaling factor");
604
605 // Fast-path: if no scaling, then it is just a copy.
606 if (Scale == 1) {
607 ScaledMask.assign(Mask.begin(), Mask.end());
608 return true;
609 }
610
611 // We must map the original elements down evenly to a type with less elements.
612 int NumElts = Mask.size();
613 if (NumElts % Scale != 0)
614 return false;
615
616 ScaledMask.clear();
617 ScaledMask.reserve(NumElts / Scale);
618
619 // Step through the input mask by splitting into Scale-sized slices.
620 do {
621 ArrayRef<int> MaskSlice = Mask.take_front(Scale);
622 assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice.");
623
624 // The first element of the slice determines how we evaluate this slice.
625 int SliceFront = MaskSlice.front();
626 if (SliceFront < 0) {
627 // Negative values (undef or other "sentinel" values) must be equal across
628 // the entire slice.
629 if (!all_equal(MaskSlice))
630 return false;
631 ScaledMask.push_back(SliceFront);
632 } else {
633 // A positive mask element must be cleanly divisible.
634 if (SliceFront % Scale != 0)
635 return false;
636 // Elements of the slice must be consecutive.
637 for (int i = 1; i < Scale; ++i)
638 if (MaskSlice[i] != SliceFront + i)
639 return false;
640 ScaledMask.push_back(SliceFront / Scale);
641 }
642 Mask = Mask.drop_front(Scale);
643 } while (!Mask.empty());
644
645 assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask");
646
647 // All elements of the original mask can be scaled down to map to the elements
648 // of a mask with wider elements.
649 return true;
650}
651
653 SmallVectorImpl<int> &NewMask) {
654 unsigned NumElts = M.size();
655 if (NumElts % 2 != 0)
656 return false;
657
658 NewMask.clear();
659 for (unsigned i = 0; i < NumElts; i += 2) {
660 int M0 = M[i];
661 int M1 = M[i + 1];
662
663 // If both elements are undef, new mask is undef too.
664 if (M0 == -1 && M1 == -1) {
665 NewMask.push_back(-1);
666 continue;
667 }
668
669 if (M0 == -1 && M1 != -1 && (M1 % 2) == 1) {
670 NewMask.push_back(M1 / 2);
671 continue;
672 }
673
674 if (M0 != -1 && (M0 % 2) == 0 && ((M0 + 1) == M1 || M1 == -1)) {
675 NewMask.push_back(M0 / 2);
676 continue;
677 }
678
679 NewMask.clear();
680 return false;
681 }
682
683 assert(NewMask.size() == NumElts / 2 && "Incorrect size for mask!");
684 return true;
685}
686
687bool llvm::scaleShuffleMaskElts(unsigned NumDstElts, ArrayRef<int> Mask,
688 SmallVectorImpl<int> &ScaledMask) {
689 unsigned NumSrcElts = Mask.size();
690 assert(NumSrcElts > 0 && NumDstElts > 0 && "Unexpected scaling factor");
691
692 // Fast-path: if no scaling, then it is just a copy.
693 if (NumSrcElts == NumDstElts) {
694 ScaledMask.assign(Mask.begin(), Mask.end());
695 return true;
696 }
697
698 // Ensure we can find a whole scale factor.
699 assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
700 "Unexpected scaling factor");
701
702 if (NumSrcElts > NumDstElts) {
703 int Scale = NumSrcElts / NumDstElts;
704 return widenShuffleMaskElts(Scale, Mask, ScaledMask);
705 }
706
707 int Scale = NumDstElts / NumSrcElts;
708 narrowShuffleMaskElts(Scale, Mask, ScaledMask);
709 return true;
710}
711
713 SmallVectorImpl<int> &ScaledMask) {
714 std::array<SmallVector<int, 16>, 2> TmpMasks;
715 SmallVectorImpl<int> *Output = &TmpMasks[0], *Tmp = &TmpMasks[1];
716 ArrayRef<int> InputMask = Mask;
717 for (unsigned Scale = 2; Scale <= InputMask.size(); ++Scale) {
718 while (widenShuffleMaskElts(Scale, InputMask, *Output)) {
719 InputMask = *Output;
720 std::swap(Output, Tmp);
721 }
722 }
723 ScaledMask.assign(InputMask.begin(), InputMask.end());
724}
725
727 ArrayRef<int> Mask, unsigned NumOfSrcRegs, unsigned NumOfDestRegs,
728 unsigned NumOfUsedRegs, function_ref<void()> NoInputAction,
729 function_ref<void(ArrayRef<int>, unsigned, unsigned)> SingleInputAction,
730 function_ref<void(ArrayRef<int>, unsigned, unsigned, bool)>
731 ManyInputsAction) {
732 SmallVector<SmallVector<SmallVector<int>>> Res(NumOfDestRegs);
733 // Try to perform better estimation of the permutation.
734 // 1. Split the source/destination vectors into real registers.
735 // 2. Do the mask analysis to identify which real registers are
736 // permuted.
737 int Sz = Mask.size();
738 unsigned SzDest = Sz / NumOfDestRegs;
739 unsigned SzSrc = Sz / NumOfSrcRegs;
740 for (unsigned I = 0; I < NumOfDestRegs; ++I) {
741 auto &RegMasks = Res[I];
742 RegMasks.assign(2 * NumOfSrcRegs, {});
743 // Check that the values in dest registers are in the one src
744 // register.
745 for (unsigned K = 0; K < SzDest; ++K) {
746 int Idx = I * SzDest + K;
747 if (Idx == Sz)
748 break;
749 if (Mask[Idx] >= 2 * Sz || Mask[Idx] == PoisonMaskElem)
750 continue;
751 int MaskIdx = Mask[Idx] % Sz;
752 int SrcRegIdx = MaskIdx / SzSrc + (Mask[Idx] >= Sz ? NumOfSrcRegs : 0);
753 // Add a cost of PermuteTwoSrc for each new source register permute,
754 // if we have more than one source registers.
755 if (RegMasks[SrcRegIdx].empty())
756 RegMasks[SrcRegIdx].assign(SzDest, PoisonMaskElem);
757 RegMasks[SrcRegIdx][K] = MaskIdx % SzSrc;
758 }
759 }
760 // Process split mask.
761 for (unsigned I : seq<unsigned>(NumOfUsedRegs)) {
762 auto &Dest = Res[I];
763 int NumSrcRegs =
764 count_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
765 switch (NumSrcRegs) {
766 case 0:
767 // No input vectors were used!
768 NoInputAction();
769 break;
770 case 1: {
771 // Find the only mask with at least single undef mask elem.
772 auto *It =
773 find_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
774 unsigned SrcReg = std::distance(Dest.begin(), It);
775 SingleInputAction(*It, SrcReg, I);
776 break;
777 }
778 default: {
779 // The first mask is a permutation of a single register. Since we have >2
780 // input registers to shuffle, we merge the masks for 2 first registers
781 // and generate a shuffle of 2 registers rather than the reordering of the
782 // first register and then shuffle with the second register. Next,
783 // generate the shuffles of the resulting register + the remaining
784 // registers from the list.
785 auto &&CombineMasks = [](MutableArrayRef<int> FirstMask,
786 ArrayRef<int> SecondMask) {
787 for (int Idx = 0, VF = FirstMask.size(); Idx < VF; ++Idx) {
788 if (SecondMask[Idx] != PoisonMaskElem) {
789 assert(FirstMask[Idx] == PoisonMaskElem &&
790 "Expected undefined mask element.");
791 FirstMask[Idx] = SecondMask[Idx] + VF;
792 }
793 }
794 };
795 auto &&NormalizeMask = [](MutableArrayRef<int> Mask) {
796 for (int Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
797 if (Mask[Idx] != PoisonMaskElem)
798 Mask[Idx] = Idx;
799 }
800 };
801 int SecondIdx;
802 bool NewReg = true;
803 do {
804 int FirstIdx = -1;
805 SecondIdx = -1;
806 MutableArrayRef<int> FirstMask, SecondMask;
807 for (unsigned I : seq<unsigned>(2 * NumOfSrcRegs)) {
808 SmallVectorImpl<int> &RegMask = Dest[I];
809 if (RegMask.empty())
810 continue;
811
812 if (FirstIdx == SecondIdx) {
813 FirstIdx = I;
814 FirstMask = RegMask;
815 continue;
816 }
817 SecondIdx = I;
818 SecondMask = RegMask;
819 CombineMasks(FirstMask, SecondMask);
820 ManyInputsAction(FirstMask, FirstIdx, SecondIdx, NewReg);
821 NewReg = false;
822 NormalizeMask(FirstMask);
823 RegMask.clear();
824 SecondMask = FirstMask;
825 SecondIdx = FirstIdx;
826 }
827 if (FirstIdx != SecondIdx && SecondIdx >= 0) {
828 CombineMasks(SecondMask, FirstMask);
829 ManyInputsAction(SecondMask, SecondIdx, FirstIdx, NewReg);
830 NewReg = false;
831 Dest[FirstIdx].clear();
832 NormalizeMask(SecondMask);
833 }
834 } while (SecondIdx >= 0);
835 break;
836 }
837 }
838 }
839}
840
841void llvm::getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth,
842 const APInt &DemandedElts,
843 APInt &DemandedLHS,
844 APInt &DemandedRHS) {
845 assert(VectorBitWidth >= 128 && "Vectors smaller than 128 bit not supported");
846 int NumLanes = VectorBitWidth / 128;
847 int NumElts = DemandedElts.getBitWidth();
848 int NumEltsPerLane = NumElts / NumLanes;
849 int HalfEltsPerLane = NumEltsPerLane / 2;
850
851 DemandedLHS = APInt::getZero(NumElts);
852 DemandedRHS = APInt::getZero(NumElts);
853
854 // Map DemandedElts to the horizontal operands.
855 for (int Idx = 0; Idx != NumElts; ++Idx) {
856 if (!DemandedElts[Idx])
857 continue;
858 int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
859 int LocalIdx = Idx % NumEltsPerLane;
860 if (LocalIdx < HalfEltsPerLane) {
861 DemandedLHS.setBit(LaneIdx + 2 * LocalIdx);
862 } else {
863 LocalIdx -= HalfEltsPerLane;
864 DemandedRHS.setBit(LaneIdx + 2 * LocalIdx);
865 }
866 }
867}
868
871 const TargetTransformInfo *TTI) {
872
873 // DemandedBits will give us every value's live-out bits. But we want
874 // to ensure no extra casts would need to be inserted, so every DAG
875 // of connected values must have the same minimum bitwidth.
881 SmallPtrSet<Instruction *, 4> InstructionSet;
883
884 // Determine the roots. We work bottom-up, from truncs or icmps.
885 bool SeenExtFromIllegalType = false;
886 for (auto *BB : Blocks)
887 for (auto &I : *BB) {
888 InstructionSet.insert(&I);
889
890 if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
891 !TTI->isTypeLegal(I.getOperand(0)->getType()))
892 SeenExtFromIllegalType = true;
893
894 // Only deal with non-vector integers up to 64-bits wide.
895 if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
896 !I.getType()->isVectorTy() &&
897 I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
898 // Don't make work for ourselves. If we know the loaded type is legal,
899 // don't add it to the worklist.
900 if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
901 continue;
902
903 Worklist.push_back(&I);
904 Roots.insert(&I);
905 }
906 }
907 // Early exit.
908 if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
909 return MinBWs;
910
911 // Now proceed breadth-first, unioning values together.
912 while (!Worklist.empty()) {
913 Instruction *I = Worklist.pop_back_val();
914 Value *Leader = ECs.getOrInsertLeaderValue(I);
915
916 if (!Visited.insert(I).second)
917 continue;
918
919 // If we encounter a type that is larger than 64 bits, we can't represent
920 // it so bail out.
921 if (DB.getDemandedBits(I).getBitWidth() > 64)
923
924 uint64_t V = DB.getDemandedBits(I).getZExtValue();
925 DBits[Leader] |= V;
926 DBits[I] = V;
927
928 // Casts, loads and instructions outside of our range terminate a chain
929 // successfully.
931 !InstructionSet.count(I))
932 continue;
933
934 // Unsafe casts terminate a chain unsuccessfully. We can't do anything
935 // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
936 // transform anything that relies on them.
938 !I->getType()->isIntegerTy()) {
939 DBits[Leader] |= ~0ULL;
940 continue;
941 }
942
943 // We don't modify the types of PHIs. Reductions will already have been
944 // truncated if possible, and inductions' sizes will have been chosen by
945 // indvars.
946 if (isa<PHINode>(I))
947 continue;
948
949 // Don't modify the types of operands of a call, as doing that would cause a
950 // signature mismatch.
951 if (isa<CallBase>(I))
952 continue;
953
954 if (DBits[Leader] == ~0ULL)
955 // All bits demanded, no point continuing.
956 continue;
957
958 for (Value *O : I->operands()) {
959 ECs.unionSets(Leader, O);
960 if (auto *OI = dyn_cast<Instruction>(O))
961 Worklist.push_back(OI);
962 }
963 }
964
965 // Now we've discovered all values, walk them to see if there are
966 // any users we didn't see. If there are, we can't optimize that
967 // chain.
968 for (auto &I : DBits)
969 for (auto *U : I.first->users())
970 if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
971 DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
972
973 for (const auto &E : ECs) {
974 if (!E->isLeader())
975 continue;
976 uint64_t LeaderDemandedBits = 0;
977 for (Value *M : ECs.members(*E))
978 LeaderDemandedBits |= DBits[M];
979
980 uint64_t MinBW = llvm::bit_width(LeaderDemandedBits);
981 // Round up to a power of 2
982 MinBW = llvm::bit_ceil(MinBW);
983
984 // We don't modify the types of PHIs. Reductions will already have been
985 // truncated if possible, and inductions' sizes will have been chosen by
986 // indvars.
987 // If we are required to shrink a PHI, abandon this entire equivalence class.
988 bool Abort = false;
989 for (Value *M : ECs.members(*E))
990 if (isa<PHINode>(M) && MinBW < M->getType()->getScalarSizeInBits()) {
991 Abort = true;
992 break;
993 }
994 if (Abort)
995 continue;
996
997 for (Value *M : ECs.members(*E)) {
998 auto *MI = dyn_cast<Instruction>(M);
999 if (!MI)
1000 continue;
1001 Type *Ty = M->getType();
1002 if (Roots.count(MI))
1003 Ty = MI->getOperand(0)->getType();
1004
1005 if (MinBW >= Ty->getScalarSizeInBits())
1006 continue;
1007
1008 // If any of M's operands demand more bits than MinBW then M cannot be
1009 // performed safely in MinBW.
1010 auto *Call = dyn_cast<CallBase>(MI);
1011 auto Ops = Call ? Call->args() : MI->operands();
1012 if (any_of(Ops, [&DB, MinBW](Use &U) {
1013 auto *CI = dyn_cast<ConstantInt>(U);
1014 // For constants shift amounts, check if the shift would result in
1015 // poison.
1016 if (CI &&
1018 U.getOperandNo() == 1)
1019 return CI->uge(MinBW);
1020 return bit_ceil(DB.getDemandedBits(&U).getActiveBits()) > MinBW;
1021 }))
1022 continue;
1023
1024 MinBWs[MI] = MinBW;
1025 }
1026 }
1027
1028 return MinBWs;
1029}
1030
1031/// Add all access groups in @p AccGroups to @p List.
1032template <typename ListT>
1033static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
1034 // Interpret an access group as a list containing itself.
1035 if (AccGroups->getNumOperands() == 0) {
1036 assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
1037 List.insert(AccGroups);
1038 return;
1039 }
1040
1041 for (const auto &AccGroupListOp : AccGroups->operands()) {
1042 auto *Item = cast<MDNode>(AccGroupListOp.get());
1043 assert(isValidAsAccessGroup(Item) && "List item must be an access group");
1044 List.insert(Item);
1045 }
1046}
1047
1048MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
1049 if (!AccGroups1)
1050 return AccGroups2;
1051 if (!AccGroups2)
1052 return AccGroups1;
1053 if (AccGroups1 == AccGroups2)
1054 return AccGroups1;
1055
1057 addToAccessGroupList(Union, AccGroups1);
1058 addToAccessGroupList(Union, AccGroups2);
1059
1060 if (Union.size() == 0)
1061 return nullptr;
1062 if (Union.size() == 1)
1063 return cast<MDNode>(Union.front());
1064
1065 LLVMContext &Ctx = AccGroups1->getContext();
1066 return MDNode::get(Ctx, Union.getArrayRef());
1067}
1068
1070 const Instruction *Inst2) {
1071 bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
1072 bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
1073
1074 if (!MayAccessMem1 && !MayAccessMem2)
1075 return nullptr;
1076 if (!MayAccessMem1)
1077 return Inst2->getMetadata(LLVMContext::MD_access_group);
1078 if (!MayAccessMem2)
1079 return Inst1->getMetadata(LLVMContext::MD_access_group);
1080
1081 MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
1082 MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
1083 if (!MD1 || !MD2)
1084 return nullptr;
1085 if (MD1 == MD2)
1086 return MD1;
1087
1088 // Use set for scalable 'contains' check.
1089 SmallPtrSet<Metadata *, 4> AccGroupSet2;
1090 addToAccessGroupList(AccGroupSet2, MD2);
1091
1092 SmallVector<Metadata *, 4> Intersection;
1093 if (MD1->getNumOperands() == 0) {
1094 assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
1095 if (AccGroupSet2.count(MD1))
1096 Intersection.push_back(MD1);
1097 } else {
1098 for (const MDOperand &Node : MD1->operands()) {
1099 auto *Item = cast<MDNode>(Node.get());
1100 assert(isValidAsAccessGroup(Item) && "List item must be an access group");
1101 if (AccGroupSet2.count(Item))
1102 Intersection.push_back(Item);
1103 }
1104 }
1105
1106 if (Intersection.size() == 0)
1107 return nullptr;
1108 if (Intersection.size() == 1)
1109 return cast<MDNode>(Intersection.front());
1110
1111 LLVMContext &Ctx = Inst1->getContext();
1112 return MDNode::get(Ctx, Intersection);
1113}
1114
1115/// Add metadata from \p Inst to \p Metadata, if it can be preserved after
1116/// vectorization.
1118 Instruction *Inst,
1119 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Metadata) {
1121 static const unsigned SupportedIDs[] = {
1122 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1123 LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
1124 LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
1125 LLVMContext::MD_access_group, LLVMContext::MD_mmra};
1126
1127 // Remove any unsupported metadata kinds from Metadata.
1128 for (unsigned Idx = 0; Idx != Metadata.size();) {
1129 if (is_contained(SupportedIDs, Metadata[Idx].first)) {
1130 ++Idx;
1131 } else {
1132 // Swap element to end and remove it.
1133 std::swap(Metadata[Idx], Metadata.back());
1134 Metadata.pop_back();
1135 }
1136 }
1137}
1138
1139/// \returns \p I after propagating metadata from \p VL.
1141 if (VL.empty())
1142 return Inst;
1145
1146 for (auto &[Kind, MD] : Metadata) {
1147 // Skip MMRA metadata if the instruction cannot have it.
1148 if (Kind == LLVMContext::MD_mmra && !canInstructionHaveMMRAs(*Inst))
1149 continue;
1150
1151 for (int J = 1, E = VL.size(); MD && J != E; ++J) {
1152 const Instruction *IJ = cast<Instruction>(VL[J]);
1153 MDNode *IMD = IJ->getMetadata(Kind);
1154
1155 switch (Kind) {
1156 case LLVMContext::MD_mmra: {
1157 MD = MMRAMetadata::combine(Inst->getContext(), MD, IMD);
1158 break;
1159 }
1160 case LLVMContext::MD_tbaa:
1161 MD = MDNode::getMostGenericTBAA(MD, IMD);
1162 break;
1163 case LLVMContext::MD_alias_scope:
1165 break;
1166 case LLVMContext::MD_fpmath:
1167 MD = MDNode::getMostGenericFPMath(MD, IMD);
1168 break;
1169 case LLVMContext::MD_noalias:
1170 case LLVMContext::MD_nontemporal:
1171 case LLVMContext::MD_invariant_load:
1172 MD = MDNode::intersect(MD, IMD);
1173 break;
1174 case LLVMContext::MD_access_group:
1175 MD = intersectAccessGroups(Inst, IJ);
1176 break;
1177 default:
1178 llvm_unreachable("unhandled metadata");
1179 }
1180 }
1181
1182 Inst->setMetadata(Kind, MD);
1183 }
1184
1185 return Inst;
1186}
1187
1188Constant *
1190 const InterleaveGroup<Instruction> &Group) {
1191 // All 1's means mask is not needed.
1192 if (Group.isFull())
1193 return nullptr;
1194
1195 // TODO: support reversed access.
1196 assert(!Group.isReverse() && "Reversed group not supported.");
1197
1199 for (unsigned i = 0; i < VF; i++)
1200 for (unsigned j = 0; j < Group.getFactor(); ++j) {
1201 unsigned HasMember = Group.getMember(j) ? 1 : 0;
1202 Mask.push_back(Builder.getInt1(HasMember));
1203 }
1204
1205 return ConstantVector::get(Mask);
1206}
1207
1209llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) {
1210 SmallVector<int, 16> MaskVec;
1211 for (unsigned i = 0; i < VF; i++)
1212 for (unsigned j = 0; j < ReplicationFactor; j++)
1213 MaskVec.push_back(i);
1214
1215 return MaskVec;
1216}
1217
1219 unsigned NumVecs) {
1221 for (unsigned i = 0; i < VF; i++)
1222 for (unsigned j = 0; j < NumVecs; j++)
1223 Mask.push_back(j * VF + i);
1224
1225 return Mask;
1226}
1227
1229llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) {
1231 for (unsigned i = 0; i < VF; i++)
1232 Mask.push_back(Start + i * Stride);
1233
1234 return Mask;
1235}
1236
1238 unsigned NumInts,
1239 unsigned NumUndefs) {
1241 for (unsigned i = 0; i < NumInts; i++)
1242 Mask.push_back(Start + i);
1243
1244 for (unsigned i = 0; i < NumUndefs; i++)
1245 Mask.push_back(-1);
1246
1247 return Mask;
1248}
1249
1251 unsigned NumElts) {
1252 // Avoid casts in the loop and make sure we have a reasonable number.
1253 int NumEltsSigned = NumElts;
1254 assert(NumEltsSigned > 0 && "Expected smaller or non-zero element count");
1255
1256 // If the mask chooses an element from operand 1, reduce it to choose from the
1257 // corresponding element of operand 0. Undef mask elements are unchanged.
1258 SmallVector<int, 16> UnaryMask;
1259 for (int MaskElt : Mask) {
1260 assert((MaskElt < NumEltsSigned * 2) && "Expected valid shuffle mask");
1261 int UnaryElt = MaskElt >= NumEltsSigned ? MaskElt - NumEltsSigned : MaskElt;
1262 UnaryMask.push_back(UnaryElt);
1263 }
1264 return UnaryMask;
1265}
1266
1267/// A helper function for concatenating vectors. This function concatenates two
1268/// vectors having the same element type. If the second vector has fewer
1269/// elements than the first, it is padded with undefs.
1271 Value *V2) {
1272 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
1273 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
1274 assert(VecTy1 && VecTy2 &&
1275 VecTy1->getScalarType() == VecTy2->getScalarType() &&
1276 "Expect two vectors with the same element type");
1277
1278 unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements();
1279 unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements();
1280 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
1281
1282 if (NumElts1 > NumElts2) {
1283 // Extend with UNDEFs.
1284 V2 = Builder.CreateShuffleVector(
1285 V2, createSequentialMask(0, NumElts2, NumElts1 - NumElts2));
1286 }
1287
1288 return Builder.CreateShuffleVector(
1289 V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0));
1290}
1291
1293 ArrayRef<Value *> Vecs) {
1294 unsigned NumVecs = Vecs.size();
1295 assert(NumVecs > 1 && "Should be at least two vectors");
1296
1298 ResList.append(Vecs.begin(), Vecs.end());
1299 do {
1301 for (unsigned i = 0; i < NumVecs - 1; i += 2) {
1302 Value *V0 = ResList[i], *V1 = ResList[i + 1];
1303 assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
1304 "Only the last vector may have a different type");
1305
1306 TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
1307 }
1308
1309 // Push the last vector if the total number of vectors is odd.
1310 if (NumVecs % 2 != 0)
1311 TmpList.push_back(ResList[NumVecs - 1]);
1312
1313 ResList = TmpList;
1314 NumVecs = ResList.size();
1315 } while (NumVecs > 1);
1316
1317 return ResList[0];
1318}
1319
1321 assert(isa<VectorType>(Mask->getType()) &&
1322 isa<IntegerType>(Mask->getType()->getScalarType()) &&
1323 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1324 1 &&
1325 "Mask must be a vector of i1");
1326
1327 auto AllOneOrUndef = m_CombineOr(m_AllOnes(), m_UndefValue());
1328 return match(Mask, m_CombineOr(AllOneOrUndef, m_ContainsMatchingVectorElement(
1329 AllOneOrUndef)));
1330}
1331
1332/// TODO: This is a lot like known bits, but for
1333/// vectors. Is there something we can common this with?
1335 assert(isa<FixedVectorType>(Mask->getType()) &&
1336 isa<IntegerType>(Mask->getType()->getScalarType()) &&
1337 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1338 1 &&
1339 "Mask must be a fixed width vector of i1");
1340
1341 const unsigned VWidth =
1342 cast<FixedVectorType>(Mask->getType())->getNumElements();
1343 APInt DemandedElts = APInt::getAllOnes(VWidth);
1344 if (auto *CV = dyn_cast<ConstantVector>(Mask))
1345 for (unsigned i = 0; i < VWidth; i++)
1346 if (CV->getAggregateElement(i)->isNullValue())
1347 DemandedElts.clearBit(i);
1348 return DemandedElts;
1349}
1350
1352 Loop *L, DominatorTree *DT,
1353 LoopInfo *LI,
1354 const LoopAccessInfo *LAI,
1355 bool OptForSize)
1356 : Opts(getAnalysisOptions(*L)), PSE(PSE), TheLoop(L), DT(DT), LI(LI),
1357 LAI(LAI), OptForSize(OptForSize) {}
1358
1359bool InterleavedAccessInfo::isStrided(int Stride) const {
1360 unsigned Factor = std::abs(Stride);
1361 return Factor >= 2 && Factor <= Opts.max_interleave_group_factor;
1362}
1363
1364void InterleavedAccessInfo::collectConstStrideAccesses(
1366 const SymbolicStrideMap &Strides,
1368 auto &DL = TheLoop->getHeader()->getDataLayout();
1369
1370 // Since it's desired that the load/store instructions be maintained in
1371 // "program order" for the interleaved access analysis, we have to visit the
1372 // blocks in the loop in reverse postorder (i.e., in a topological order).
1373 // Such an ordering will ensure that any load/store that may be executed
1374 // before a second load/store will precede the second load/store in
1375 // AccessStrideInfo.
1376 LoopBlocksDFS DFS(TheLoop);
1377 DFS.perform(LI);
1378 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
1379 for (auto &I : *BB) {
1381 if (!Ptr)
1382 continue;
1383 Type *ElementTy = getLoadStoreType(&I);
1384
1385 // Currently, codegen doesn't support cases where the type size doesn't
1386 // match the alloc size. Skip them for now.
1387 uint64_t Size = DL.getTypeAllocSize(ElementTy);
1388 if (Size * 8 != DL.getTypeSizeInBits(ElementTy))
1389 continue;
1390
1391 // We don't check wrapping here because we don't know yet if Ptr will be
1392 // part of a full group or a group with gaps. Checking wrapping for all
1393 // pointers (even those that end up in groups with no gaps) will be overly
1394 // conservative. For full groups, wrapping should be ok since if we would
1395 // wrap around the address space we would do a memory access at nullptr
1396 // even without the transformation. The wrapping checks are therefore
1397 // deferred until after we've formed the interleaved groups.
1398 int64_t Stride = getPtrStride(PSE, ElementTy, Ptr, TheLoop, *DT, Strides,
1399 /*ShouldCheckWrap=*/false, Predicates)
1400 .value_or(0);
1401
1402 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, TheLoop, Strides, Ptr);
1403 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size,
1405 }
1406}
1407
1408// Analyze interleaved accesses and collect them into interleaved load and
1409// store groups.
1410//
1411// When generating code for an interleaved load group, we effectively hoist all
1412// loads in the group to the location of the first load in program order. When
1413// generating code for an interleaved store group, we sink all stores to the
1414// location of the last store. This code motion can change the order of load
1415// and store instructions and may break dependences.
1416//
1417// The code generation strategy mentioned above ensures that we won't violate
1418// any write-after-read (WAR) dependences.
1419//
1420// E.g., for the WAR dependence: a = A[i]; // (1)
1421// A[i] = b; // (2)
1422//
1423// The store group of (2) is always inserted at or below (2), and the load
1424// group of (1) is always inserted at or above (1). Thus, the instructions will
1425// never be reordered. All other dependences are checked to ensure the
1426// correctness of the instruction reordering.
1427//
1428// The algorithm visits all memory accesses in the loop in bottom-up program
1429// order. Program order is established by traversing the blocks in the loop in
1430// reverse postorder when collecting the accesses.
1431//
1432// We visit the memory accesses in bottom-up order because it can simplify the
1433// construction of store groups in the presence of write-after-write (WAW)
1434// dependences.
1435//
1436// E.g., for the WAW dependence: A[i] = a; // (1)
1437// A[i] = b; // (2)
1438// A[i + 1] = c; // (3)
1439//
1440// We will first create a store group with (3) and (2). (1) can't be added to
1441// this group because it and (2) are dependent. However, (1) can be grouped
1442// with other accesses that may precede it in program order. Note that a
1443// bottom-up order does not imply that WAW dependences should not be checked.
1445 bool EnablePredicatedInterleavedMemAccesses) {
1446 LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
1447 const auto &Strides = LAI->getSymbolicStrides();
1448
1449 // Holds all accesses with a constant stride.
1452 collectConstStrideAccesses(AccessStrideInfo, Strides,
1453 OptForSize ? nullptr : &Predicates);
1454
1455 if (AccessStrideInfo.empty())
1456 return;
1457
1458 // Collect the dependences in the loop.
1459 collectDependences();
1460
1461 // Holds all interleaved store groups temporarily.
1463 // Holds all interleaved load groups temporarily.
1465 // Groups added to this set cannot have new members added.
1466 SmallPtrSet<InterleaveGroup<Instruction> *, 4> CompletedLoadGroups;
1467
1468 // Search in bottom-up program order for pairs of accesses (A and B) that can
1469 // form interleaved load or store groups. In the algorithm below, access A
1470 // precedes access B in program order. We initialize a group for B in the
1471 // outer loop of the algorithm, and then in the inner loop, we attempt to
1472 // insert each A into B's group if:
1473 //
1474 // 1. A and B have the same stride,
1475 // 2. A and B have the same memory object size, and
1476 // 3. A belongs in B's group according to its distance from B.
1477 //
1478 // Special care is taken to ensure group formation will not break any
1479 // dependences.
1480 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
1481 BI != E; ++BI) {
1482 Instruction *B = BI->first;
1483 StrideDescriptor DesB = BI->second;
1484
1485 // Initialize a group for B if it has an allowable stride. Even if we don't
1486 // create a group for B, we continue with the bottom-up algorithm to ensure
1487 // we don't break any of B's dependences.
1488 InterleaveGroup<Instruction> *GroupB = nullptr;
1489 if (isStrided(DesB.Stride) &&
1490 (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
1491 GroupB = getInterleaveGroup(B);
1492 if (!GroupB) {
1493 LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
1494 << '\n');
1495 GroupB = createInterleaveGroup(B, DesB.Stride, DesB.Alignment);
1496 if (B->mayWriteToMemory())
1497 StoreGroups.insert(GroupB);
1498 else
1499 LoadGroups.insert(GroupB);
1500 }
1501 }
1502
1503 for (auto AI = std::next(BI); AI != E; ++AI) {
1504 Instruction *A = AI->first;
1505 StrideDescriptor DesA = AI->second;
1506
1507 // Our code motion strategy implies that we can't have dependences
1508 // between accesses in an interleaved group and other accesses located
1509 // between the first and last member of the group. Note that this also
1510 // means that a group can't have more than one member at a given offset.
1511 // The accesses in a group can have dependences with other accesses, but
1512 // we must ensure we don't extend the boundaries of the group such that
1513 // we encompass those dependent accesses.
1514 //
1515 // For example, assume we have the sequence of accesses shown below in a
1516 // stride-2 loop:
1517 //
1518 // (1, 2) is a group | A[i] = a; // (1)
1519 // | A[i-1] = b; // (2) |
1520 // A[i-3] = c; // (3)
1521 // A[i] = d; // (4) | (2, 4) is not a group
1522 //
1523 // Because accesses (2) and (3) are dependent, we can group (2) with (1)
1524 // but not with (4). If we did, the dependent access (3) would be within
1525 // the boundaries of the (2, 4) group.
1526 auto DependentMember = [&](InterleaveGroup<Instruction> *Group,
1527 StrideEntry *A) -> Instruction * {
1528 for (uint32_t Index = 0; Index < Group->getFactor(); ++Index) {
1529 Instruction *MemberOfGroupB = Group->getMember(Index);
1530 if (MemberOfGroupB && !canReorderMemAccessesForInterleavedGroups(
1531 A, &*AccessStrideInfo.find(MemberOfGroupB)))
1532 return MemberOfGroupB;
1533 }
1534 return nullptr;
1535 };
1536
1537 auto GroupA = getInterleaveGroup(A);
1538 // If A is a load, dependencies are tolerable, there's nothing to do here.
1539 // If both A and B belong to the same (store) group, they are independent,
1540 // even if dependencies have not been recorded.
1541 // If both GroupA and GroupB are null, there's nothing to do here.
1542 if (A->mayWriteToMemory() && GroupA != GroupB) {
1543 Instruction *DependentInst = nullptr;
1544 // If GroupB is a load group, we have to compare AI against all
1545 // members of GroupB because if any load within GroupB has a dependency
1546 // on AI, we need to mark GroupB as complete and also release the
1547 // store GroupA (if A belongs to one). The former prevents incorrect
1548 // hoisting of load B above store A while the latter prevents incorrect
1549 // sinking of store A below load B.
1550 if (GroupB && LoadGroups.contains(GroupB))
1551 DependentInst = DependentMember(GroupB, &*AI);
1552 else if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI))
1553 DependentInst = B;
1554
1555 if (DependentInst) {
1556 // A has a store dependence on B (or on some load within GroupB) and
1557 // is part of a store group. Release A's group to prevent illegal
1558 // sinking of A below B. A will then be free to form another group
1559 // with instructions that precede it.
1560 if (GroupA && StoreGroups.contains(GroupA)) {
1561 LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
1562 "dependence between "
1563 << *A << " and " << *DependentInst << '\n');
1564 StoreGroups.remove(GroupA);
1565 releaseGroup(GroupA);
1566 }
1567 // If B is a load and part of an interleave group, no earlier loads
1568 // can be added to B's interleave group, because this would mean the
1569 // DependentInst would move across store A. Mark the interleave group
1570 // as complete.
1571 if (GroupB && LoadGroups.contains(GroupB)) {
1572 LLVM_DEBUG(dbgs() << "LV: Marking interleave group for " << *B
1573 << " as complete.\n");
1574 CompletedLoadGroups.insert(GroupB);
1575 }
1576 }
1577 }
1578 if (CompletedLoadGroups.contains(GroupB)) {
1579 // Skip trying to add A to B, continue to look for other conflicting A's
1580 // in groups to be released.
1581 continue;
1582 }
1583
1584 // At this point, we've checked for illegal code motion. If either A or B
1585 // isn't strided, there's nothing left to do.
1586 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
1587 continue;
1588
1589 // Ignore A if it's already in a group or isn't the same kind of memory
1590 // operation as B.
1591 // Note that mayReadFromMemory() isn't mutually exclusive to
1592 // mayWriteToMemory in the case of atomic loads. We shouldn't see those
1593 // here, canVectorizeMemory() should have returned false - except for the
1594 // case we asked for optimization remarks.
1595 if (isInterleaved(A) ||
1596 (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
1597 (A->mayWriteToMemory() != B->mayWriteToMemory()))
1598 continue;
1599
1600 // Check rules 1 and 2. Ignore A if its stride or size is different from
1601 // that of B.
1602 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
1603 continue;
1604
1605 // Ignore A if the memory object of A and B don't belong to the same
1606 // address space
1608 continue;
1609
1610 // Calculate the distance from A to B.
1611 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
1612 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
1613 if (!DistToB)
1614 continue;
1615 int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
1616
1617 // Check rule 3. Ignore A if its distance to B is not a multiple of the
1618 // size.
1619 if (DistanceToB % static_cast<int64_t>(DesB.Size))
1620 continue;
1621
1622 // All members of a predicated interleave-group must have the same predicate,
1623 // and currently must reside in the same BB.
1624 BasicBlock *BlockA = A->getParent();
1625 BasicBlock *BlockB = B->getParent();
1626 if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
1627 (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
1628 continue;
1629
1630 // The index of A is the index of B plus A's distance to B in multiples
1631 // of the size.
1632 int IndexA =
1633 GroupB->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
1634
1635 // Try to insert A into B's group.
1636 if (GroupB->insertMember(A, IndexA, DesA.Alignment)) {
1637 LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
1638 << " into the interleave group with" << *B
1639 << '\n');
1640 InterleaveGroupMap[A] = GroupB;
1641
1642 // Set the first load in program order as the insert position.
1643 if (A->mayReadFromMemory())
1644 GroupB->setInsertPos(A);
1645 }
1646 } // Iteration over A accesses.
1647 } // Iteration over B accesses.
1648
1649 // Commit the collected predicates to PSE if any candidate group was formed.
1650 if (!LoadGroups.empty() || !StoreGroups.empty())
1651 PSE.addPredicates(Predicates);
1652
1653 auto InvalidateGroupIfMemberMayWrap = [&](InterleaveGroup<Instruction> *Group,
1654 int Index,
1655 const char *FirstOrLast) -> bool {
1656 Instruction *Member = Group->getMember(Index);
1657 assert(Member && "Group member does not exist");
1658 Value *MemberPtr = getLoadStorePointerOperand(Member);
1659 Type *AccessTy = getLoadStoreType(Member);
1660 if (getPtrStride(PSE, AccessTy, MemberPtr, TheLoop, *DT, Strides,
1661 /*ShouldCheckWrap=*/true)
1662 .value_or(0))
1663 return false;
1664 LLVM_DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
1665 << FirstOrLast
1666 << " group member potentially pointer-wrapping.\n");
1667 releaseGroup(Group);
1668 return true;
1669 };
1670
1671 // Remove interleaved groups with gaps whose memory
1672 // accesses may wrap around. We have to revisit the getPtrStride analysis,
1673 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
1674 // not check wrapping (see documentation there).
1675 // FORNOW we use Assume=false;
1676 // TODO: Change to Assume=true but making sure we don't exceed the threshold
1677 // of runtime SCEV assumptions checks (thereby potentially failing to
1678 // vectorize altogether).
1679 // Additional optional optimizations:
1680 // TODO: If we are peeling the loop and we know that the first pointer doesn't
1681 // wrap then we can deduce that all pointers in the group don't wrap.
1682 // This means that we can forcefully peel the loop in order to only have to
1683 // check the first pointer for no-wrap. When we'll change to use Assume=true
1684 // we'll only need at most one runtime check per interleaved group.
1685 for (auto *Group : LoadGroups) {
1686 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1687 // load would wrap around the address space we would do a memory access at
1688 // nullptr even without the transformation.
1689 if (Group->isFull())
1690 continue;
1691
1692 // Case 2: If first and last members of the group don't wrap this implies
1693 // that all the pointers in the group don't wrap.
1694 // So we check only group member 0 (which is always guaranteed to exist),
1695 // and group member Factor - 1; If the latter doesn't exist we rely on
1696 // peeling (if it is a non-reversed access -- see Case 3).
1697 if (InvalidateGroupIfMemberMayWrap(Group, 0, "first"))
1698 continue;
1699 if (Group->getMember(Group->getFactor() - 1))
1700 InvalidateGroupIfMemberMayWrap(Group, Group->getFactor() - 1, "last");
1701 else {
1702 // Case 3: A non-reversed interleaved load group with gaps: We need
1703 // to execute at least one scalar epilogue iteration. This will ensure
1704 // we don't speculatively access memory out-of-bounds. We only need
1705 // to look for a member at index factor - 1, since every group must have
1706 // a member at index zero.
1707 if (Group->isReverse()) {
1708 LLVM_DEBUG(
1709 dbgs() << "LV: Invalidate candidate interleaved group due to "
1710 "a reverse access with gaps.\n");
1711 releaseGroup(Group);
1712 continue;
1713 }
1714 LLVM_DEBUG(
1715 dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
1716 RequiresScalarEpilogue = true;
1717 }
1718 }
1719
1720 for (auto *Group : StoreGroups) {
1721 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1722 // store would wrap around the address space we would do a memory access at
1723 // nullptr even without the transformation.
1724 if (Group->isFull())
1725 continue;
1726
1727 // Interleave-store-group with gaps is implemented using masked wide store.
1728 // Remove interleaved store groups with gaps if
1729 // masked-interleaved-accesses are not enabled by the target.
1730 if (!EnablePredicatedInterleavedMemAccesses) {
1731 LLVM_DEBUG(
1732 dbgs() << "LV: Invalidate candidate interleaved store group due "
1733 "to gaps.\n");
1734 releaseGroup(Group);
1735 continue;
1736 }
1737
1738 // Case 2: If first and last members of the group don't wrap this implies
1739 // that all the pointers in the group don't wrap.
1740 // So we check only group member 0 (which is always guaranteed to exist),
1741 // and the last group member. Case 3 (scalar epilog) is not relevant for
1742 // stores with gaps, which are implemented with masked-store (rather than
1743 // speculative access, as in loads).
1744 if (InvalidateGroupIfMemberMayWrap(Group, 0, "first"))
1745 continue;
1746 for (int Index = Group->getFactor() - 1; Index > 0; Index--)
1747 if (Group->getMember(Index)) {
1748 InvalidateGroupIfMemberMayWrap(Group, Index, "last");
1749 break;
1750 }
1751 }
1752}
1753
1755 // If no group had triggered the requirement to create an epilogue loop,
1756 // there is nothing to do.
1758 return;
1759
1760 // Release groups requiring scalar epilogues. Note that this also removes them
1761 // from InterleaveGroups.
1762 bool ReleasedGroup = InterleaveGroups.remove_if([&](auto *Group) {
1763 if (!Group->requiresScalarEpilogue())
1764 return false;
1765 LLVM_DEBUG(
1766 dbgs()
1767 << "LV: Invalidate candidate interleaved group due to gaps that "
1768 "require a scalar epilogue (not allowed under optsize) and cannot "
1769 "be masked (not enabled). \n");
1770 releaseGroupWithoutRemovingFromSet(Group);
1771 return true;
1772 });
1773 assert(ReleasedGroup && "At least one group must be invalidated, as a "
1774 "scalar epilogue was required");
1775 (void)ReleasedGroup;
1776 RequiresScalarEpilogue = false;
1777}
1778
1779template <typename InstT>
1780void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
1781 llvm_unreachable("addMetadata can only be used for Instruction");
1782}
1783
1784namespace llvm {
1785template <>
1790} // namespace llvm
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static unsigned getScalarSizeInBits(Type *Ty)
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 pass exposes codegen information to IR-level passes.
static Value * concatenateTwoVectors(IRBuilderBase &Builder, Value *V1, Value *V2)
A helper function for concatenating vectors.
static void addToAccessGroupList(ListT &List, MDNode *AccGroups)
Add all access groups in AccGroups to List.
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 clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
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
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This represents a collection of equivalence classes and supports three efficient operations: insert a...
iterator_range< member_iterator > members(const ECValue &ECV) const
const ElemTy & getOrInsertLeaderValue(const ElemTy &V)
Return the leader for the specified value that is in the set.
member_iterator unionSets(const ElemTy &V1, const ElemTy &V2)
Merge the two equivalence sets for the specified values, inserting them if they do not already exist ...
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
This instruction inserts a single (scalar) element into a VectorType value.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
This does the same thing as getAllMetadata, except that it filters out the debug location.
LLVM_ABI bool mayReadOrWriteMemory() const LLVM_READONLY
Return true if this instruction may read or write memory.
The group of interleaved loads/stores sharing the same stride and close to each other.
uint32_t getFactor() const
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
bool isFull() const
Return true if this group is full, i.e. it has no gaps.
uint32_t getIndex(const InstTy *Instr) const
Get the index for the given member.
void setInsertPos(InstTy *Inst)
bool isReverse() const
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
bool insertMember(InstTy *Instr, int32_t Index, Align NewAlign)
Try to insert a new member Instr with index Index and alignment NewAlign.
InterleaveGroup< Instruction > * getInterleaveGroup(const Instruction *Instr) const
Get the interleave group that Instr belongs to.
bool requiresScalarEpilogue() const
Returns true if an interleaved group that may access memory out-of-bounds requires a scalar epilogue ...
bool isInterleaved(Instruction *Instr) const
Check if Instr belongs to any interleave group.
LLVM_ABI InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L, DominatorTree *DT, LoopInfo *LI, const LoopAccessInfo *LAI, bool OptForSize)
LLVM_ABI void analyzeInterleaving(bool EnableMaskedInterleavedGroup)
Analyze the interleaved accesses and collect them in interleave groups.
LLVM_ABI void invalidateGroupsRequiringScalarEpilogue()
Invalidate groups that require a scalar epilogue (due to gaps).
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Drive the analysis of memory accesses in the loop.
BlockT * getHeader() const
Store the result of a depth first search within basic blocks contained by a single loop.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
LLVMContext & getContext() const
Definition Metadata.h:1245
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
static LLVM_ABI MDNode * combine(LLVMContext &Ctx, const MMRAMetadata &A, const MMRAMetadata &B)
Combines A and B according to MMRA semantics.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
iterator find(const KeyT &Key)
Definition MapVector.h:157
bool empty() const
Definition MapVector.h:80
reverse_iterator rend()
Definition MapVector.h:77
reverse_iterator rbegin()
Definition MapVector.h:73
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
This class represents a constant integer value.
const APInt & getAPInt() const
This class represents an analyzed expression in the program.
bool remove(const value_type &X)
Remove an item from the set vector.
Definition SetVector.h:187
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
This instruction constructs a fixed permutation of two input vectors.
int getMaskValue(unsigned Elt) const
Return the shuffle mask value of this instruction for the given element index.
VectorType * getType() const
Overload to return most specific vector type.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool remove_if(UnaryPredicate P)
Remove elements that match the given predicate.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
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.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
ArrayRef< Type * > subtypes() const
Definition Type.h:376
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
static LLVM_ABI std::optional< unsigned > getMaskParamPos(Intrinsic::ID IntrinsicID)
static LLVM_ABI std::optional< unsigned > getVectorLengthParamPos(Intrinsic::ID IntrinsicID)
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
Base class of all SIMD vector types.
Type * getElementType() const
An efficient, type-erasing, non-owning reference to a callable.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
LLVM_ABI bool isTriviallyScalarizable(ID id)
Returns true if the intrinsic is trivially scalarizable.
LLVM_ABI bool isTargetIntrinsic(ID IID)
isTargetIntrinsic - Returns true if IID is an intrinsic specific to a certain target.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
AllOnesConstantMatch m_AllOnes()
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_UndefValue()
Match an arbitrary UndefValue constant.
auto m_Constant()
Match an arbitrary Constant and ignore it.
ContainsMatchingVectorElement_match< SPTy > m_ContainsMatchingVectorElement(const SPTy &SubPattern)
Match a vector constant where at least one of its elements matches the subpattern.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
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
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
LLVM_ABI bool canInstructionHaveMMRAs(const Instruction &I)
LLVM_ABI APInt possiblyDemandedEltsInMask(Value *Mask)
Given a mask vector of the form <Y x i1>, return an APInt (of bitwidth Y) for each lane which may be ...
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:2570
LLVM_ABI std::optional< unsigned > getVectorStoreIntrinsicDataArgIdx(Intrinsic::ID ID)
Returns the argument index of the data value of the vector store intrinsic ID, or std::nullopt if the...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
LLVM_ABI llvm::SmallVector< int, 16 > createUnaryMask(ArrayRef< int > Mask, unsigned NumElts)
Given a shuffle mask for a binary shuffle, create the equivalent shuffle mask assuming both operands ...
LLVM_ABI void getMetadataToPropagate(Instruction *Inst, SmallVectorImpl< std::pair< unsigned, MDNode * > > &Metadata)
Add metadata from Inst to Metadata, if it can be preserved after vectorization.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI const SCEV * replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, const Loop *Lp, const SymbolicStrideMap &PtrToStride, Value *Ptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return the SCEV corresponding to a pointer with the symbolic stride replaced with constant one,...
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
Align getLoadStoreAlignment(const Value *I)
A helper function that returns the alignment of load or store instruction.
LLVM_ABI bool widenShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Try to transform a shuffle mask by replacing elements with the scaled index for an equivalent mask of...
LLVM_ABI Instruction * propagateMetadata(Instruction *I, ArrayRef< Value * > VL)
Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath, MD_nontemporal,...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI std::optional< int64_t > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DominatorTree &DT, const SymbolicStrideMap &StridesMap=SymbolicStrideMap(), bool ShouldCheckWrap=true, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
If the pointer has a constant stride return it in units of the access type size.
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
LLVM_ABI MDNode * intersectAccessGroups(const Instruction *Inst1, const Instruction *Inst2)
Compute the access-group list of access groups that Inst1 and Inst2 are both in.
unsigned M1(unsigned Val)
Definition VE.h:394
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
LLVM_ABI Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
LLVM_ABI void getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
Compute the demanded elements mask of horizontal binary operations.
LLVM_ABI llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
DenseMap< Value *, const SCEVUnknown * > SymbolicStrideMap
Maps a pointer to its symbolic (non-constant) stride.
LLVM_ABI unsigned getDeinterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.deinterleaveN intrinsics.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI unsigned getInterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.interleaveN intrinsics.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr int PoisonMaskElem
LLVM_ABI bool isTriviallyScalarizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially scalarizable.
LLVM_ABI bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
LLVM_ABI bool isVectorIntrinsicWithStructReturnOverloadAtField(Intrinsic::ID ID, int RetIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic that returns a struct is overloaded at the struct elem...
TargetTransformInfo TTI
LLVM_ABI void narrowShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Replace each shuffle mask index with the scaled sequential indices for an equivalent mask of narrowed...
LLVM_ABI bool isMaskedSlidePair(ArrayRef< int > Mask, int NumElts, std::array< std::pair< int, int >, 2 > &SrcInfo)
Does this shuffle mask represent either one slide shuffle or a pair of two slide shuffles,...
LLVM_ABI VectorType * getDeinterleavedVectorType(IntrinsicInst *DI)
Given a deinterleaveN intrinsic, return the (narrow) vector type of each factor.
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
LLVM_ABI std::optional< unsigned > getVectorMemoryIntrinsicPointerArgIdx(Intrinsic::ID ID)
Returns the argument index of the pointer parameter for the vector memory intrinsic ID,...
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register,...
LLVM_ABI MDNode * uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2)
Compute the union of two access-group lists.
unsigned M0(unsigned Val)
Definition VE.h:393
LLVM_ABI std::optional< unsigned > getVectorIntrinsicMaskArgIdx(Intrinsic::ID ID)
Returns the argument index of the mask for the vector intrinsic ID, or std::nullopt if the intrinsic ...
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1425
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
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
LLVM_ABI void getShuffleMaskWithWidestElts(ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Repetitively apply widenShuffleMaskElts() for as long as it succeeds, to get the shuffle mask with wi...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI void processShuffleMasks(ArrayRef< int > Mask, unsigned NumOfSrcRegs, unsigned NumOfDestRegs, unsigned NumOfUsedRegs, function_ref< void()> NoInputAction, function_ref< void(ArrayRef< int >, unsigned, unsigned)> SingleInputAction, function_ref< void(ArrayRef< int >, unsigned, unsigned, bool)> ManyInputsAction)
Splits and processes shuffle mask depending on the number of input and output registers.
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI bool maskContainsAllOneOrUndef(Value *Mask)
Given a mask vector of i1, Return true if any of the elements of this predicate mask are known to be ...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI llvm::SmallVector< int, 16 > createSequentialMask(unsigned Start, unsigned NumInts, unsigned NumUndefs)
Create a sequential shuffle mask.
LLVM_ABI bool isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic is overloaded on the type of the operand at index OpdI...
LLVM_ABI MapVector< Instruction *, uint64_t > computeMinimumValueSizes(ArrayRef< BasicBlock * > Blocks, DemandedBits &DB, const TargetTransformInfo *TTI=nullptr)
Compute a map of integer instructions to their minimum legal type size.
LLVM_ABI bool scaleShuffleMaskElts(unsigned NumDstElts, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Attempt to narrow/widen the Mask shuffle mask to the NumDstElts target width.
LLVM_ABI int getSplatIndex(ArrayRef< int > Mask)
If all non-negative Mask elements are the same value, return that value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881