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