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