LLVM 24.0.0git
LoopAccessAnalysis.h
Go to the documentation of this file.
1//===- llvm/Analysis/LoopAccessAnalysis.h -----------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interface for the loop memory dependence framework that
10// was originally developed for the Loop Vectorizer.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
15#define LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
16
22#include <optional>
23#include <variant>
24
25namespace llvm {
26
27class AAResults;
28class DataLayout;
29class Loop;
30class raw_ostream;
32
33/// Collection of parameters shared beetween the Loop Vectorizer and the
34/// Loop Access Analysis.
36 /// Maximum SIMD width.
37 LLVM_ABI static const unsigned MaxVectorWidth;
38
39 /// VF as overridden by the user.
41 /// Interleave factor as overridden by the user.
43 /// True if force-vector-interleave was specified by the user.
44 LLVM_ABI static bool isInterleaveForced();
45
46 /// \When performing memory disambiguation checks at runtime do not
47 /// make more than this number of comparisons.
49
50 // When creating runtime checks for nested loops, where possible try to
51 // write the checks in a form that allows them to be easily hoisted out of
52 // the outermost loop. For example, we can do this by expanding the range of
53 // addresses considered to include the entire nested loop so that they are
54 // loop invariant.
56};
57
58/// Maps a pointer to its symbolic (non-constant) stride. Strides are loop
59/// invariant, which collectStridedAccess checks before inserting.
61
62/// Checks memory dependences among accesses to the same underlying
63/// object to determine whether there vectorization is legal or not (and at
64/// which vectorization factor).
65///
66/// Note: This class will compute a conservative dependence for access to
67/// different underlying pointers. Clients, such as the loop vectorizer, will
68/// sometimes deal these potential dependencies by emitting runtime checks.
69///
70/// We use the ScalarEvolution framework to symbolically evalutate access
71/// functions pairs. Since we currently don't restructure the loop we can rely
72/// on the program order of memory accesses to determine their safety.
73/// At the moment we will only deem accesses as safe for:
74/// * A negative constant distance assuming program order.
75///
76/// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
77/// a[i] = tmp; y = a[i];
78///
79/// The latter case is safe because later checks guarantuee that there can't
80/// be a cycle through a phi node (that is, we check that "x" and "y" is not
81/// the same variable: a header phi can only be an induction or a reduction, a
82/// reduction can't have a memory sink, an induction can't have a memory
83/// source). This is important and must not be violated (or we have to
84/// resort to checking for cycles through memory).
85///
86/// * A positive constant distance assuming program order that is bigger
87/// than the biggest memory access.
88///
89/// tmp = a[i] OR b[i] = x
90/// a[i+2] = tmp y = b[i+2];
91///
92/// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
93///
94/// * Zero distances and all accesses have the same size.
95///
97public:
99 PointerIntPair<Value * /* AccessPtr */, 1, bool /* IsWrite */>;
100 /// Set of potential dependent memory accesses.
102
103 /// Type to keep track of the status of the dependence check. The order of
104 /// the elements is important and has to be from most permissive to least
105 /// permissive.
107 // Can vectorize safely without RT checks. All dependences are known to be
108 // safe.
110 // Can possibly vectorize with RT checks to overcome unknown dependencies.
112 // Cannot vectorize due to known unsafe dependencies.
114 };
115
116 /// Dependece between memory access instructions.
117 struct Dependence {
118 /// The type of the dependence.
119 enum DepType {
120 // No dependence.
122 // We couldn't determine the direction or the distance.
124 // At least one of the memory access instructions may access a loop
125 // varying object, e.g. the address of underlying object is loaded inside
126 // the loop, like A[B[i]]. We cannot determine direction or distance in
127 // those cases, and also are unable to generate any runtime checks.
129 // Both accesses to the same loop-invariant address and at least one is a
130 // write. Vectorization is unsafe because different vector lanes would
131 // read/write the same memory location, and the ordering of accesses
132 // across lanes matters.
134
135 // Lexically forward.
136 //
137 // FIXME: If we only have loop-independent forward dependences (e.g. a
138 // read and write of A[i]), LAA will locally deem the dependence "safe"
139 // without querying the MemoryDepChecker. Therefore we can miss
140 // enumerating loop-independent forward dependences in
141 // getDependences. Note that as soon as there are different
142 // indices used to access the same array, the MemoryDepChecker *is*
143 // queried and the dependence list is complete.
145 // Forward, but if vectorized, is likely to prevent store-to-load
146 // forwarding.
148 // Lexically backward.
150 // Backward, but the distance allows a vectorization factor of dependent
151 // on MinDepDistBytes.
153 // Same, but may prevent store-to-load forwarding.
155 };
156
157 /// String version of the types.
158 LLVM_ABI static const char *DepName[];
159
160 /// Index of the source of the dependence in the InstMap vector.
161 unsigned Source;
162 /// Index of the destination of the dependence in the InstMap vector.
163 unsigned Destination;
164 /// The type of the dependence.
166
169
170 /// Return the source instruction of the dependence.
171 Instruction *getSource(const MemoryDepChecker &DepChecker) const;
172 /// Return the destination instruction of the dependence.
173 Instruction *getDestination(const MemoryDepChecker &DepChecker) const;
174
175 /// Dependence types that don't prevent vectorization.
178
179 /// Lexically forward dependence.
180 LLVM_ABI bool isForward() const;
181 /// Lexically backward dependence.
182 LLVM_ABI bool isBackward() const;
183
184 /// May be a lexically backward dependence type (includes Unknown).
185 LLVM_ABI bool isPossiblyBackward() const;
186
187 /// Print the dependence. \p Instr is used to map the instruction
188 /// indices to instructions.
189 LLVM_ABI void print(raw_ostream &OS, unsigned Depth,
190 const SmallVectorImpl<Instruction *> &Instrs) const;
191 };
192
194 DominatorTree *DT, const Loop *L,
195 const SymbolicStrideMap &SymbolicStrides,
196 unsigned MaxTargetVectorWidthInBits,
197 std::optional<ScalarEvolution::LoopGuards> &LoopGuards)
198 : PSE(PSE), AC(AC), DT(DT), InnermostLoop(L),
199 SymbolicStrides(SymbolicStrides),
200 MaxTargetVectorWidthInBits(MaxTargetVectorWidthInBits),
201 LoopGuards(LoopGuards) {}
202
203 /// Register the location (instructions are given increasing numbers)
204 /// of a write access.
206
207 /// Register the location (instructions are given increasing numbers)
208 /// of a write access.
209 LLVM_ABI void addAccess(LoadInst *LI);
210
211 /// Check whether the dependencies between the accesses are safe, and records
212 /// the dependence information in Dependences if so.
213 ///
214 /// Only checks sets with elements in \p CheckDeps.
215 LLVM_ABI bool areDepsSafe(const DepCandidates &AccessSets,
216 ArrayRef<MemAccessInfo> CheckDeps);
217
218 /// No memory dependence was encountered that would inhibit
219 /// vectorization.
221 return Status == VectorizationSafetyStatus::Safe;
222 }
223
224 /// Return true if the number of elements that are safe to operate on
225 /// simultaneously is not bounded.
227 return MaxSafeVectorWidthInBits == UINT_MAX;
228 }
229
230 /// Return the number of elements that are safe to operate on
231 /// simultaneously, multiplied by the size of the element in bits.
233 return MaxSafeVectorWidthInBits;
234 }
235
236 /// Return true if there are no store-load forwarding dependencies.
238 return MaxStoreLoadForwardSafeDistanceInBits ==
239 std::numeric_limits<uint64_t>::max();
240 }
241
242 /// Returns true if a memory dependence at byte distance \p Distance between
243 /// a store (with element size \p TypeByteSize bytes) widened to
244 /// \p VectorStoreSize bytes and a subsequent load of \p LoadElementSize bytes
245 /// would prevent store-to-load forwarding.
246 ///
247 /// The conflicting store must still be likely to be in the store buffer, i.e.
248 /// \c Distance / VectorStoreSize is below 8 * TypeByteSize iterations. Given
249 /// that, the load overruns from the widened store it starts in into the next
250 /// one when either:
251 /// (a) it starts misaligned, \c R = \c Distance % VectorStoreSize bytes
252 /// below a widened-store boundary, and is wider than those \c R bytes
253 /// (\p LoadElementSize > \c R), or
254 /// (b) it starts aligned (\c R == 0) but is itself wider than the widened
255 /// store window (\p LoadElementSize > \p VectorStoreSize).
256 /// A \p LoadElementSize of 0 (the default) leaves the load width unknown and
257 /// disables both terms. Passing \p VectorStoreSize makes (a) reduce to "any
258 /// misalignment conflicts" and (b) never fire, matching the original,
259 /// width-agnostic predicate.
261 uint64_t VectorStoreSize,
262 uint64_t TypeByteSize,
263 uint64_t LoadElementSize = 0) {
264 assert(VectorStoreSize != 0 && "Expected non-zero vector store size");
265 const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
266 if (Distance / VectorStoreSize >= NumItersForStoreLoadThroughMemory)
267 return false;
268 if (uint64_t R = Distance % VectorStoreSize)
269 return LoadElementSize > R;
270 return LoadElementSize > VectorStoreSize;
271 }
272
273 /// Return safe power-of-2 number of elements, which do not prevent store-load
274 /// forwarding, multiplied by the size of the elements in bits.
277 "Expected the distance, that prevent store-load forwarding, to be "
278 "set.");
279 return MaxStoreLoadForwardSafeDistanceInBits;
280 }
281
282 /// In same cases when the dependency check fails we can still
283 /// vectorize the loop with a dynamic array access check.
285 return ShouldRetryWithRuntimeChecks &&
287 }
288
289 /// Returns the memory dependences. If null is returned we exceeded
290 /// the MaxDependences threshold and this information is not
291 /// available.
293 return RecordDependences ? &Dependences : nullptr;
294 }
295
296 void clearDependences() { Dependences.clear(); }
297
298 /// The vector of memory access instructions. The indices are used as
299 /// instruction identifiers in the Dependence class.
301 return InstMap;
302 }
303
304 /// Generate a mapping between the memory instructions and their
305 /// indices according to program order.
308
309 for (unsigned I = 0; I < InstMap.size(); ++I)
310 OrderMap[InstMap[I]] = I;
311
312 return OrderMap;
313 }
314
315 /// Find the set of instructions that read or write via \p Ptr.
317 getInstructionsForAccess(Value *Ptr, bool isWrite) const;
318
319 /// Return the program order indices for the access location (Ptr, IsWrite).
320 /// Returns an empty ArrayRef if there are no accesses for the location.
321 ArrayRef<unsigned> getOrderForAccess(Value *Ptr, bool IsWrite) const {
322 auto I = Accesses.find({Ptr, IsWrite});
323 if (I != Accesses.end())
324 return I->second;
325 return {};
326 }
327
328 const Loop *getInnermostLoop() const { return InnermostLoop; }
329
331 std::pair<const SCEV *, const SCEV *>> &
333 return PointerBounds;
334 }
335
337 assert(DT && "requested DT, but it is not available");
338 return DT;
339 }
341 assert(AC && "requested AC, but it is not available");
342 return AC;
343 }
344
345private:
346 /// A wrapper around ScalarEvolution, used to add runtime SCEV checks, and
347 /// applies dynamic knowledge to simplify SCEV expressions and convert them
348 /// to a more usable form. We need this in case assumptions about SCEV
349 /// expressions need to be made in order to avoid unknown dependences. For
350 /// example we might assume a unit stride for a pointer in order to prove
351 /// that a memory access is strided and doesn't wrap.
353
354 AssumptionCache *AC;
355 DominatorTree *DT;
356
357 const Loop *InnermostLoop;
358
359 /// Reference to map of pointer values to
360 /// their stride symbols, if they have a symbolic stride.
361 const SymbolicStrideMap &SymbolicStrides;
362
363 /// Maps access locations (ptr, read/write) to program order.
365
366 /// Memory access instructions in program order.
368
369 /// The program order index to be used for the next instruction.
370 unsigned AccessIdx = 0;
371
372 /// The smallest dependence distance in bytes in the loop. This may not be
373 /// the same as the maximum number of bytes that are safe to operate on
374 /// simultaneously.
375 uint64_t MinDepDistBytes = 0;
376
377 /// Number of elements (from consecutive iterations) that are safe to
378 /// operate on simultaneously, multiplied by the size of the element in bits.
379 /// The size of the element is taken from the memory access that is most
380 /// restrictive.
381 uint64_t MaxSafeVectorWidthInBits = -1U;
382
383 /// Maximum power-of-2 number of elements, which do not prevent store-load
384 /// forwarding, multiplied by the size of the elements in bits.
385 uint64_t MaxStoreLoadForwardSafeDistanceInBits =
386 std::numeric_limits<uint64_t>::max();
387
388 /// Whether we should try to vectorize the loop with runtime checks, if the
389 /// dependencies are not safe.
390 bool ShouldRetryWithRuntimeChecks = false;
391
392 /// Result of the dependence checks, indicating whether the checked
393 /// dependences are safe for vectorization, require RT checks or are known to
394 /// be unsafe.
395 VectorizationSafetyStatus Status = VectorizationSafetyStatus::Safe;
396
397 //// True if Dependences reflects the dependences in the
398 //// loop. If false we exceeded MaxDependences and
399 //// Dependences is invalid.
400 bool RecordDependences = true;
401
402 /// Memory dependences collected during the analysis. Only valid if
403 /// RecordDependences is true.
404 SmallVector<Dependence, 8> Dependences;
405
406 /// The maximum width of a target's vector registers multiplied by 2 to also
407 /// roughly account for additional interleaving. Is used to decide if a
408 /// backwards dependence with non-constant stride should be classified as
409 /// backwards-vectorizable or unknown (triggering a runtime check).
410 unsigned MaxTargetVectorWidthInBits = 0;
411
412 /// Mapping of SCEV expressions to their expanded pointer bounds (pair of
413 /// start and end pointer expressions).
415 std::pair<const SCEV *, const SCEV *>>
417
418 /// Cache for the loop guards of InnermostLoop.
419 std::optional<ScalarEvolution::LoopGuards> &LoopGuards;
420
421 /// Check whether there is a plausible dependence between the two
422 /// accesses.
423 ///
424 /// Access \p A must happen before \p B in program order. The two indices
425 /// identify the index into the program order map.
426 ///
427 /// This function checks whether there is a plausible dependence (or the
428 /// absence of such can't be proved) between the two accesses. If there is a
429 /// plausible dependence but the dependence distance is bigger than one
430 /// element access it records this distance in \p MinDepDistBytes (if this
431 /// distance is smaller than any other distance encountered so far).
432 /// Otherwise, this function returns true signaling a possible dependence.
433 Dependence::DepType isDependent(const MemAccessInfo &A, unsigned AIdx,
434 const MemAccessInfo &B, unsigned BIdx);
435
436 /// Check whether the data dependence could prevent store-load
437 /// forwarding.
438 ///
439 /// \return false if we shouldn't vectorize at all or avoid larger
440 /// vectorization factors by limiting MinDepDistBytes.
441 bool couldPreventStoreLoadForward(uint64_t Distance, uint64_t TypeByteSize,
442 unsigned CommonStride = 0);
443
444 /// Updates the current safety status with \p S. We can go from Safe to
445 /// either PossiblySafeWithRtChecks or Unsafe and from
446 /// PossiblySafeWithRtChecks to Unsafe.
447 void mergeInStatus(VectorizationSafetyStatus S);
448
449 struct DepDistanceStrideAndSizeInfo {
450 const SCEV *Dist;
451
452 /// Strides here are scaled; i.e. in bytes, taking the size of the
453 /// underlying type into account.
454 uint64_t MaxStride;
455 std::optional<uint64_t> CommonStride;
456
457 /// TypeByteSize is either the common store size of both accesses, or 0 when
458 /// store sizes mismatch.
459 uint64_t TypeByteSize;
460
461 bool AIsWrite;
462 bool BIsWrite;
463
464 DepDistanceStrideAndSizeInfo(const SCEV *Dist, uint64_t MaxStride,
465 std::optional<uint64_t> CommonStride,
466 uint64_t TypeByteSize, bool AIsWrite,
467 bool BIsWrite)
468 : Dist(Dist), MaxStride(MaxStride), CommonStride(CommonStride),
469 TypeByteSize(TypeByteSize), AIsWrite(AIsWrite), BIsWrite(BIsWrite) {}
470 };
471
472 /// Get the dependence distance, strides, type size and whether it is a write
473 /// for the dependence between A and B. Returns a DepType, if we can prove
474 /// there's no dependence or the analysis fails. Outlined to lambda to limit
475 /// he scope of various temporary variables, like A/BPtr, StrideA/BPtr and
476 /// others. Returns either the dependence result, if it could already be
477 /// determined, or a DepDistanceStrideAndSizeInfo struct, noting that
478 /// TypeByteSize could be 0 when store sizes mismatch, and this should be
479 /// checked in the caller.
480 std::variant<Dependence::DepType, DepDistanceStrideAndSizeInfo>
481 getDependenceDistanceStrideAndSize(const MemAccessInfo &A, Instruction *AInst,
482 const MemAccessInfo &B,
483 Instruction *BInst);
484
485 // Return true if we can prove that \p Sink only accesses memory after \p
486 // Src's end or vice versa.
487 bool areAccessesCompletelyBeforeOrAfter(const SCEV *Src, Type *SrcTy,
488 const SCEV *Sink, Type *SinkTy);
489};
490
492/// A grouping of pointers. A single memcheck is required between
493/// two groups.
495 /// Create a new pointer checking group containing a single
496 /// pointer, with index \p Index in RtCheck.
497 LLVM_ABI RuntimeCheckingPtrGroup(unsigned Index,
498 const RuntimePointerChecking &RtCheck);
499
500 /// Tries to add the pointer recorded in RtCheck at index
501 /// \p Index to this pointer checking group. We can only add a pointer
502 /// to a checking group if we will still be able to get
503 /// the upper and lower bounds of the check. Returns true in case
504 /// of success, false otherwise.
505 LLVM_ABI bool addPointer(unsigned Index,
506 const RuntimePointerChecking &RtCheck);
507 LLVM_ABI bool addPointer(unsigned Index, const SCEV *Start, const SCEV *End,
508 unsigned AS, bool NeedsFreeze, ScalarEvolution &SE);
509
510 /// The SCEV expression which represents the upper bound of all the
511 /// pointers in this group.
512 const SCEV *High;
513 /// The SCEV expression which represents the lower bound of all the
514 /// pointers in this group.
515 const SCEV *Low;
516 /// Indices of all the pointers that constitute this grouping.
518 /// Address space of the involved pointers.
519 unsigned AddressSpace;
520 /// Whether the pointer needs to be frozen after expansion, e.g. because it
521 /// may be poison outside the loop.
522 bool NeedsFreeze = false;
523};
524
525/// A memcheck which made up of a pair of grouped pointers.
527 std::pair<const RuntimeCheckingPtrGroup *, const RuntimeCheckingPtrGroup *>;
528
540
541/// Holds information about the memory runtime legality checks to verify
542/// that a group of pointers do not overlap.
545
546public:
547 struct PointerInfo {
548 /// Holds the pointer value that we need to check.
550 /// Holds the smallest byte address accessed by the pointer throughout all
551 /// iterations of the loop.
552 const SCEV *Start;
553 /// Holds the largest byte address accessed by the pointer throughout all
554 /// iterations of the loop, plus 1.
555 const SCEV *End;
556 /// Holds the information if this pointer is used for writing to memory.
558 /// Holds the id of the set of pointers that could be dependent because of a
559 /// shared underlying object.
561 /// Holds the id of the disjoint alias set to which this pointer belongs.
562 unsigned AliasSetId;
563 /// SCEV for the access.
564 const SCEV *Expr;
565 /// True if the pointer expressions needs to be frozen after expansion.
567
574 };
575
577 std::optional<ScalarEvolution::LoopGuards> &LoopGuards)
578 : DC(DC), SE(SE), LoopGuards(LoopGuards) {}
579
580 /// Reset the state of the pointer runtime information.
581 void reset() {
582 Need = false;
583 CanUseDiffCheck = true;
584 Pointers.clear();
585 Checks.clear();
586 DiffChecks.clear();
587 CheckingGroups.clear();
588 }
589
590 /// Insert a pointer and calculate the start and end SCEVs.
591 /// We need \p PSE in order to compute the SCEV expression of the pointer
592 /// according to the assumptions that we've made during the analysis.
593 /// The method might also version the pointer stride according to \p Strides,
594 /// and add new predicates to \p PSE. Returns false without inserting anything
595 /// if the bounds of \p PtrExpr cannot be computed.
596 LLVM_ABI bool insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
597 Type *AccessTy, bool WritePtr, unsigned DepSetId,
598 unsigned ASId, PredicatedScalarEvolution &PSE,
599 bool NeedsFreeze);
600
601 /// No run-time memory checking is necessary.
602 bool empty() const { return Pointers.empty(); }
603
604 /// Generate the checks and store it. This also performs the grouping
605 /// of pointers to reduce the number of memchecks necessary.
607
608 /// Returns the checks that generateChecks created. They can be used to ensure
609 /// no read/write accesses overlap across all loop iterations.
611 return Checks;
612 }
613
614 // Returns an optional list of (pointer-difference expressions, access size)
615 // pairs that can be used to prove that there are no vectorization-preventing
616 // dependencies at runtime. There are is a vectorization-preventing dependency
617 // if any pointer-difference is <u VF * InterleaveCount * access size. Returns
618 // std::nullopt if pointer-difference checks cannot be used.
619 std::optional<ArrayRef<PointerDiffInfo>> getDiffChecks() const {
620 if (!CanUseDiffCheck)
621 return std::nullopt;
622 return {DiffChecks};
623 }
624
625 /// Decide if we need to add a check between two groups of pointers,
626 /// according to needsChecking.
628 const RuntimeCheckingPtrGroup &N) const;
629
630 /// Returns the number of run-time checks required according to
631 /// needsChecking.
632 unsigned getNumberOfChecks() const { return Checks.size(); }
633
634 /// Print the list run-time memory checks necessary.
635 LLVM_ABI void print(raw_ostream &OS, unsigned Depth = 0) const;
636
637 /// Print \p Checks.
640 unsigned Depth = 0) const;
641
642 /// This flag indicates if we need to add the runtime check.
643 bool Need = false;
644
645 /// Information about the pointers that may require checking.
647
648 /// Holds a partitioning of pointers into "check groups".
650
651 /// Check if pointers are in the same partition
652 ///
653 /// \p PtrToPartition contains the partition number for pointers (-1 if the
654 /// pointer belongs to multiple partitions).
655 LLVM_ABI static bool
657 unsigned PtrIdx1, unsigned PtrIdx2);
658
659 /// Decide whether we need to issue a run-time check for pointer at
660 /// index \p I and \p J to prove their independence.
661 LLVM_ABI bool needsChecking(unsigned I, unsigned J) const;
662
663 /// Return PointerInfo for pointer at index \p PtrIdx.
664 const PointerInfo &getPointerInfo(unsigned PtrIdx) const {
665 return Pointers[PtrIdx];
666 }
667
668 ScalarEvolution *getSE() const { return SE; }
669
670private:
671 /// Groups pointers such that a single memcheck is required
672 /// between two different groups. This will clear the CheckingGroups vector
673 /// and re-compute it.
674 void groupChecks(MemoryDepChecker::DepCandidates &DepCands);
675
676 /// Generate the checks and return them.
678
679 /// Try to create add a new (pointer-difference, access size) pair to
680 /// DiffCheck for checking groups \p CGI and \p CGJ. If pointer-difference
681 /// checks cannot be used for the groups, set CanUseDiffCheck to false.
682 bool tryToCreateDiffCheck(const RuntimeCheckingPtrGroup &CGI,
683 const RuntimeCheckingPtrGroup &CGJ);
684
686
687 /// Holds a pointer to the ScalarEvolution analysis.
688 ScalarEvolution *SE;
689
690 /// Cache for the loop guards of the loop.
691 std::optional<ScalarEvolution::LoopGuards> &LoopGuards;
692
693 /// Set of run-time checks required to establish independence of
694 /// otherwise may-aliasing pointers in the loop.
696
697 /// Flag indicating if pointer-difference checks can be used
698 bool CanUseDiffCheck = true;
699
700 /// A list of (pointer-difference, access size) pairs that can be used to
701 /// prove that there are no vectorization-preventing dependencies.
703};
704
705/// Drive the analysis of memory accesses in the loop
706///
707/// This class is responsible for analyzing the memory accesses of a loop. It
708/// collects the accesses and then its main helper the AccessAnalysis class
709/// finds and categorizes the dependences in buildDependenceSets.
710///
711/// For memory dependences that can be analyzed at compile time, it determines
712/// whether the dependence is part of cycle inhibiting vectorization. This work
713/// is delegated to the MemoryDepChecker class.
714///
715/// For memory dependences that cannot be determined at compile time, it
716/// generates run-time checks to prove independence. This is done by
717/// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
718/// RuntimePointerCheck class. \p AllowPartial determines whether partial checks
719/// are generated when not all pointers could be analyzed.
720///
721/// If pointers can wrap or can't be expressed as affine AddRec expressions by
722/// ScalarEvolution, we will generate run-time checks by emitting a
723/// SCEVUnionPredicate.
724///
725/// Checks for both memory dependences and the SCEV predicates contained in the
726/// PSE must be emitted in order for the results of this analysis to be valid.
728public:
731 const TargetLibraryInfo *TLI, AAResults *AA,
733 bool AllowPartial = false);
734
735 /// Return true we can analyze the memory accesses in the loop and there are
736 /// no memory dependence cycles. Note that for dependences between loads &
737 /// stores with uniform addresses,
738 /// hasStoreStoreDependenceInvolvingLoopInvariantAddress and
739 /// hasLoadStoreDependenceInvolvingLoopInvariantAddress also need to be
740 /// checked.
741 bool canVectorizeMemory() const { return CanVecMem; }
742
743 /// Return true if there is a convergent operation in the loop. There may
744 /// still be reported runtime pointer checks that would be required, but it is
745 /// not legal to insert them.
746 bool hasConvergentOp() const { return HasConvergentOp; }
747
748 /// Return true if, when runtime pointer checking does not have complete
749 /// results, it instead has partial results for those memory accesses that
750 /// could be analyzed.
751 bool hasAllowPartial() const { return AllowPartial; }
752
754 return PtrRtChecking.get();
755 }
756
757 /// Number of memchecks required to prove independence of otherwise
758 /// may-alias pointers.
759 unsigned getNumRuntimePointerChecks() const {
760 return PtrRtChecking->getNumberOfChecks();
761 }
762
763 /// Return true if the block BB needs to be predicated in order for the loop
764 /// to be vectorized.
765 /// \pre \p TheLoop has a unique latch.
766 LLVM_ABI static bool blockNeedsPredication(const BasicBlock *BB,
767 const Loop *TheLoop,
768 const DominatorTree *DT);
769
770 /// Returns true if value \p V is loop invariant.
771 LLVM_ABI bool isInvariant(Value *V) const;
772
773 unsigned getNumStores() const { return NumStores; }
774 unsigned getNumLoads() const { return NumLoads;}
775
776 /// The diagnostics report generated for the analysis. E.g. why we
777 /// couldn't analyze the loop.
778 const OptimizationRemarkAnalysis *getReport() const { return Report.get(); }
779
780 /// the Memory Dependence Checker which can determine the
781 /// loop-independent and loop-carried dependences between memory accesses.
782 const MemoryDepChecker &getDepChecker() const { return *DepChecker; }
783
784 /// Return the list of instructions that use \p Ptr to read or write
785 /// memory.
787 bool isWrite) const {
788 return DepChecker->getInstructionsForAccess(Ptr, isWrite);
789 }
790
791 /// If an access has a symbolic strides, this maps the pointer value to
792 /// the stride symbol.
794 return SymbolicStrides;
795 }
796
797 /// Print the information about the memory accesses in the loop.
798 LLVM_ABI void print(raw_ostream &OS, unsigned Depth = 0) const;
799
800 /// Return true if the loop has memory dependence involving two stores to an
801 /// invariant address, else return false.
803 return HasStoreStoreDependenceInvolvingLoopInvariantAddress;
804 }
805
806 /// Return true if the loop has memory dependence involving a load and a store
807 /// to an invariant address, else return false.
809 return HasLoadStoreDependenceInvolvingLoopInvariantAddress;
810 }
811
812 /// Return the list of stores to invariant addresses.
814 return StoresToInvariantAddresses;
815 }
816
817 /// Used to add runtime SCEV checks. Simplifies SCEV expressions and converts
818 /// them to a more usable form. All SCEV expressions during the analysis
819 /// should be re-written (and therefore simplified) according to PSE.
820 /// A user of LoopAccessAnalysis will need to emit the runtime checks
821 /// associated with this predicate.
822 const PredicatedScalarEvolution &getPSE() const { return *PSE; }
823
824private:
825 /// Analyze the loop. Returns true if all memory access in the loop can be
826 /// vectorized.
827 bool analyzeLoop(AAResults *AA, const LoopInfo *LI,
828 const TargetLibraryInfo *TLI, DominatorTree *DT);
829
830 /// Check if the structure of the loop allows it to be analyzed by this
831 /// pass.
832 bool canAnalyzeLoop();
833
834 /// Save the analysis remark.
835 ///
836 /// LAA does not directly emits the remarks. Instead it stores it which the
837 /// client can retrieve and presents as its own analysis
838 /// (e.g. -Rpass-analysis=loop-vectorize).
840 recordAnalysis(StringRef RemarkName, const Instruction *Instr = nullptr);
841
842 /// Collect memory access with loop invariant strides.
843 ///
844 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
845 /// invariant.
846 void collectStridedAccess(Value *LoadOrStoreInst);
847
848 // Emits the first unsafe memory dependence in a loop.
849 // Emits nothing if there are no unsafe dependences
850 // or if the dependences were not recorded.
851 void emitUnsafeDependenceRemark();
852
853 std::unique_ptr<PredicatedScalarEvolution> PSE;
854
855 /// We need to check that all of the pointers in this list are disjoint
856 /// at runtime. Using std::unique_ptr to make using move ctor simpler.
857 /// If AllowPartial is true then this list may contain only partial
858 /// information when we've failed to analyze all the memory accesses in the
859 /// loop, in which case HasCompletePtrRtChecking will be false.
860 std::unique_ptr<RuntimePointerChecking> PtrRtChecking;
861
862 /// The Memory Dependence Checker which can determine the
863 /// loop-independent and loop-carried dependences between memory accesses.
864 /// This will be empty if we've failed to analyze all the memory access in the
865 /// loop (i.e. CanVecMem is false).
866 std::unique_ptr<MemoryDepChecker> DepChecker;
867
868 Loop *TheLoop;
869
870 /// Cache for the loop guards of TheLoop.
871 std::optional<ScalarEvolution::LoopGuards> LoopGuards;
872
873 /// Determines whether we should generate partial runtime checks when not all
874 /// memory accesses could be analyzed.
875 bool AllowPartial;
876
877 unsigned NumLoads = 0;
878 unsigned NumStores = 0;
879
880 /// Cache the result of analyzeLoop.
881 bool CanVecMem = false;
882 bool HasConvergentOp = false;
883 bool HasCompletePtrRtChecking = false;
884
885 /// Indicator that there are two non vectorizable stores to the same uniform
886 /// address.
887 bool HasStoreStoreDependenceInvolvingLoopInvariantAddress = false;
888 /// Indicator that there is non vectorizable load and store to the same
889 /// uniform address.
890 bool HasLoadStoreDependenceInvolvingLoopInvariantAddress = false;
891
892 /// List of stores to invariant addresses.
893 SmallVector<StoreInst *> StoresToInvariantAddresses;
894
895 /// The diagnostics report generated for the analysis. E.g. why we
896 /// couldn't analyze the loop.
897 std::unique_ptr<OptimizationRemarkAnalysis> Report;
898
899 /// If an access has a symbolic strides, this maps the pointer value to
900 /// the stride symbol.
901 SymbolicStrideMap SymbolicStrides;
902};
903
904/// Return the SCEV corresponding to a pointer with the symbolic stride
905/// replaced with constant one, assuming the SCEV predicate associated with
906/// \p PSE is true.
907///
908/// If necessary this method will version the stride of the pointer according
909/// to \p PtrToStride and therefore add further predicates to \p PSE.
910///
911/// \p PtrToStride provides the mapping between the pointer value and its
912/// stride as collected by LoopVectorizationLegality::collectStridedAccess.
913LLVM_ABI const SCEV *
914replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
915 const SymbolicStrideMap &PtrToStride, Value *Ptr);
916
917/// If \p AR is an affine AddRec for \p Lp with a constant step, return the
918/// step in units of \p AccessTy's allocation size. Returns std::nullopt if the
919/// step is not constant, does not divide the access size, or \p AccessTy is a
920/// scalable vector. \p Ptr is only used for debug output and may be null.
921LLVM_ABI std::optional<int64_t>
922getStrideFromAddRec(const SCEVAddRecExpr *AR, const Loop *Lp, Type *AccessTy,
923 Value *Ptr, PredicatedScalarEvolution &PSE);
924
925/// If the pointer has a constant stride return it in units of the access type
926/// size. If the pointer is loop-invariant, return 0. Otherwise return
927/// std::nullopt.
928///
929/// Ensure that it does not wrap in the address space, assuming the predicate
930/// associated with \p PSE is true.
931///
932/// If necessary this method will version the stride of the pointer according
933/// to \p PtrToStride and therefore add further predicates to \p PSE.
934///
935/// If \p Predicates is non-null, add no-wrap SCEV predicates if needed.
936///
937/// Note that the analysis results are defined if-and-only-if the original
938/// memory access was defined. If that access was dead, or UB, then the
939/// result of this function is undefined.
940LLVM_ABI std::optional<int64_t>
941getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr,
942 const Loop *Lp, const DominatorTree &DT,
943 const SymbolicStrideMap &StridesMap = SymbolicStrideMap(),
944 bool ShouldCheckWrap = true,
945 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr);
946
947/// Overload of \ref getPtrStride that adds the no-wrap predicates directly to
948/// \p PSE. The \p Assume parameter indicates whether such additional run-time
949/// assumptions are allowed.
950LLVM_ABI std::optional<int64_t>
951getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr,
952 const Loop *Lp, const DominatorTree &DT,
953 const SymbolicStrideMap &StridesMap, bool Assume,
954 bool ShouldCheckWrap = true);
955
956/// Returns the distance between the pointers \p PtrA and \p PtrB iff they are
957/// compatible and it is possible to calculate the distance between them. This
958/// is a simple API that does not depend on the analysis pass.
959/// \param StrictCheck Ensure that the calculated distance matches the
960/// type-based one after all the bitcasts removal in the provided pointers.
961LLVM_ABI std::optional<int64_t>
962getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB, Value *PtrB,
963 const DataLayout &DL, ScalarEvolution &SE,
964 bool StrictCheck = false, bool CheckType = true);
965
966/// Attempt to sort the pointers in \p VL and return the sorted indices
967/// in \p SortedIndices, if reordering is required.
968///
969/// Returns 'true' if sorting is legal, otherwise returns 'false'.
970///
971/// For example, for a given \p VL of memory accesses in program order, a[i+4],
972/// a[i+0], a[i+1] and a[i+7], this function will sort the \p VL and save the
973/// sorted indices in \p SortedIndices as a[i+0], a[i+1], a[i+4], a[i+7] and
974/// saves the mask for actual memory accesses in program order in
975/// \p SortedIndices as <1,2,0,3>
976LLVM_ABI bool sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
977 const DataLayout &DL, ScalarEvolution &SE,
978 SmallVectorImpl<unsigned> &SortedIndices);
979
980/// Returns true if the memory operations \p A and \p B are consecutive.
981/// This is a simple API that does not depend on the analysis pass.
982LLVM_ABI bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
983 ScalarEvolution &SE, bool CheckType = true);
984
985/// Calculate Start and End points of memory access using exact backedge taken
986/// count \p BTC if computable or maximum backedge taken count \p MaxBTC
987/// otherwise.
988///
989/// Let's assume A is the first access and B is a memory access on N-th loop
990/// iteration. Then B is calculated as:
991/// B = A + Step*N .
992/// Step value may be positive or negative.
993/// N is a calculated back-edge taken count:
994/// N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
995/// Start and End points are calculated in the following way:
996/// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
997/// where SizeOfElt is the size of single memory access in bytes.
998///
999/// There is no conflict when the intervals are disjoint:
1000/// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
1001LLVM_ABI std::pair<const SCEV *, const SCEV *> getStartAndEndForAccess(
1002 const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *BTC,
1003 const SCEV *MaxBTC, ScalarEvolution *SE,
1004 DenseMap<std::pair<const SCEV *, const SCEV *>,
1005 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
1006 DominatorTree *DT, AssumptionCache *AC,
1007 std::optional<ScalarEvolution::LoopGuards> &LoopGuards);
1008LLVM_ABI std::pair<const SCEV *, const SCEV *> getStartAndEndForAccess(
1009 const Loop *Lp, const SCEV *PtrExpr, const SCEV *EltSizeSCEV,
1010 const SCEV *BTC, const SCEV *MaxBTC, ScalarEvolution *SE,
1011 DenseMap<std::pair<const SCEV *, const SCEV *>,
1012 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
1013 DominatorTree *DT, AssumptionCache *AC,
1014 std::optional<ScalarEvolution::LoopGuards> &LoopGuards);
1015
1017 /// The cache.
1019
1020 // The used analysis passes.
1021 ScalarEvolution &SE;
1022 AAResults &AA;
1023 DominatorTree &DT;
1024 LoopInfo &LI;
1026 const TargetLibraryInfo *TLI = nullptr;
1027 AssumptionCache *AC;
1028
1029public:
1031 LoopInfo &LI, TargetTransformInfo *TTI,
1032 const TargetLibraryInfo *TLI, AssumptionCache *AC)
1033 : SE(SE), AA(AA), DT(DT), LI(LI), TTI(TTI), TLI(TLI), AC(AC) {}
1034
1035 LLVM_ABI const LoopAccessInfo &getInfo(Loop &L, bool AllowPartial = false);
1036
1037 LLVM_ABI void clear();
1038
1040 FunctionAnalysisManager::Invalidator &Inv);
1041};
1042
1043/// This analysis provides dependence information for the memory
1044/// accesses of a loop.
1045///
1046/// It runs the analysis for a loop on demand. This can be initiated by
1047/// querying the loop access info via AM.getResult<LoopAccessAnalysis>.
1048/// getResult return a LoopAccessInfo object. See this class for the
1049/// specifics of what information is provided.
1051 : public AnalysisInfoMixin<LoopAccessAnalysis> {
1053 LLVM_ABI static AnalysisKey Key;
1054
1055public:
1057
1059};
1060
1062 const MemoryDepChecker &DepChecker) const {
1063 return DepChecker.getMemoryInstructions()[Source];
1064}
1065
1067 const MemoryDepChecker &DepChecker) const {
1068 return DepChecker.getMemoryInstructions()[Destination];
1069}
1070
1071} // End llvm namespace
1072
1073#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
DXIL Forward Handle Accesses
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckType(MVT::SimpleValueType VT, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This represents a collection of equivalence classes and supports three efficient operations: insert a...
An instruction for reading from memory.
This analysis provides dependence information for the memory accesses of a loop.
LoopAccessInfoManager Result
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LoopAccessInfoManager(ScalarEvolution &SE, AAResults &AA, DominatorTree &DT, LoopInfo &LI, TargetTransformInfo *TTI, const TargetLibraryInfo *TLI, AssumptionCache *AC)
LLVM_ABI const LoopAccessInfo & getInfo(Loop &L, bool AllowPartial=false)
Drive the analysis of memory accesses in the loop.
const MemoryDepChecker & getDepChecker() const
the Memory Dependence Checker which can determine the loop-independent and loop-carried dependences b...
ArrayRef< StoreInst * > getStoresToInvariantAddresses() const
Return the list of stores to invariant addresses.
const OptimizationRemarkAnalysis * getReport() const
The diagnostics report generated for the analysis.
const RuntimePointerChecking * getRuntimePointerChecking() const
bool canVectorizeMemory() const
Return true we can analyze the memory accesses in the loop and there are no memory dependence cycles.
unsigned getNumLoads() const
unsigned getNumRuntimePointerChecks() const
Number of memchecks required to prove independence of otherwise may-alias pointers.
const SymbolicStrideMap & getSymbolicStrides() const
If an access has a symbolic strides, this maps the pointer value to the stride symbol.
LLVM_ABI bool isInvariant(Value *V) const
Returns true if value V is loop invariant.
bool hasLoadStoreDependenceInvolvingLoopInvariantAddress() const
Return true if the loop has memory dependence involving a load and a store to an invariant address,...
LLVM_ABI void print(raw_ostream &OS, unsigned Depth=0) const
Print the information about the memory accesses in the loop.
static LLVM_ABI bool blockNeedsPredication(const BasicBlock *BB, const Loop *TheLoop, const DominatorTree *DT)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
const PredicatedScalarEvolution & getPSE() const
Used to add runtime SCEV checks.
LLVM_ABI LoopAccessInfo(Loop *L, ScalarEvolution *SE, const TargetTransformInfo *TTI, const TargetLibraryInfo *TLI, AAResults *AA, DominatorTree *DT, LoopInfo *LI, AssumptionCache *AC, bool AllowPartial=false)
unsigned getNumStores() const
SmallVector< Instruction *, 4 > getInstructionsForAccess(Value *Ptr, bool isWrite) const
Return the list of instructions that use Ptr to read or write memory.
bool hasAllowPartial() const
Return true if, when runtime pointer checking does not have complete results, it instead has partial ...
bool hasStoreStoreDependenceInvolvingLoopInvariantAddress() const
Return true if the loop has memory dependence involving two stores to an invariant address,...
bool hasConvergentOp() const
Return true if there is a convergent operation in the loop.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Checks memory dependences among accesses to the same underlying object to determine whether there vec...
DominatorTree * getDT() const
ArrayRef< unsigned > getOrderForAccess(Value *Ptr, bool IsWrite) const
Return the program order indices for the access location (Ptr, IsWrite).
bool isSafeForAnyStoreLoadForwardDistances() const
Return true if there are no store-load forwarding dependencies.
LLVM_ABI bool areDepsSafe(const DepCandidates &AccessSets, ArrayRef< MemAccessInfo > CheckDeps)
Check whether the dependencies between the accesses are safe, and records the dependence information ...
bool isSafeForAnyVectorWidth() const
Return true if the number of elements that are safe to operate on simultaneously is not bounded.
static bool isStoreLoadForwardingConflict(uint64_t Distance, uint64_t VectorStoreSize, uint64_t TypeByteSize, uint64_t LoadElementSize=0)
Returns true if a memory dependence at byte distance Distance between a store (with element size Type...
DenseMap< std::pair< const SCEV *, const SCEV * >, std::pair< const SCEV *, const SCEV * > > & getPointerBounds()
PointerIntPair< Value *, 1, bool > MemAccessInfo
const SmallVectorImpl< Instruction * > & getMemoryInstructions() const
The vector of memory access instructions.
EquivalenceClasses< MemAccessInfo > DepCandidates
Set of potential dependent memory accesses.
bool shouldRetryWithRuntimeChecks() const
In same cases when the dependency check fails we can still vectorize the loop with a dynamic array ac...
const Loop * getInnermostLoop() const
uint64_t getMaxSafeVectorWidthInBits() const
Return the number of elements that are safe to operate on simultaneously, multiplied by the size of t...
bool isSafeForVectorization() const
No memory dependence was encountered that would inhibit vectorization.
AssumptionCache * getAC() const
const SmallVectorImpl< Dependence > * getDependences() const
Returns the memory dependences.
LLVM_ABI SmallVector< Instruction *, 4 > getInstructionsForAccess(Value *Ptr, bool isWrite) const
Find the set of instructions that read or write via Ptr.
VectorizationSafetyStatus
Type to keep track of the status of the dependence check.
LLVM_ABI void addAccess(StoreInst *SI)
Register the location (instructions are given increasing numbers) of a write access.
uint64_t getStoreLoadForwardSafeDistanceInBits() const
Return safe power-of-2 number of elements, which do not prevent store-load forwarding,...
DenseMap< Instruction *, unsigned > generateInstructionOrderMap() const
Generate a mapping between the memory instructions and their indices according to program order.
MemoryDepChecker(PredicatedScalarEvolution &PSE, AssumptionCache *AC, DominatorTree *DT, const Loop *L, const SymbolicStrideMap &SymbolicStrides, unsigned MaxTargetVectorWidthInBits, std::optional< ScalarEvolution::LoopGuards > &LoopGuards)
Diagnostic information for optimization analysis remarks.
PointerIntPair - This class implements a pair of a pointer and small integer.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
RuntimePointerChecking(MemoryDepChecker &DC, ScalarEvolution *SE, std::optional< ScalarEvolution::LoopGuards > &LoopGuards)
bool Need
This flag indicates if we need to add the runtime check.
void reset()
Reset the state of the pointer runtime information.
unsigned getNumberOfChecks() const
Returns the number of run-time checks required according to needsChecking.
LLVM_ABI void printChecks(raw_ostream &OS, const SmallVectorImpl< RuntimePointerCheck > &Checks, unsigned Depth=0) const
Print Checks.
LLVM_ABI bool needsChecking(const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const
Decide if we need to add a check between two groups of pointers, according to needsChecking.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth=0) const
Print the list run-time memory checks necessary.
std::optional< ArrayRef< PointerDiffInfo > > getDiffChecks() const
SmallVector< RuntimeCheckingPtrGroup, 2 > CheckingGroups
Holds a partitioning of pointers into "check groups".
static LLVM_ABI bool arePointersInSamePartition(const SmallVectorImpl< int > &PtrToPartition, unsigned PtrIdx1, unsigned PtrIdx2)
Check if pointers are in the same partition.
LLVM_ABI bool insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr, Type *AccessTy, bool WritePtr, unsigned DepSetId, unsigned ASId, PredicatedScalarEvolution &PSE, bool NeedsFreeze)
Insert a pointer and calculate the start and end SCEVs.
LLVM_ABI void generateChecks(MemoryDepChecker::DepCandidates &DepCands)
Generate the checks and store it.
bool empty() const
No run-time memory checking is necessary.
SmallVector< PointerInfo, 2 > Pointers
Information about the pointers that may require checking.
ScalarEvolution * getSE() const
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
const PointerInfo & getPointerInfo(unsigned PtrIdx) const
Return PointerInfo for pointer at index PtrIdx.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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.
Value handle that tracks a Value across RAUW.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Abstract Attribute helper functions.
Definition Attributor.h:165
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI std::pair< const SCEV *, const SCEV * > getStartAndEndForAccess(const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *BTC, const SCEV *MaxBTC, ScalarEvolution *SE, DenseMap< std::pair< const SCEV *, const SCEV * >, std::pair< const SCEV *, const SCEV * > > *PointerBounds, DominatorTree *DT, AssumptionCache *AC, std::optional< ScalarEvolution::LoopGuards > &LoopGuards)
Calculate Start and End points of memory access using exact backedge taken count BTC if computable or...
LLVM_ABI const SCEV * replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, const SymbolicStrideMap &PtrToStride, Value *Ptr)
Return the SCEV corresponding to a pointer with the symbolic stride replaced with constant one,...
std::pair< const RuntimeCheckingPtrGroup *, const RuntimeCheckingPtrGroup * > RuntimePointerCheck
A memcheck which made up of a pair of grouped pointers.
LLVM_ABI std::optional< int64_t > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DominatorTree &DT, const SymbolicStrideMap &StridesMap=SymbolicStrideMap(), bool ShouldCheckWrap=true, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
If the pointer has a constant stride return it in units of the access type size.
DenseMap< Value *, const SCEVUnknown * > SymbolicStrideMap
Maps a pointer to its symbolic (non-constant) stride.
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 bool sortPtrAccesses(ArrayRef< Value * > VL, Type *ElemTy, const DataLayout &DL, ScalarEvolution &SE, SmallVectorImpl< unsigned > &SortedIndices)
Attempt to sort the pointers in VL and return the sorted indices in SortedIndices,...
TargetTransformInfo TTI
LLVM_ABI bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
ArrayRef(const T &OneElt) -> ArrayRef< T >
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI std::optional< int64_t > getStrideFromAddRec(const SCEVAddRecExpr *AR, const Loop *Lp, Type *AccessTy, Value *Ptr, PredicatedScalarEvolution &PSE)
If AR is an affine AddRec for Lp with a constant step, return the step in units of AccessTy's allocat...
#define N
IR Values for the lower and upper bounds of a pointer evolution.
A CRTP mix-in that provides informational APIs needed for analysis passes.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
Instruction * getDestination(const MemoryDepChecker &DepChecker) const
Return the destination instruction of the dependence.
DepType Type
The type of the dependence.
unsigned Destination
Index of the destination of the dependence in the InstMap vector.
Dependence(unsigned Source, unsigned Destination, DepType Type)
LLVM_ABI bool isPossiblyBackward() const
May be a lexically backward dependence type (includes Unknown).
Instruction * getSource(const MemoryDepChecker &DepChecker) const
Return the source instruction of the dependence.
LLVM_ABI bool isForward() const
Lexically forward dependence.
LLVM_ABI bool isBackward() const
Lexically backward dependence.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth, const SmallVectorImpl< Instruction * > &Instrs) const
Print the dependence.
unsigned Source
Index of the source of the dependence in the InstMap vector.
DepType
The type of the dependence.
static LLVM_ABI const char * DepName[]
String version of the types.
PointerDiffInfo(const SCEV *SrcStart, const SCEV *SinkStart, unsigned AccessSize, bool NeedsFreeze)
unsigned AddressSpace
Address space of the involved pointers.
LLVM_ABI bool addPointer(unsigned Index, const RuntimePointerChecking &RtCheck)
Tries to add the pointer recorded in RtCheck at index Index to this pointer checking group.
bool NeedsFreeze
Whether the pointer needs to be frozen after expansion, e.g.
LLVM_ABI RuntimeCheckingPtrGroup(unsigned Index, const RuntimePointerChecking &RtCheck)
Create a new pointer checking group containing a single pointer, with index Index in RtCheck.
const SCEV * High
The SCEV expression which represents the upper bound of all the pointers in this group.
SmallVector< unsigned, 2 > Members
Indices of all the pointers that constitute this grouping.
const SCEV * Low
The SCEV expression which represents the lower bound of all the pointers in this group.
PointerInfo(Value *PointerValue, const SCEV *Start, const SCEV *End, bool IsWritePtr, unsigned DependencySetId, unsigned AliasSetId, const SCEV *Expr, bool NeedsFreeze)
const SCEV * Start
Holds the smallest byte address accessed by the pointer throughout all iterations of the loop.
const SCEV * Expr
SCEV for the access.
bool NeedsFreeze
True if the pointer expressions needs to be frozen after expansion.
bool IsWritePtr
Holds the information if this pointer is used for writing to memory.
unsigned DependencySetId
Holds the id of the set of pointers that could be dependent because of a shared underlying object.
unsigned AliasSetId
Holds the id of the disjoint alias set to which this pointer belongs.
const SCEV * End
Holds the largest byte address accessed by the pointer throughout all iterations of the loop,...
TrackingVH< Value > PointerValue
Holds the pointer value that we need to check.
Collection of parameters shared beetween the Loop Vectorizer and the Loop Access Analysis.
static LLVM_ABI const unsigned MaxVectorWidth
Maximum SIMD width.
static LLVM_ABI unsigned RuntimeMemoryCheckThreshold
\When performing memory disambiguation checks at runtime do not make more than this number of compari...
static LLVM_ABI bool isInterleaveForced()
True if force-vector-interleave was specified by the user.
static LLVM_ABI unsigned VectorizationInterleave
Interleave factor as overridden by the user.
static LLVM_ABI ElementCount VectorizationFactor
VF as overridden by the user.
static LLVM_ABI bool HoistRuntimeChecks