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