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