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