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