11a82d4c0SDimitry Andric //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
25ca98fd9SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ca98fd9SDimitry Andric //
75ca98fd9SDimitry Andric //===----------------------------------------------------------------------===//
85ca98fd9SDimitry Andric //
91a82d4c0SDimitry Andric // This file defines vectorizer utilities.
105ca98fd9SDimitry Andric //
115ca98fd9SDimitry Andric //===----------------------------------------------------------------------===//
125ca98fd9SDimitry Andric
137ab83427SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
14dd58ef01SDimitry Andric #include "llvm/ADT/EquivalenceClasses.h"
1599aabd70SDimitry Andric #include "llvm/ADT/SmallVector.h"
16dd58ef01SDimitry Andric #include "llvm/Analysis/DemandedBits.h"
17ee8648bdSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
18d8e91e46SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
19ee8648bdSDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
207ab83427SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
21dd58ef01SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
2201095a5dSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
237ab83427SDimitry Andric #include "llvm/IR/Constants.h"
2499aabd70SDimitry Andric #include "llvm/IR/DerivedTypes.h"
257ab83427SDimitry Andric #include "llvm/IR/IRBuilder.h"
26ac9a064cSDimitry Andric #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
27ee8648bdSDimitry Andric #include "llvm/IR/PatternMatch.h"
28ee8648bdSDimitry Andric #include "llvm/IR/Value.h"
29706b4fc4SDimitry Andric #include "llvm/Support/CommandLine.h"
30dd58ef01SDimitry Andric
31d8e91e46SDimitry Andric #define DEBUG_TYPE "vectorutils"
32d8e91e46SDimitry Andric
33dd58ef01SDimitry Andric using namespace llvm;
34dd58ef01SDimitry Andric using namespace llvm::PatternMatch;
355ca98fd9SDimitry Andric
36d8e91e46SDimitry Andric /// Maximum factor for an interleaved memory access.
37d8e91e46SDimitry Andric static cl::opt<unsigned> MaxInterleaveGroupFactor(
38d8e91e46SDimitry Andric "max-interleave-group-factor", cl::Hidden,
39d8e91e46SDimitry Andric cl::desc("Maximum factor for an interleaved access group (default = 8)"),
40d8e91e46SDimitry Andric cl::init(8));
41d8e91e46SDimitry Andric
42d8e91e46SDimitry Andric /// Return true if all of the intrinsic's arguments and return type are scalars
43e6d15924SDimitry Andric /// for the scalar form of the intrinsic, and vectors for the vector form of the
44e6d15924SDimitry Andric /// intrinsic (except operands that are marked as always being scalar by
45145449b1SDimitry Andric /// isVectorIntrinsicWithScalarOpAtArg).
isTriviallyVectorizable(Intrinsic::ID ID)461a82d4c0SDimitry Andric bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
475ca98fd9SDimitry Andric switch (ID) {
48b60736ecSDimitry Andric case Intrinsic::abs: // Begin integer bit-manipulation.
49b60736ecSDimitry Andric case Intrinsic::bswap:
50d8e91e46SDimitry Andric case Intrinsic::bitreverse:
51d8e91e46SDimitry Andric case Intrinsic::ctpop:
52d8e91e46SDimitry Andric case Intrinsic::ctlz:
53d8e91e46SDimitry Andric case Intrinsic::cttz:
54d8e91e46SDimitry Andric case Intrinsic::fshl:
55d8e91e46SDimitry Andric case Intrinsic::fshr:
56b60736ecSDimitry Andric case Intrinsic::smax:
57b60736ecSDimitry Andric case Intrinsic::smin:
58b60736ecSDimitry Andric case Intrinsic::umax:
59b60736ecSDimitry Andric case Intrinsic::umin:
60e6d15924SDimitry Andric case Intrinsic::sadd_sat:
61e6d15924SDimitry Andric case Intrinsic::ssub_sat:
62e6d15924SDimitry Andric case Intrinsic::uadd_sat:
63e6d15924SDimitry Andric case Intrinsic::usub_sat:
64e6d15924SDimitry Andric case Intrinsic::smul_fix:
65e6d15924SDimitry Andric case Intrinsic::smul_fix_sat:
66e6d15924SDimitry Andric case Intrinsic::umul_fix:
671d5ae102SDimitry Andric case Intrinsic::umul_fix_sat:
68d8e91e46SDimitry Andric case Intrinsic::sqrt: // Begin floating-point.
695ca98fd9SDimitry Andric case Intrinsic::sin:
705ca98fd9SDimitry Andric case Intrinsic::cos:
71ac9a064cSDimitry Andric case Intrinsic::tan:
725ca98fd9SDimitry Andric case Intrinsic::exp:
735ca98fd9SDimitry Andric case Intrinsic::exp2:
745ca98fd9SDimitry Andric case Intrinsic::log:
755ca98fd9SDimitry Andric case Intrinsic::log10:
765ca98fd9SDimitry Andric case Intrinsic::log2:
775ca98fd9SDimitry Andric case Intrinsic::fabs:
7867c32a98SDimitry Andric case Intrinsic::minnum:
7967c32a98SDimitry Andric case Intrinsic::maxnum:
80d8e91e46SDimitry Andric case Intrinsic::minimum:
81d8e91e46SDimitry Andric case Intrinsic::maximum:
825ca98fd9SDimitry Andric case Intrinsic::copysign:
835ca98fd9SDimitry Andric case Intrinsic::floor:
845ca98fd9SDimitry Andric case Intrinsic::ceil:
855ca98fd9SDimitry Andric case Intrinsic::trunc:
865ca98fd9SDimitry Andric case Intrinsic::rint:
875ca98fd9SDimitry Andric case Intrinsic::nearbyint:
885ca98fd9SDimitry Andric case Intrinsic::round:
89cfca06d7SDimitry Andric case Intrinsic::roundeven:
905ca98fd9SDimitry Andric case Intrinsic::pow:
915ca98fd9SDimitry Andric case Intrinsic::fma:
925ca98fd9SDimitry Andric case Intrinsic::fmuladd:
937fa27ce4SDimitry Andric case Intrinsic::is_fpclass:
945ca98fd9SDimitry Andric case Intrinsic::powi:
95d8e91e46SDimitry Andric case Intrinsic::canonicalize:
96145449b1SDimitry Andric case Intrinsic::fptosi_sat:
97145449b1SDimitry Andric case Intrinsic::fptoui_sat:
98b1c73532SDimitry Andric case Intrinsic::lrint:
99b1c73532SDimitry Andric case Intrinsic::llrint:
1005ca98fd9SDimitry Andric return true;
1015ca98fd9SDimitry Andric default:
1025ca98fd9SDimitry Andric return false;
1035ca98fd9SDimitry Andric }
1045ca98fd9SDimitry Andric }
1055ca98fd9SDimitry Andric
106e6d15924SDimitry Andric /// Identifies if the vector form of the intrinsic has a scalar operand.
isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID,unsigned ScalarOpdIdx)107145449b1SDimitry Andric bool llvm::isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID,
1085ca98fd9SDimitry Andric unsigned ScalarOpdIdx) {
1095ca98fd9SDimitry Andric switch (ID) {
110b60736ecSDimitry Andric case Intrinsic::abs:
1115ca98fd9SDimitry Andric case Intrinsic::ctlz:
1125ca98fd9SDimitry Andric case Intrinsic::cttz:
1137fa27ce4SDimitry Andric case Intrinsic::is_fpclass:
1145ca98fd9SDimitry Andric case Intrinsic::powi:
1155ca98fd9SDimitry Andric return (ScalarOpdIdx == 1);
116e6d15924SDimitry Andric case Intrinsic::smul_fix:
117e6d15924SDimitry Andric case Intrinsic::smul_fix_sat:
118e6d15924SDimitry Andric case Intrinsic::umul_fix:
1191d5ae102SDimitry Andric case Intrinsic::umul_fix_sat:
120e6d15924SDimitry Andric return (ScalarOpdIdx == 2);
1215ca98fd9SDimitry Andric default:
1225ca98fd9SDimitry Andric return false;
1235ca98fd9SDimitry Andric }
1245ca98fd9SDimitry Andric }
1255ca98fd9SDimitry Andric
isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID,int OpdIdx)126145449b1SDimitry Andric bool llvm::isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID,
1277fa27ce4SDimitry Andric int OpdIdx) {
12877dbea07SDimitry Andric assert(ID != Intrinsic::not_intrinsic && "Not an intrinsic!");
12977dbea07SDimitry Andric
130344a3780SDimitry Andric switch (ID) {
131145449b1SDimitry Andric case Intrinsic::fptosi_sat:
132145449b1SDimitry Andric case Intrinsic::fptoui_sat:
133b1c73532SDimitry Andric case Intrinsic::lrint:
134b1c73532SDimitry Andric case Intrinsic::llrint:
1357fa27ce4SDimitry Andric return OpdIdx == -1 || OpdIdx == 0;
1367fa27ce4SDimitry Andric case Intrinsic::is_fpclass:
137145449b1SDimitry Andric return OpdIdx == 0;
138344a3780SDimitry Andric case Intrinsic::powi:
1397fa27ce4SDimitry Andric return OpdIdx == -1 || OpdIdx == 1;
140344a3780SDimitry Andric default:
1417fa27ce4SDimitry Andric return OpdIdx == -1;
142344a3780SDimitry Andric }
143344a3780SDimitry Andric }
144344a3780SDimitry Andric
145eb11fae6SDimitry Andric /// Returns intrinsic ID for call.
1461a82d4c0SDimitry Andric /// For the input call instruction it finds mapping intrinsic and returns
1471a82d4c0SDimitry Andric /// its ID, in case it does not found it return not_intrinsic.
getVectorIntrinsicIDForCall(const CallInst * CI,const TargetLibraryInfo * TLI)14801095a5dSDimitry Andric Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
1491a82d4c0SDimitry Andric const TargetLibraryInfo *TLI) {
150cfca06d7SDimitry Andric Intrinsic::ID ID = getIntrinsicForCallSite(*CI, TLI);
15101095a5dSDimitry Andric if (ID == Intrinsic::not_intrinsic)
15201095a5dSDimitry Andric return Intrinsic::not_intrinsic;
15301095a5dSDimitry Andric
1545ca98fd9SDimitry Andric if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
155044eb2f6SDimitry Andric ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
156b60736ecSDimitry Andric ID == Intrinsic::experimental_noalias_scope_decl ||
157b60736ecSDimitry Andric ID == Intrinsic::sideeffect || ID == Intrinsic::pseudoprobe)
1585ca98fd9SDimitry Andric return ID;
1595ca98fd9SDimitry Andric return Intrinsic::not_intrinsic;
1605ca98fd9SDimitry Andric }
1615ca98fd9SDimitry Andric
162eb11fae6SDimitry Andric /// Given a vector and an element number, see if the scalar value is
163ee8648bdSDimitry Andric /// already around as a register, for example if it were inserted then extracted
164ee8648bdSDimitry Andric /// from the vector.
findScalarElement(Value * V,unsigned EltNo)165dd58ef01SDimitry Andric Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
166ee8648bdSDimitry Andric assert(V->getType()->isVectorTy() && "Not looking at a vector?");
167ee8648bdSDimitry Andric VectorType *VTy = cast<VectorType>(V->getType());
168ac9a064cSDimitry Andric // For fixed-length vector, return poison for out of range access.
169cfca06d7SDimitry Andric if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
170cfca06d7SDimitry Andric unsigned Width = FVTy->getNumElements();
171cfca06d7SDimitry Andric if (EltNo >= Width)
172ac9a064cSDimitry Andric return PoisonValue::get(FVTy->getElementType());
173cfca06d7SDimitry Andric }
174ee8648bdSDimitry Andric
175ee8648bdSDimitry Andric if (Constant *C = dyn_cast<Constant>(V))
176ee8648bdSDimitry Andric return C->getAggregateElement(EltNo);
177ee8648bdSDimitry Andric
178ee8648bdSDimitry Andric if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
179ee8648bdSDimitry Andric // If this is an insert to a variable element, we don't know what it is.
180ee8648bdSDimitry Andric if (!isa<ConstantInt>(III->getOperand(2)))
181ee8648bdSDimitry Andric return nullptr;
182ee8648bdSDimitry Andric unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
183ee8648bdSDimitry Andric
184ee8648bdSDimitry Andric // If this is an insert to the element we are looking for, return the
185ee8648bdSDimitry Andric // inserted value.
186ee8648bdSDimitry Andric if (EltNo == IIElt)
187ee8648bdSDimitry Andric return III->getOperand(1);
188ee8648bdSDimitry Andric
189b60736ecSDimitry Andric // Guard against infinite loop on malformed, unreachable IR.
190b60736ecSDimitry Andric if (III == III->getOperand(0))
191b60736ecSDimitry Andric return nullptr;
192b60736ecSDimitry Andric
193ee8648bdSDimitry Andric // Otherwise, the insertelement doesn't modify the value, recurse on its
194ee8648bdSDimitry Andric // vector input.
195ee8648bdSDimitry Andric return findScalarElement(III->getOperand(0), EltNo);
196ee8648bdSDimitry Andric }
197ee8648bdSDimitry Andric
198cfca06d7SDimitry Andric ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
199cfca06d7SDimitry Andric // Restrict the following transformation to fixed-length vector.
200cfca06d7SDimitry Andric if (SVI && isa<FixedVectorType>(SVI->getType())) {
201cfca06d7SDimitry Andric unsigned LHSWidth =
202cfca06d7SDimitry Andric cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements();
203ee8648bdSDimitry Andric int InEl = SVI->getMaskValue(EltNo);
204ee8648bdSDimitry Andric if (InEl < 0)
205ac9a064cSDimitry Andric return PoisonValue::get(VTy->getElementType());
206ee8648bdSDimitry Andric if (InEl < (int)LHSWidth)
207ee8648bdSDimitry Andric return findScalarElement(SVI->getOperand(0), InEl);
208ee8648bdSDimitry Andric return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
209ee8648bdSDimitry Andric }
210ee8648bdSDimitry Andric
211ee8648bdSDimitry Andric // Extract a value from a vector add operation with a constant zero.
212d8e91e46SDimitry Andric // TODO: Use getBinOpIdentity() to generalize this.
213d8e91e46SDimitry Andric Value *Val; Constant *C;
214d8e91e46SDimitry Andric if (match(V, m_Add(m_Value(Val), m_Constant(C))))
215d8e91e46SDimitry Andric if (Constant *Elt = C->getAggregateElement(EltNo))
21669156b4cSDimitry Andric if (Elt->isNullValue())
217ee8648bdSDimitry Andric return findScalarElement(Val, EltNo);
218ee8648bdSDimitry Andric
219c0981da4SDimitry Andric // If the vector is a splat then we can trivially find the scalar element.
220c0981da4SDimitry Andric if (isa<ScalableVectorType>(VTy))
221c0981da4SDimitry Andric if (Value *Splat = getSplatValue(V))
222c0981da4SDimitry Andric if (EltNo < VTy->getElementCount().getKnownMinValue())
223c0981da4SDimitry Andric return Splat;
224c0981da4SDimitry Andric
225ee8648bdSDimitry Andric // Otherwise, we don't know.
226ee8648bdSDimitry Andric return nullptr;
227ee8648bdSDimitry Andric }
228dd58ef01SDimitry Andric
getSplatIndex(ArrayRef<int> Mask)229cfca06d7SDimitry Andric int llvm::getSplatIndex(ArrayRef<int> Mask) {
230cfca06d7SDimitry Andric int SplatIndex = -1;
231cfca06d7SDimitry Andric for (int M : Mask) {
232cfca06d7SDimitry Andric // Ignore invalid (undefined) mask elements.
233cfca06d7SDimitry Andric if (M < 0)
234cfca06d7SDimitry Andric continue;
235cfca06d7SDimitry Andric
236cfca06d7SDimitry Andric // There can be only 1 non-negative mask element value if this is a splat.
237cfca06d7SDimitry Andric if (SplatIndex != -1 && SplatIndex != M)
238cfca06d7SDimitry Andric return -1;
239cfca06d7SDimitry Andric
240cfca06d7SDimitry Andric // Initialize the splat index to the 1st non-negative mask element.
241cfca06d7SDimitry Andric SplatIndex = M;
242cfca06d7SDimitry Andric }
243cfca06d7SDimitry Andric assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?");
244cfca06d7SDimitry Andric return SplatIndex;
245cfca06d7SDimitry Andric }
246cfca06d7SDimitry Andric
247eb11fae6SDimitry Andric /// Get splat value if the input is a splat vector or return nullptr.
248dd58ef01SDimitry Andric /// This function is not fully general. It checks only 2 cases:
249e6d15924SDimitry Andric /// the input value is (1) a splat constant vector or (2) a sequence
250e6d15924SDimitry Andric /// of instructions that broadcasts a scalar at element 0.
getSplatValue(const Value * V)251b60736ecSDimitry Andric Value *llvm::getSplatValue(const Value *V) {
252dd58ef01SDimitry Andric if (isa<VectorType>(V->getType()))
253e6d15924SDimitry Andric if (auto *C = dyn_cast<Constant>(V))
254dd58ef01SDimitry Andric return C->getSplatValue();
255dd58ef01SDimitry Andric
256e6d15924SDimitry Andric // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
257e6d15924SDimitry Andric Value *Splat;
258cfca06d7SDimitry Andric if (match(V,
259cfca06d7SDimitry Andric m_Shuffle(m_InsertElt(m_Value(), m_Value(Splat), m_ZeroInt()),
260cfca06d7SDimitry Andric m_Value(), m_ZeroMask())))
261e6d15924SDimitry Andric return Splat;
262dd58ef01SDimitry Andric
263e6d15924SDimitry Andric return nullptr;
264e6d15924SDimitry Andric }
265e6d15924SDimitry Andric
isSplatValue(const Value * V,int Index,unsigned Depth)266cfca06d7SDimitry Andric bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) {
267b60736ecSDimitry Andric assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
268e6d15924SDimitry Andric
269e6d15924SDimitry Andric if (isa<VectorType>(V->getType())) {
270e6d15924SDimitry Andric if (isa<UndefValue>(V))
271e6d15924SDimitry Andric return true;
272cfca06d7SDimitry Andric // FIXME: We can allow undefs, but if Index was specified, we may want to
273cfca06d7SDimitry Andric // check that the constant is defined at that index.
274e6d15924SDimitry Andric if (auto *C = dyn_cast<Constant>(V))
275e6d15924SDimitry Andric return C->getSplatValue() != nullptr;
276e6d15924SDimitry Andric }
277e6d15924SDimitry Andric
278cfca06d7SDimitry Andric if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) {
279cfca06d7SDimitry Andric // FIXME: We can safely allow undefs here. If Index was specified, we will
280cfca06d7SDimitry Andric // check that the mask elt is defined at the required index.
281e3b55780SDimitry Andric if (!all_equal(Shuf->getShuffleMask()))
282cfca06d7SDimitry Andric return false;
283cfca06d7SDimitry Andric
284cfca06d7SDimitry Andric // Match any index.
285cfca06d7SDimitry Andric if (Index == -1)
286cfca06d7SDimitry Andric return true;
287cfca06d7SDimitry Andric
288cfca06d7SDimitry Andric // Match a specific element. The mask should be defined at and match the
289cfca06d7SDimitry Andric // specified index.
290cfca06d7SDimitry Andric return Shuf->getMaskValue(Index) == Index;
291cfca06d7SDimitry Andric }
292e6d15924SDimitry Andric
293e6d15924SDimitry Andric // The remaining tests are all recursive, so bail out if we hit the limit.
294b60736ecSDimitry Andric if (Depth++ == MaxAnalysisRecursionDepth)
295e6d15924SDimitry Andric return false;
296e6d15924SDimitry Andric
297e6d15924SDimitry Andric // If both operands of a binop are splats, the result is a splat.
298e6d15924SDimitry Andric Value *X, *Y, *Z;
299e6d15924SDimitry Andric if (match(V, m_BinOp(m_Value(X), m_Value(Y))))
300cfca06d7SDimitry Andric return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth);
301e6d15924SDimitry Andric
302e6d15924SDimitry Andric // If all operands of a select are splats, the result is a splat.
303e6d15924SDimitry Andric if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z))))
304cfca06d7SDimitry Andric return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) &&
305cfca06d7SDimitry Andric isSplatValue(Z, Index, Depth);
306e6d15924SDimitry Andric
307e6d15924SDimitry Andric // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
308e6d15924SDimitry Andric
309e6d15924SDimitry Andric return false;
310dd58ef01SDimitry Andric }
311dd58ef01SDimitry Andric
getShuffleDemandedElts(int SrcWidth,ArrayRef<int> Mask,const APInt & DemandedElts,APInt & DemandedLHS,APInt & DemandedRHS,bool AllowUndefElts)312e3b55780SDimitry Andric bool llvm::getShuffleDemandedElts(int SrcWidth, ArrayRef<int> Mask,
313e3b55780SDimitry Andric const APInt &DemandedElts, APInt &DemandedLHS,
314e3b55780SDimitry Andric APInt &DemandedRHS, bool AllowUndefElts) {
315e3b55780SDimitry Andric DemandedLHS = DemandedRHS = APInt::getZero(SrcWidth);
316e3b55780SDimitry Andric
317e3b55780SDimitry Andric // Early out if we don't demand any elements.
318e3b55780SDimitry Andric if (DemandedElts.isZero())
319e3b55780SDimitry Andric return true;
320e3b55780SDimitry Andric
321e3b55780SDimitry Andric // Simple case of a shuffle with zeroinitializer.
322e3b55780SDimitry Andric if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
323e3b55780SDimitry Andric DemandedLHS.setBit(0);
324e3b55780SDimitry Andric return true;
325e3b55780SDimitry Andric }
326e3b55780SDimitry Andric
327e3b55780SDimitry Andric for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
328e3b55780SDimitry Andric int M = Mask[I];
329e3b55780SDimitry Andric assert((-1 <= M) && (M < (SrcWidth * 2)) &&
330e3b55780SDimitry Andric "Invalid shuffle mask constant");
331e3b55780SDimitry Andric
332e3b55780SDimitry Andric if (!DemandedElts[I] || (AllowUndefElts && (M < 0)))
333e3b55780SDimitry Andric continue;
334e3b55780SDimitry Andric
335e3b55780SDimitry Andric // For undef elements, we don't know anything about the common state of
336e3b55780SDimitry Andric // the shuffle result.
337e3b55780SDimitry Andric if (M < 0)
338e3b55780SDimitry Andric return false;
339e3b55780SDimitry Andric
340e3b55780SDimitry Andric if (M < SrcWidth)
341e3b55780SDimitry Andric DemandedLHS.setBit(M);
342e3b55780SDimitry Andric else
343e3b55780SDimitry Andric DemandedRHS.setBit(M - SrcWidth);
344e3b55780SDimitry Andric }
345e3b55780SDimitry Andric
346e3b55780SDimitry Andric return true;
347e3b55780SDimitry Andric }
348e3b55780SDimitry Andric
narrowShuffleMaskElts(int Scale,ArrayRef<int> Mask,SmallVectorImpl<int> & ScaledMask)349cfca06d7SDimitry Andric void llvm::narrowShuffleMaskElts(int Scale, ArrayRef<int> Mask,
350cfca06d7SDimitry Andric SmallVectorImpl<int> &ScaledMask) {
351cfca06d7SDimitry Andric assert(Scale > 0 && "Unexpected scaling factor");
352cfca06d7SDimitry Andric
353cfca06d7SDimitry Andric // Fast-path: if no scaling, then it is just a copy.
354cfca06d7SDimitry Andric if (Scale == 1) {
355cfca06d7SDimitry Andric ScaledMask.assign(Mask.begin(), Mask.end());
356cfca06d7SDimitry Andric return;
357cfca06d7SDimitry Andric }
358cfca06d7SDimitry Andric
359cfca06d7SDimitry Andric ScaledMask.clear();
360cfca06d7SDimitry Andric for (int MaskElt : Mask) {
361cfca06d7SDimitry Andric if (MaskElt >= 0) {
362b60736ecSDimitry Andric assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= INT32_MAX &&
363cfca06d7SDimitry Andric "Overflowed 32-bits");
364cfca06d7SDimitry Andric }
365cfca06d7SDimitry Andric for (int SliceElt = 0; SliceElt != Scale; ++SliceElt)
366cfca06d7SDimitry Andric ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt);
367cfca06d7SDimitry Andric }
368cfca06d7SDimitry Andric }
369cfca06d7SDimitry Andric
widenShuffleMaskElts(int Scale,ArrayRef<int> Mask,SmallVectorImpl<int> & ScaledMask)370cfca06d7SDimitry Andric bool llvm::widenShuffleMaskElts(int Scale, ArrayRef<int> Mask,
371cfca06d7SDimitry Andric SmallVectorImpl<int> &ScaledMask) {
372cfca06d7SDimitry Andric assert(Scale > 0 && "Unexpected scaling factor");
373cfca06d7SDimitry Andric
374cfca06d7SDimitry Andric // Fast-path: if no scaling, then it is just a copy.
375cfca06d7SDimitry Andric if (Scale == 1) {
376cfca06d7SDimitry Andric ScaledMask.assign(Mask.begin(), Mask.end());
377cfca06d7SDimitry Andric return true;
378cfca06d7SDimitry Andric }
379cfca06d7SDimitry Andric
380cfca06d7SDimitry Andric // We must map the original elements down evenly to a type with less elements.
381cfca06d7SDimitry Andric int NumElts = Mask.size();
382cfca06d7SDimitry Andric if (NumElts % Scale != 0)
383cfca06d7SDimitry Andric return false;
384cfca06d7SDimitry Andric
385cfca06d7SDimitry Andric ScaledMask.clear();
386cfca06d7SDimitry Andric ScaledMask.reserve(NumElts / Scale);
387cfca06d7SDimitry Andric
388cfca06d7SDimitry Andric // Step through the input mask by splitting into Scale-sized slices.
389cfca06d7SDimitry Andric do {
390cfca06d7SDimitry Andric ArrayRef<int> MaskSlice = Mask.take_front(Scale);
391cfca06d7SDimitry Andric assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice.");
392cfca06d7SDimitry Andric
393cfca06d7SDimitry Andric // The first element of the slice determines how we evaluate this slice.
394cfca06d7SDimitry Andric int SliceFront = MaskSlice.front();
395cfca06d7SDimitry Andric if (SliceFront < 0) {
396cfca06d7SDimitry Andric // Negative values (undef or other "sentinel" values) must be equal across
397cfca06d7SDimitry Andric // the entire slice.
398e3b55780SDimitry Andric if (!all_equal(MaskSlice))
399cfca06d7SDimitry Andric return false;
400cfca06d7SDimitry Andric ScaledMask.push_back(SliceFront);
401cfca06d7SDimitry Andric } else {
402cfca06d7SDimitry Andric // A positive mask element must be cleanly divisible.
403cfca06d7SDimitry Andric if (SliceFront % Scale != 0)
404cfca06d7SDimitry Andric return false;
405cfca06d7SDimitry Andric // Elements of the slice must be consecutive.
406cfca06d7SDimitry Andric for (int i = 1; i < Scale; ++i)
407cfca06d7SDimitry Andric if (MaskSlice[i] != SliceFront + i)
408cfca06d7SDimitry Andric return false;
409cfca06d7SDimitry Andric ScaledMask.push_back(SliceFront / Scale);
410cfca06d7SDimitry Andric }
411cfca06d7SDimitry Andric Mask = Mask.drop_front(Scale);
412cfca06d7SDimitry Andric } while (!Mask.empty());
413cfca06d7SDimitry Andric
414cfca06d7SDimitry Andric assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask");
415cfca06d7SDimitry Andric
416cfca06d7SDimitry Andric // All elements of the original mask can be scaled down to map to the elements
417cfca06d7SDimitry Andric // of a mask with wider elements.
418cfca06d7SDimitry Andric return true;
419cfca06d7SDimitry Andric }
420cfca06d7SDimitry Andric
scaleShuffleMaskElts(unsigned NumDstElts,ArrayRef<int> Mask,SmallVectorImpl<int> & ScaledMask)421ac9a064cSDimitry Andric bool llvm::scaleShuffleMaskElts(unsigned NumDstElts, ArrayRef<int> Mask,
422ac9a064cSDimitry Andric SmallVectorImpl<int> &ScaledMask) {
423ac9a064cSDimitry Andric unsigned NumSrcElts = Mask.size();
424ac9a064cSDimitry Andric assert(NumSrcElts > 0 && NumDstElts > 0 && "Unexpected scaling factor");
425ac9a064cSDimitry Andric
426ac9a064cSDimitry Andric // Fast-path: if no scaling, then it is just a copy.
427ac9a064cSDimitry Andric if (NumSrcElts == NumDstElts) {
428ac9a064cSDimitry Andric ScaledMask.assign(Mask.begin(), Mask.end());
429ac9a064cSDimitry Andric return true;
430ac9a064cSDimitry Andric }
431ac9a064cSDimitry Andric
432ac9a064cSDimitry Andric // Ensure we can find a whole scale factor.
433ac9a064cSDimitry Andric assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
434ac9a064cSDimitry Andric "Unexpected scaling factor");
435ac9a064cSDimitry Andric
436ac9a064cSDimitry Andric if (NumSrcElts > NumDstElts) {
437ac9a064cSDimitry Andric int Scale = NumSrcElts / NumDstElts;
438ac9a064cSDimitry Andric return widenShuffleMaskElts(Scale, Mask, ScaledMask);
439ac9a064cSDimitry Andric }
440ac9a064cSDimitry Andric
441ac9a064cSDimitry Andric int Scale = NumDstElts / NumSrcElts;
442ac9a064cSDimitry Andric narrowShuffleMaskElts(Scale, Mask, ScaledMask);
443ac9a064cSDimitry Andric return true;
444ac9a064cSDimitry Andric }
445ac9a064cSDimitry Andric
getShuffleMaskWithWidestElts(ArrayRef<int> Mask,SmallVectorImpl<int> & ScaledMask)446e3b55780SDimitry Andric void llvm::getShuffleMaskWithWidestElts(ArrayRef<int> Mask,
447e3b55780SDimitry Andric SmallVectorImpl<int> &ScaledMask) {
448e3b55780SDimitry Andric std::array<SmallVector<int, 16>, 2> TmpMasks;
449e3b55780SDimitry Andric SmallVectorImpl<int> *Output = &TmpMasks[0], *Tmp = &TmpMasks[1];
450e3b55780SDimitry Andric ArrayRef<int> InputMask = Mask;
451e3b55780SDimitry Andric for (unsigned Scale = 2; Scale <= InputMask.size(); ++Scale) {
452e3b55780SDimitry Andric while (widenShuffleMaskElts(Scale, InputMask, *Output)) {
453e3b55780SDimitry Andric InputMask = *Output;
454e3b55780SDimitry Andric std::swap(Output, Tmp);
455e3b55780SDimitry Andric }
456e3b55780SDimitry Andric }
457e3b55780SDimitry Andric ScaledMask.assign(InputMask.begin(), InputMask.end());
458e3b55780SDimitry Andric }
459e3b55780SDimitry Andric
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)460145449b1SDimitry Andric void llvm::processShuffleMasks(
461145449b1SDimitry Andric ArrayRef<int> Mask, unsigned NumOfSrcRegs, unsigned NumOfDestRegs,
462145449b1SDimitry Andric unsigned NumOfUsedRegs, function_ref<void()> NoInputAction,
463145449b1SDimitry Andric function_ref<void(ArrayRef<int>, unsigned, unsigned)> SingleInputAction,
464145449b1SDimitry Andric function_ref<void(ArrayRef<int>, unsigned, unsigned)> ManyInputsAction) {
465145449b1SDimitry Andric SmallVector<SmallVector<SmallVector<int>>> Res(NumOfDestRegs);
466145449b1SDimitry Andric // Try to perform better estimation of the permutation.
467145449b1SDimitry Andric // 1. Split the source/destination vectors into real registers.
468145449b1SDimitry Andric // 2. Do the mask analysis to identify which real registers are
469145449b1SDimitry Andric // permuted.
470145449b1SDimitry Andric int Sz = Mask.size();
471145449b1SDimitry Andric unsigned SzDest = Sz / NumOfDestRegs;
472145449b1SDimitry Andric unsigned SzSrc = Sz / NumOfSrcRegs;
473145449b1SDimitry Andric for (unsigned I = 0; I < NumOfDestRegs; ++I) {
474145449b1SDimitry Andric auto &RegMasks = Res[I];
475145449b1SDimitry Andric RegMasks.assign(NumOfSrcRegs, {});
476145449b1SDimitry Andric // Check that the values in dest registers are in the one src
477145449b1SDimitry Andric // register.
478145449b1SDimitry Andric for (unsigned K = 0; K < SzDest; ++K) {
479145449b1SDimitry Andric int Idx = I * SzDest + K;
480145449b1SDimitry Andric if (Idx == Sz)
481145449b1SDimitry Andric break;
4827fa27ce4SDimitry Andric if (Mask[Idx] >= Sz || Mask[Idx] == PoisonMaskElem)
483145449b1SDimitry Andric continue;
484145449b1SDimitry Andric int SrcRegIdx = Mask[Idx] / SzSrc;
485145449b1SDimitry Andric // Add a cost of PermuteTwoSrc for each new source register permute,
486145449b1SDimitry Andric // if we have more than one source registers.
487145449b1SDimitry Andric if (RegMasks[SrcRegIdx].empty())
4887fa27ce4SDimitry Andric RegMasks[SrcRegIdx].assign(SzDest, PoisonMaskElem);
489145449b1SDimitry Andric RegMasks[SrcRegIdx][K] = Mask[Idx] % SzSrc;
490145449b1SDimitry Andric }
491145449b1SDimitry Andric }
492145449b1SDimitry Andric // Process split mask.
493145449b1SDimitry Andric for (unsigned I = 0; I < NumOfUsedRegs; ++I) {
494145449b1SDimitry Andric auto &Dest = Res[I];
495145449b1SDimitry Andric int NumSrcRegs =
496145449b1SDimitry Andric count_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
497145449b1SDimitry Andric switch (NumSrcRegs) {
498145449b1SDimitry Andric case 0:
499145449b1SDimitry Andric // No input vectors were used!
500145449b1SDimitry Andric NoInputAction();
501145449b1SDimitry Andric break;
502145449b1SDimitry Andric case 1: {
503145449b1SDimitry Andric // Find the only mask with at least single undef mask elem.
504145449b1SDimitry Andric auto *It =
505145449b1SDimitry Andric find_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
506145449b1SDimitry Andric unsigned SrcReg = std::distance(Dest.begin(), It);
507145449b1SDimitry Andric SingleInputAction(*It, SrcReg, I);
508145449b1SDimitry Andric break;
509145449b1SDimitry Andric }
510145449b1SDimitry Andric default: {
511145449b1SDimitry Andric // The first mask is a permutation of a single register. Since we have >2
512145449b1SDimitry Andric // input registers to shuffle, we merge the masks for 2 first registers
513145449b1SDimitry Andric // and generate a shuffle of 2 registers rather than the reordering of the
514145449b1SDimitry Andric // first register and then shuffle with the second register. Next,
515145449b1SDimitry Andric // generate the shuffles of the resulting register + the remaining
516145449b1SDimitry Andric // registers from the list.
517145449b1SDimitry Andric auto &&CombineMasks = [](MutableArrayRef<int> FirstMask,
518145449b1SDimitry Andric ArrayRef<int> SecondMask) {
519145449b1SDimitry Andric for (int Idx = 0, VF = FirstMask.size(); Idx < VF; ++Idx) {
5207fa27ce4SDimitry Andric if (SecondMask[Idx] != PoisonMaskElem) {
5217fa27ce4SDimitry Andric assert(FirstMask[Idx] == PoisonMaskElem &&
522145449b1SDimitry Andric "Expected undefined mask element.");
523145449b1SDimitry Andric FirstMask[Idx] = SecondMask[Idx] + VF;
524145449b1SDimitry Andric }
525145449b1SDimitry Andric }
526145449b1SDimitry Andric };
527145449b1SDimitry Andric auto &&NormalizeMask = [](MutableArrayRef<int> Mask) {
528145449b1SDimitry Andric for (int Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
5297fa27ce4SDimitry Andric if (Mask[Idx] != PoisonMaskElem)
530145449b1SDimitry Andric Mask[Idx] = Idx;
531145449b1SDimitry Andric }
532145449b1SDimitry Andric };
533145449b1SDimitry Andric int SecondIdx;
534145449b1SDimitry Andric do {
535145449b1SDimitry Andric int FirstIdx = -1;
536145449b1SDimitry Andric SecondIdx = -1;
537145449b1SDimitry Andric MutableArrayRef<int> FirstMask, SecondMask;
538145449b1SDimitry Andric for (unsigned I = 0; I < NumOfDestRegs; ++I) {
539145449b1SDimitry Andric SmallVectorImpl<int> &RegMask = Dest[I];
540145449b1SDimitry Andric if (RegMask.empty())
541145449b1SDimitry Andric continue;
542145449b1SDimitry Andric
543145449b1SDimitry Andric if (FirstIdx == SecondIdx) {
544145449b1SDimitry Andric FirstIdx = I;
545145449b1SDimitry Andric FirstMask = RegMask;
546145449b1SDimitry Andric continue;
547145449b1SDimitry Andric }
548145449b1SDimitry Andric SecondIdx = I;
549145449b1SDimitry Andric SecondMask = RegMask;
550145449b1SDimitry Andric CombineMasks(FirstMask, SecondMask);
551145449b1SDimitry Andric ManyInputsAction(FirstMask, FirstIdx, SecondIdx);
552145449b1SDimitry Andric NormalizeMask(FirstMask);
553145449b1SDimitry Andric RegMask.clear();
554145449b1SDimitry Andric SecondMask = FirstMask;
555145449b1SDimitry Andric SecondIdx = FirstIdx;
556145449b1SDimitry Andric }
557145449b1SDimitry Andric if (FirstIdx != SecondIdx && SecondIdx >= 0) {
558145449b1SDimitry Andric CombineMasks(SecondMask, FirstMask);
559145449b1SDimitry Andric ManyInputsAction(SecondMask, SecondIdx, FirstIdx);
560145449b1SDimitry Andric Dest[FirstIdx].clear();
561145449b1SDimitry Andric NormalizeMask(SecondMask);
562145449b1SDimitry Andric }
563145449b1SDimitry Andric } while (SecondIdx >= 0);
564145449b1SDimitry Andric break;
565145449b1SDimitry Andric }
566145449b1SDimitry Andric }
567145449b1SDimitry Andric }
568145449b1SDimitry Andric }
569145449b1SDimitry Andric
getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth,const APInt & DemandedElts,APInt & DemandedLHS,APInt & DemandedRHS)570ac9a064cSDimitry Andric void llvm::getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth,
571ac9a064cSDimitry Andric const APInt &DemandedElts,
572ac9a064cSDimitry Andric APInt &DemandedLHS,
573ac9a064cSDimitry Andric APInt &DemandedRHS) {
574ac9a064cSDimitry Andric assert(VectorBitWidth >= 128 && "Vectors smaller than 128 bit not supported");
575ac9a064cSDimitry Andric int NumLanes = VectorBitWidth / 128;
576ac9a064cSDimitry Andric int NumElts = DemandedElts.getBitWidth();
577ac9a064cSDimitry Andric int NumEltsPerLane = NumElts / NumLanes;
578ac9a064cSDimitry Andric int HalfEltsPerLane = NumEltsPerLane / 2;
579ac9a064cSDimitry Andric
580ac9a064cSDimitry Andric DemandedLHS = APInt::getZero(NumElts);
581ac9a064cSDimitry Andric DemandedRHS = APInt::getZero(NumElts);
582ac9a064cSDimitry Andric
583ac9a064cSDimitry Andric // Map DemandedElts to the horizontal operands.
584ac9a064cSDimitry Andric for (int Idx = 0; Idx != NumElts; ++Idx) {
585ac9a064cSDimitry Andric if (!DemandedElts[Idx])
586ac9a064cSDimitry Andric continue;
587ac9a064cSDimitry Andric int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
588ac9a064cSDimitry Andric int LocalIdx = Idx % NumEltsPerLane;
589ac9a064cSDimitry Andric if (LocalIdx < HalfEltsPerLane) {
590ac9a064cSDimitry Andric DemandedLHS.setBit(LaneIdx + 2 * LocalIdx);
591ac9a064cSDimitry Andric } else {
592ac9a064cSDimitry Andric LocalIdx -= HalfEltsPerLane;
593ac9a064cSDimitry Andric DemandedRHS.setBit(LaneIdx + 2 * LocalIdx);
594ac9a064cSDimitry Andric }
595ac9a064cSDimitry Andric }
596ac9a064cSDimitry Andric }
597ac9a064cSDimitry Andric
598dd58ef01SDimitry Andric MapVector<Instruction *, uint64_t>
computeMinimumValueSizes(ArrayRef<BasicBlock * > Blocks,DemandedBits & DB,const TargetTransformInfo * TTI)599dd58ef01SDimitry Andric llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
600dd58ef01SDimitry Andric const TargetTransformInfo *TTI) {
601dd58ef01SDimitry Andric
602dd58ef01SDimitry Andric // DemandedBits will give us every value's live-out bits. But we want
603dd58ef01SDimitry Andric // to ensure no extra casts would need to be inserted, so every DAG
604dd58ef01SDimitry Andric // of connected values must have the same minimum bitwidth.
605dd58ef01SDimitry Andric EquivalenceClasses<Value *> ECs;
606dd58ef01SDimitry Andric SmallVector<Value *, 16> Worklist;
607dd58ef01SDimitry Andric SmallPtrSet<Value *, 4> Roots;
608dd58ef01SDimitry Andric SmallPtrSet<Value *, 16> Visited;
609dd58ef01SDimitry Andric DenseMap<Value *, uint64_t> DBits;
610dd58ef01SDimitry Andric SmallPtrSet<Instruction *, 4> InstructionSet;
611dd58ef01SDimitry Andric MapVector<Instruction *, uint64_t> MinBWs;
612dd58ef01SDimitry Andric
613dd58ef01SDimitry Andric // Determine the roots. We work bottom-up, from truncs or icmps.
614dd58ef01SDimitry Andric bool SeenExtFromIllegalType = false;
615dd58ef01SDimitry Andric for (auto *BB : Blocks)
616dd58ef01SDimitry Andric for (auto &I : *BB) {
617dd58ef01SDimitry Andric InstructionSet.insert(&I);
618dd58ef01SDimitry Andric
619dd58ef01SDimitry Andric if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
620dd58ef01SDimitry Andric !TTI->isTypeLegal(I.getOperand(0)->getType()))
621dd58ef01SDimitry Andric SeenExtFromIllegalType = true;
622dd58ef01SDimitry Andric
623dd58ef01SDimitry Andric // Only deal with non-vector integers up to 64-bits wide.
624dd58ef01SDimitry Andric if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
625dd58ef01SDimitry Andric !I.getType()->isVectorTy() &&
626dd58ef01SDimitry Andric I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
627dd58ef01SDimitry Andric // Don't make work for ourselves. If we know the loaded type is legal,
628dd58ef01SDimitry Andric // don't add it to the worklist.
629dd58ef01SDimitry Andric if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
630dd58ef01SDimitry Andric continue;
631dd58ef01SDimitry Andric
632dd58ef01SDimitry Andric Worklist.push_back(&I);
633dd58ef01SDimitry Andric Roots.insert(&I);
634dd58ef01SDimitry Andric }
635dd58ef01SDimitry Andric }
636dd58ef01SDimitry Andric // Early exit.
637dd58ef01SDimitry Andric if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
638dd58ef01SDimitry Andric return MinBWs;
639dd58ef01SDimitry Andric
640dd58ef01SDimitry Andric // Now proceed breadth-first, unioning values together.
641dd58ef01SDimitry Andric while (!Worklist.empty()) {
642dd58ef01SDimitry Andric Value *Val = Worklist.pop_back_val();
643dd58ef01SDimitry Andric Value *Leader = ECs.getOrInsertLeaderValue(Val);
644dd58ef01SDimitry Andric
645145449b1SDimitry Andric if (!Visited.insert(Val).second)
646dd58ef01SDimitry Andric continue;
647dd58ef01SDimitry Andric
648dd58ef01SDimitry Andric // Non-instructions terminate a chain successfully.
649dd58ef01SDimitry Andric if (!isa<Instruction>(Val))
650dd58ef01SDimitry Andric continue;
651dd58ef01SDimitry Andric Instruction *I = cast<Instruction>(Val);
652dd58ef01SDimitry Andric
653dd58ef01SDimitry Andric // If we encounter a type that is larger than 64 bits, we can't represent
654dd58ef01SDimitry Andric // it so bail out.
655dd58ef01SDimitry Andric if (DB.getDemandedBits(I).getBitWidth() > 64)
656dd58ef01SDimitry Andric return MapVector<Instruction *, uint64_t>();
657dd58ef01SDimitry Andric
658dd58ef01SDimitry Andric uint64_t V = DB.getDemandedBits(I).getZExtValue();
659dd58ef01SDimitry Andric DBits[Leader] |= V;
66001095a5dSDimitry Andric DBits[I] = V;
661dd58ef01SDimitry Andric
662dd58ef01SDimitry Andric // Casts, loads and instructions outside of our range terminate a chain
663dd58ef01SDimitry Andric // successfully.
664dd58ef01SDimitry Andric if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
665dd58ef01SDimitry Andric !InstructionSet.count(I))
666dd58ef01SDimitry Andric continue;
667dd58ef01SDimitry Andric
668dd58ef01SDimitry Andric // Unsafe casts terminate a chain unsuccessfully. We can't do anything
669dd58ef01SDimitry Andric // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
670dd58ef01SDimitry Andric // transform anything that relies on them.
671dd58ef01SDimitry Andric if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
672dd58ef01SDimitry Andric !I->getType()->isIntegerTy()) {
673dd58ef01SDimitry Andric DBits[Leader] |= ~0ULL;
674dd58ef01SDimitry Andric continue;
675dd58ef01SDimitry Andric }
676dd58ef01SDimitry Andric
677dd58ef01SDimitry Andric // We don't modify the types of PHIs. Reductions will already have been
678dd58ef01SDimitry Andric // truncated if possible, and inductions' sizes will have been chosen by
679dd58ef01SDimitry Andric // indvars.
680dd58ef01SDimitry Andric if (isa<PHINode>(I))
681dd58ef01SDimitry Andric continue;
682dd58ef01SDimitry Andric
683dd58ef01SDimitry Andric if (DBits[Leader] == ~0ULL)
684dd58ef01SDimitry Andric // All bits demanded, no point continuing.
685dd58ef01SDimitry Andric continue;
686dd58ef01SDimitry Andric
687dd58ef01SDimitry Andric for (Value *O : cast<User>(I)->operands()) {
688dd58ef01SDimitry Andric ECs.unionSets(Leader, O);
689dd58ef01SDimitry Andric Worklist.push_back(O);
690dd58ef01SDimitry Andric }
691dd58ef01SDimitry Andric }
692dd58ef01SDimitry Andric
693dd58ef01SDimitry Andric // Now we've discovered all values, walk them to see if there are
694dd58ef01SDimitry Andric // any users we didn't see. If there are, we can't optimize that
695dd58ef01SDimitry Andric // chain.
696dd58ef01SDimitry Andric for (auto &I : DBits)
697dd58ef01SDimitry Andric for (auto *U : I.first->users())
698dd58ef01SDimitry Andric if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
699dd58ef01SDimitry Andric DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
700dd58ef01SDimitry Andric
701dd58ef01SDimitry Andric for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
702dd58ef01SDimitry Andric uint64_t LeaderDemandedBits = 0;
703344a3780SDimitry Andric for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
704344a3780SDimitry Andric LeaderDemandedBits |= DBits[M];
705dd58ef01SDimitry Andric
7067fa27ce4SDimitry Andric uint64_t MinBW = llvm::bit_width(LeaderDemandedBits);
707dd58ef01SDimitry Andric // Round up to a power of 2
7087fa27ce4SDimitry Andric MinBW = llvm::bit_ceil(MinBW);
70901095a5dSDimitry Andric
71001095a5dSDimitry Andric // We don't modify the types of PHIs. Reductions will already have been
71101095a5dSDimitry Andric // truncated if possible, and inductions' sizes will have been chosen by
71201095a5dSDimitry Andric // indvars.
71301095a5dSDimitry Andric // If we are required to shrink a PHI, abandon this entire equivalence class.
71401095a5dSDimitry Andric bool Abort = false;
715344a3780SDimitry Andric for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
716344a3780SDimitry Andric if (isa<PHINode>(M) && MinBW < M->getType()->getScalarSizeInBits()) {
71701095a5dSDimitry Andric Abort = true;
71801095a5dSDimitry Andric break;
71901095a5dSDimitry Andric }
72001095a5dSDimitry Andric if (Abort)
72101095a5dSDimitry Andric continue;
72201095a5dSDimitry Andric
723344a3780SDimitry Andric for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end())) {
7247fa27ce4SDimitry Andric auto *MI = dyn_cast<Instruction>(M);
7257fa27ce4SDimitry Andric if (!MI)
726dd58ef01SDimitry Andric continue;
727344a3780SDimitry Andric Type *Ty = M->getType();
728344a3780SDimitry Andric if (Roots.count(M))
7297fa27ce4SDimitry Andric Ty = MI->getOperand(0)->getType();
7307fa27ce4SDimitry Andric
7317fa27ce4SDimitry Andric if (MinBW >= Ty->getScalarSizeInBits())
7327fa27ce4SDimitry Andric continue;
7337fa27ce4SDimitry Andric
7347fa27ce4SDimitry Andric // If any of M's operands demand more bits than MinBW then M cannot be
7357fa27ce4SDimitry Andric // performed safely in MinBW.
7367fa27ce4SDimitry Andric if (any_of(MI->operands(), [&DB, MinBW](Use &U) {
7377fa27ce4SDimitry Andric auto *CI = dyn_cast<ConstantInt>(U);
7387fa27ce4SDimitry Andric // For constants shift amounts, check if the shift would result in
7397fa27ce4SDimitry Andric // poison.
7407fa27ce4SDimitry Andric if (CI &&
7417fa27ce4SDimitry Andric isa<ShlOperator, LShrOperator, AShrOperator>(U.getUser()) &&
7427fa27ce4SDimitry Andric U.getOperandNo() == 1)
7437fa27ce4SDimitry Andric return CI->uge(MinBW);
7447fa27ce4SDimitry Andric uint64_t BW = bit_width(DB.getDemandedBits(&U).getZExtValue());
7457fa27ce4SDimitry Andric return bit_ceil(BW) > MinBW;
7467fa27ce4SDimitry Andric }))
7477fa27ce4SDimitry Andric continue;
7487fa27ce4SDimitry Andric
7497fa27ce4SDimitry Andric MinBWs[MI] = MinBW;
750dd58ef01SDimitry Andric }
751dd58ef01SDimitry Andric }
752dd58ef01SDimitry Andric
753dd58ef01SDimitry Andric return MinBWs;
754dd58ef01SDimitry Andric }
75501095a5dSDimitry Andric
756d8e91e46SDimitry Andric /// Add all access groups in @p AccGroups to @p List.
757d8e91e46SDimitry Andric template <typename ListT>
addToAccessGroupList(ListT & List,MDNode * AccGroups)758d8e91e46SDimitry Andric static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
759d8e91e46SDimitry Andric // Interpret an access group as a list containing itself.
760d8e91e46SDimitry Andric if (AccGroups->getNumOperands() == 0) {
761d8e91e46SDimitry Andric assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
762d8e91e46SDimitry Andric List.insert(AccGroups);
763d8e91e46SDimitry Andric return;
764d8e91e46SDimitry Andric }
765d8e91e46SDimitry Andric
7664b4fe385SDimitry Andric for (const auto &AccGroupListOp : AccGroups->operands()) {
767d8e91e46SDimitry Andric auto *Item = cast<MDNode>(AccGroupListOp.get());
768d8e91e46SDimitry Andric assert(isValidAsAccessGroup(Item) && "List item must be an access group");
769d8e91e46SDimitry Andric List.insert(Item);
770d8e91e46SDimitry Andric }
771d8e91e46SDimitry Andric }
772d8e91e46SDimitry Andric
uniteAccessGroups(MDNode * AccGroups1,MDNode * AccGroups2)773d8e91e46SDimitry Andric MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
774d8e91e46SDimitry Andric if (!AccGroups1)
775d8e91e46SDimitry Andric return AccGroups2;
776d8e91e46SDimitry Andric if (!AccGroups2)
777d8e91e46SDimitry Andric return AccGroups1;
778d8e91e46SDimitry Andric if (AccGroups1 == AccGroups2)
779d8e91e46SDimitry Andric return AccGroups1;
780d8e91e46SDimitry Andric
781d8e91e46SDimitry Andric SmallSetVector<Metadata *, 4> Union;
782d8e91e46SDimitry Andric addToAccessGroupList(Union, AccGroups1);
783d8e91e46SDimitry Andric addToAccessGroupList(Union, AccGroups2);
784d8e91e46SDimitry Andric
785d8e91e46SDimitry Andric if (Union.size() == 0)
786d8e91e46SDimitry Andric return nullptr;
787d8e91e46SDimitry Andric if (Union.size() == 1)
788d8e91e46SDimitry Andric return cast<MDNode>(Union.front());
789d8e91e46SDimitry Andric
790d8e91e46SDimitry Andric LLVMContext &Ctx = AccGroups1->getContext();
791d8e91e46SDimitry Andric return MDNode::get(Ctx, Union.getArrayRef());
792d8e91e46SDimitry Andric }
793d8e91e46SDimitry Andric
intersectAccessGroups(const Instruction * Inst1,const Instruction * Inst2)794d8e91e46SDimitry Andric MDNode *llvm::intersectAccessGroups(const Instruction *Inst1,
795d8e91e46SDimitry Andric const Instruction *Inst2) {
796d8e91e46SDimitry Andric bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
797d8e91e46SDimitry Andric bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
798d8e91e46SDimitry Andric
799d8e91e46SDimitry Andric if (!MayAccessMem1 && !MayAccessMem2)
800d8e91e46SDimitry Andric return nullptr;
801d8e91e46SDimitry Andric if (!MayAccessMem1)
802d8e91e46SDimitry Andric return Inst2->getMetadata(LLVMContext::MD_access_group);
803d8e91e46SDimitry Andric if (!MayAccessMem2)
804d8e91e46SDimitry Andric return Inst1->getMetadata(LLVMContext::MD_access_group);
805d8e91e46SDimitry Andric
806d8e91e46SDimitry Andric MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
807d8e91e46SDimitry Andric MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
808d8e91e46SDimitry Andric if (!MD1 || !MD2)
809d8e91e46SDimitry Andric return nullptr;
810d8e91e46SDimitry Andric if (MD1 == MD2)
811d8e91e46SDimitry Andric return MD1;
812d8e91e46SDimitry Andric
813d8e91e46SDimitry Andric // Use set for scalable 'contains' check.
814d8e91e46SDimitry Andric SmallPtrSet<Metadata *, 4> AccGroupSet2;
815d8e91e46SDimitry Andric addToAccessGroupList(AccGroupSet2, MD2);
816d8e91e46SDimitry Andric
817d8e91e46SDimitry Andric SmallVector<Metadata *, 4> Intersection;
818d8e91e46SDimitry Andric if (MD1->getNumOperands() == 0) {
819d8e91e46SDimitry Andric assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
820d8e91e46SDimitry Andric if (AccGroupSet2.count(MD1))
821d8e91e46SDimitry Andric Intersection.push_back(MD1);
822d8e91e46SDimitry Andric } else {
823d8e91e46SDimitry Andric for (const MDOperand &Node : MD1->operands()) {
824d8e91e46SDimitry Andric auto *Item = cast<MDNode>(Node.get());
825d8e91e46SDimitry Andric assert(isValidAsAccessGroup(Item) && "List item must be an access group");
826d8e91e46SDimitry Andric if (AccGroupSet2.count(Item))
827d8e91e46SDimitry Andric Intersection.push_back(Item);
828d8e91e46SDimitry Andric }
829d8e91e46SDimitry Andric }
830d8e91e46SDimitry Andric
831d8e91e46SDimitry Andric if (Intersection.size() == 0)
832d8e91e46SDimitry Andric return nullptr;
833d8e91e46SDimitry Andric if (Intersection.size() == 1)
834d8e91e46SDimitry Andric return cast<MDNode>(Intersection.front());
835d8e91e46SDimitry Andric
836d8e91e46SDimitry Andric LLVMContext &Ctx = Inst1->getContext();
837d8e91e46SDimitry Andric return MDNode::get(Ctx, Intersection);
838d8e91e46SDimitry Andric }
839d8e91e46SDimitry Andric
84001095a5dSDimitry Andric /// \returns \p I after propagating metadata from \p VL.
propagateMetadata(Instruction * Inst,ArrayRef<Value * > VL)84101095a5dSDimitry Andric Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
842344a3780SDimitry Andric if (VL.empty())
843344a3780SDimitry Andric return Inst;
84401095a5dSDimitry Andric Instruction *I0 = cast<Instruction>(VL[0]);
84501095a5dSDimitry Andric SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
84601095a5dSDimitry Andric I0->getAllMetadataOtherThanDebugLoc(Metadata);
84701095a5dSDimitry Andric
848d8e91e46SDimitry Andric for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
84901095a5dSDimitry Andric LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
850d8e91e46SDimitry Andric LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
851ac9a064cSDimitry Andric LLVMContext::MD_access_group, LLVMContext::MD_mmra}) {
85201095a5dSDimitry Andric MDNode *MD = I0->getMetadata(Kind);
85301095a5dSDimitry Andric for (int J = 1, E = VL.size(); MD && J != E; ++J) {
85401095a5dSDimitry Andric const Instruction *IJ = cast<Instruction>(VL[J]);
85501095a5dSDimitry Andric MDNode *IMD = IJ->getMetadata(Kind);
856ac9a064cSDimitry Andric
85701095a5dSDimitry Andric switch (Kind) {
858ac9a064cSDimitry Andric case LLVMContext::MD_mmra: {
859ac9a064cSDimitry Andric MD = MMRAMetadata::combine(Inst->getContext(), MD, IMD);
860ac9a064cSDimitry Andric break;
861ac9a064cSDimitry Andric }
86201095a5dSDimitry Andric case LLVMContext::MD_tbaa:
86301095a5dSDimitry Andric MD = MDNode::getMostGenericTBAA(MD, IMD);
86401095a5dSDimitry Andric break;
86501095a5dSDimitry Andric case LLVMContext::MD_alias_scope:
86601095a5dSDimitry Andric MD = MDNode::getMostGenericAliasScope(MD, IMD);
86701095a5dSDimitry Andric break;
86801095a5dSDimitry Andric case LLVMContext::MD_fpmath:
86901095a5dSDimitry Andric MD = MDNode::getMostGenericFPMath(MD, IMD);
87001095a5dSDimitry Andric break;
871b915e9e0SDimitry Andric case LLVMContext::MD_noalias:
87201095a5dSDimitry Andric case LLVMContext::MD_nontemporal:
873b915e9e0SDimitry Andric case LLVMContext::MD_invariant_load:
87401095a5dSDimitry Andric MD = MDNode::intersect(MD, IMD);
87501095a5dSDimitry Andric break;
876d8e91e46SDimitry Andric case LLVMContext::MD_access_group:
877d8e91e46SDimitry Andric MD = intersectAccessGroups(Inst, IJ);
878d8e91e46SDimitry Andric break;
87901095a5dSDimitry Andric default:
88001095a5dSDimitry Andric llvm_unreachable("unhandled metadata");
88101095a5dSDimitry Andric }
88201095a5dSDimitry Andric }
88301095a5dSDimitry Andric
88401095a5dSDimitry Andric Inst->setMetadata(Kind, MD);
88501095a5dSDimitry Andric }
88601095a5dSDimitry Andric
88701095a5dSDimitry Andric return Inst;
88801095a5dSDimitry Andric }
88971d5a254SDimitry Andric
890d8e91e46SDimitry Andric Constant *
createBitMaskForGaps(IRBuilderBase & Builder,unsigned VF,const InterleaveGroup<Instruction> & Group)891cfca06d7SDimitry Andric llvm::createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF,
892d8e91e46SDimitry Andric const InterleaveGroup<Instruction> &Group) {
893d8e91e46SDimitry Andric // All 1's means mask is not needed.
894d8e91e46SDimitry Andric if (Group.getNumMembers() == Group.getFactor())
895d8e91e46SDimitry Andric return nullptr;
896d8e91e46SDimitry Andric
897d8e91e46SDimitry Andric // TODO: support reversed access.
898d8e91e46SDimitry Andric assert(!Group.isReverse() && "Reversed group not supported.");
899d8e91e46SDimitry Andric
900d8e91e46SDimitry Andric SmallVector<Constant *, 16> Mask;
901d8e91e46SDimitry Andric for (unsigned i = 0; i < VF; i++)
902d8e91e46SDimitry Andric for (unsigned j = 0; j < Group.getFactor(); ++j) {
903d8e91e46SDimitry Andric unsigned HasMember = Group.getMember(j) ? 1 : 0;
904d8e91e46SDimitry Andric Mask.push_back(Builder.getInt1(HasMember));
905d8e91e46SDimitry Andric }
906d8e91e46SDimitry Andric
907d8e91e46SDimitry Andric return ConstantVector::get(Mask);
908d8e91e46SDimitry Andric }
909d8e91e46SDimitry Andric
910cfca06d7SDimitry Andric llvm::SmallVector<int, 16>
createReplicatedMask(unsigned ReplicationFactor,unsigned VF)911cfca06d7SDimitry Andric llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) {
912cfca06d7SDimitry Andric SmallVector<int, 16> MaskVec;
913d8e91e46SDimitry Andric for (unsigned i = 0; i < VF; i++)
914d8e91e46SDimitry Andric for (unsigned j = 0; j < ReplicationFactor; j++)
915cfca06d7SDimitry Andric MaskVec.push_back(i);
916d8e91e46SDimitry Andric
917cfca06d7SDimitry Andric return MaskVec;
918d8e91e46SDimitry Andric }
919d8e91e46SDimitry Andric
createInterleaveMask(unsigned VF,unsigned NumVecs)920cfca06d7SDimitry Andric llvm::SmallVector<int, 16> llvm::createInterleaveMask(unsigned VF,
92171d5a254SDimitry Andric unsigned NumVecs) {
922cfca06d7SDimitry Andric SmallVector<int, 16> Mask;
92371d5a254SDimitry Andric for (unsigned i = 0; i < VF; i++)
92471d5a254SDimitry Andric for (unsigned j = 0; j < NumVecs; j++)
925cfca06d7SDimitry Andric Mask.push_back(j * VF + i);
92671d5a254SDimitry Andric
927cfca06d7SDimitry Andric return Mask;
92871d5a254SDimitry Andric }
92971d5a254SDimitry Andric
930cfca06d7SDimitry Andric llvm::SmallVector<int, 16>
createStrideMask(unsigned Start,unsigned Stride,unsigned VF)931cfca06d7SDimitry Andric llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) {
932cfca06d7SDimitry Andric SmallVector<int, 16> Mask;
93371d5a254SDimitry Andric for (unsigned i = 0; i < VF; i++)
934cfca06d7SDimitry Andric Mask.push_back(Start + i * Stride);
93571d5a254SDimitry Andric
936cfca06d7SDimitry Andric return Mask;
93771d5a254SDimitry Andric }
93871d5a254SDimitry Andric
createSequentialMask(unsigned Start,unsigned NumInts,unsigned NumUndefs)939cfca06d7SDimitry Andric llvm::SmallVector<int, 16> llvm::createSequentialMask(unsigned Start,
940cfca06d7SDimitry Andric unsigned NumInts,
941cfca06d7SDimitry Andric unsigned NumUndefs) {
942cfca06d7SDimitry Andric SmallVector<int, 16> Mask;
94371d5a254SDimitry Andric for (unsigned i = 0; i < NumInts; i++)
944cfca06d7SDimitry Andric Mask.push_back(Start + i);
94571d5a254SDimitry Andric
94671d5a254SDimitry Andric for (unsigned i = 0; i < NumUndefs; i++)
947cfca06d7SDimitry Andric Mask.push_back(-1);
94871d5a254SDimitry Andric
949cfca06d7SDimitry Andric return Mask;
95071d5a254SDimitry Andric }
95171d5a254SDimitry Andric
createUnaryMask(ArrayRef<int> Mask,unsigned NumElts)952c0981da4SDimitry Andric llvm::SmallVector<int, 16> llvm::createUnaryMask(ArrayRef<int> Mask,
953c0981da4SDimitry Andric unsigned NumElts) {
954c0981da4SDimitry Andric // Avoid casts in the loop and make sure we have a reasonable number.
955c0981da4SDimitry Andric int NumEltsSigned = NumElts;
956c0981da4SDimitry Andric assert(NumEltsSigned > 0 && "Expected smaller or non-zero element count");
957c0981da4SDimitry Andric
958c0981da4SDimitry Andric // If the mask chooses an element from operand 1, reduce it to choose from the
959c0981da4SDimitry Andric // corresponding element of operand 0. Undef mask elements are unchanged.
960c0981da4SDimitry Andric SmallVector<int, 16> UnaryMask;
961c0981da4SDimitry Andric for (int MaskElt : Mask) {
962c0981da4SDimitry Andric assert((MaskElt < NumEltsSigned * 2) && "Expected valid shuffle mask");
963c0981da4SDimitry Andric int UnaryElt = MaskElt >= NumEltsSigned ? MaskElt - NumEltsSigned : MaskElt;
964c0981da4SDimitry Andric UnaryMask.push_back(UnaryElt);
965c0981da4SDimitry Andric }
966c0981da4SDimitry Andric return UnaryMask;
967c0981da4SDimitry Andric }
968c0981da4SDimitry Andric
96971d5a254SDimitry Andric /// A helper function for concatenating vectors. This function concatenates two
97071d5a254SDimitry Andric /// vectors having the same element type. If the second vector has fewer
97171d5a254SDimitry Andric /// elements than the first, it is padded with undefs.
concatenateTwoVectors(IRBuilderBase & Builder,Value * V1,Value * V2)972cfca06d7SDimitry Andric static Value *concatenateTwoVectors(IRBuilderBase &Builder, Value *V1,
97371d5a254SDimitry Andric Value *V2) {
97471d5a254SDimitry Andric VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
97571d5a254SDimitry Andric VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
97671d5a254SDimitry Andric assert(VecTy1 && VecTy2 &&
97771d5a254SDimitry Andric VecTy1->getScalarType() == VecTy2->getScalarType() &&
97871d5a254SDimitry Andric "Expect two vectors with the same element type");
97971d5a254SDimitry Andric
980b60736ecSDimitry Andric unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements();
981b60736ecSDimitry Andric unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements();
98271d5a254SDimitry Andric assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
98371d5a254SDimitry Andric
98471d5a254SDimitry Andric if (NumElts1 > NumElts2) {
98571d5a254SDimitry Andric // Extend with UNDEFs.
986cfca06d7SDimitry Andric V2 = Builder.CreateShuffleVector(
987b60736ecSDimitry Andric V2, createSequentialMask(0, NumElts2, NumElts1 - NumElts2));
98871d5a254SDimitry Andric }
98971d5a254SDimitry Andric
990cfca06d7SDimitry Andric return Builder.CreateShuffleVector(
991cfca06d7SDimitry Andric V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0));
99271d5a254SDimitry Andric }
99371d5a254SDimitry Andric
concatenateVectors(IRBuilderBase & Builder,ArrayRef<Value * > Vecs)994cfca06d7SDimitry Andric Value *llvm::concatenateVectors(IRBuilderBase &Builder,
995cfca06d7SDimitry Andric ArrayRef<Value *> Vecs) {
99671d5a254SDimitry Andric unsigned NumVecs = Vecs.size();
99771d5a254SDimitry Andric assert(NumVecs > 1 && "Should be at least two vectors");
99871d5a254SDimitry Andric
99971d5a254SDimitry Andric SmallVector<Value *, 8> ResList;
100071d5a254SDimitry Andric ResList.append(Vecs.begin(), Vecs.end());
100171d5a254SDimitry Andric do {
100271d5a254SDimitry Andric SmallVector<Value *, 8> TmpList;
100371d5a254SDimitry Andric for (unsigned i = 0; i < NumVecs - 1; i += 2) {
100471d5a254SDimitry Andric Value *V0 = ResList[i], *V1 = ResList[i + 1];
100571d5a254SDimitry Andric assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
100671d5a254SDimitry Andric "Only the last vector may have a different type");
100771d5a254SDimitry Andric
100871d5a254SDimitry Andric TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
100971d5a254SDimitry Andric }
101071d5a254SDimitry Andric
101171d5a254SDimitry Andric // Push the last vector if the total number of vectors is odd.
101271d5a254SDimitry Andric if (NumVecs % 2 != 0)
101371d5a254SDimitry Andric TmpList.push_back(ResList[NumVecs - 1]);
101471d5a254SDimitry Andric
101571d5a254SDimitry Andric ResList = TmpList;
101671d5a254SDimitry Andric NumVecs = ResList.size();
101771d5a254SDimitry Andric } while (NumVecs > 1);
101871d5a254SDimitry Andric
101971d5a254SDimitry Andric return ResList[0];
102071d5a254SDimitry Andric }
1021d8e91e46SDimitry Andric
maskIsAllZeroOrUndef(Value * Mask)1022e6d15924SDimitry Andric bool llvm::maskIsAllZeroOrUndef(Value *Mask) {
1023b60736ecSDimitry Andric assert(isa<VectorType>(Mask->getType()) &&
1024b60736ecSDimitry Andric isa<IntegerType>(Mask->getType()->getScalarType()) &&
1025b60736ecSDimitry Andric cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1026b60736ecSDimitry Andric 1 &&
1027b60736ecSDimitry Andric "Mask must be a vector of i1");
1028b60736ecSDimitry Andric
1029e6d15924SDimitry Andric auto *ConstMask = dyn_cast<Constant>(Mask);
1030e6d15924SDimitry Andric if (!ConstMask)
1031e6d15924SDimitry Andric return false;
1032e6d15924SDimitry Andric if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
1033e6d15924SDimitry Andric return true;
1034b60736ecSDimitry Andric if (isa<ScalableVectorType>(ConstMask->getType()))
1035b60736ecSDimitry Andric return false;
1036b60736ecSDimitry Andric for (unsigned
1037b60736ecSDimitry Andric I = 0,
1038b60736ecSDimitry Andric E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
1039cfca06d7SDimitry Andric I != E; ++I) {
1040e6d15924SDimitry Andric if (auto *MaskElt = ConstMask->getAggregateElement(I))
1041e6d15924SDimitry Andric if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
1042e6d15924SDimitry Andric continue;
1043e6d15924SDimitry Andric return false;
1044e6d15924SDimitry Andric }
1045e6d15924SDimitry Andric return true;
1046e6d15924SDimitry Andric }
1047e6d15924SDimitry Andric
maskIsAllOneOrUndef(Value * Mask)1048e6d15924SDimitry Andric bool llvm::maskIsAllOneOrUndef(Value *Mask) {
1049b60736ecSDimitry Andric assert(isa<VectorType>(Mask->getType()) &&
1050b60736ecSDimitry Andric isa<IntegerType>(Mask->getType()->getScalarType()) &&
1051b60736ecSDimitry Andric cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1052b60736ecSDimitry Andric 1 &&
1053b60736ecSDimitry Andric "Mask must be a vector of i1");
1054b60736ecSDimitry Andric
1055e6d15924SDimitry Andric auto *ConstMask = dyn_cast<Constant>(Mask);
1056e6d15924SDimitry Andric if (!ConstMask)
1057e6d15924SDimitry Andric return false;
1058e6d15924SDimitry Andric if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1059e6d15924SDimitry Andric return true;
1060b60736ecSDimitry Andric if (isa<ScalableVectorType>(ConstMask->getType()))
1061b60736ecSDimitry Andric return false;
1062b60736ecSDimitry Andric for (unsigned
1063b60736ecSDimitry Andric I = 0,
1064b60736ecSDimitry Andric E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
1065cfca06d7SDimitry Andric I != E; ++I) {
1066e6d15924SDimitry Andric if (auto *MaskElt = ConstMask->getAggregateElement(I))
1067e6d15924SDimitry Andric if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1068e6d15924SDimitry Andric continue;
1069e6d15924SDimitry Andric return false;
1070e6d15924SDimitry Andric }
1071e6d15924SDimitry Andric return true;
1072e6d15924SDimitry Andric }
1073e6d15924SDimitry Andric
maskContainsAllOneOrUndef(Value * Mask)1074ac9a064cSDimitry Andric bool llvm::maskContainsAllOneOrUndef(Value *Mask) {
1075ac9a064cSDimitry Andric assert(isa<VectorType>(Mask->getType()) &&
1076ac9a064cSDimitry Andric isa<IntegerType>(Mask->getType()->getScalarType()) &&
1077ac9a064cSDimitry Andric cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1078ac9a064cSDimitry Andric 1 &&
1079ac9a064cSDimitry Andric "Mask must be a vector of i1");
1080ac9a064cSDimitry Andric
1081ac9a064cSDimitry Andric auto *ConstMask = dyn_cast<Constant>(Mask);
1082ac9a064cSDimitry Andric if (!ConstMask)
1083ac9a064cSDimitry Andric return false;
1084ac9a064cSDimitry Andric if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1085ac9a064cSDimitry Andric return true;
1086ac9a064cSDimitry Andric if (isa<ScalableVectorType>(ConstMask->getType()))
1087ac9a064cSDimitry Andric return false;
1088ac9a064cSDimitry Andric for (unsigned
1089ac9a064cSDimitry Andric I = 0,
1090ac9a064cSDimitry Andric E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
1091ac9a064cSDimitry Andric I != E; ++I) {
1092ac9a064cSDimitry Andric if (auto *MaskElt = ConstMask->getAggregateElement(I))
1093ac9a064cSDimitry Andric if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1094ac9a064cSDimitry Andric return true;
1095ac9a064cSDimitry Andric }
1096ac9a064cSDimitry Andric return false;
1097ac9a064cSDimitry Andric }
1098ac9a064cSDimitry Andric
1099e6d15924SDimitry Andric /// TODO: This is a lot like known bits, but for
1100e6d15924SDimitry Andric /// vectors. Is there something we can common this with?
possiblyDemandedEltsInMask(Value * Mask)1101e6d15924SDimitry Andric APInt llvm::possiblyDemandedEltsInMask(Value *Mask) {
1102b60736ecSDimitry Andric assert(isa<FixedVectorType>(Mask->getType()) &&
1103b60736ecSDimitry Andric isa<IntegerType>(Mask->getType()->getScalarType()) &&
1104b60736ecSDimitry Andric cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1105b60736ecSDimitry Andric 1 &&
1106b60736ecSDimitry Andric "Mask must be a fixed width vector of i1");
1107e6d15924SDimitry Andric
1108b60736ecSDimitry Andric const unsigned VWidth =
1109b60736ecSDimitry Andric cast<FixedVectorType>(Mask->getType())->getNumElements();
1110c0981da4SDimitry Andric APInt DemandedElts = APInt::getAllOnes(VWidth);
1111e6d15924SDimitry Andric if (auto *CV = dyn_cast<ConstantVector>(Mask))
1112e6d15924SDimitry Andric for (unsigned i = 0; i < VWidth; i++)
1113e6d15924SDimitry Andric if (CV->getAggregateElement(i)->isNullValue())
1114e6d15924SDimitry Andric DemandedElts.clearBit(i);
1115e6d15924SDimitry Andric return DemandedElts;
1116e6d15924SDimitry Andric }
1117e6d15924SDimitry Andric
isStrided(int Stride)1118d8e91e46SDimitry Andric bool InterleavedAccessInfo::isStrided(int Stride) {
1119d8e91e46SDimitry Andric unsigned Factor = std::abs(Stride);
1120d8e91e46SDimitry Andric return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
1121d8e91e46SDimitry Andric }
1122d8e91e46SDimitry Andric
collectConstStrideAccesses(MapVector<Instruction *,StrideDescriptor> & AccessStrideInfo,const DenseMap<Value *,const SCEV * > & Strides)1123d8e91e46SDimitry Andric void InterleavedAccessInfo::collectConstStrideAccesses(
1124d8e91e46SDimitry Andric MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
11257fa27ce4SDimitry Andric const DenseMap<Value*, const SCEV*> &Strides) {
1126ac9a064cSDimitry Andric auto &DL = TheLoop->getHeader()->getDataLayout();
1127d8e91e46SDimitry Andric
1128d8e91e46SDimitry Andric // Since it's desired that the load/store instructions be maintained in
1129d8e91e46SDimitry Andric // "program order" for the interleaved access analysis, we have to visit the
1130d8e91e46SDimitry Andric // blocks in the loop in reverse postorder (i.e., in a topological order).
1131d8e91e46SDimitry Andric // Such an ordering will ensure that any load/store that may be executed
1132d8e91e46SDimitry Andric // before a second load/store will precede the second load/store in
1133d8e91e46SDimitry Andric // AccessStrideInfo.
1134d8e91e46SDimitry Andric LoopBlocksDFS DFS(TheLoop);
1135d8e91e46SDimitry Andric DFS.perform(LI);
1136d8e91e46SDimitry Andric for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
1137d8e91e46SDimitry Andric for (auto &I : *BB) {
1138d8e91e46SDimitry Andric Value *Ptr = getLoadStorePointerOperand(&I);
1139344a3780SDimitry Andric if (!Ptr)
1140344a3780SDimitry Andric continue;
1141344a3780SDimitry Andric Type *ElementTy = getLoadStoreType(&I);
1142344a3780SDimitry Andric
1143e3b55780SDimitry Andric // Currently, codegen doesn't support cases where the type size doesn't
1144e3b55780SDimitry Andric // match the alloc size. Skip them for now.
1145e3b55780SDimitry Andric uint64_t Size = DL.getTypeAllocSize(ElementTy);
1146e3b55780SDimitry Andric if (Size * 8 != DL.getTypeSizeInBits(ElementTy))
1147e3b55780SDimitry Andric continue;
1148e3b55780SDimitry Andric
1149d8e91e46SDimitry Andric // We don't check wrapping here because we don't know yet if Ptr will be
1150d8e91e46SDimitry Andric // part of a full group or a group with gaps. Checking wrapping for all
1151d8e91e46SDimitry Andric // pointers (even those that end up in groups with no gaps) will be overly
1152d8e91e46SDimitry Andric // conservative. For full groups, wrapping should be ok since if we would
1153d8e91e46SDimitry Andric // wrap around the address space we would do a memory access at nullptr
1154d8e91e46SDimitry Andric // even without the transformation. The wrapping checks are therefore
1155d8e91e46SDimitry Andric // deferred until after we've formed the interleaved groups.
1156e3b55780SDimitry Andric int64_t Stride =
1157e3b55780SDimitry Andric getPtrStride(PSE, ElementTy, Ptr, TheLoop, Strides,
1158e3b55780SDimitry Andric /*Assume=*/true, /*ShouldCheckWrap=*/false).value_or(0);
1159d8e91e46SDimitry Andric
1160d8e91e46SDimitry Andric const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
1161cfca06d7SDimitry Andric AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size,
1162cfca06d7SDimitry Andric getLoadStoreAlignment(&I));
1163d8e91e46SDimitry Andric }
1164d8e91e46SDimitry Andric }
1165d8e91e46SDimitry Andric
1166d8e91e46SDimitry Andric // Analyze interleaved accesses and collect them into interleaved load and
1167d8e91e46SDimitry Andric // store groups.
1168d8e91e46SDimitry Andric //
1169d8e91e46SDimitry Andric // When generating code for an interleaved load group, we effectively hoist all
1170d8e91e46SDimitry Andric // loads in the group to the location of the first load in program order. When
1171d8e91e46SDimitry Andric // generating code for an interleaved store group, we sink all stores to the
1172d8e91e46SDimitry Andric // location of the last store. This code motion can change the order of load
1173d8e91e46SDimitry Andric // and store instructions and may break dependences.
1174d8e91e46SDimitry Andric //
1175d8e91e46SDimitry Andric // The code generation strategy mentioned above ensures that we won't violate
1176d8e91e46SDimitry Andric // any write-after-read (WAR) dependences.
1177d8e91e46SDimitry Andric //
1178d8e91e46SDimitry Andric // E.g., for the WAR dependence: a = A[i]; // (1)
1179d8e91e46SDimitry Andric // A[i] = b; // (2)
1180d8e91e46SDimitry Andric //
1181d8e91e46SDimitry Andric // The store group of (2) is always inserted at or below (2), and the load
1182d8e91e46SDimitry Andric // group of (1) is always inserted at or above (1). Thus, the instructions will
1183d8e91e46SDimitry Andric // never be reordered. All other dependences are checked to ensure the
1184d8e91e46SDimitry Andric // correctness of the instruction reordering.
1185d8e91e46SDimitry Andric //
1186d8e91e46SDimitry Andric // The algorithm visits all memory accesses in the loop in bottom-up program
1187d8e91e46SDimitry Andric // order. Program order is established by traversing the blocks in the loop in
1188d8e91e46SDimitry Andric // reverse postorder when collecting the accesses.
1189d8e91e46SDimitry Andric //
1190d8e91e46SDimitry Andric // We visit the memory accesses in bottom-up order because it can simplify the
1191d8e91e46SDimitry Andric // construction of store groups in the presence of write-after-write (WAW)
1192d8e91e46SDimitry Andric // dependences.
1193d8e91e46SDimitry Andric //
1194d8e91e46SDimitry Andric // E.g., for the WAW dependence: A[i] = a; // (1)
1195d8e91e46SDimitry Andric // A[i] = b; // (2)
1196d8e91e46SDimitry Andric // A[i + 1] = c; // (3)
1197d8e91e46SDimitry Andric //
1198d8e91e46SDimitry Andric // We will first create a store group with (3) and (2). (1) can't be added to
1199d8e91e46SDimitry Andric // this group because it and (2) are dependent. However, (1) can be grouped
1200d8e91e46SDimitry Andric // with other accesses that may precede it in program order. Note that a
1201d8e91e46SDimitry Andric // bottom-up order does not imply that WAW dependences should not be checked.
analyzeInterleaving(bool EnablePredicatedInterleavedMemAccesses)1202d8e91e46SDimitry Andric void InterleavedAccessInfo::analyzeInterleaving(
1203d8e91e46SDimitry Andric bool EnablePredicatedInterleavedMemAccesses) {
1204d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
12057fa27ce4SDimitry Andric const auto &Strides = LAI->getSymbolicStrides();
1206d8e91e46SDimitry Andric
1207d8e91e46SDimitry Andric // Holds all accesses with a constant stride.
1208d8e91e46SDimitry Andric MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
1209d8e91e46SDimitry Andric collectConstStrideAccesses(AccessStrideInfo, Strides);
1210d8e91e46SDimitry Andric
1211d8e91e46SDimitry Andric if (AccessStrideInfo.empty())
1212d8e91e46SDimitry Andric return;
1213d8e91e46SDimitry Andric
1214d8e91e46SDimitry Andric // Collect the dependences in the loop.
1215d8e91e46SDimitry Andric collectDependences();
1216d8e91e46SDimitry Andric
1217d8e91e46SDimitry Andric // Holds all interleaved store groups temporarily.
1218d8e91e46SDimitry Andric SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
1219d8e91e46SDimitry Andric // Holds all interleaved load groups temporarily.
1220d8e91e46SDimitry Andric SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
12217fa27ce4SDimitry Andric // Groups added to this set cannot have new members added.
12227fa27ce4SDimitry Andric SmallPtrSet<InterleaveGroup<Instruction> *, 4> CompletedLoadGroups;
1223d8e91e46SDimitry Andric
1224d8e91e46SDimitry Andric // Search in bottom-up program order for pairs of accesses (A and B) that can
1225d8e91e46SDimitry Andric // form interleaved load or store groups. In the algorithm below, access A
1226d8e91e46SDimitry Andric // precedes access B in program order. We initialize a group for B in the
1227d8e91e46SDimitry Andric // outer loop of the algorithm, and then in the inner loop, we attempt to
1228d8e91e46SDimitry Andric // insert each A into B's group if:
1229d8e91e46SDimitry Andric //
1230d8e91e46SDimitry Andric // 1. A and B have the same stride,
1231d8e91e46SDimitry Andric // 2. A and B have the same memory object size, and
1232d8e91e46SDimitry Andric // 3. A belongs in B's group according to its distance from B.
1233d8e91e46SDimitry Andric //
1234d8e91e46SDimitry Andric // Special care is taken to ensure group formation will not break any
1235d8e91e46SDimitry Andric // dependences.
1236d8e91e46SDimitry Andric for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
1237d8e91e46SDimitry Andric BI != E; ++BI) {
1238d8e91e46SDimitry Andric Instruction *B = BI->first;
1239d8e91e46SDimitry Andric StrideDescriptor DesB = BI->second;
1240d8e91e46SDimitry Andric
1241d8e91e46SDimitry Andric // Initialize a group for B if it has an allowable stride. Even if we don't
1242d8e91e46SDimitry Andric // create a group for B, we continue with the bottom-up algorithm to ensure
1243d8e91e46SDimitry Andric // we don't break any of B's dependences.
12447fa27ce4SDimitry Andric InterleaveGroup<Instruction> *GroupB = nullptr;
1245d8e91e46SDimitry Andric if (isStrided(DesB.Stride) &&
1246d8e91e46SDimitry Andric (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
12477fa27ce4SDimitry Andric GroupB = getInterleaveGroup(B);
12487fa27ce4SDimitry Andric if (!GroupB) {
1249d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
1250d8e91e46SDimitry Andric << '\n');
12517fa27ce4SDimitry Andric GroupB = createInterleaveGroup(B, DesB.Stride, DesB.Alignment);
1252d8e91e46SDimitry Andric if (B->mayWriteToMemory())
12537fa27ce4SDimitry Andric StoreGroups.insert(GroupB);
1254d8e91e46SDimitry Andric else
12557fa27ce4SDimitry Andric LoadGroups.insert(GroupB);
1256d8e91e46SDimitry Andric }
1257b1c73532SDimitry Andric }
1258d8e91e46SDimitry Andric
1259d8e91e46SDimitry Andric for (auto AI = std::next(BI); AI != E; ++AI) {
1260d8e91e46SDimitry Andric Instruction *A = AI->first;
1261d8e91e46SDimitry Andric StrideDescriptor DesA = AI->second;
1262d8e91e46SDimitry Andric
1263d8e91e46SDimitry Andric // Our code motion strategy implies that we can't have dependences
1264d8e91e46SDimitry Andric // between accesses in an interleaved group and other accesses located
1265d8e91e46SDimitry Andric // between the first and last member of the group. Note that this also
1266d8e91e46SDimitry Andric // means that a group can't have more than one member at a given offset.
1267d8e91e46SDimitry Andric // The accesses in a group can have dependences with other accesses, but
1268d8e91e46SDimitry Andric // we must ensure we don't extend the boundaries of the group such that
1269d8e91e46SDimitry Andric // we encompass those dependent accesses.
1270d8e91e46SDimitry Andric //
1271d8e91e46SDimitry Andric // For example, assume we have the sequence of accesses shown below in a
1272d8e91e46SDimitry Andric // stride-2 loop:
1273d8e91e46SDimitry Andric //
1274d8e91e46SDimitry Andric // (1, 2) is a group | A[i] = a; // (1)
1275d8e91e46SDimitry Andric // | A[i-1] = b; // (2) |
1276d8e91e46SDimitry Andric // A[i-3] = c; // (3)
1277d8e91e46SDimitry Andric // A[i] = d; // (4) | (2, 4) is not a group
1278d8e91e46SDimitry Andric //
1279d8e91e46SDimitry Andric // Because accesses (2) and (3) are dependent, we can group (2) with (1)
1280d8e91e46SDimitry Andric // but not with (4). If we did, the dependent access (3) would be within
1281d8e91e46SDimitry Andric // the boundaries of the (2, 4) group.
1282b1c73532SDimitry Andric auto DependentMember = [&](InterleaveGroup<Instruction> *Group,
1283b1c73532SDimitry Andric StrideEntry *A) -> Instruction * {
1284b1c73532SDimitry Andric for (uint32_t Index = 0; Index < Group->getFactor(); ++Index) {
1285b1c73532SDimitry Andric Instruction *MemberOfGroupB = Group->getMember(Index);
1286b1c73532SDimitry Andric if (MemberOfGroupB && !canReorderMemAccessesForInterleavedGroups(
1287b1c73532SDimitry Andric A, &*AccessStrideInfo.find(MemberOfGroupB)))
1288b1c73532SDimitry Andric return MemberOfGroupB;
1289d8e91e46SDimitry Andric }
1290b1c73532SDimitry Andric return nullptr;
1291b1c73532SDimitry Andric };
1292b1c73532SDimitry Andric
1293b1c73532SDimitry Andric auto GroupA = getInterleaveGroup(A);
1294b1c73532SDimitry Andric // If A is a load, dependencies are tolerable, there's nothing to do here.
1295b1c73532SDimitry Andric // If both A and B belong to the same (store) group, they are independent,
1296b1c73532SDimitry Andric // even if dependencies have not been recorded.
1297b1c73532SDimitry Andric // If both GroupA and GroupB are null, there's nothing to do here.
1298b1c73532SDimitry Andric if (A->mayWriteToMemory() && GroupA != GroupB) {
1299b1c73532SDimitry Andric Instruction *DependentInst = nullptr;
1300b1c73532SDimitry Andric // If GroupB is a load group, we have to compare AI against all
1301b1c73532SDimitry Andric // members of GroupB because if any load within GroupB has a dependency
1302b1c73532SDimitry Andric // on AI, we need to mark GroupB as complete and also release the
1303b1c73532SDimitry Andric // store GroupA (if A belongs to one). The former prevents incorrect
1304b1c73532SDimitry Andric // hoisting of load B above store A while the latter prevents incorrect
1305b1c73532SDimitry Andric // sinking of store A below load B.
1306b1c73532SDimitry Andric if (GroupB && LoadGroups.contains(GroupB))
1307b1c73532SDimitry Andric DependentInst = DependentMember(GroupB, &*AI);
1308b1c73532SDimitry Andric else if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI))
1309b1c73532SDimitry Andric DependentInst = B;
1310b1c73532SDimitry Andric
1311b1c73532SDimitry Andric if (DependentInst) {
1312b1c73532SDimitry Andric // A has a store dependence on B (or on some load within GroupB) and
1313b1c73532SDimitry Andric // is part of a store group. Release A's group to prevent illegal
1314b1c73532SDimitry Andric // sinking of A below B. A will then be free to form another group
1315b1c73532SDimitry Andric // with instructions that precede it.
1316b1c73532SDimitry Andric if (GroupA && StoreGroups.contains(GroupA)) {
1317b1c73532SDimitry Andric LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
1318b1c73532SDimitry Andric "dependence between "
1319b1c73532SDimitry Andric << *A << " and " << *DependentInst << '\n');
1320b1c73532SDimitry Andric StoreGroups.remove(GroupA);
1321b1c73532SDimitry Andric releaseGroup(GroupA);
1322b1c73532SDimitry Andric }
1323b1c73532SDimitry Andric // If B is a load and part of an interleave group, no earlier loads
1324b1c73532SDimitry Andric // can be added to B's interleave group, because this would mean the
1325b1c73532SDimitry Andric // DependentInst would move across store A. Mark the interleave group
1326b1c73532SDimitry Andric // as complete.
1327b1c73532SDimitry Andric if (GroupB && LoadGroups.contains(GroupB)) {
13287fa27ce4SDimitry Andric LLVM_DEBUG(dbgs() << "LV: Marking interleave group for " << *B
13297fa27ce4SDimitry Andric << " as complete.\n");
13307fa27ce4SDimitry Andric CompletedLoadGroups.insert(GroupB);
13317fa27ce4SDimitry Andric }
1332b1c73532SDimitry Andric }
1333b1c73532SDimitry Andric }
1334b1c73532SDimitry Andric if (CompletedLoadGroups.contains(GroupB)) {
1335b1c73532SDimitry Andric // Skip trying to add A to B, continue to look for other conflicting A's
1336b1c73532SDimitry Andric // in groups to be released.
1337b1c73532SDimitry Andric continue;
1338d8e91e46SDimitry Andric }
1339d8e91e46SDimitry Andric
1340d8e91e46SDimitry Andric // At this point, we've checked for illegal code motion. If either A or B
1341d8e91e46SDimitry Andric // isn't strided, there's nothing left to do.
1342d8e91e46SDimitry Andric if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
1343d8e91e46SDimitry Andric continue;
1344d8e91e46SDimitry Andric
1345d8e91e46SDimitry Andric // Ignore A if it's already in a group or isn't the same kind of memory
1346d8e91e46SDimitry Andric // operation as B.
1347d8e91e46SDimitry Andric // Note that mayReadFromMemory() isn't mutually exclusive to
1348d8e91e46SDimitry Andric // mayWriteToMemory in the case of atomic loads. We shouldn't see those
1349d8e91e46SDimitry Andric // here, canVectorizeMemory() should have returned false - except for the
1350d8e91e46SDimitry Andric // case we asked for optimization remarks.
1351d8e91e46SDimitry Andric if (isInterleaved(A) ||
1352d8e91e46SDimitry Andric (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
1353d8e91e46SDimitry Andric (A->mayWriteToMemory() != B->mayWriteToMemory()))
1354d8e91e46SDimitry Andric continue;
1355d8e91e46SDimitry Andric
1356d8e91e46SDimitry Andric // Check rules 1 and 2. Ignore A if its stride or size is different from
1357d8e91e46SDimitry Andric // that of B.
1358d8e91e46SDimitry Andric if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
1359d8e91e46SDimitry Andric continue;
1360d8e91e46SDimitry Andric
1361d8e91e46SDimitry Andric // Ignore A if the memory object of A and B don't belong to the same
1362d8e91e46SDimitry Andric // address space
1363d8e91e46SDimitry Andric if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
1364d8e91e46SDimitry Andric continue;
1365d8e91e46SDimitry Andric
1366d8e91e46SDimitry Andric // Calculate the distance from A to B.
1367d8e91e46SDimitry Andric const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
1368d8e91e46SDimitry Andric PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
1369d8e91e46SDimitry Andric if (!DistToB)
1370d8e91e46SDimitry Andric continue;
1371d8e91e46SDimitry Andric int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
1372d8e91e46SDimitry Andric
1373d8e91e46SDimitry Andric // Check rule 3. Ignore A if its distance to B is not a multiple of the
1374d8e91e46SDimitry Andric // size.
1375d8e91e46SDimitry Andric if (DistanceToB % static_cast<int64_t>(DesB.Size))
1376d8e91e46SDimitry Andric continue;
1377d8e91e46SDimitry Andric
1378d8e91e46SDimitry Andric // All members of a predicated interleave-group must have the same predicate,
1379d8e91e46SDimitry Andric // and currently must reside in the same BB.
1380d8e91e46SDimitry Andric BasicBlock *BlockA = A->getParent();
1381d8e91e46SDimitry Andric BasicBlock *BlockB = B->getParent();
1382d8e91e46SDimitry Andric if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
1383d8e91e46SDimitry Andric (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
1384d8e91e46SDimitry Andric continue;
1385d8e91e46SDimitry Andric
1386d8e91e46SDimitry Andric // The index of A is the index of B plus A's distance to B in multiples
1387d8e91e46SDimitry Andric // of the size.
1388d8e91e46SDimitry Andric int IndexA =
13897fa27ce4SDimitry Andric GroupB->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
1390d8e91e46SDimitry Andric
1391d8e91e46SDimitry Andric // Try to insert A into B's group.
13927fa27ce4SDimitry Andric if (GroupB->insertMember(A, IndexA, DesA.Alignment)) {
1393d8e91e46SDimitry Andric LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
1394d8e91e46SDimitry Andric << " into the interleave group with" << *B
1395d8e91e46SDimitry Andric << '\n');
13967fa27ce4SDimitry Andric InterleaveGroupMap[A] = GroupB;
1397d8e91e46SDimitry Andric
1398d8e91e46SDimitry Andric // Set the first load in program order as the insert position.
1399d8e91e46SDimitry Andric if (A->mayReadFromMemory())
14007fa27ce4SDimitry Andric GroupB->setInsertPos(A);
1401d8e91e46SDimitry Andric }
1402d8e91e46SDimitry Andric } // Iteration over A accesses.
1403d8e91e46SDimitry Andric } // Iteration over B accesses.
1404d8e91e46SDimitry Andric
1405c0981da4SDimitry Andric auto InvalidateGroupIfMemberMayWrap = [&](InterleaveGroup<Instruction> *Group,
1406c0981da4SDimitry Andric int Index,
1407c0981da4SDimitry Andric std::string FirstOrLast) -> bool {
1408c0981da4SDimitry Andric Instruction *Member = Group->getMember(Index);
1409c0981da4SDimitry Andric assert(Member && "Group member does not exist");
1410c0981da4SDimitry Andric Value *MemberPtr = getLoadStorePointerOperand(Member);
1411c0981da4SDimitry Andric Type *AccessTy = getLoadStoreType(Member);
1412c0981da4SDimitry Andric if (getPtrStride(PSE, AccessTy, MemberPtr, TheLoop, Strides,
1413e3b55780SDimitry Andric /*Assume=*/false, /*ShouldCheckWrap=*/true).value_or(0))
1414c0981da4SDimitry Andric return false;
1415c0981da4SDimitry Andric LLVM_DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
1416c0981da4SDimitry Andric << FirstOrLast
1417c0981da4SDimitry Andric << " group member potentially pointer-wrapping.\n");
1418d8e91e46SDimitry Andric releaseGroup(Group);
1419c0981da4SDimitry Andric return true;
1420c0981da4SDimitry Andric };
1421c0981da4SDimitry Andric
1422c0981da4SDimitry Andric // Remove interleaved groups with gaps whose memory
1423d8e91e46SDimitry Andric // accesses may wrap around. We have to revisit the getPtrStride analysis,
1424d8e91e46SDimitry Andric // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
1425d8e91e46SDimitry Andric // not check wrapping (see documentation there).
1426d8e91e46SDimitry Andric // FORNOW we use Assume=false;
1427d8e91e46SDimitry Andric // TODO: Change to Assume=true but making sure we don't exceed the threshold
1428d8e91e46SDimitry Andric // of runtime SCEV assumptions checks (thereby potentially failing to
1429d8e91e46SDimitry Andric // vectorize altogether).
1430d8e91e46SDimitry Andric // Additional optional optimizations:
1431d8e91e46SDimitry Andric // TODO: If we are peeling the loop and we know that the first pointer doesn't
1432d8e91e46SDimitry Andric // wrap then we can deduce that all pointers in the group don't wrap.
1433d8e91e46SDimitry Andric // This means that we can forcefully peel the loop in order to only have to
1434d8e91e46SDimitry Andric // check the first pointer for no-wrap. When we'll change to use Assume=true
1435d8e91e46SDimitry Andric // we'll only need at most one runtime check per interleaved group.
1436d8e91e46SDimitry Andric for (auto *Group : LoadGroups) {
1437d8e91e46SDimitry Andric // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1438d8e91e46SDimitry Andric // load would wrap around the address space we would do a memory access at
1439d8e91e46SDimitry Andric // nullptr even without the transformation.
1440d8e91e46SDimitry Andric if (Group->getNumMembers() == Group->getFactor())
1441d8e91e46SDimitry Andric continue;
1442d8e91e46SDimitry Andric
1443d8e91e46SDimitry Andric // Case 2: If first and last members of the group don't wrap this implies
1444d8e91e46SDimitry Andric // that all the pointers in the group don't wrap.
1445d8e91e46SDimitry Andric // So we check only group member 0 (which is always guaranteed to exist),
1446d8e91e46SDimitry Andric // and group member Factor - 1; If the latter doesn't exist we rely on
1447e6d15924SDimitry Andric // peeling (if it is a non-reversed accsess -- see Case 3).
1448c0981da4SDimitry Andric if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
1449d8e91e46SDimitry Andric continue;
1450c0981da4SDimitry Andric if (Group->getMember(Group->getFactor() - 1))
1451c0981da4SDimitry Andric InvalidateGroupIfMemberMayWrap(Group, Group->getFactor() - 1,
1452c0981da4SDimitry Andric std::string("last"));
1453c0981da4SDimitry Andric else {
1454d8e91e46SDimitry Andric // Case 3: A non-reversed interleaved load group with gaps: We need
1455d8e91e46SDimitry Andric // to execute at least one scalar epilogue iteration. This will ensure
1456d8e91e46SDimitry Andric // we don't speculatively access memory out-of-bounds. We only need
1457d8e91e46SDimitry Andric // to look for a member at index factor - 1, since every group must have
1458d8e91e46SDimitry Andric // a member at index zero.
1459d8e91e46SDimitry Andric if (Group->isReverse()) {
1460d8e91e46SDimitry Andric LLVM_DEBUG(
1461d8e91e46SDimitry Andric dbgs() << "LV: Invalidate candidate interleaved group due to "
1462d8e91e46SDimitry Andric "a reverse access with gaps.\n");
1463d8e91e46SDimitry Andric releaseGroup(Group);
1464d8e91e46SDimitry Andric continue;
1465d8e91e46SDimitry Andric }
1466d8e91e46SDimitry Andric LLVM_DEBUG(
1467d8e91e46SDimitry Andric dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
1468d8e91e46SDimitry Andric RequiresScalarEpilogue = true;
1469d8e91e46SDimitry Andric }
1470d8e91e46SDimitry Andric }
1471c0981da4SDimitry Andric
1472c0981da4SDimitry Andric for (auto *Group : StoreGroups) {
1473c0981da4SDimitry Andric // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1474c0981da4SDimitry Andric // store would wrap around the address space we would do a memory access at
1475c0981da4SDimitry Andric // nullptr even without the transformation.
1476c0981da4SDimitry Andric if (Group->getNumMembers() == Group->getFactor())
1477c0981da4SDimitry Andric continue;
1478c0981da4SDimitry Andric
1479c0981da4SDimitry Andric // Interleave-store-group with gaps is implemented using masked wide store.
1480c0981da4SDimitry Andric // Remove interleaved store groups with gaps if
1481c0981da4SDimitry Andric // masked-interleaved-accesses are not enabled by the target.
1482c0981da4SDimitry Andric if (!EnablePredicatedInterleavedMemAccesses) {
1483c0981da4SDimitry Andric LLVM_DEBUG(
1484c0981da4SDimitry Andric dbgs() << "LV: Invalidate candidate interleaved store group due "
1485c0981da4SDimitry Andric "to gaps.\n");
1486c0981da4SDimitry Andric releaseGroup(Group);
1487c0981da4SDimitry Andric continue;
1488c0981da4SDimitry Andric }
1489c0981da4SDimitry Andric
1490c0981da4SDimitry Andric // Case 2: If first and last members of the group don't wrap this implies
1491c0981da4SDimitry Andric // that all the pointers in the group don't wrap.
1492c0981da4SDimitry Andric // So we check only group member 0 (which is always guaranteed to exist),
1493c0981da4SDimitry Andric // and the last group member. Case 3 (scalar epilog) is not relevant for
1494c0981da4SDimitry Andric // stores with gaps, which are implemented with masked-store (rather than
1495c0981da4SDimitry Andric // speculative access, as in loads).
1496c0981da4SDimitry Andric if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
1497c0981da4SDimitry Andric continue;
1498c0981da4SDimitry Andric for (int Index = Group->getFactor() - 1; Index > 0; Index--)
1499c0981da4SDimitry Andric if (Group->getMember(Index)) {
1500c0981da4SDimitry Andric InvalidateGroupIfMemberMayWrap(Group, Index, std::string("last"));
1501c0981da4SDimitry Andric break;
1502c0981da4SDimitry Andric }
1503c0981da4SDimitry Andric }
1504d8e91e46SDimitry Andric }
1505d8e91e46SDimitry Andric
invalidateGroupsRequiringScalarEpilogue()1506d8e91e46SDimitry Andric void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
1507d8e91e46SDimitry Andric // If no group had triggered the requirement to create an epilogue loop,
1508d8e91e46SDimitry Andric // there is nothing to do.
1509d8e91e46SDimitry Andric if (!requiresScalarEpilogue())
1510d8e91e46SDimitry Andric return;
1511d8e91e46SDimitry Andric
1512cfca06d7SDimitry Andric // Release groups requiring scalar epilogues. Note that this also removes them
1513cfca06d7SDimitry Andric // from InterleaveGroups.
1514ac9a064cSDimitry Andric bool ReleasedGroup = InterleaveGroups.remove_if([&](auto *Group) {
1515cfca06d7SDimitry Andric if (!Group->requiresScalarEpilogue())
1516ac9a064cSDimitry Andric return false;
1517d8e91e46SDimitry Andric LLVM_DEBUG(
1518d8e91e46SDimitry Andric dbgs()
1519d8e91e46SDimitry Andric << "LV: Invalidate candidate interleaved group due to gaps that "
1520d8e91e46SDimitry Andric "require a scalar epilogue (not allowed under optsize) and cannot "
1521d8e91e46SDimitry Andric "be masked (not enabled). \n");
1522ac9a064cSDimitry Andric releaseGroupWithoutRemovingFromSet(Group);
1523ac9a064cSDimitry Andric return true;
1524ac9a064cSDimitry Andric });
1525cfca06d7SDimitry Andric assert(ReleasedGroup && "At least one group must be invalidated, as a "
1526cfca06d7SDimitry Andric "scalar epilogue was required");
1527cfca06d7SDimitry Andric (void)ReleasedGroup;
1528d8e91e46SDimitry Andric RequiresScalarEpilogue = false;
1529d8e91e46SDimitry Andric }
1530d8e91e46SDimitry Andric
1531d8e91e46SDimitry Andric template <typename InstT>
addMetadata(InstT * NewInst) const1532d8e91e46SDimitry Andric void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
1533d8e91e46SDimitry Andric llvm_unreachable("addMetadata can only be used for Instruction");
1534d8e91e46SDimitry Andric }
1535d8e91e46SDimitry Andric
1536d8e91e46SDimitry Andric namespace llvm {
1537d8e91e46SDimitry Andric template <>
addMetadata(Instruction * NewInst) const1538d8e91e46SDimitry Andric void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
1539d8e91e46SDimitry Andric SmallVector<Value *, 4> VL;
1540d8e91e46SDimitry Andric std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
1541d8e91e46SDimitry Andric [](std::pair<int, Instruction *> p) { return p.second; });
1542d8e91e46SDimitry Andric propagateMetadata(NewInst, VL);
1543d8e91e46SDimitry Andric }
15444df029ccSDimitry Andric } // namespace llvm
1545