LLVM 24.0.0git
SLPMemoryUtils.cpp
Go to the documentation of this file.
1//===- SLPMemoryUtils.cpp - SLP pointer/stride helpers --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "SLPMemoryUtils.h"
11#include "SLPCostAnalysis.h"
12#include "SLPTypeUtils.h"
13#include "SLPUtils.h"
14
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/Sequence.h"
20#include "llvm/Analysis/Loads.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Intrinsics.h"
34
35#include <algorithm>
36#include <limits>
37#include <optional>
38#include <set>
39#include <tuple>
40#include <utility>
41
42using namespace llvm;
43
44namespace llvm::slpvectorizer {
45
47 const DataLayout &DL) {
48 bool ToPtr = cast<VectorType>(DstTy)->getElementType()->isPointerTy();
49 if (ToPtr == cast<VectorType>(V->getType())->getElementType()->isPointerTy())
50 return Builder.CreateBitOrPointerCast(V, DstTy);
51 if (ToPtr)
52 return Builder.CreateIntToPtr(
53 Builder.CreateBitCast(V, DL.getIntPtrType(DstTy)), DstTy);
54 return Builder.CreateBitCast(
55 Builder.CreatePtrToInt(V, DL.getIntPtrType(V->getType())), DstTy);
56}
57
59 const TargetLibraryInfo &TLI, unsigned MaxDepth,
60 bool CompareOpcodes) {
61 if (getUnderlyingObject(Ptr1, MaxDepth) !=
62 getUnderlyingObject(Ptr2, MaxDepth))
63 return false;
64 auto *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
65 auto *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
66 return (!GEP1 || GEP1->getNumOperands() == 2) &&
67 (!GEP2 || GEP2->getNumOperands() == 2) &&
68 (((!GEP1 || isConstant(GEP1->getOperand(1))) &&
69 (!GEP2 || isConstant(GEP2->getOperand(1)))) ||
70 !CompareOpcodes ||
71 (GEP1 && GEP2 &&
72 getSameOpcode({GEP1->getOperand(1), GEP2->getOperand(1)}, TLI)));
73}
74
75/// Calculates minimal alignment as a common alignment.
77 Align CommonAlignment = cast<T>(VL.consume_front())->getAlign();
78 for (Value *V : VL)
79 CommonAlignment = std::min(CommonAlignment, cast<T>(V)->getAlign());
80 return CommonAlignment;
81}
82
85
87 const DataLayout &DL, ScalarEvolution &SE,
88 SmallVectorImpl<unsigned> &SortedIndices) {
90 const SCEV *PtrSCEVLowest = nullptr;
91 const SCEV *PtrSCEVHighest = nullptr;
92 // Find lower/upper pointers from the PointerOps (i.e. with lowest and highest
93 // addresses).
94 for (Value *Ptr : PointerOps) {
95 const SCEV *PtrSCEV = SE.getSCEV(Ptr);
96 if (!PtrSCEV)
97 return nullptr;
98 SCEVs.push_back(PtrSCEV);
99 if (!PtrSCEVLowest && !PtrSCEVHighest) {
100 PtrSCEVLowest = PtrSCEVHighest = PtrSCEV;
101 continue;
102 }
103 const SCEV *Diff = SE.getMinusSCEV(PtrSCEV, PtrSCEVLowest);
104 if (isa<SCEVCouldNotCompute>(Diff))
105 return nullptr;
106 if (Diff->isNonConstantNegative()) {
107 PtrSCEVLowest = PtrSCEV;
108 continue;
109 }
110 const SCEV *Diff1 = SE.getMinusSCEV(PtrSCEVHighest, PtrSCEV);
111 if (isa<SCEVCouldNotCompute>(Diff1))
112 return nullptr;
113 if (Diff1->isNonConstantNegative()) {
114 PtrSCEVHighest = PtrSCEV;
115 continue;
116 }
117 }
118 // Dist = PtrSCEVHighest - PtrSCEVLowest;
119 const SCEV *Dist = SE.getMinusSCEV(PtrSCEVHighest, PtrSCEVLowest);
120 if (isa<SCEVCouldNotCompute>(Dist))
121 return nullptr;
122 int Size = DL.getTypeStoreSize(ElemTy);
123 auto TryGetStride = [&](const SCEV *Dist,
124 const SCEV *Multiplier) -> const SCEV * {
125 if (const auto *M = dyn_cast<SCEVMulExpr>(Dist)) {
126 if (M->getOperand(0) == Multiplier)
127 return M->getOperand(1);
128 if (M->getOperand(1) == Multiplier)
129 return M->getOperand(0);
130 return nullptr;
131 }
132 if (Multiplier == Dist)
133 return SE.getConstant(Dist->getType(), 1);
134 return SE.getUDivExactExpr(Dist, Multiplier);
135 };
136 // Stride_in_elements = Dist / element_size * (num_elems - 1).
137 const SCEV *Stride = nullptr;
138 if (Size != 1 || SCEVs.size() > 1) {
139 const SCEV *Sz = SE.getConstant(Dist->getType(), Size * (SCEVs.size() - 1));
140 Stride = TryGetStride(Dist, Sz);
141 if (!Stride)
142 return nullptr;
143 }
144 if (!Stride || isa<SCEVConstant>(Stride))
145 return nullptr;
146 // Iterate through all pointers and check if all distances are
147 // unique multiple of Stride.
148 using DistOrdPair = std::pair<int64_t, int>;
149 auto Compare = llvm::less_first();
150 std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
151 bool IsConsecutive = true;
152 for (const auto [Idx, PtrSCEV] : enumerate(SCEVs)) {
153 unsigned Dist = 0;
154 if (PtrSCEV != PtrSCEVLowest) {
155 const SCEV *Diff = SE.getMinusSCEV(PtrSCEV, PtrSCEVLowest);
156 const SCEV *Coeff = TryGetStride(Diff, Stride);
157 if (!Coeff)
158 return nullptr;
159 const auto *SC = dyn_cast<SCEVConstant>(Coeff);
160 if (!SC || isa<SCEVCouldNotCompute>(SC))
161 return nullptr;
162 if (!SE.getMinusSCEV(PtrSCEV, SE.getAddExpr(PtrSCEVLowest,
163 SE.getMulExpr(Stride, SC)))
164 ->isZero())
165 return nullptr;
166 Dist = SC->getAPInt().getZExtValue();
167 }
168 // If the strides are not the same or repeated, we can't vectorize.
169 if ((Dist / Size) * Size != Dist || (Dist / Size) >= SCEVs.size())
170 return nullptr;
171 auto Res = Offsets.emplace(Dist, Idx);
172 if (!Res.second)
173 return nullptr;
174 // Consecutive order if the inserted element is the last one.
175 IsConsecutive = IsConsecutive && std::next(Res.first) == Offsets.end();
176 }
177 SortedIndices.clear();
178 if (!IsConsecutive) {
179 // Fill SortedIndices array only if it is non-consecutive.
180 SortedIndices.resize(PointerOps.size());
181 for (const auto [Idx, Pair] : enumerate(Offsets))
182 SortedIndices[Idx] = Pair.second;
183 }
184 return Stride;
185}
186
187std::optional<int64_t>
189 Value *PtrB, const DataLayout &DL,
190 ScalarEvolution &SE, bool StrictCheck,
191 bool CheckType) {
192 if (PtrA == PtrB)
193 return 0;
194 unsigned Flags = unsigned(StrictCheck) | (unsigned(CheckType) << 1);
195 PtrsDiffKeyT Key(ElemTyA, PtrA, ElemTyB, PtrB, Flags);
196 auto [It, Inserted] = PtrsDiffCache.try_emplace(Key);
197 if (!Inserted)
198 return It->second;
199 std::optional<int64_t> Diff = llvm::getPointersDiff(
200 ElemTyA, PtrA, ElemTyB, PtrB, DL, SE, StrictCheck, CheckType);
201 // Set before the reverse insertion below, which may rehash.
202 It->second = Diff;
203 // The distance is counted in elements of ElemTyA, so querying the pair the
204 // other way round gives the negation, provided both elements have the same
205 // size. A failed query is recorded for this order only.
206 if (Diff && *Diff != std::numeric_limits<int64_t>::min() &&
207 DL.getTypeStoreSize(ElemTyA) == DL.getTypeStoreSize(ElemTyB))
208 PtrsDiffCache.try_emplace(PtrsDiffKeyT(ElemTyB, PtrB, ElemTyA, PtrA, Flags),
209 -*Diff);
210 return Diff;
211}
212
215 ScalarEvolution &SE, SmallVectorImpl<unsigned> &SortedIndices) {
216 using DistOrdPair = std::pair<int64_t, unsigned>;
217 auto Compare = less_first();
218 std::set<DistOrdPair, decltype(Compare)> Offsets(Compare);
219 Offsets.emplace(0, 0);
220 bool IsConsecutive = true;
221 for (auto [Idx, Ptr] : drop_begin(enumerate(VL))) {
222 std::optional<int64_t> Diff =
223 getPointersDiff(ElemTy, VL.front(), ElemTy, Ptr, DL, SE,
224 /*StrictCheck=*/true);
225 if (!Diff)
226 return false;
227 auto [It, IsInserted] = Offsets.emplace(*Diff, Idx);
228 if (!IsInserted)
229 return false;
230 IsConsecutive &= std::next(It) == Offsets.end();
231 }
232 SortedIndices.clear();
233 if (!IsConsecutive) {
234 SortedIndices.resize(VL.size());
235 for (auto [Idx, Off] : enumerate(Offsets))
236 SortedIndices[Idx] = Off.second;
237 }
238 return true;
239}
240
242 AssumptionCache *AC) {
243 auto [It, Inserted] = NotPoisonCache.try_emplace(V, false);
244 if (Inserted)
245 It->second = llvm::isGuaranteedNotToBePoison(V, AC);
246 return It->second;
247}
248
249/// Builds compress-like mask for shuffles for the given \p PointerOps, ordered
250/// with \p Order.
251/// \return true if the mask represents strided access, false - otherwise.
253 ArrayRef<unsigned> Order, Type *ScalarTy,
254 const DataLayout &DL, ScalarEvolution &SE,
255 SmallVectorImpl<int> &CompressMask,
256 SLPAnalysisCache &Cache) {
257 const unsigned Sz = PointerOps.size();
258 CompressMask.assign(Sz, PoisonMaskElem);
259 // The first element always set.
260 CompressMask[0] = 0;
261 // Check if the mask represents strided access.
262 std::optional<unsigned> Stride = 0;
263 Value *Ptr0 = Order.empty() ? PointerOps.front() : PointerOps[Order.front()];
264 for (unsigned I : seq<unsigned>(1, Sz)) {
265 Value *Ptr = Order.empty() ? PointerOps[I] : PointerOps[Order[I]];
266 std::optional<int64_t> OptPos =
267 Cache.getPointersDiff(ScalarTy, Ptr0, ScalarTy, Ptr, DL, SE);
268 if (!OptPos || OptPos > std::numeric_limits<unsigned>::max())
269 return false;
270 unsigned Pos = static_cast<unsigned>(*OptPos);
271 CompressMask[I] = Pos;
272 if (!Stride)
273 continue;
274 if (*Stride == 0) {
275 *Stride = Pos;
276 continue;
277 }
278 if (Pos != *Stride * I)
279 Stride.reset();
280 }
281 return Stride.has_value();
282}
283
284/// Checks if the \p VL can be transformed to a (masked)load + compress or
285/// (masked) interleaved load.
290 const DominatorTree &DT, const TargetLibraryInfo &TLI,
292 const function_ref<bool(Value *)> AreAllUsersVectorized, bool ReVec,
293 CompressedLoadInfo &Info, SLPAnalysisCache &Cache) {
294 Info.InterleaveFactor = 0;
295 Type *ScalarTy = VL.front()->getType();
296 const size_t Sz = VL.size();
297 auto *VecTy = cast<VectorType>(getWidenedType(ScalarTy, Sz));
298 SmallVector<int> Mask;
299 if (!Order.empty())
300 inversePermutation(Order, Mask);
301 // Check external uses.
302 for (const auto [I, V] : enumerate(VL)) {
303 if (AreAllUsersVectorized(V))
304 continue;
305 InstructionCost ExtractCost =
306 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind,
307 Mask.empty() ? I : Mask[I]);
308 InstructionCost ScalarCost =
309 TTI.getInstructionCost(cast<Instruction>(V), CostKind);
310 if (ExtractCost <= ScalarCost)
311 return false;
312 }
313 Value *Ptr0;
314 Value *PtrN;
315 if (Order.empty()) {
316 Ptr0 = PointerOps.front();
317 PtrN = PointerOps.back();
318 } else {
319 Ptr0 = PointerOps[Order.front()];
320 PtrN = PointerOps[Order.back()];
321 }
322 std::optional<int64_t> Diff =
323 Cache.getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
324 if (!Diff)
325 return false;
326 const size_t MaxRegSize =
328 .getFixedValue();
329 // Check for very large distances between elements.
330 if (*Diff / Sz >= MaxRegSize / 8)
331 return false;
332 Info.LoadVecTy = cast<FixedVectorType>(getWidenedType(ScalarTy, *Diff + 1));
333 auto *LI = cast<LoadInst>(Order.empty() ? VL.front() : VL[Order.front()]);
334 Align CommonAlignment = LI->getAlign();
335 SimplifyQuery SQ(
336 DL, &TLI, &DT, &AC,
337 cast<LoadInst>(Order.empty() ? VL.back() : VL[Order.back()]));
338 Info.IsMasked =
339 !isSafeToLoadUnconditionally(Ptr0, Info.LoadVecTy, CommonAlignment, SQ);
340 if (Info.IsMasked && !TTI.isLegalMaskedLoad(Info.LoadVecTy, CommonAlignment,
341 LI->getPointerAddressSpace()))
342 return false;
343 // TODO: perform the analysis of each scalar load for better
344 // safe-load-unconditionally analysis.
345 bool IsStrided = buildCompressMask(PointerOps, Order, ScalarTy, DL, SE,
346 Info.CompressMask, Cache);
347 assert(Info.CompressMask.size() >= 2 && "At least two elements are required");
348 SmallVector<Value *> OrderedPointerOps(PointerOps);
349 if (!Order.empty())
350 reorderScalars(OrderedPointerOps, Mask);
351 auto [ScalarGEPCost, VectorGEPCost] =
352 getGEPCosts(TTI, OrderedPointerOps, OrderedPointerOps.front(),
353 Instruction::Load, CostKind, ScalarTy, Info.LoadVecTy);
354 // The cost of scalar loads.
355 InstructionCost ScalarLoadsCost =
357 [&](InstructionCost C, Value *V) {
358 return C + TTI.getInstructionCost(cast<Instruction>(V),
359 CostKind);
360 }) +
361 ScalarGEPCost;
362 APInt DemandedElts = APInt::getAllOnes(Sz);
363 InstructionCost GatherCost =
364 getScalarizationOverhead(TTI, ReVec, ScalarTy, VecTy, DemandedElts,
365 /*Insert=*/true,
366 /*Extract=*/false, CostKind) +
367 ScalarLoadsCost;
368 InstructionCost LoadCost = 0;
369 if (Info.IsMasked) {
370 LoadCost = TTI.getMemIntrinsicInstrCost(
371 MemIntrinsicCostAttributes(Intrinsic::masked_load, Info.LoadVecTy,
372 CommonAlignment,
373 LI->getPointerAddressSpace()),
374 CostKind);
375 } else {
376 LoadCost =
377 TTI.getMemoryOpCost(Instruction::Load, Info.LoadVecTy, CommonAlignment,
378 LI->getPointerAddressSpace(), CostKind,
379 TTI::getOperandInfo(LI->getPointerOperand()));
380 }
381 if (IsStrided && !Info.IsMasked && Order.empty()) {
382 // Check for potential segmented(interleaved) loads.
383 VectorType *AlignedLoadVecTy = cast<VectorType>(getWidenedType(
384 ScalarTy,
385 getFullVectorNumberOfElements(TTI, ScalarTy, *Diff + 1, ReVec)));
386 SimplifyQuery SQ(DL, &TLI, &DT, &AC, cast<LoadInst>(VL.back()));
387 if (!isSafeToLoadUnconditionally(Ptr0, AlignedLoadVecTy, CommonAlignment,
388 SQ))
389 AlignedLoadVecTy = Info.LoadVecTy;
390 if (TTI.isLegalInterleavedAccessType(AlignedLoadVecTy, Info.CompressMask[1],
391 CommonAlignment,
392 LI->getPointerAddressSpace())) {
393 InstructionCost InterleavedCost =
394 VectorGEPCost + TTI.getInterleavedMemoryOpCost(
395 Instruction::Load, AlignedLoadVecTy,
396 Info.CompressMask[1], {}, CommonAlignment,
397 LI->getPointerAddressSpace(), CostKind,
398 Info.IsMasked);
399 if (InterleavedCost < GatherCost) {
400 Info.InterleaveFactor = Info.CompressMask[1];
401 Info.LoadVecTy = AlignedLoadVecTy;
402 return true;
403 }
404 }
405 }
406 SmallVector<int> CostMask(Info.CompressMask.begin(), Info.CompressMask.end());
407 if (!Order.empty()) {
408 SmallVector<int> NewMask(Sz, PoisonMaskElem);
409 for (unsigned I : seq<unsigned>(Sz))
410 NewMask[I] = Info.CompressMask[Mask[I]];
411 Info.CompressMask.swap(NewMask);
412 }
413 // Estimating the compression shuffle cost below can be extremely expensive
414 // for a very wide LoadVecTy, which is split into a large number of vector
415 // registers (see processShuffleMasks). The shuffle cost is always
416 // non-negative, so if the load cost alone already reaches the gather cost the
417 // masked-load-compress cannot be profitable. Bail out before the costly
418 // shuffle cost estimation in that case.
419 if (VectorGEPCost + LoadCost >= GatherCost)
420 return false;
421 // For REVEC the scalars are vectors, and the emitted shuffle uses the
422 // compress mask expanded to the individual elements. Cost that mask.
424 InstructionCost CompressCost = getShuffleCost(
425 TTI, TTI::SK_PermuteSingleSrc, Info.LoadVecTy, CostKind, CostMask);
426 InstructionCost TotalVecCost = VectorGEPCost + LoadCost + CompressCost;
427 return TotalVecCost < GatherCost;
428}
429
430/// Checks if the \p VL can be transformed to a (masked)load + compress or
431/// (masked) interleaved load.
436 const DominatorTree &DT, const TargetLibraryInfo &TLI,
438 const function_ref<bool(Value *)> AreAllUsersVectorized, bool ReVec,
439 SLPAnalysisCache &Cache) {
441 return isMaskedLoadCompress(VL, PointerOps, Order, TTI, DL, SE, AC, DT, TLI,
442 CostKind, AreAllUsersVectorized, ReVec, Info,
443 Cache);
444}
445
448 const DominatorTree &DT,
449 const TargetLibraryInfo &TLI) {
450 if (count_if(VL, IsaPred<LoadInst>) < 2)
451 return false;
452 const auto *FirstIt = find_if(VL, IsaPred<LoadInst>);
453 const unsigned FirstLane = std::distance(VL.begin(), FirstIt);
454 auto *FirstLI = cast<LoadInst>(*FirstIt);
455 // The wide load may read the memory with a different tag.
456 if (FirstLI->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag))
457 return false;
458 Type *ScalarTy = FirstLI->getType();
459 Value *Ptr0 = FirstLI->getPointerOperand();
460 LoadInst *LastLI = FirstLI;
461 for (auto [Lane, V] : enumerate(VL)) {
462 if (isa<UndefValue>(V))
463 continue;
464 auto *LI = dyn_cast<LoadInst>(V);
465 if (!LI || !LI->isSimple() || mustSuppressSpeculation(*LI))
466 return false;
467 std::optional<int64_t> Dist =
468 getPointersDiff(ScalarTy, Ptr0, ScalarTy, LI->getPointerOperand(), DL,
469 SE, /*StrictCheck=*/true);
470 if (!Dist || *Dist != static_cast<int64_t>(Lane) - FirstLane)
471 return false;
472 if (LastLI->comesBefore(LI))
473 LastLI = LI;
474 }
475 // The wide load starts before the first load, so check the range as the one
476 // starting at the underlying object.
477 const uint64_t EltSize = DL.getTypeAllocSize(ScalarTy).getFixedValue();
478 const unsigned BitWidth = DL.getIndexTypeSizeInBits(Ptr0->getType());
481 DL, Offset, /*AllowNonInbounds=*/true);
482 bool Overflow = false;
483 APInt Start = Offset.ssub_ov(APInt(BitWidth, FirstLane * EltSize), Overflow);
484 if (Overflow || Start.isNegative())
485 return false;
486 APInt End = Start.sadd_ov(APInt(BitWidth, VL.size() * EltSize), Overflow);
487 return !Overflow &&
489 Base, Align(1), End, SimplifyQuery(DL, &TLI, &DT, &AC, LastLI));
490}
491
493 const auto *It = find_if(Scalars, IsaPred<LoadInst>);
494 auto *LI = cast<LoadInst>(*It);
495 return std::distance(Scalars.begin(), It) *
496 LI->getDataLayout().getTypeAllocSize(LI->getType()).getFixedValue();
497}
498
499/// Checks if the stores \p VL with pointers \p PointerOps can be lowered as a
500/// single masked store. On success \p StoreVecTy is the widened store type and
501/// \p ReuseShuffleIndices is the expand mask that places each stored value at
502/// its element offset from the base (poison in the gaps).
504 ArrayRef<unsigned> Order,
505 const TargetTransformInfo &TTI, const DataLayout &DL,
506 ScalarEvolution &SE, Align CommonAlignment,
507 SmallVectorImpl<int> &ReuseShuffleIndices,
508 FixedVectorType *&StoreVecTy,
509 SLPAnalysisCache &Cache) {
510 Type *ScalarTy = cast<StoreInst>(VL.front())->getValueOperand()->getType();
511 const size_t Sz = VL.size();
512 // Only simple scalar element types are supported.
513 if (Sz < 2 || (!ScalarTy->isIntOrPtrTy() && !ScalarTy->isFloatingPointTy()))
514 return false;
515 Value *Ptr0 = Order.empty() ? PointerOps.front() : PointerOps[Order.front()];
516 Value *PtrN = Order.empty() ? PointerOps.back() : PointerOps[Order.back()];
517 std::optional<int64_t> Diff =
518 Cache.getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
519 if (!Diff || *Diff <= 0)
520 return false;
521 // Avoid widened vectors with very large gaps between the stored elements.
522 const unsigned MaxRegSize =
524 .getFixedValue();
525 const unsigned ScalarBits = DL.getTypeSizeInBits(ScalarTy).getFixedValue();
526 if (ScalarBits == 0 ||
527 static_cast<uint64_t>(*Diff) / Sz >= MaxRegSize / ScalarBits)
528 return false;
529 StoreVecTy = cast<FixedVectorType>(getWidenedType(ScalarTy, *Diff + 1));
530 unsigned AS = cast<StoreInst>(VL.front())->getPointerAddressSpace();
531 if (!TTI.isLegalMaskedStore(StoreVecTy, CommonAlignment, AS,
533 return false;
534 // Build the expand mask: store I (in address-sorted order) is placed at its
535 // element offset from the base, other widened lanes are poison.
536 ReuseShuffleIndices.assign(*Diff + 1, PoisonMaskElem);
537 int64_t Prev = -1;
538 for (unsigned I : seq<unsigned>(Sz)) {
539 Value *Ptr = Order.empty() ? PointerOps[I] : PointerOps[Order[I]];
540 std::optional<int64_t> Off =
541 Cache.getPointersDiff(ScalarTy, Ptr0, ScalarTy, Ptr, DL, SE);
542 if (!Off || *Off <= Prev || *Off > *Diff)
543 return false;
544 ReuseShuffleIndices[*Off] = static_cast<int>(I);
545 Prev = *Off;
546 }
547 return true;
548}
549
551 Type *ElemTy, const DataLayout &DL,
552 ScalarEvolution &SE, unsigned MaxDepth,
553 SmallVectorImpl<unsigned> &SortedIndices,
554 SLPAnalysisCache &Cache) {
555 assert(
556 all_of(VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
557 "Expected list of pointer operands.");
558 // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
559 // Ptr into, sort and return the sorted indices with values next to one
560 // another.
562 std::pair<BasicBlock *, Value *>,
564 Bases;
565 Bases
566 .try_emplace(std::make_pair(BBs.front(),
567 getUnderlyingObject(VL.front(), MaxDepth)))
568 .first->second.emplace_back()
569 .emplace_back(VL.front(), 0U, 0U);
570
571 SortedIndices.clear();
572 for (auto [Cnt, Ptr] : enumerate(VL.drop_front())) {
573 auto Key = std::make_pair(BBs[Cnt + 1], getUnderlyingObject(Ptr, MaxDepth));
574 bool Found = any_of(Bases.try_emplace(Key).first->second,
575 [&, &Cnt = Cnt, &Ptr = Ptr](auto &Base) {
576 std::optional<int64_t> Diff = Cache.getPointersDiff(
577 ElemTy, std::get<0>(Base.front()), ElemTy, Ptr,
578 DL, SE, /*StrictCheck=*/true);
579 if (!Diff)
580 return false;
581
582 Base.emplace_back(Ptr, *Diff, Cnt + 1);
583 return true;
584 });
585
586 if (!Found) {
587 // If we haven't found enough to usefully cluster, return early.
588 if (Bases.size() > VL.size() / 2 - 1)
589 return false;
590
591 // Not found already - add a new Base
592 Bases.find(Key)->second.emplace_back().emplace_back(Ptr, 0, Cnt + 1);
593 }
594 }
595
596 if (Bases.size() == VL.size())
597 return false;
598
599 if (Bases.size() == 1 && (Bases.front().second.size() == 1 ||
600 Bases.front().second.size() == VL.size()))
601 return false;
602
603 // For each of the bases sort the pointers by Offset and check if any of the
604 // base become consecutively allocated.
605 auto ComparePointers = [MaxDepth](Value *Ptr1, Value *Ptr2) {
606 SmallPtrSet<Value *, 13> FirstPointers;
607 SmallPtrSet<Value *, 13> SecondPointers;
608 Value *P1 = Ptr1;
609 Value *P2 = Ptr2;
610 unsigned Depth = 0;
611 while (!FirstPointers.contains(P2) && !SecondPointers.contains(P1)) {
612 if (P1 == P2 || Depth > MaxDepth)
613 return false;
614 FirstPointers.insert(P1);
615 SecondPointers.insert(P2);
616 P1 = getUnderlyingObject(P1, /*MaxLookup=*/1);
617 P2 = getUnderlyingObject(P2, /*MaxLookup=*/1);
618 ++Depth;
619 }
620 assert((FirstPointers.contains(P2) || SecondPointers.contains(P1)) &&
621 "Unable to find matching root.");
622 return FirstPointers.contains(P2) && !SecondPointers.contains(P1);
623 };
624 for (auto &Base : Bases) {
625 for (auto &Vec : Base.second) {
626 if (Vec.size() > 1) {
628 int64_t InitialOffset = std::get<1>(Vec[0]);
629 bool AnyConsecutive =
630 all_of(enumerate(Vec), [InitialOffset](const auto &P) {
631 return std::get<1>(P.value()) ==
632 int64_t(P.index()) + InitialOffset;
633 });
634 // Fill SortedIndices array only if it looks worth-while to sort the
635 // ptrs.
636 if (!AnyConsecutive)
637 return false;
638 }
639 }
640 stable_sort(Base.second, [&](const auto &V1, const auto &V2) {
641 return ComparePointers(std::get<0>(V1.front()), std::get<0>(V2.front()));
642 });
643 }
644
645 for (auto &T : Bases)
646 for (const auto &Vec : T.second)
647 for (const auto &P : Vec)
648 SortedIndices.push_back(std::get<2>(P));
649
650 assert(SortedIndices.size() == VL.size() &&
651 "Expected SortedIndices to be the size of VL");
652 return true;
653}
654
655} // namespace llvm::slpvectorizer
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static MaybeAlign getAlign(Value *Ptr)
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
#define T
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This pass exposes codegen information to IR-level passes.
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:194
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
const T & consume_front()
consume_front() - Returns the first element and drops it from ArrayRef.
Definition ArrayRef.h:156
A cache of @llvm.assume calls within a function.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Class to represent fixed width SIMD vectors.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
An instruction for reading from memory.
Information for memory intrinsic cost model.
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI const SCEV * getUDivExactExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void swap(SmallVectorImpl &RHS)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
TargetCostKind
The kind of cost model.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
Base class of all SIMD vector types.
An efficient, type-erasing, non-owning reference to a callable.
Caches the results of the expensive analyses that are queried repeatedly for the same values while th...
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC)
Cached llvm::isGuaranteedNotToBePoison().
bool sortPtrAccesses(ArrayRef< Value * > VL, Type *ElemTy, const DataLayout &DL, ScalarEvolution &SE, SmallVectorImpl< unsigned > &SortedIndices)
llvm::sortPtrAccesses() with the cached pointer distances.
std::optional< int64_t > getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB, Value *PtrB, const DataLayout &DL, ScalarEvolution &SE, bool StrictCheck=false, bool CheckType=true)
Cached llvm::getPointersDiff(), a miss may require SCEV analysis.
A private "module" namespace for types and utilities used by this pass.
bool isMaskedLoadCompress(ArrayRef< Value * > VL, ArrayRef< Value * > PointerOps, ArrayRef< unsigned > Order, const TargetTransformInfo &TTI, const DataLayout &DL, ScalarEvolution &SE, AssumptionCache &AC, const DominatorTree &DT, const TargetLibraryInfo &TLI, const TargetTransformInfo::TargetCostKind CostKind, const function_ref< bool(Value *)> AreAllUsersVectorized, bool ReVec, CompressedLoadInfo &Info, SLPAnalysisCache &Cache)
Checks if the VL can be transformed to a (masked)load + compress or (masked) interleaved load.
InstructionCost getShuffleCost(const TargetTransformInfo &TTI, TTI::ShuffleKind Kind, VectorType *Tp, const TTI::TargetCostKind CostKind, ArrayRef< int > Mask, int Index, VectorType *SubTp, ArrayRef< const Value * > Args, TTI::VectorInstrContext VIC)
Returns the cost of the shuffle instructions with the given Kind, vector type Tp and optional Mask.
template Align computeCommonAlignment< StoreInst >(ArrayRef< Value * >)
std::pair< InstructionCost, InstructionCost > getGEPCosts(const TargetTransformInfo &TTI, ArrayRef< Value * > Ptrs, Value *BasePtr, unsigned Opcode, const TTI::TargetCostKind CostKind, Type *ScalarTy, VectorType *VecTy)
Calculate the scalar and the vector costs from vectorizing set of GEPs.
bool clusterSortPtrAccesses(ArrayRef< Value * > VL, ArrayRef< BasicBlock * > BBs, Type *ElemTy, const DataLayout &DL, ScalarEvolution &SE, unsigned MaxDepth, SmallVectorImpl< unsigned > &SortedIndices, SLPAnalysisCache &Cache)
Clusters VL pointers by (basic block, underlying object) pair and sorts each cluster by offset.
void reorderScalars(SmallVectorImpl< Value * > &Scalars, ArrayRef< int > Mask)
Reorders the list of scalars in accordance with the given Mask.
Definition SLPUtils.cpp:332
Value * createWidenedStridedCast(IRBuilderBase &Builder, Value *V, Type *DstTy, const DataLayout &DL)
Casts V between the widened strided access type and the entry vector type DstTy.
Align computeCommonAlignment(ArrayRef< Value * > VL)
Calculates minimal alignment as a common alignment.
template Align computeCommonAlignment< LoadInst >(ArrayRef< Value * >)
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:118
const SCEV * calculateRtStride(ArrayRef< Value * > PointerOps, Type *ElemTy, const DataLayout &DL, ScalarEvolution &SE, SmallVectorImpl< unsigned > &SortedIndices)
Checks if the provided list of pointers Pointers represents the strided pointers for type ElemTy.
Type * getWidenedType(Type *ScalarTy, unsigned VF)
void transformScalarShuffleIndiciesToVector(unsigned VecTyNumElements, SmallVectorImpl< int > &Mask)
Definition SLPUtils.cpp:512
bool isMaskedStoreCompress(ArrayRef< Value * > VL, ArrayRef< Value * > PointerOps, ArrayRef< unsigned > Order, const TargetTransformInfo &TTI, const DataLayout &DL, ScalarEvolution &SE, Align CommonAlignment, SmallVectorImpl< int > &ReuseShuffleIndices, FixedVectorType *&StoreVecTy, SLPAnalysisCache &Cache)
Checks if the stores VL with pointers PointerOps can be lowered as a single masked store.
void inversePermutation(ArrayRef< unsigned > Indices, SmallVectorImpl< int > &Mask)
Compute the inverse permutation Mask of Indices.
Definition SLPUtils.cpp:323
uint64_t getVectorLoadShift(ArrayRef< Value * > Scalars)
Returns the distance in bytes from the start of the vector load to the first load of Scalars: the lea...
bool canWidenLoadsOverUndefLanes(ArrayRef< Value * > VL, const DataLayout &DL, ScalarEvolution &SE, AssumptionCache &AC, const DominatorTree &DT, const TargetLibraryInfo &TLI)
Checks if the simple loads of VL, mixed with the undef and poison lanes, can be replaced by a single ...
InstructionCost getScalarizationOverhead(const TargetTransformInfo &TTI, bool ReVec, Type *ScalarTy, VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, const TTI::TargetCostKind CostKind, bool ForPoisonSrc, ArrayRef< Value * > VL, TTI::VectorInstrContext VIC)
This is similar to TargetTransformInfo::getScalarizationOverhead, but if ScalarTy is a FixedVectorTyp...
InstructionsState getSameOpcode(ArrayRef< Value * > VL, const TargetLibraryInfo &TLI)
static bool buildCompressMask(ArrayRef< Value * > PointerOps, ArrayRef< unsigned > Order, Type *ScalarTy, const DataLayout &DL, ScalarEvolution &SE, SmallVectorImpl< int > &CompressMask, SLPAnalysisCache &Cache)
Builds compress-like mask for shuffles for the given PointerOps, ordered with Order.
bool arePointersCompatible(Value *Ptr1, Value *Ptr2, const TargetLibraryInfo &TLI, unsigned MaxDepth, bool CompareOpcodes)
MaxDepth is the recursion limit for getUnderlyingObject.
bool isConstant(Value *V)
Definition SLPUtils.cpp:48
unsigned getFullVectorNumberOfElements(const TargetTransformInfo &TTI, Type *Ty, unsigned Sz, bool ReVec)
Returns the number of elements of the given type Ty, not less than Sz, which forms type,...
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto accumulate(R &&Range, E &&Init)
Wrapper for std::accumulate.
Definition STLExtras.h:1718
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:452
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
@ Off
Use window algorithm after SMS algorithm fails.
LLVM_ABI std::optional< int64_t > getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB, Value *PtrB, const DataLayout &DL, ScalarEvolution &SE, bool StrictCheck=false, bool CheckType=true)
Returns the distance between the pointers PtrA and PtrB iff they are compatible and it is possible to...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
constexpr int PoisonMaskElem
TargetTransformInfo TTI
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ, bool IgnoreFree=false)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:456
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:246
constexpr unsigned BitWidth
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1455
Function object to check whether the second component of a container supported by std::get (like std:...
Definition STLExtras.h:1464
Describe a single compressed load for costing and generating the vector instruction.