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