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