LLVM 19.0.0git
VectorUtils.cpp
Go to the documentation of this file.
1//===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines vectorizer utilities.
10//
11//===----------------------------------------------------------------------===//
12
23#include "llvm/IR/Constants.h"
25#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Value.h"
30
31#define DEBUG_TYPE "vectorutils"
32
33using namespace llvm;
34using namespace llvm::PatternMatch;
35
36/// Maximum factor for an interleaved memory access.
38 "max-interleave-group-factor", cl::Hidden,
39 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
40 cl::init(8));
41
42/// Return true if all of the intrinsic's arguments and return type are scalars
43/// for the scalar form of the intrinsic, and vectors for the vector form of the
44/// intrinsic (except operands that are marked as always being scalar by
45/// isVectorIntrinsicWithScalarOpAtArg).
47 switch (ID) {
48 case Intrinsic::abs: // Begin integer bit-manipulation.
49 case Intrinsic::bswap:
50 case Intrinsic::bitreverse:
51 case Intrinsic::ctpop:
52 case Intrinsic::ctlz:
53 case Intrinsic::cttz:
54 case Intrinsic::fshl:
55 case Intrinsic::fshr:
56 case Intrinsic::smax:
57 case Intrinsic::smin:
58 case Intrinsic::umax:
59 case Intrinsic::umin:
60 case Intrinsic::sadd_sat:
61 case Intrinsic::ssub_sat:
62 case Intrinsic::uadd_sat:
63 case Intrinsic::usub_sat:
64 case Intrinsic::smul_fix:
65 case Intrinsic::smul_fix_sat:
66 case Intrinsic::umul_fix:
67 case Intrinsic::umul_fix_sat:
68 case Intrinsic::sqrt: // Begin floating-point.
69 case Intrinsic::sin:
70 case Intrinsic::cos:
71 case Intrinsic::tan:
72 case Intrinsic::exp:
73 case Intrinsic::exp2:
74 case Intrinsic::log:
75 case Intrinsic::log10:
76 case Intrinsic::log2:
77 case Intrinsic::fabs:
78 case Intrinsic::minnum:
79 case Intrinsic::maxnum:
80 case Intrinsic::minimum:
81 case Intrinsic::maximum:
82 case Intrinsic::copysign:
83 case Intrinsic::floor:
84 case Intrinsic::ceil:
85 case Intrinsic::trunc:
86 case Intrinsic::rint:
87 case Intrinsic::nearbyint:
88 case Intrinsic::round:
89 case Intrinsic::roundeven:
90 case Intrinsic::pow:
91 case Intrinsic::fma:
92 case Intrinsic::fmuladd:
93 case Intrinsic::is_fpclass:
94 case Intrinsic::powi:
95 case Intrinsic::canonicalize:
96 case Intrinsic::fptosi_sat:
97 case Intrinsic::fptoui_sat:
98 case Intrinsic::lrint:
99 case Intrinsic::llrint:
100 return true;
101 default:
102 return false;
103 }
104}
105
106/// Identifies if the vector form of the intrinsic has a scalar operand.
108 unsigned ScalarOpdIdx) {
109 switch (ID) {
110 case Intrinsic::abs:
111 case Intrinsic::ctlz:
112 case Intrinsic::cttz:
113 case Intrinsic::is_fpclass:
114 case Intrinsic::powi:
115 return (ScalarOpdIdx == 1);
116 case Intrinsic::smul_fix:
117 case Intrinsic::smul_fix_sat:
118 case Intrinsic::umul_fix:
119 case Intrinsic::umul_fix_sat:
120 return (ScalarOpdIdx == 2);
121 default:
122 return false;
123 }
124}
125
127 int OpdIdx) {
128 assert(ID != Intrinsic::not_intrinsic && "Not an intrinsic!");
129
130 switch (ID) {
131 case Intrinsic::fptosi_sat:
132 case Intrinsic::fptoui_sat:
133 case Intrinsic::lrint:
134 case Intrinsic::llrint:
135 return OpdIdx == -1 || OpdIdx == 0;
136 case Intrinsic::is_fpclass:
137 return OpdIdx == 0;
138 case Intrinsic::powi:
139 return OpdIdx == -1 || OpdIdx == 1;
140 default:
141 return OpdIdx == -1;
142 }
143}
144
145/// Returns intrinsic ID for call.
146/// For the input call instruction it finds mapping intrinsic and returns
147/// its ID, in case it does not found it return not_intrinsic.
149 const TargetLibraryInfo *TLI) {
153
154 if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
155 ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
156 ID == Intrinsic::experimental_noalias_scope_decl ||
157 ID == Intrinsic::sideeffect || ID == Intrinsic::pseudoprobe)
158 return ID;
160}
161
162/// Given a vector and an element number, see if the scalar value is
163/// already around as a register, for example if it were inserted then extracted
164/// from the vector.
165Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
166 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
167 VectorType *VTy = cast<VectorType>(V->getType());
168 // For fixed-length vector, return undef for out of range access.
169 if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
170 unsigned Width = FVTy->getNumElements();
171 if (EltNo >= Width)
172 return UndefValue::get(FVTy->getElementType());
173 }
174
175 if (Constant *C = dyn_cast<Constant>(V))
176 return C->getAggregateElement(EltNo);
177
178 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
179 // If this is an insert to a variable element, we don't know what it is.
180 if (!isa<ConstantInt>(III->getOperand(2)))
181 return nullptr;
182 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
183
184 // If this is an insert to the element we are looking for, return the
185 // inserted value.
186 if (EltNo == IIElt)
187 return III->getOperand(1);
188
189 // Guard against infinite loop on malformed, unreachable IR.
190 if (III == III->getOperand(0))
191 return nullptr;
192
193 // Otherwise, the insertelement doesn't modify the value, recurse on its
194 // vector input.
195 return findScalarElement(III->getOperand(0), EltNo);
196 }
197
198 ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
199 // Restrict the following transformation to fixed-length vector.
200 if (SVI && isa<FixedVectorType>(SVI->getType())) {
201 unsigned LHSWidth =
202 cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements();
203 int InEl = SVI->getMaskValue(EltNo);
204 if (InEl < 0)
205 return UndefValue::get(VTy->getElementType());
206 if (InEl < (int)LHSWidth)
207 return findScalarElement(SVI->getOperand(0), InEl);
208 return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
209 }
210
211 // Extract a value from a vector add operation with a constant zero.
212 // TODO: Use getBinOpIdentity() to generalize this.
213 Value *Val; Constant *C;
214 if (match(V, m_Add(m_Value(Val), m_Constant(C))))
215 if (Constant *Elt = C->getAggregateElement(EltNo))
216 if (Elt->isNullValue())
217 return findScalarElement(Val, EltNo);
218
219 // If the vector is a splat then we can trivially find the scalar element.
220 if (isa<ScalableVectorType>(VTy))
221 if (Value *Splat = getSplatValue(V))
222 if (EltNo < VTy->getElementCount().getKnownMinValue())
223 return Splat;
224
225 // Otherwise, we don't know.
226 return nullptr;
227}
228
230 int SplatIndex = -1;
231 for (int M : Mask) {
232 // Ignore invalid (undefined) mask elements.
233 if (M < 0)
234 continue;
235
236 // There can be only 1 non-negative mask element value if this is a splat.
237 if (SplatIndex != -1 && SplatIndex != M)
238 return -1;
239
240 // Initialize the splat index to the 1st non-negative mask element.
241 SplatIndex = M;
242 }
243 assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?");
244 return SplatIndex;
245}
246
247/// Get splat value if the input is a splat vector or return nullptr.
248/// This function is not fully general. It checks only 2 cases:
249/// the input value is (1) a splat constant vector or (2) a sequence
250/// of instructions that broadcasts a scalar at element 0.
252 if (isa<VectorType>(V->getType()))
253 if (auto *C = dyn_cast<Constant>(V))
254 return C->getSplatValue();
255
256 // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
257 Value *Splat;
258 if (match(V,
260 m_Value(), m_ZeroMask())))
261 return Splat;
262
263 return nullptr;
264}
265
266bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) {
267 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
268
269 if (isa<VectorType>(V->getType())) {
270 if (isa<UndefValue>(V))
271 return true;
272 // FIXME: We can allow undefs, but if Index was specified, we may want to
273 // check that the constant is defined at that index.
274 if (auto *C = dyn_cast<Constant>(V))
275 return C->getSplatValue() != nullptr;
276 }
277
278 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) {
279 // FIXME: We can safely allow undefs here. If Index was specified, we will
280 // check that the mask elt is defined at the required index.
281 if (!all_equal(Shuf->getShuffleMask()))
282 return false;
283
284 // Match any index.
285 if (Index == -1)
286 return true;
287
288 // Match a specific element. The mask should be defined at and match the
289 // specified index.
290 return Shuf->getMaskValue(Index) == Index;
291 }
292
293 // The remaining tests are all recursive, so bail out if we hit the limit.
295 return false;
296
297 // If both operands of a binop are splats, the result is a splat.
298 Value *X, *Y, *Z;
299 if (match(V, m_BinOp(m_Value(X), m_Value(Y))))
301
302 // If all operands of a select are splats, the result is a splat.
303 if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z))))
304 return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) &&
306
307 // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
308
309 return false;
310}
311
313 const APInt &DemandedElts, APInt &DemandedLHS,
314 APInt &DemandedRHS, bool AllowUndefElts) {
315 DemandedLHS = DemandedRHS = APInt::getZero(SrcWidth);
316
317 // Early out if we don't demand any elements.
318 if (DemandedElts.isZero())
319 return true;
320
321 // Simple case of a shuffle with zeroinitializer.
322 if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
323 DemandedLHS.setBit(0);
324 return true;
325 }
326
327 for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
328 int M = Mask[I];
329 assert((-1 <= M) && (M < (SrcWidth * 2)) &&
330 "Invalid shuffle mask constant");
331
332 if (!DemandedElts[I] || (AllowUndefElts && (M < 0)))
333 continue;
334
335 // For undef elements, we don't know anything about the common state of
336 // the shuffle result.
337 if (M < 0)
338 return false;
339
340 if (M < SrcWidth)
341 DemandedLHS.setBit(M);
342 else
343 DemandedRHS.setBit(M - SrcWidth);
344 }
345
346 return true;
347}
348
350 SmallVectorImpl<int> &ScaledMask) {
351 assert(Scale > 0 && "Unexpected scaling factor");
352
353 // Fast-path: if no scaling, then it is just a copy.
354 if (Scale == 1) {
355 ScaledMask.assign(Mask.begin(), Mask.end());
356 return;
357 }
358
359 ScaledMask.clear();
360 for (int MaskElt : Mask) {
361 if (MaskElt >= 0) {
362 assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= INT32_MAX &&
363 "Overflowed 32-bits");
364 }
365 for (int SliceElt = 0; SliceElt != Scale; ++SliceElt)
366 ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt);
367 }
368}
369
371 SmallVectorImpl<int> &ScaledMask) {
372 assert(Scale > 0 && "Unexpected scaling factor");
373
374 // Fast-path: if no scaling, then it is just a copy.
375 if (Scale == 1) {
376 ScaledMask.assign(Mask.begin(), Mask.end());
377 return true;
378 }
379
380 // We must map the original elements down evenly to a type with less elements.
381 int NumElts = Mask.size();
382 if (NumElts % Scale != 0)
383 return false;
384
385 ScaledMask.clear();
386 ScaledMask.reserve(NumElts / Scale);
387
388 // Step through the input mask by splitting into Scale-sized slices.
389 do {
390 ArrayRef<int> MaskSlice = Mask.take_front(Scale);
391 assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice.");
392
393 // The first element of the slice determines how we evaluate this slice.
394 int SliceFront = MaskSlice.front();
395 if (SliceFront < 0) {
396 // Negative values (undef or other "sentinel" values) must be equal across
397 // the entire slice.
398 if (!all_equal(MaskSlice))
399 return false;
400 ScaledMask.push_back(SliceFront);
401 } else {
402 // A positive mask element must be cleanly divisible.
403 if (SliceFront % Scale != 0)
404 return false;
405 // Elements of the slice must be consecutive.
406 for (int i = 1; i < Scale; ++i)
407 if (MaskSlice[i] != SliceFront + i)
408 return false;
409 ScaledMask.push_back(SliceFront / Scale);
410 }
411 Mask = Mask.drop_front(Scale);
412 } while (!Mask.empty());
413
414 assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask");
415
416 // All elements of the original mask can be scaled down to map to the elements
417 // of a mask with wider elements.
418 return true;
419}
420
422 SmallVectorImpl<int> &ScaledMask) {
423 std::array<SmallVector<int, 16>, 2> TmpMasks;
424 SmallVectorImpl<int> *Output = &TmpMasks[0], *Tmp = &TmpMasks[1];
425 ArrayRef<int> InputMask = Mask;
426 for (unsigned Scale = 2; Scale <= InputMask.size(); ++Scale) {
427 while (widenShuffleMaskElts(Scale, InputMask, *Output)) {
428 InputMask = *Output;
429 std::swap(Output, Tmp);
430 }
431 }
432 ScaledMask.assign(InputMask.begin(), InputMask.end());
433}
434
436 ArrayRef<int> Mask, unsigned NumOfSrcRegs, unsigned NumOfDestRegs,
437 unsigned NumOfUsedRegs, function_ref<void()> NoInputAction,
438 function_ref<void(ArrayRef<int>, unsigned, unsigned)> SingleInputAction,
439 function_ref<void(ArrayRef<int>, unsigned, unsigned)> ManyInputsAction) {
440 SmallVector<SmallVector<SmallVector<int>>> Res(NumOfDestRegs);
441 // Try to perform better estimation of the permutation.
442 // 1. Split the source/destination vectors into real registers.
443 // 2. Do the mask analysis to identify which real registers are
444 // permuted.
445 int Sz = Mask.size();
446 unsigned SzDest = Sz / NumOfDestRegs;
447 unsigned SzSrc = Sz / NumOfSrcRegs;
448 for (unsigned I = 0; I < NumOfDestRegs; ++I) {
449 auto &RegMasks = Res[I];
450 RegMasks.assign(NumOfSrcRegs, {});
451 // Check that the values in dest registers are in the one src
452 // register.
453 for (unsigned K = 0; K < SzDest; ++K) {
454 int Idx = I * SzDest + K;
455 if (Idx == Sz)
456 break;
457 if (Mask[Idx] >= Sz || Mask[Idx] == PoisonMaskElem)
458 continue;
459 int SrcRegIdx = Mask[Idx] / SzSrc;
460 // Add a cost of PermuteTwoSrc for each new source register permute,
461 // if we have more than one source registers.
462 if (RegMasks[SrcRegIdx].empty())
463 RegMasks[SrcRegIdx].assign(SzDest, PoisonMaskElem);
464 RegMasks[SrcRegIdx][K] = Mask[Idx] % SzSrc;
465 }
466 }
467 // Process split mask.
468 for (unsigned I = 0; I < NumOfUsedRegs; ++I) {
469 auto &Dest = Res[I];
470 int NumSrcRegs =
471 count_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
472 switch (NumSrcRegs) {
473 case 0:
474 // No input vectors were used!
475 NoInputAction();
476 break;
477 case 1: {
478 // Find the only mask with at least single undef mask elem.
479 auto *It =
480 find_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
481 unsigned SrcReg = std::distance(Dest.begin(), It);
482 SingleInputAction(*It, SrcReg, I);
483 break;
484 }
485 default: {
486 // The first mask is a permutation of a single register. Since we have >2
487 // input registers to shuffle, we merge the masks for 2 first registers
488 // and generate a shuffle of 2 registers rather than the reordering of the
489 // first register and then shuffle with the second register. Next,
490 // generate the shuffles of the resulting register + the remaining
491 // registers from the list.
492 auto &&CombineMasks = [](MutableArrayRef<int> FirstMask,
493 ArrayRef<int> SecondMask) {
494 for (int Idx = 0, VF = FirstMask.size(); Idx < VF; ++Idx) {
495 if (SecondMask[Idx] != PoisonMaskElem) {
496 assert(FirstMask[Idx] == PoisonMaskElem &&
497 "Expected undefined mask element.");
498 FirstMask[Idx] = SecondMask[Idx] + VF;
499 }
500 }
501 };
502 auto &&NormalizeMask = [](MutableArrayRef<int> Mask) {
503 for (int Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
504 if (Mask[Idx] != PoisonMaskElem)
505 Mask[Idx] = Idx;
506 }
507 };
508 int SecondIdx;
509 do {
510 int FirstIdx = -1;
511 SecondIdx = -1;
512 MutableArrayRef<int> FirstMask, SecondMask;
513 for (unsigned I = 0; I < NumOfDestRegs; ++I) {
514 SmallVectorImpl<int> &RegMask = Dest[I];
515 if (RegMask.empty())
516 continue;
517
518 if (FirstIdx == SecondIdx) {
519 FirstIdx = I;
520 FirstMask = RegMask;
521 continue;
522 }
523 SecondIdx = I;
524 SecondMask = RegMask;
525 CombineMasks(FirstMask, SecondMask);
526 ManyInputsAction(FirstMask, FirstIdx, SecondIdx);
527 NormalizeMask(FirstMask);
528 RegMask.clear();
529 SecondMask = FirstMask;
530 SecondIdx = FirstIdx;
531 }
532 if (FirstIdx != SecondIdx && SecondIdx >= 0) {
533 CombineMasks(SecondMask, FirstMask);
534 ManyInputsAction(SecondMask, SecondIdx, FirstIdx);
535 Dest[FirstIdx].clear();
536 NormalizeMask(SecondMask);
537 }
538 } while (SecondIdx >= 0);
539 break;
541 }
542 }
543}
544
547 const TargetTransformInfo *TTI) {
548
549 // DemandedBits will give us every value's live-out bits. But we want
550 // to ensure no extra casts would need to be inserted, so every DAG
551 // of connected values must have the same minimum bitwidth.
557 SmallPtrSet<Instruction *, 4> InstructionSet;
559
560 // Determine the roots. We work bottom-up, from truncs or icmps.
561 bool SeenExtFromIllegalType = false;
562 for (auto *BB : Blocks)
563 for (auto &I : *BB) {
564 InstructionSet.insert(&I);
565
566 if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
567 !TTI->isTypeLegal(I.getOperand(0)->getType()))
568 SeenExtFromIllegalType = true;
569
570 // Only deal with non-vector integers up to 64-bits wide.
571 if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
572 !I.getType()->isVectorTy() &&
573 I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
574 // Don't make work for ourselves. If we know the loaded type is legal,
575 // don't add it to the worklist.
576 if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
577 continue;
578
579 Worklist.push_back(&I);
580 Roots.insert(&I);
581 }
582 }
583 // Early exit.
584 if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
585 return MinBWs;
586
587 // Now proceed breadth-first, unioning values together.
588 while (!Worklist.empty()) {
589 Value *Val = Worklist.pop_back_val();
590 Value *Leader = ECs.getOrInsertLeaderValue(Val);
591
592 if (!Visited.insert(Val).second)
593 continue;
594
595 // Non-instructions terminate a chain successfully.
596 if (!isa<Instruction>(Val))
597 continue;
598 Instruction *I = cast<Instruction>(Val);
599
600 // If we encounter a type that is larger than 64 bits, we can't represent
601 // it so bail out.
602 if (DB.getDemandedBits(I).getBitWidth() > 64)
604
605 uint64_t V = DB.getDemandedBits(I).getZExtValue();
606 DBits[Leader] |= V;
607 DBits[I] = V;
608
609 // Casts, loads and instructions outside of our range terminate a chain
610 // successfully.
611 if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
612 !InstructionSet.count(I))
613 continue;
614
615 // Unsafe casts terminate a chain unsuccessfully. We can't do anything
616 // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
617 // transform anything that relies on them.
618 if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
619 !I->getType()->isIntegerTy()) {
620 DBits[Leader] |= ~0ULL;
621 continue;
622 }
623
624 // We don't modify the types of PHIs. Reductions will already have been
625 // truncated if possible, and inductions' sizes will have been chosen by
626 // indvars.
627 if (isa<PHINode>(I))
628 continue;
629
630 if (DBits[Leader] == ~0ULL)
631 // All bits demanded, no point continuing.
632 continue;
633
634 for (Value *O : cast<User>(I)->operands()) {
635 ECs.unionSets(Leader, O);
636 Worklist.push_back(O);
637 }
638 }
639
640 // Now we've discovered all values, walk them to see if there are
641 // any users we didn't see. If there are, we can't optimize that
642 // chain.
643 for (auto &I : DBits)
644 for (auto *U : I.first->users())
645 if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
646 DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
647
648 for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
649 uint64_t LeaderDemandedBits = 0;
650 for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
651 LeaderDemandedBits |= DBits[M];
652
653 uint64_t MinBW = llvm::bit_width(LeaderDemandedBits);
654 // Round up to a power of 2
655 MinBW = llvm::bit_ceil(MinBW);
656
657 // We don't modify the types of PHIs. Reductions will already have been
658 // truncated if possible, and inductions' sizes will have been chosen by
659 // indvars.
660 // If we are required to shrink a PHI, abandon this entire equivalence class.
661 bool Abort = false;
662 for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
663 if (isa<PHINode>(M) && MinBW < M->getType()->getScalarSizeInBits()) {
664 Abort = true;
665 break;
666 }
667 if (Abort)
668 continue;
669
670 for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end())) {
671 auto *MI = dyn_cast<Instruction>(M);
672 if (!MI)
673 continue;
674 Type *Ty = M->getType();
675 if (Roots.count(M))
676 Ty = MI->getOperand(0)->getType();
677
678 if (MinBW >= Ty->getScalarSizeInBits())
679 continue;
680
681 // If any of M's operands demand more bits than MinBW then M cannot be
682 // performed safely in MinBW.
683 if (any_of(MI->operands(), [&DB, MinBW](Use &U) {
684 auto *CI = dyn_cast<ConstantInt>(U);
685 // For constants shift amounts, check if the shift would result in
686 // poison.
687 if (CI &&
688 isa<ShlOperator, LShrOperator, AShrOperator>(U.getUser()) &&
689 U.getOperandNo() == 1)
690 return CI->uge(MinBW);
691 uint64_t BW = bit_width(DB.getDemandedBits(&U).getZExtValue());
692 return bit_ceil(BW) > MinBW;
693 }))
694 continue;
695
696 MinBWs[MI] = MinBW;
697 }
698 }
699
700 return MinBWs;
701}
702
703/// Add all access groups in @p AccGroups to @p List.
704template <typename ListT>
705static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
706 // Interpret an access group as a list containing itself.
707 if (AccGroups->getNumOperands() == 0) {
708 assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
709 List.insert(AccGroups);
710 return;
711 }
712
713 for (const auto &AccGroupListOp : AccGroups->operands()) {
714 auto *Item = cast<MDNode>(AccGroupListOp.get());
715 assert(isValidAsAccessGroup(Item) && "List item must be an access group");
716 List.insert(Item);
717 }
718}
719
720MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
721 if (!AccGroups1)
722 return AccGroups2;
723 if (!AccGroups2)
724 return AccGroups1;
725 if (AccGroups1 == AccGroups2)
726 return AccGroups1;
727
729 addToAccessGroupList(Union, AccGroups1);
730 addToAccessGroupList(Union, AccGroups2);
731
732 if (Union.size() == 0)
733 return nullptr;
734 if (Union.size() == 1)
735 return cast<MDNode>(Union.front());
736
737 LLVMContext &Ctx = AccGroups1->getContext();
738 return MDNode::get(Ctx, Union.getArrayRef());
739}
740
742 const Instruction *Inst2) {
743 bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
744 bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
745
746 if (!MayAccessMem1 && !MayAccessMem2)
747 return nullptr;
748 if (!MayAccessMem1)
749 return Inst2->getMetadata(LLVMContext::MD_access_group);
750 if (!MayAccessMem2)
751 return Inst1->getMetadata(LLVMContext::MD_access_group);
752
753 MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
754 MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
755 if (!MD1 || !MD2)
756 return nullptr;
757 if (MD1 == MD2)
758 return MD1;
759
760 // Use set for scalable 'contains' check.
761 SmallPtrSet<Metadata *, 4> AccGroupSet2;
762 addToAccessGroupList(AccGroupSet2, MD2);
763
764 SmallVector<Metadata *, 4> Intersection;
765 if (MD1->getNumOperands() == 0) {
766 assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
767 if (AccGroupSet2.count(MD1))
768 Intersection.push_back(MD1);
769 } else {
770 for (const MDOperand &Node : MD1->operands()) {
771 auto *Item = cast<MDNode>(Node.get());
772 assert(isValidAsAccessGroup(Item) && "List item must be an access group");
773 if (AccGroupSet2.count(Item))
774 Intersection.push_back(Item);
775 }
776 }
777
778 if (Intersection.size() == 0)
779 return nullptr;
780 if (Intersection.size() == 1)
781 return cast<MDNode>(Intersection.front());
782
783 LLVMContext &Ctx = Inst1->getContext();
784 return MDNode::get(Ctx, Intersection);
785}
786
787/// \returns \p I after propagating metadata from \p VL.
789 if (VL.empty())
790 return Inst;
791 Instruction *I0 = cast<Instruction>(VL[0]);
794
795 for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
796 LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
797 LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
798 LLVMContext::MD_access_group, LLVMContext::MD_mmra}) {
799 MDNode *MD = I0->getMetadata(Kind);
800 for (int J = 1, E = VL.size(); MD && J != E; ++J) {
801 const Instruction *IJ = cast<Instruction>(VL[J]);
802 MDNode *IMD = IJ->getMetadata(Kind);
803
804 switch (Kind) {
805 case LLVMContext::MD_mmra: {
806 MD = MMRAMetadata::combine(Inst->getContext(), MD, IMD);
807 break;
808 }
809 case LLVMContext::MD_tbaa:
810 MD = MDNode::getMostGenericTBAA(MD, IMD);
811 break;
812 case LLVMContext::MD_alias_scope:
814 break;
815 case LLVMContext::MD_fpmath:
816 MD = MDNode::getMostGenericFPMath(MD, IMD);
817 break;
818 case LLVMContext::MD_noalias:
819 case LLVMContext::MD_nontemporal:
820 case LLVMContext::MD_invariant_load:
821 MD = MDNode::intersect(MD, IMD);
822 break;
823 case LLVMContext::MD_access_group:
824 MD = intersectAccessGroups(Inst, IJ);
825 break;
826 default:
827 llvm_unreachable("unhandled metadata");
828 }
829 }
830
831 Inst->setMetadata(Kind, MD);
832 }
833
834 return Inst;
835}
836
837Constant *
839 const InterleaveGroup<Instruction> &Group) {
840 // All 1's means mask is not needed.
841 if (Group.getNumMembers() == Group.getFactor())
842 return nullptr;
843
844 // TODO: support reversed access.
845 assert(!Group.isReverse() && "Reversed group not supported.");
846
848 for (unsigned i = 0; i < VF; i++)
849 for (unsigned j = 0; j < Group.getFactor(); ++j) {
850 unsigned HasMember = Group.getMember(j) ? 1 : 0;
851 Mask.push_back(Builder.getInt1(HasMember));
852 }
853
854 return ConstantVector::get(Mask);
855}
856
858llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) {
859 SmallVector<int, 16> MaskVec;
860 for (unsigned i = 0; i < VF; i++)
861 for (unsigned j = 0; j < ReplicationFactor; j++)
862 MaskVec.push_back(i);
863
864 return MaskVec;
865}
866
868 unsigned NumVecs) {
870 for (unsigned i = 0; i < VF; i++)
871 for (unsigned j = 0; j < NumVecs; j++)
872 Mask.push_back(j * VF + i);
873
874 return Mask;
875}
876
878llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) {
880 for (unsigned i = 0; i < VF; i++)
881 Mask.push_back(Start + i * Stride);
882
883 return Mask;
884}
885
887 unsigned NumInts,
888 unsigned NumUndefs) {
890 for (unsigned i = 0; i < NumInts; i++)
891 Mask.push_back(Start + i);
892
893 for (unsigned i = 0; i < NumUndefs; i++)
894 Mask.push_back(-1);
895
896 return Mask;
897}
898
900 unsigned NumElts) {
901 // Avoid casts in the loop and make sure we have a reasonable number.
902 int NumEltsSigned = NumElts;
903 assert(NumEltsSigned > 0 && "Expected smaller or non-zero element count");
904
905 // If the mask chooses an element from operand 1, reduce it to choose from the
906 // corresponding element of operand 0. Undef mask elements are unchanged.
907 SmallVector<int, 16> UnaryMask;
908 for (int MaskElt : Mask) {
909 assert((MaskElt < NumEltsSigned * 2) && "Expected valid shuffle mask");
910 int UnaryElt = MaskElt >= NumEltsSigned ? MaskElt - NumEltsSigned : MaskElt;
911 UnaryMask.push_back(UnaryElt);
912 }
913 return UnaryMask;
914}
915
916/// A helper function for concatenating vectors. This function concatenates two
917/// vectors having the same element type. If the second vector has fewer
918/// elements than the first, it is padded with undefs.
920 Value *V2) {
921 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
922 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
923 assert(VecTy1 && VecTy2 &&
924 VecTy1->getScalarType() == VecTy2->getScalarType() &&
925 "Expect two vectors with the same element type");
926
927 unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements();
928 unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements();
929 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
930
931 if (NumElts1 > NumElts2) {
932 // Extend with UNDEFs.
933 V2 = Builder.CreateShuffleVector(
934 V2, createSequentialMask(0, NumElts2, NumElts1 - NumElts2));
935 }
936
937 return Builder.CreateShuffleVector(
938 V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0));
939}
940
942 ArrayRef<Value *> Vecs) {
943 unsigned NumVecs = Vecs.size();
944 assert(NumVecs > 1 && "Should be at least two vectors");
945
947 ResList.append(Vecs.begin(), Vecs.end());
948 do {
950 for (unsigned i = 0; i < NumVecs - 1; i += 2) {
951 Value *V0 = ResList[i], *V1 = ResList[i + 1];
952 assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
953 "Only the last vector may have a different type");
954
955 TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
956 }
957
958 // Push the last vector if the total number of vectors is odd.
959 if (NumVecs % 2 != 0)
960 TmpList.push_back(ResList[NumVecs - 1]);
961
962 ResList = TmpList;
963 NumVecs = ResList.size();
964 } while (NumVecs > 1);
965
966 return ResList[0];
967}
968
970 assert(isa<VectorType>(Mask->getType()) &&
971 isa<IntegerType>(Mask->getType()->getScalarType()) &&
972 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
973 1 &&
974 "Mask must be a vector of i1");
975
976 auto *ConstMask = dyn_cast<Constant>(Mask);
977 if (!ConstMask)
978 return false;
979 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
980 return true;
981 if (isa<ScalableVectorType>(ConstMask->getType()))
982 return false;
983 for (unsigned
984 I = 0,
985 E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
986 I != E; ++I) {
987 if (auto *MaskElt = ConstMask->getAggregateElement(I))
988 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
989 continue;
990 return false;
991 }
992 return true;
993}
994
996 assert(isa<VectorType>(Mask->getType()) &&
997 isa<IntegerType>(Mask->getType()->getScalarType()) &&
998 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
999 1 &&
1000 "Mask must be a vector of i1");
1001
1002 auto *ConstMask = dyn_cast<Constant>(Mask);
1003 if (!ConstMask)
1004 return false;
1005 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1006 return true;
1007 if (isa<ScalableVectorType>(ConstMask->getType()))
1008 return false;
1009 for (unsigned
1010 I = 0,
1011 E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
1012 I != E; ++I) {
1013 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1014 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1015 continue;
1016 return false;
1017 }
1018 return true;
1019}
1020
1022 assert(isa<VectorType>(Mask->getType()) &&
1023 isa<IntegerType>(Mask->getType()->getScalarType()) &&
1024 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1025 1 &&
1026 "Mask must be a vector of i1");
1027
1028 auto *ConstMask = dyn_cast<Constant>(Mask);
1029 if (!ConstMask)
1030 return false;
1031 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1032 return true;
1033 if (isa<ScalableVectorType>(ConstMask->getType()))
1034 return false;
1035 for (unsigned
1036 I = 0,
1037 E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
1038 I != E; ++I) {
1039 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1040 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1041 return true;
1042 }
1043 return false;
1044}
1045
1046/// TODO: This is a lot like known bits, but for
1047/// vectors. Is there something we can common this with?
1049 assert(isa<FixedVectorType>(Mask->getType()) &&
1050 isa<IntegerType>(Mask->getType()->getScalarType()) &&
1051 cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1052 1 &&
1053 "Mask must be a fixed width vector of i1");
1054
1055 const unsigned VWidth =
1056 cast<FixedVectorType>(Mask->getType())->getNumElements();
1057 APInt DemandedElts = APInt::getAllOnes(VWidth);
1058 if (auto *CV = dyn_cast<ConstantVector>(Mask))
1059 for (unsigned i = 0; i < VWidth; i++)
1060 if (CV->getAggregateElement(i)->isNullValue())
1061 DemandedElts.clearBit(i);
1062 return DemandedElts;
1063}
1064
1065bool InterleavedAccessInfo::isStrided(int Stride) {
1066 unsigned Factor = std::abs(Stride);
1067 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
1068}
1069
1070void InterleavedAccessInfo::collectConstStrideAccesses(
1072 const DenseMap<Value*, const SCEV*> &Strides) {
1073 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
1074
1075 // Since it's desired that the load/store instructions be maintained in
1076 // "program order" for the interleaved access analysis, we have to visit the
1077 // blocks in the loop in reverse postorder (i.e., in a topological order).
1078 // Such an ordering will ensure that any load/store that may be executed
1079 // before a second load/store will precede the second load/store in
1080 // AccessStrideInfo.
1081 LoopBlocksDFS DFS(TheLoop);
1082 DFS.perform(LI);
1083 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
1084 for (auto &I : *BB) {
1086 if (!Ptr)
1087 continue;
1088 Type *ElementTy = getLoadStoreType(&I);
1089
1090 // Currently, codegen doesn't support cases where the type size doesn't
1091 // match the alloc size. Skip them for now.
1092 uint64_t Size = DL.getTypeAllocSize(ElementTy);
1093 if (Size * 8 != DL.getTypeSizeInBits(ElementTy))
1094 continue;
1095
1096 // We don't check wrapping here because we don't know yet if Ptr will be
1097 // part of a full group or a group with gaps. Checking wrapping for all
1098 // pointers (even those that end up in groups with no gaps) will be overly
1099 // conservative. For full groups, wrapping should be ok since if we would
1100 // wrap around the address space we would do a memory access at nullptr
1101 // even without the transformation. The wrapping checks are therefore
1102 // deferred until after we've formed the interleaved groups.
1103 int64_t Stride =
1104 getPtrStride(PSE, ElementTy, Ptr, TheLoop, Strides,
1105 /*Assume=*/true, /*ShouldCheckWrap=*/false).value_or(0);
1106
1107 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
1108 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size,
1110 }
1111}
1112
1113// Analyze interleaved accesses and collect them into interleaved load and
1114// store groups.
1115//
1116// When generating code for an interleaved load group, we effectively hoist all
1117// loads in the group to the location of the first load in program order. When
1118// generating code for an interleaved store group, we sink all stores to the
1119// location of the last store. This code motion can change the order of load
1120// and store instructions and may break dependences.
1121//
1122// The code generation strategy mentioned above ensures that we won't violate
1123// any write-after-read (WAR) dependences.
1124//
1125// E.g., for the WAR dependence: a = A[i]; // (1)
1126// A[i] = b; // (2)
1127//
1128// The store group of (2) is always inserted at or below (2), and the load
1129// group of (1) is always inserted at or above (1). Thus, the instructions will
1130// never be reordered. All other dependences are checked to ensure the
1131// correctness of the instruction reordering.
1132//
1133// The algorithm visits all memory accesses in the loop in bottom-up program
1134// order. Program order is established by traversing the blocks in the loop in
1135// reverse postorder when collecting the accesses.
1136//
1137// We visit the memory accesses in bottom-up order because it can simplify the
1138// construction of store groups in the presence of write-after-write (WAW)
1139// dependences.
1140//
1141// E.g., for the WAW dependence: A[i] = a; // (1)
1142// A[i] = b; // (2)
1143// A[i + 1] = c; // (3)
1144//
1145// We will first create a store group with (3) and (2). (1) can't be added to
1146// this group because it and (2) are dependent. However, (1) can be grouped
1147// with other accesses that may precede it in program order. Note that a
1148// bottom-up order does not imply that WAW dependences should not be checked.
1150 bool EnablePredicatedInterleavedMemAccesses) {
1151 LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
1152 const auto &Strides = LAI->getSymbolicStrides();
1153
1154 // Holds all accesses with a constant stride.
1156 collectConstStrideAccesses(AccessStrideInfo, Strides);
1157
1158 if (AccessStrideInfo.empty())
1159 return;
1160
1161 // Collect the dependences in the loop.
1162 collectDependences();
1163
1164 // Holds all interleaved store groups temporarily.
1166 // Holds all interleaved load groups temporarily.
1168 // Groups added to this set cannot have new members added.
1169 SmallPtrSet<InterleaveGroup<Instruction> *, 4> CompletedLoadGroups;
1170
1171 // Search in bottom-up program order for pairs of accesses (A and B) that can
1172 // form interleaved load or store groups. In the algorithm below, access A
1173 // precedes access B in program order. We initialize a group for B in the
1174 // outer loop of the algorithm, and then in the inner loop, we attempt to
1175 // insert each A into B's group if:
1176 //
1177 // 1. A and B have the same stride,
1178 // 2. A and B have the same memory object size, and
1179 // 3. A belongs in B's group according to its distance from B.
1180 //
1181 // Special care is taken to ensure group formation will not break any
1182 // dependences.
1183 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
1184 BI != E; ++BI) {
1185 Instruction *B = BI->first;
1186 StrideDescriptor DesB = BI->second;
1187
1188 // Initialize a group for B if it has an allowable stride. Even if we don't
1189 // create a group for B, we continue with the bottom-up algorithm to ensure
1190 // we don't break any of B's dependences.
1191 InterleaveGroup<Instruction> *GroupB = nullptr;
1192 if (isStrided(DesB.Stride) &&
1193 (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
1194 GroupB = getInterleaveGroup(B);
1195 if (!GroupB) {
1196 LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
1197 << '\n');
1198 GroupB = createInterleaveGroup(B, DesB.Stride, DesB.Alignment);
1199 if (B->mayWriteToMemory())
1200 StoreGroups.insert(GroupB);
1201 else
1202 LoadGroups.insert(GroupB);
1203 }
1204 }
1205
1206 for (auto AI = std::next(BI); AI != E; ++AI) {
1207 Instruction *A = AI->first;
1208 StrideDescriptor DesA = AI->second;
1209
1210 // Our code motion strategy implies that we can't have dependences
1211 // between accesses in an interleaved group and other accesses located
1212 // between the first and last member of the group. Note that this also
1213 // means that a group can't have more than one member at a given offset.
1214 // The accesses in a group can have dependences with other accesses, but
1215 // we must ensure we don't extend the boundaries of the group such that
1216 // we encompass those dependent accesses.
1217 //
1218 // For example, assume we have the sequence of accesses shown below in a
1219 // stride-2 loop:
1220 //
1221 // (1, 2) is a group | A[i] = a; // (1)
1222 // | A[i-1] = b; // (2) |
1223 // A[i-3] = c; // (3)
1224 // A[i] = d; // (4) | (2, 4) is not a group
1225 //
1226 // Because accesses (2) and (3) are dependent, we can group (2) with (1)
1227 // but not with (4). If we did, the dependent access (3) would be within
1228 // the boundaries of the (2, 4) group.
1229 auto DependentMember = [&](InterleaveGroup<Instruction> *Group,
1230 StrideEntry *A) -> Instruction * {
1231 for (uint32_t Index = 0; Index < Group->getFactor(); ++Index) {
1232 Instruction *MemberOfGroupB = Group->getMember(Index);
1233 if (MemberOfGroupB && !canReorderMemAccessesForInterleavedGroups(
1234 A, &*AccessStrideInfo.find(MemberOfGroupB)))
1235 return MemberOfGroupB;
1236 }
1237 return nullptr;
1238 };
1239
1240 auto GroupA = getInterleaveGroup(A);
1241 // If A is a load, dependencies are tolerable, there's nothing to do here.
1242 // If both A and B belong to the same (store) group, they are independent,
1243 // even if dependencies have not been recorded.
1244 // If both GroupA and GroupB are null, there's nothing to do here.
1245 if (A->mayWriteToMemory() && GroupA != GroupB) {
1246 Instruction *DependentInst = nullptr;
1247 // If GroupB is a load group, we have to compare AI against all
1248 // members of GroupB because if any load within GroupB has a dependency
1249 // on AI, we need to mark GroupB as complete and also release the
1250 // store GroupA (if A belongs to one). The former prevents incorrect
1251 // hoisting of load B above store A while the latter prevents incorrect
1252 // sinking of store A below load B.
1253 if (GroupB && LoadGroups.contains(GroupB))
1254 DependentInst = DependentMember(GroupB, &*AI);
1255 else if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI))
1256 DependentInst = B;
1257
1258 if (DependentInst) {
1259 // A has a store dependence on B (or on some load within GroupB) and
1260 // is part of a store group. Release A's group to prevent illegal
1261 // sinking of A below B. A will then be free to form another group
1262 // with instructions that precede it.
1263 if (GroupA && StoreGroups.contains(GroupA)) {
1264 LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
1265 "dependence between "
1266 << *A << " and " << *DependentInst << '\n');
1267 StoreGroups.remove(GroupA);
1268 releaseGroup(GroupA);
1269 }
1270 // If B is a load and part of an interleave group, no earlier loads
1271 // can be added to B's interleave group, because this would mean the
1272 // DependentInst would move across store A. Mark the interleave group
1273 // as complete.
1274 if (GroupB && LoadGroups.contains(GroupB)) {
1275 LLVM_DEBUG(dbgs() << "LV: Marking interleave group for " << *B
1276 << " as complete.\n");
1277 CompletedLoadGroups.insert(GroupB);
1278 }
1279 }
1280 }
1281 if (CompletedLoadGroups.contains(GroupB)) {
1282 // Skip trying to add A to B, continue to look for other conflicting A's
1283 // in groups to be released.
1284 continue;
1285 }
1286
1287 // At this point, we've checked for illegal code motion. If either A or B
1288 // isn't strided, there's nothing left to do.
1289 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
1290 continue;
1291
1292 // Ignore A if it's already in a group or isn't the same kind of memory
1293 // operation as B.
1294 // Note that mayReadFromMemory() isn't mutually exclusive to
1295 // mayWriteToMemory in the case of atomic loads. We shouldn't see those
1296 // here, canVectorizeMemory() should have returned false - except for the
1297 // case we asked for optimization remarks.
1298 if (isInterleaved(A) ||
1299 (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
1300 (A->mayWriteToMemory() != B->mayWriteToMemory()))
1301 continue;
1302
1303 // Check rules 1 and 2. Ignore A if its stride or size is different from
1304 // that of B.
1305 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
1306 continue;
1307
1308 // Ignore A if the memory object of A and B don't belong to the same
1309 // address space
1311 continue;
1312
1313 // Calculate the distance from A to B.
1314 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
1315 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
1316 if (!DistToB)
1317 continue;
1318 int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
1319
1320 // Check rule 3. Ignore A if its distance to B is not a multiple of the
1321 // size.
1322 if (DistanceToB % static_cast<int64_t>(DesB.Size))
1323 continue;
1324
1325 // All members of a predicated interleave-group must have the same predicate,
1326 // and currently must reside in the same BB.
1327 BasicBlock *BlockA = A->getParent();
1328 BasicBlock *BlockB = B->getParent();
1329 if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
1330 (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
1331 continue;
1332
1333 // The index of A is the index of B plus A's distance to B in multiples
1334 // of the size.
1335 int IndexA =
1336 GroupB->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
1337
1338 // Try to insert A into B's group.
1339 if (GroupB->insertMember(A, IndexA, DesA.Alignment)) {
1340 LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
1341 << " into the interleave group with" << *B
1342 << '\n');
1343 InterleaveGroupMap[A] = GroupB;
1344
1345 // Set the first load in program order as the insert position.
1346 if (A->mayReadFromMemory())
1347 GroupB->setInsertPos(A);
1348 }
1349 } // Iteration over A accesses.
1350 } // Iteration over B accesses.
1351
1352 auto InvalidateGroupIfMemberMayWrap = [&](InterleaveGroup<Instruction> *Group,
1353 int Index,
1354 std::string FirstOrLast) -> bool {
1355 Instruction *Member = Group->getMember(Index);
1356 assert(Member && "Group member does not exist");
1357 Value *MemberPtr = getLoadStorePointerOperand(Member);
1358 Type *AccessTy = getLoadStoreType(Member);
1359 if (getPtrStride(PSE, AccessTy, MemberPtr, TheLoop, Strides,
1360 /*Assume=*/false, /*ShouldCheckWrap=*/true).value_or(0))
1361 return false;
1362 LLVM_DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
1363 << FirstOrLast
1364 << " group member potentially pointer-wrapping.\n");
1365 releaseGroup(Group);
1366 return true;
1367 };
1368
1369 // Remove interleaved groups with gaps whose memory
1370 // accesses may wrap around. We have to revisit the getPtrStride analysis,
1371 // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
1372 // not check wrapping (see documentation there).
1373 // FORNOW we use Assume=false;
1374 // TODO: Change to Assume=true but making sure we don't exceed the threshold
1375 // of runtime SCEV assumptions checks (thereby potentially failing to
1376 // vectorize altogether).
1377 // Additional optional optimizations:
1378 // TODO: If we are peeling the loop and we know that the first pointer doesn't
1379 // wrap then we can deduce that all pointers in the group don't wrap.
1380 // This means that we can forcefully peel the loop in order to only have to
1381 // check the first pointer for no-wrap. When we'll change to use Assume=true
1382 // we'll only need at most one runtime check per interleaved group.
1383 for (auto *Group : LoadGroups) {
1384 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1385 // load would wrap around the address space we would do a memory access at
1386 // nullptr even without the transformation.
1387 if (Group->getNumMembers() == Group->getFactor())
1388 continue;
1389
1390 // Case 2: If first and last members of the group don't wrap this implies
1391 // that all the pointers in the group don't wrap.
1392 // So we check only group member 0 (which is always guaranteed to exist),
1393 // and group member Factor - 1; If the latter doesn't exist we rely on
1394 // peeling (if it is a non-reversed accsess -- see Case 3).
1395 if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
1396 continue;
1397 if (Group->getMember(Group->getFactor() - 1))
1398 InvalidateGroupIfMemberMayWrap(Group, Group->getFactor() - 1,
1399 std::string("last"));
1400 else {
1401 // Case 3: A non-reversed interleaved load group with gaps: We need
1402 // to execute at least one scalar epilogue iteration. This will ensure
1403 // we don't speculatively access memory out-of-bounds. We only need
1404 // to look for a member at index factor - 1, since every group must have
1405 // a member at index zero.
1406 if (Group->isReverse()) {
1407 LLVM_DEBUG(
1408 dbgs() << "LV: Invalidate candidate interleaved group due to "
1409 "a reverse access with gaps.\n");
1410 releaseGroup(Group);
1411 continue;
1412 }
1413 LLVM_DEBUG(
1414 dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
1415 RequiresScalarEpilogue = true;
1416 }
1417 }
1418
1419 for (auto *Group : StoreGroups) {
1420 // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1421 // store would wrap around the address space we would do a memory access at
1422 // nullptr even without the transformation.
1423 if (Group->getNumMembers() == Group->getFactor())
1424 continue;
1425
1426 // Interleave-store-group with gaps is implemented using masked wide store.
1427 // Remove interleaved store groups with gaps if
1428 // masked-interleaved-accesses are not enabled by the target.
1429 if (!EnablePredicatedInterleavedMemAccesses) {
1430 LLVM_DEBUG(
1431 dbgs() << "LV: Invalidate candidate interleaved store group due "
1432 "to gaps.\n");
1433 releaseGroup(Group);
1434 continue;
1435 }
1436
1437 // Case 2: If first and last members of the group don't wrap this implies
1438 // that all the pointers in the group don't wrap.
1439 // So we check only group member 0 (which is always guaranteed to exist),
1440 // and the last group member. Case 3 (scalar epilog) is not relevant for
1441 // stores with gaps, which are implemented with masked-store (rather than
1442 // speculative access, as in loads).
1443 if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
1444 continue;
1445 for (int Index = Group->getFactor() - 1; Index > 0; Index--)
1446 if (Group->getMember(Index)) {
1447 InvalidateGroupIfMemberMayWrap(Group, Index, std::string("last"));
1448 break;
1449 }
1450 }
1451}
1452
1454 // If no group had triggered the requirement to create an epilogue loop,
1455 // there is nothing to do.
1457 return;
1458
1459 bool ReleasedGroup = false;
1460 // Release groups requiring scalar epilogues. Note that this also removes them
1461 // from InterleaveGroups.
1462 for (auto *Group : make_early_inc_range(InterleaveGroups)) {
1463 if (!Group->requiresScalarEpilogue())
1464 continue;
1465 LLVM_DEBUG(
1466 dbgs()
1467 << "LV: Invalidate candidate interleaved group due to gaps that "
1468 "require a scalar epilogue (not allowed under optsize) and cannot "
1469 "be masked (not enabled). \n");
1470 releaseGroup(Group);
1471 ReleasedGroup = true;
1472 }
1473 assert(ReleasedGroup && "At least one group must be invalidated, as a "
1474 "scalar epilogue was required");
1475 (void)ReleasedGroup;
1476 RequiresScalarEpilogue = false;
1477}
1478
1479template <typename InstT>
1480void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
1481 llvm_unreachable("addMetadata can only be used for Instruction");
1482}
1483
1484namespace llvm {
1485template <>
1488 std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
1489 [](std::pair<int, Instruction *> p) { return p.second; });
1490 propagateMetadata(NewInst, VL);
1491}
1492} // namespace llvm
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Size
DenseMap< Block *, BlockRelaxAux > Blocks
Definition: ELF_riscv.cpp:507
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
const NodeList & List
Definition: RDFGraph.cpp:201
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
static unsigned getScalarSizeInBits(Type *Ty)
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
This pass exposes codegen information to IR-level passes.
static Value * concatenateTwoVectors(IRBuilderBase &Builder, Value *V1, Value *V2)
A helper function for concatenating vectors.
static cl::opt< unsigned > MaxInterleaveGroupFactor("max-interleave-group-factor", cl::Hidden, cl::desc("Maximum factor for an interleaved access group (default = 8)"), cl::init(8))
Maximum factor for an interleaved memory access.
static void addToAccessGroupList(ListT &List, MDNode *AccGroups)
Add all access groups in AccGroups to List.
Class for arbitrary precision integers.
Definition: APInt.h:77
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:213
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition: APInt.h:1386
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition: APInt.h:1309
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:359
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:179
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1521
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:168
iterator end() const
Definition: ArrayRef.h:154
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
iterator begin() const
Definition: ArrayRef.h:153
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:290
This class represents a function call, abstracting a target machine's calling convention.
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1399
This is an important base class in LLVM.
Definition: Constant.h:41
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:151
EquivalenceClasses - This represents a collection of equivalence classes and supports three efficient...
const ElemTy & getOrInsertLeaderValue(const ElemTy &V)
getOrInsertLeaderValue - Return the leader for the specified value that is in the set.
member_iterator member_end() const
member_iterator member_begin(iterator I) const
member_iterator unionSets(const ElemTy &V1, const ElemTy &V2)
union - Merge the two equivalence sets for the specified values, inserting them if they do not alread...
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:94
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
Definition: IRBuilder.h:461
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition: IRBuilder.h:2494
This instruction inserts a single (scalar) element into a VectorType value.
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.
Definition: Instruction.h:741
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:358
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1635
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
This does the same thing as getAllMetadata, except that it filters out the debug location.
Definition: Instruction.h:383
The group of interleaved loads/stores sharing the same stride and close to each other.
Definition: VectorUtils.h:445
uint32_t getFactor() const
Definition: VectorUtils.h:461
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
Definition: VectorUtils.h:515
uint32_t getIndex(const InstTy *Instr) const
Get the index for the given member.
Definition: VectorUtils.h:522
void setInsertPos(InstTy *Inst)
Definition: VectorUtils.h:532
bool isReverse() const
Definition: VectorUtils.h:460
void addMetadata(InstTy *NewInst) const
Add metadata (e.g.
bool insertMember(InstTy *Instr, int32_t Index, Align NewAlign)
Try to insert a new member Instr with index Index and alignment NewAlign.
Definition: VectorUtils.h:470
uint32_t getNumMembers() const
Definition: VectorUtils.h:463
InterleaveGroup< Instruction > * getInterleaveGroup(const Instruction *Instr) const
Get the interleave group that Instr belongs to.
Definition: VectorUtils.h:632
bool requiresScalarEpilogue() const
Returns true if an interleaved group that may access memory out-of-bounds requires a scalar epilogue ...
Definition: VectorUtils.h:643
bool isInterleaved(Instruction *Instr) const
Check if Instr belongs to any interleave group.
Definition: VectorUtils.h:624
void analyzeInterleaving(bool EnableMaskedInterleavedGroup)
Analyze the interleaved accesses and collect them in interleave groups.
void invalidateGroupsRequiringScalarEpilogue()
Invalidate groups that require a scalar epilogue (due to gaps).
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
const DenseMap< Value *, const SCEV * > & getSymbolicStrides() const
If an access has a symbolic strides, this maps the pointer value to the stride symbol.
BlockT * getHeader() const
Store the result of a depth first search within basic blocks contained by a single loop.
Definition: LoopIterator.h:97
Metadata node.
Definition: Metadata.h:1067
static MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1135
static MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1426
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
static MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1167
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1434
static MDNode * intersect(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1122
LLVMContext & getContext() const
Definition: Metadata.h:1231
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:889
static MDNode * combine(LLVMContext &Ctx, const MMRAMetadata &A, const MMRAMetadata &B)
Combines A and B according to MMRA semantics.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
reverse_iterator rend()
Definition: MapVector.h:76
iterator find(const KeyT &Key)
Definition: MapVector.h:167
bool empty() const
Definition: MapVector.h:79
reverse_iterator rbegin()
Definition: MapVector.h:74
Root of the metadata hierarchy.
Definition: Metadata.h:62
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:293
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:307
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
This class represents a constant integer value.
const APInt & getAPInt() const
This class represents an analyzed expression in the program.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
bool remove(const value_type &X)
Remove an item from the set vector.
Definition: SetVector.h:188
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
bool contains(const key_type &key) const
Check if the SetVector contains the given key.
Definition: SetVector.h:254
This instruction constructs a fixed permutation of two input vectors.
int getMaskValue(unsigned Elt) const
Return the shuffle mask value of this instruction for the given element index.
VectorType * getType() const
Overload to return most specific vector type.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:360
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:366
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void assign(size_type NumElts, ValueParamT Elt)
Definition: SmallVector.h:717
void reserve(size_type N)
Definition: SmallVector.h:676
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:696
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
bool isTypeLegal(Type *Ty) const
Return true if this type is legal.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1795
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1074
Base class of all SIMD vector types.
Definition: DerivedTypes.h:403
Type * getElementType() const
Definition: DerivedTypes.h:436
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:100
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:165
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
Definition: PatternMatch.h:599
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
APInt possiblyDemandedEltsInMask(Value *Mask)
Given a mask vector of the form <Y x i1>, return an APInt (of bitwidth Y) for each lane which may be ...
bool isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx)
Identifies if the vector form of the intrinsic is overloaded on the type of the operand at index OpdI...
unsigned getLoadStoreAddressSpace(Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
llvm::SmallVector< int, 16 > createUnaryMask(ArrayRef< int > Mask, unsigned NumElts)
Given a shuffle mask for a binary shuffle, create the equivalent shuffle mask assuming both operands ...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition: bit.h:317
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:656
Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
bool widenShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Try to transform a shuffle mask by replacing elements with the scaled index for an equivalent mask of...
Instruction * propagateMetadata(Instruction *I, ArrayRef< Value * > VL)
Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath, MD_nontemporal,...
Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition: bit.h:342
MDNode * intersectAccessGroups(const Instruction *Inst1, const Instruction *Inst2)
Compute the access-group list of access groups that Inst1 and Inst2 are both in.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
Constant * createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF, const InterleaveGroup< Instruction > &Group)
Create a mask that filters the members of an interleave group where there are gaps.
constexpr unsigned MaxAnalysisRecursionDepth
Definition: ValueTracking.h:48
llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
llvm::SmallVector< int, 16 > createReplicatedMask(unsigned ReplicationFactor, unsigned VF)
Create a mask with replicated elements.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
std::optional< int64_t > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DenseMap< Value *, const SCEV * > &StridesMap=DenseMap< Value *, const SCEV * >(), bool Assume=false, bool ShouldCheckWrap=true)
If the pointer has a constant stride return it in units of the access type size.
Align getLoadStoreAlignment(Value *I)
A helper function that returns the alignment of load or store instruction.
bool maskIsAllOneOrUndef(Value *Mask)
Given a mask vector of i1, Return true if all of the elements of this predicate mask are known to be ...
constexpr int PoisonMaskElem
bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
Definition: LoopInfo.cpp:1142
Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
void processShuffleMasks(ArrayRef< int > Mask, unsigned NumOfSrcRegs, unsigned NumOfDestRegs, unsigned NumOfUsedRegs, function_ref< void()> NoInputAction, function_ref< void(ArrayRef< int >, unsigned, unsigned)> SingleInputAction, function_ref< void(ArrayRef< int >, unsigned, unsigned)> ManyInputsAction)
Splits and processes shuffle mask depending on the number of input and output registers.
void narrowShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Replace each shuffle mask index with the scaled sequential indices for an equivalent mask of narrowed...
llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
const SCEV * replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, const DenseMap< Value *, const SCEV * > &PtrToStride, Value *Ptr)
Return the SCEV corresponding to a pointer with the symbolic stride replaced with constant one,...
Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register,...
MDNode * uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2)
Compute the union of two access-group lists.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition: STLExtras.h:1921
bool maskIsAllZeroOrUndef(Value *Mask)
Given a mask vector of i1, Return true if all of the elements of this predicate mask are known to be ...
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1749
void getShuffleMaskWithWidestElts(ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Repetitively apply widenShuffleMaskElts() for as long as it succeeds, to get the shuffle mask with wi...
bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx)
Identifies if the vector form of the intrinsic has a scalar operand.
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition: STLExtras.h:2039
bool maskContainsAllOneOrUndef(Value *Mask)
Given a mask vector of i1, Return true if any of the elements of this predicate mask are known to be ...
bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
Definition: VectorUtils.cpp:46
llvm::SmallVector< int, 16 > createSequentialMask(unsigned Start, unsigned NumInts, unsigned NumUndefs)
Create a sequential shuffle mask.
Type * getLoadStoreType(Value *I)
A helper function that returns the type of a load or store instruction.
MapVector< Instruction *, uint64_t > computeMinimumValueSizes(ArrayRef< BasicBlock * > Blocks, DemandedBits &DB, const TargetTransformInfo *TTI=nullptr)
Compute a map of integer instructions to their minimum legal type size.
int getSplatIndex(ArrayRef< int > Mask)
If all non-negative Mask elements are the same value, return that value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860