LLVM 23.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
21#include <optional>
22#include <variant>
23
24namespace llvm {
25
26class AAResults;
27class DataLayout;
28class Loop;
29class raw_ostream;
31
32/// Collection of parameters shared beetween the Loop Vectorizer and the
33/// Loop Access Analysis.
35 /// Maximum SIMD width.
36 LLVM_ABI static const unsigned MaxVectorWidth;
37
38 /// VF as overridden by the user.
40 /// Interleave factor as overridden by the user.
42 /// True if force-vector-interleave was specified by the user.
43 LLVM_ABI static bool isInterleaveForced();
44
45 /// \When performing memory disambiguation checks at runtime do not
46 /// make more than this number of comparisons.
48
49 // When creating runtime checks for nested loops, where possible try to
50 // write the checks in a form that allows them to be easily hoisted out of
51 // the outermost loop. For example, we can do this by expanding the range of
52 // addresses considered to include the entire nested loop so that they are
53 // loop invariant.
55};
56
57/// Checks memory dependences among accesses to the same underlying
58/// object to determine whether there vectorization is legal or not (and at
59/// which vectorization factor).
60///
61/// Note: This class will compute a conservative dependence for access to
62/// different underlying pointers. Clients, such as the loop vectorizer, will
63/// sometimes deal these potential dependencies by emitting runtime checks.
64///
65/// We use the ScalarEvolution framework to symbolically evalutate access
66/// functions pairs. Since we currently don't restructure the loop we can rely
67/// on the program order of memory accesses to determine their safety.
68/// At the moment we will only deem accesses as safe for:
69/// * A negative constant distance assuming program order.
70///
71/// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
72/// a[i] = tmp; y = a[i];
73///
74/// The latter case is safe because later checks guarantuee that there can't
75/// be a cycle through a phi node (that is, we check that "x" and "y" is not
76/// the same variable: a header phi can only be an induction or a reduction, a
77/// reduction can't have a memory sink, an induction can't have a memory
78/// source). This is important and must not be violated (or we have to
79/// resort to checking for cycles through memory).
80///
81/// * A positive constant distance assuming program order that is bigger
82/// than the biggest memory access.
83///
84/// tmp = a[i] OR b[i] = x
85/// a[i+2] = tmp y = b[i+2];
86///
87/// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
88///
89/// * Zero distances and all accesses have the same size.
90///
92public:
94 PointerIntPair<Value * /* AccessPtr */, 1, bool /* IsWrite */>;
95 /// Set of potential dependent memory accesses.
97
98 /// Type to keep track of the status of the dependence check. The order of
99 /// the elements is important and has to be from most permissive to least
100 /// permissive.
102 // Can vectorize safely without RT checks. All dependences are known to be
103 // safe.
105 // Can possibly vectorize with RT checks to overcome unknown dependencies.
107 // Cannot vectorize due to known unsafe dependencies.
109 };
110
111 /// Dependece between memory access instructions.
112 struct Dependence {
113 /// The type of the dependence.
114 enum DepType {
115 // No dependence.
117 // We couldn't determine the direction or the distance.
119 // At least one of the memory access instructions may access a loop
120 // varying object, e.g. the address of underlying object is loaded inside
121 // the loop, like A[B[i]]. We cannot determine direction or distance in
122 // those cases, and also are unable to generate any runtime checks.
124
125 // Lexically forward.
126 //
127 // FIXME: If we only have loop-independent forward dependences (e.g. a
128 // read and write of A[i]), LAA will locally deem the dependence "safe"
129 // without querying the MemoryDepChecker. Therefore we can miss
130 // enumerating loop-independent forward dependences in
131 // getDependences. Note that as soon as there are different
132 // indices used to access the same array, the MemoryDepChecker *is*
133 // queried and the dependence list is complete.
135 // Forward, but if vectorized, is likely to prevent store-to-load
136 // forwarding.
138 // Lexically backward.
140 // Backward, but the distance allows a vectorization factor of dependent
141 // on MinDepDistBytes.
143 // Same, but may prevent store-to-load forwarding.
145 };
146
147 /// String version of the types.
148 LLVM_ABI static const char *DepName[];
149
150 /// Index of the source of the dependence in the InstMap vector.
151 unsigned Source;
152 /// Index of the destination of the dependence in the InstMap vector.
153 unsigned Destination;
154 /// The type of the dependence.
156
159
160 /// Return the source instruction of the dependence.
161 Instruction *getSource(const MemoryDepChecker &DepChecker) const;
162 /// Return the destination instruction of the dependence.
163 Instruction *getDestination(const MemoryDepChecker &DepChecker) const;
164
165 /// Dependence types that don't prevent vectorization.
168
169 /// Lexically forward dependence.
170 LLVM_ABI bool isForward() const;
171 /// Lexically backward dependence.
172 LLVM_ABI bool isBackward() const;
173
174 /// May be a lexically backward dependence type (includes Unknown).
175 LLVM_ABI bool isPossiblyBackward() const;
176
177 /// Print the dependence. \p Instr is used to map the instruction
178 /// indices to instructions.
179 LLVM_ABI void print(raw_ostream &OS, unsigned Depth,
180 const SmallVectorImpl<Instruction *> &Instrs) const;
181 };
182
184 DominatorTree *DT, const Loop *L,
185 const DenseMap<Value *, const SCEV *> &SymbolicStrides,
186 unsigned MaxTargetVectorWidthInBits,
187 std::optional<ScalarEvolution::LoopGuards> &LoopGuards)
188 : PSE(PSE), AC(AC), DT(DT), InnermostLoop(L),
189 SymbolicStrides(SymbolicStrides),
190 MaxTargetVectorWidthInBits(MaxTargetVectorWidthInBits),
191 LoopGuards(LoopGuards) {}
192
193 /// Register the location (instructions are given increasing numbers)
194 /// of a write access.
196
197 /// Register the location (instructions are given increasing numbers)
198 /// of a write access.
199 LLVM_ABI void addAccess(LoadInst *LI);
200
201 /// Check whether the dependencies between the accesses are safe, and records
202 /// the dependence information in Dependences if so.
203 ///
204 /// Only checks sets with elements in \p CheckDeps.
205 LLVM_ABI bool areDepsSafe(const DepCandidates &AccessSets,
206 ArrayRef<MemAccessInfo> CheckDeps);
207
208 /// No memory dependence was encountered that would inhibit
209 /// vectorization.
211 return Status == VectorizationSafetyStatus::Safe;
212 }
213
214 /// Return true if the number of elements that are safe to operate on
215 /// simultaneously is not bounded.
217 return MaxSafeVectorWidthInBits == UINT_MAX;
218 }
219
220 /// Return the number of elements that are safe to operate on
221 /// simultaneously, multiplied by the size of the element in bits.
223 return MaxSafeVectorWidthInBits;
224 }
225
226 /// Return true if there are no store-load forwarding dependencies.
228 return MaxStoreLoadForwardSafeDistanceInBits ==
229 std::numeric_limits<uint64_t>::max();
230 }
231
232 /// Return safe power-of-2 number of elements, which do not prevent store-load
233 /// forwarding, multiplied by the size of the elements in bits.
236 "Expected the distance, that prevent store-load forwarding, to be "
237 "set.");
238 return MaxStoreLoadForwardSafeDistanceInBits;
239 }
240
241 /// In same cases when the dependency check fails we can still
242 /// vectorize the loop with a dynamic array access check.
244 return ShouldRetryWithRuntimeChecks &&
246 }
247
248 /// Returns the memory dependences. If null is returned we exceeded
249 /// the MaxDependences threshold and this information is not
250 /// available.
252 return RecordDependences ? &Dependences : nullptr;
253 }
254
255 void clearDependences() { Dependences.clear(); }
256
257 /// The vector of memory access instructions. The indices are used as
258 /// instruction identifiers in the Dependence class.
260 return InstMap;
261 }
262
263 /// Generate a mapping between the memory instructions and their
264 /// indices according to program order.
267
268 for (unsigned I = 0; I < InstMap.size(); ++I)
269 OrderMap[InstMap[I]] = I;
270
271 return OrderMap;
272 }
273
274 /// Find the set of instructions that read or write via \p Ptr.
276 getInstructionsForAccess(Value *Ptr, bool isWrite) const;
277
278 /// Return the program order indices for the access location (Ptr, IsWrite).
279 /// Returns an empty ArrayRef if there are no accesses for the location.
280 ArrayRef<unsigned> getOrderForAccess(Value *Ptr, bool IsWrite) const {
281 auto I = Accesses.find({Ptr, IsWrite});
282 if (I != Accesses.end())
283 return I->second;
284 return {};
285 }
286
287 const Loop *getInnermostLoop() const { return InnermostLoop; }
288
290 std::pair<const SCEV *, const SCEV *>> &
292 return PointerBounds;
293 }
294
296 assert(DT && "requested DT, but it is not available");
297 return DT;
298 }
300 assert(AC && "requested AC, but it is not available");
301 return AC;
302 }
303
304private:
305 /// A wrapper around ScalarEvolution, used to add runtime SCEV checks, and
306 /// applies dynamic knowledge to simplify SCEV expressions and convert them
307 /// to a more usable form. We need this in case assumptions about SCEV
308 /// expressions need to be made in order to avoid unknown dependences. For
309 /// example we might assume a unit stride for a pointer in order to prove
310 /// that a memory access is strided and doesn't wrap.
312
313 AssumptionCache *AC;
314 DominatorTree *DT;
315
316 const Loop *InnermostLoop;
317
318 /// Reference to map of pointer values to
319 /// their stride symbols, if they have a symbolic stride.
320 const DenseMap<Value *, const SCEV *> &SymbolicStrides;
321
322 /// Maps access locations (ptr, read/write) to program order.
324
325 /// Memory access instructions in program order.
327
328 /// The program order index to be used for the next instruction.
329 unsigned AccessIdx = 0;
330
331 /// The smallest dependence distance in bytes in the loop. This may not be
332 /// the same as the maximum number of bytes that are safe to operate on
333 /// simultaneously.
334 uint64_t MinDepDistBytes = 0;
335
336 /// Number of elements (from consecutive iterations) that are safe to
337 /// operate on simultaneously, multiplied by the size of the element in bits.
338 /// The size of the element is taken from the memory access that is most
339 /// restrictive.
340 uint64_t MaxSafeVectorWidthInBits = -1U;
341
342 /// Maximum power-of-2 number of elements, which do not prevent store-load
343 /// forwarding, multiplied by the size of the elements in bits.
344 uint64_t MaxStoreLoadForwardSafeDistanceInBits =
345 std::numeric_limits<uint64_t>::max();
346
347 /// Whether we should try to vectorize the loop with runtime checks, if the
348 /// dependencies are not safe.
349 bool ShouldRetryWithRuntimeChecks = false;
350
351 /// Result of the dependence checks, indicating whether the checked
352 /// dependences are safe for vectorization, require RT checks or are known to
353 /// be unsafe.
354 VectorizationSafetyStatus Status = VectorizationSafetyStatus::Safe;
355
356 //// True if Dependences reflects the dependences in the
357 //// loop. If false we exceeded MaxDependences and
358 //// Dependences is invalid.
359 bool RecordDependences = true;
360
361 /// Memory dependences collected during the analysis. Only valid if
362 /// RecordDependences is true.
363 SmallVector<Dependence, 8> Dependences;
364
365 /// The maximum width of a target's vector registers multiplied by 2 to also
366 /// roughly account for additional interleaving. Is used to decide if a
367 /// backwards dependence with non-constant stride should be classified as
368 /// backwards-vectorizable or unknown (triggering a runtime check).
369 unsigned MaxTargetVectorWidthInBits = 0;
370
371 /// Mapping of SCEV expressions to their expanded pointer bounds (pair of
372 /// start and end pointer expressions).
374 std::pair<const SCEV *, const SCEV *>>
376
377 /// Cache for the loop guards of InnermostLoop.
378 std::optional<ScalarEvolution::LoopGuards> &LoopGuards;
379
380 /// Check whether there is a plausible dependence between the two
381 /// accesses.
382 ///
383 /// Access \p A must happen before \p B in program order. The two indices
384 /// identify the index into the program order map.
385 ///
386 /// This function checks whether there is a plausible dependence (or the
387 /// absence of such can't be proved) between the two accesses. If there is a
388 /// plausible dependence but the dependence distance is bigger than one
389 /// element access it records this distance in \p MinDepDistBytes (if this
390 /// distance is smaller than any other distance encountered so far).
391 /// Otherwise, this function returns true signaling a possible dependence.
392 Dependence::DepType isDependent(const MemAccessInfo &A, unsigned AIdx,
393 const MemAccessInfo &B, unsigned BIdx);
394
395 /// Check whether the data dependence could prevent store-load
396 /// forwarding.
397 ///
398 /// \return false if we shouldn't vectorize at all or avoid larger
399 /// vectorization factors by limiting MinDepDistBytes.
400 bool couldPreventStoreLoadForward(uint64_t Distance, uint64_t TypeByteSize,
401 unsigned CommonStride = 0);
402
403 /// Updates the current safety status with \p S. We can go from Safe to
404 /// either PossiblySafeWithRtChecks or Unsafe and from
405 /// PossiblySafeWithRtChecks to Unsafe.
406 void mergeInStatus(VectorizationSafetyStatus S);
407
408 struct DepDistanceStrideAndSizeInfo {
409 const SCEV *Dist;
410
411 /// Strides here are scaled; i.e. in bytes, taking the size of the
412 /// underlying type into account.
413 uint64_t MaxStride;
414 std::optional<uint64_t> CommonStride;
415
416 /// TypeByteSize is either the common store size of both accesses, or 0 when
417 /// store sizes mismatch.
418 uint64_t TypeByteSize;
419
420 bool AIsWrite;
421 bool BIsWrite;
422
423 DepDistanceStrideAndSizeInfo(const SCEV *Dist, uint64_t MaxStride,
424 std::optional<uint64_t> CommonStride,
425 uint64_t TypeByteSize, bool AIsWrite,
426 bool BIsWrite)
427 : Dist(Dist), MaxStride(MaxStride), CommonStride(CommonStride),
428 TypeByteSize(TypeByteSize), AIsWrite(AIsWrite), BIsWrite(BIsWrite) {}
429 };
430
431 /// Get the dependence distance, strides, type size and whether it is a write
432 /// for the dependence between A and B. Returns a DepType, if we can prove
433 /// there's no dependence or the analysis fails. Outlined to lambda to limit
434 /// he scope of various temporary variables, like A/BPtr, StrideA/BPtr and
435 /// others. Returns either the dependence result, if it could already be
436 /// determined, or a DepDistanceStrideAndSizeInfo struct, noting that
437 /// TypeByteSize could be 0 when store sizes mismatch, and this should be
438 /// checked in the caller.
439 std::variant<Dependence::DepType, DepDistanceStrideAndSizeInfo>
440 getDependenceDistanceStrideAndSize(const MemAccessInfo &A, Instruction *AInst,
441 const MemAccessInfo &B,
442 Instruction *BInst);
443
444 // Return true if we can prove that \p Sink only accesses memory after \p
445 // Src's end or vice versa.
446 bool areAccessesCompletelyBeforeOrAfter(const SCEV *Src, Type *SrcTy,
447 const SCEV *Sink, Type *SinkTy);
448};
449
451/// A grouping of pointers. A single memcheck is required between
452/// two groups.
454 /// Create a new pointer checking group containing a single
455 /// pointer, with index \p Index in RtCheck.
456 LLVM_ABI RuntimeCheckingPtrGroup(unsigned Index,
457 const RuntimePointerChecking &RtCheck);
458
459 /// Tries to add the pointer recorded in RtCheck at index
460 /// \p Index to this pointer checking group. We can only add a pointer
461 /// to a checking group if we will still be able to get
462 /// the upper and lower bounds of the check. Returns true in case
463 /// of success, false otherwise.
464 LLVM_ABI bool addPointer(unsigned Index,
465 const RuntimePointerChecking &RtCheck);
466 LLVM_ABI bool addPointer(unsigned Index, const SCEV *Start, const SCEV *End,
467 unsigned AS, bool NeedsFreeze, ScalarEvolution &SE);
468
469 /// The SCEV expression which represents the upper bound of all the
470 /// pointers in this group.
471 const SCEV *High;
472 /// The SCEV expression which represents the lower bound of all the
473 /// pointers in this group.
474 const SCEV *Low;
475 /// Indices of all the pointers that constitute this grouping.
477 /// Address space of the involved pointers.
478 unsigned AddressSpace;
479 /// Whether the pointer needs to be frozen after expansion, e.g. because it
480 /// may be poison outside the loop.
481 bool NeedsFreeze = false;
482};
483
484/// A memcheck which made up of a pair of grouped pointers.
486 std::pair<const RuntimeCheckingPtrGroup *, const RuntimeCheckingPtrGroup *>;
487
499
500/// Holds information about the memory runtime legality checks to verify
501/// that a group of pointers do not overlap.
504
505public:
506 struct PointerInfo {
507 /// Holds the pointer value that we need to check.
509 /// Holds the smallest byte address accessed by the pointer throughout all
510 /// iterations of the loop.
511 const SCEV *Start;
512 /// Holds the largest byte address accessed by the pointer throughout all
513 /// iterations of the loop, plus 1.
514 const SCEV *End;
515 /// Holds the information if this pointer is used for writing to memory.
517 /// Holds the id of the set of pointers that could be dependent because of a
518 /// shared underlying object.
520 /// Holds the id of the disjoint alias set to which this pointer belongs.
521 unsigned AliasSetId;
522 /// SCEV for the access.
523 const SCEV *Expr;
524 /// True if the pointer expressions needs to be frozen after expansion.
526
533 };
534
536 std::optional<ScalarEvolution::LoopGuards> &LoopGuards)
537 : DC(DC), SE(SE), LoopGuards(LoopGuards) {}
538
539 /// Reset the state of the pointer runtime information.
540 void reset() {
541 Need = false;
542 CanUseDiffCheck = true;
543 Pointers.clear();
544 Checks.clear();
545 DiffChecks.clear();
546 CheckingGroups.clear();
547 }
548
549 /// Insert a pointer and calculate the start and end SCEVs.
550 /// We need \p PSE in order to compute the SCEV expression of the pointer
551 /// according to the assumptions that we've made during the analysis.
552 /// The method might also version the pointer stride according to \p Strides,
553 /// and add new predicates to \p PSE.
554 LLVM_ABI void insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
555 Type *AccessTy, bool WritePtr, unsigned DepSetId,
556 unsigned ASId, PredicatedScalarEvolution &PSE,
557 bool NeedsFreeze);
558
559 /// No run-time memory checking is necessary.
560 bool empty() const { return Pointers.empty(); }
561
562 /// Generate the checks and store it. This also performs the grouping
563 /// of pointers to reduce the number of memchecks necessary.
565
566 /// Returns the checks that generateChecks created. They can be used to ensure
567 /// no read/write accesses overlap across all loop iterations.
569 return Checks;
570 }
571
572 // Returns an optional list of (pointer-difference expressions, access size)
573 // pairs that can be used to prove that there are no vectorization-preventing
574 // dependencies at runtime. There are is a vectorization-preventing dependency
575 // if any pointer-difference is <u VF * InterleaveCount * access size. Returns
576 // std::nullopt if pointer-difference checks cannot be used.
577 std::optional<ArrayRef<PointerDiffInfo>> getDiffChecks() const {
578 if (!CanUseDiffCheck)
579 return std::nullopt;
580 return {DiffChecks};
581 }
582
583 /// Decide if we need to add a check between two groups of pointers,
584 /// according to needsChecking.
586 const RuntimeCheckingPtrGroup &N) const;
587
588 /// Returns the number of run-time checks required according to
589 /// needsChecking.
590 unsigned getNumberOfChecks() const { return Checks.size(); }
591
592 /// Print the list run-time memory checks necessary.
593 LLVM_ABI void print(raw_ostream &OS, unsigned Depth = 0) const;
594
595 /// Print \p Checks.
598 unsigned Depth = 0) const;
599
600 /// This flag indicates if we need to add the runtime check.
601 bool Need = false;
602
603 /// Information about the pointers that may require checking.
605
606 /// Holds a partitioning of pointers into "check groups".
608
609 /// Check if pointers are in the same partition
610 ///
611 /// \p PtrToPartition contains the partition number for pointers (-1 if the
612 /// pointer belongs to multiple partitions).
613 LLVM_ABI static bool
615 unsigned PtrIdx1, unsigned PtrIdx2);
616
617 /// Decide whether we need to issue a run-time check for pointer at
618 /// index \p I and \p J to prove their independence.
619 LLVM_ABI bool needsChecking(unsigned I, unsigned J) const;
620
621 /// Return PointerInfo for pointer at index \p PtrIdx.
622 const PointerInfo &getPointerInfo(unsigned PtrIdx) const {
623 return Pointers[PtrIdx];
624 }
625
626 ScalarEvolution *getSE() const { return SE; }
627
628private:
629 /// Groups pointers such that a single memcheck is required
630 /// between two different groups. This will clear the CheckingGroups vector
631 /// and re-compute it.
632 void groupChecks(MemoryDepChecker::DepCandidates &DepCands);
633
634 /// Generate the checks and return them.
636
637 /// Try to create add a new (pointer-difference, access size) pair to
638 /// DiffCheck for checking groups \p CGI and \p CGJ. If pointer-difference
639 /// checks cannot be used for the groups, set CanUseDiffCheck to false.
640 bool tryToCreateDiffCheck(const RuntimeCheckingPtrGroup &CGI,
641 const RuntimeCheckingPtrGroup &CGJ);
642
644
645 /// Holds a pointer to the ScalarEvolution analysis.
646 ScalarEvolution *SE;
647
648 /// Cache for the loop guards of the loop.
649 std::optional<ScalarEvolution::LoopGuards> &LoopGuards;
650
651 /// Set of run-time checks required to establish independence of
652 /// otherwise may-aliasing pointers in the loop.
654
655 /// Flag indicating if pointer-difference checks can be used
656 bool CanUseDiffCheck = true;
657
658 /// A list of (pointer-difference, access size) pairs that can be used to
659 /// prove that there are no vectorization-preventing dependencies.
661};
662
663/// Drive the analysis of memory accesses in the loop
664///
665/// This class is responsible for analyzing the memory accesses of a loop. It
666/// collects the accesses and then its main helper the AccessAnalysis class
667/// finds and categorizes the dependences in buildDependenceSets.
668///
669/// For memory dependences that can be analyzed at compile time, it determines
670/// whether the dependence is part of cycle inhibiting vectorization. This work
671/// is delegated to the MemoryDepChecker class.
672///
673/// For memory dependences that cannot be determined at compile time, it
674/// generates run-time checks to prove independence. This is done by
675/// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
676/// RuntimePointerCheck class. \p AllowPartial determines whether partial checks
677/// are generated when not all pointers could be analyzed.
678///
679/// If pointers can wrap or can't be expressed as affine AddRec expressions by
680/// ScalarEvolution, we will generate run-time checks by emitting a
681/// SCEVUnionPredicate.
682///
683/// Checks for both memory dependences and the SCEV predicates contained in the
684/// PSE must be emitted in order for the results of this analysis to be valid.
686public:
689 const TargetLibraryInfo *TLI, AAResults *AA,
691 bool AllowPartial = false);
692
693 /// Return true we can analyze the memory accesses in the loop and there are
694 /// no memory dependence cycles. Note that for dependences between loads &
695 /// stores with uniform addresses,
696 /// hasStoreStoreDependenceInvolvingLoopInvariantAddress and
697 /// hasLoadStoreDependenceInvolvingLoopInvariantAddress also need to be
698 /// checked.
699 bool canVectorizeMemory() const { return CanVecMem; }
700
701 /// Return true if there is a convergent operation in the loop. There may
702 /// still be reported runtime pointer checks that would be required, but it is
703 /// not legal to insert them.
704 bool hasConvergentOp() const { return HasConvergentOp; }
705
706 /// Return true if, when runtime pointer checking does not have complete
707 /// results, it instead has partial results for those memory accesses that
708 /// could be analyzed.
709 bool hasAllowPartial() const { return AllowPartial; }
710
712 return PtrRtChecking.get();
713 }
714
715 /// Number of memchecks required to prove independence of otherwise
716 /// may-alias pointers.
717 unsigned getNumRuntimePointerChecks() const {
718 return PtrRtChecking->getNumberOfChecks();
719 }
720
721 /// Return true if the block BB needs to be predicated in order for the loop
722 /// to be vectorized.
723 LLVM_ABI static bool blockNeedsPredication(const BasicBlock *BB,
724 const Loop *TheLoop,
725 const DominatorTree *DT);
726
727 /// Returns true if value \p V is loop invariant.
728 LLVM_ABI bool isInvariant(Value *V) const;
729
730 unsigned getNumStores() const { return NumStores; }
731 unsigned getNumLoads() const { return NumLoads;}
732
733 /// The diagnostics report generated for the analysis. E.g. why we
734 /// couldn't analyze the loop.
735 const OptimizationRemarkAnalysis *getReport() const { return Report.get(); }
736
737 /// the Memory Dependence Checker which can determine the
738 /// loop-independent and loop-carried dependences between memory accesses.
739 const MemoryDepChecker &getDepChecker() const { return *DepChecker; }
740
741 /// Return the list of instructions that use \p Ptr to read or write
742 /// memory.
744 bool isWrite) const {
745 return DepChecker->getInstructionsForAccess(Ptr, isWrite);
746 }
747
748 /// If an access has a symbolic strides, this maps the pointer value to
749 /// the stride symbol.
751 return SymbolicStrides;
752 }
753
754 /// Print the information about the memory accesses in the loop.
755 LLVM_ABI void print(raw_ostream &OS, unsigned Depth = 0) const;
756
757 /// Return true if the loop has memory dependence involving two stores to an
758 /// invariant address, else return false.
760 return HasStoreStoreDependenceInvolvingLoopInvariantAddress;
761 }
762
763 /// Return true if the loop has memory dependence involving a load and a store
764 /// to an invariant address, else return false.
766 return HasLoadStoreDependenceInvolvingLoopInvariantAddress;
767 }
768
769 /// Return the list of stores to invariant addresses.
771 return StoresToInvariantAddresses;
772 }
773
774 /// Used to add runtime SCEV checks. Simplifies SCEV expressions and converts
775 /// them to a more usable form. All SCEV expressions during the analysis
776 /// should be re-written (and therefore simplified) according to PSE.
777 /// A user of LoopAccessAnalysis will need to emit the runtime checks
778 /// associated with this predicate.
779 const PredicatedScalarEvolution &getPSE() const { return *PSE; }
780
781private:
782 /// Analyze the loop. Returns true if all memory access in the loop can be
783 /// vectorized.
784 bool analyzeLoop(AAResults *AA, const LoopInfo *LI,
785 const TargetLibraryInfo *TLI, DominatorTree *DT);
786
787 /// Check if the structure of the loop allows it to be analyzed by this
788 /// pass.
789 bool canAnalyzeLoop();
790
791 /// Save the analysis remark.
792 ///
793 /// LAA does not directly emits the remarks. Instead it stores it which the
794 /// client can retrieve and presents as its own analysis
795 /// (e.g. -Rpass-analysis=loop-vectorize).
797 recordAnalysis(StringRef RemarkName, const Instruction *Instr = nullptr);
798
799 /// Collect memory access with loop invariant strides.
800 ///
801 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
802 /// invariant.
803 void collectStridedAccess(Value *LoadOrStoreInst);
804
805 // Emits the first unsafe memory dependence in a loop.
806 // Emits nothing if there are no unsafe dependences
807 // or if the dependences were not recorded.
808 void emitUnsafeDependenceRemark();
809
810 std::unique_ptr<PredicatedScalarEvolution> PSE;
811
812 /// We need to check that all of the pointers in this list are disjoint
813 /// at runtime. Using std::unique_ptr to make using move ctor simpler.
814 /// If AllowPartial is true then this list may contain only partial
815 /// information when we've failed to analyze all the memory accesses in the
816 /// loop, in which case HasCompletePtrRtChecking will be false.
817 std::unique_ptr<RuntimePointerChecking> PtrRtChecking;
818
819 /// The Memory Dependence Checker which can determine the
820 /// loop-independent and loop-carried dependences between memory accesses.
821 /// This will be empty if we've failed to analyze all the memory access in the
822 /// loop (i.e. CanVecMem is false).
823 std::unique_ptr<MemoryDepChecker> DepChecker;
824
825 Loop *TheLoop;
826
827 /// Cache for the loop guards of TheLoop.
828 std::optional<ScalarEvolution::LoopGuards> LoopGuards;
829
830 /// Determines whether we should generate partial runtime checks when not all
831 /// memory accesses could be analyzed.
832 bool AllowPartial;
833
834 unsigned NumLoads = 0;
835 unsigned NumStores = 0;
836
837 /// Cache the result of analyzeLoop.
838 bool CanVecMem = false;
839 bool HasConvergentOp = false;
840 bool HasCompletePtrRtChecking = false;
841
842 /// Indicator that there are two non vectorizable stores to the same uniform
843 /// address.
844 bool HasStoreStoreDependenceInvolvingLoopInvariantAddress = false;
845 /// Indicator that there is non vectorizable load and store to the same
846 /// uniform address.
847 bool HasLoadStoreDependenceInvolvingLoopInvariantAddress = false;
848
849 /// List of stores to invariant addresses.
850 SmallVector<StoreInst *> StoresToInvariantAddresses;
851
852 /// The diagnostics report generated for the analysis. E.g. why we
853 /// couldn't analyze the loop.
854 std::unique_ptr<OptimizationRemarkAnalysis> Report;
855
856 /// If an access has a symbolic strides, this maps the pointer value to
857 /// the stride symbol.
858 DenseMap<Value *, const SCEV *> SymbolicStrides;
859};
860
861/// Return the SCEV corresponding to a pointer with the symbolic stride
862/// replaced with constant one, assuming the SCEV predicate associated with
863/// \p PSE is true.
864///
865/// If necessary this method will version the stride of the pointer according
866/// to \p PtrToStride and therefore add further predicates to \p PSE.
867///
868/// \p PtrToStride provides the mapping between the pointer value and its
869/// stride as collected by LoopVectorizationLegality::collectStridedAccess.
870LLVM_ABI const SCEV *
871replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
872 const DenseMap<Value *, const SCEV *> &PtrToStride,
873 Value *Ptr);
874
875/// If the pointer has a constant stride return it in units of the access type
876/// size. If the pointer is loop-invariant, return 0. Otherwise return
877/// std::nullopt.
878///
879/// Ensure that it does not wrap in the address space, assuming the predicate
880/// associated with \p PSE is true.
881///
882/// If necessary this method will version the stride of the pointer according
883/// to \p PtrToStride and therefore add further predicates to \p PSE.
884/// The \p Assume parameter indicates if we are allowed to make additional
885/// run-time assumptions.
886///
887/// Note that the analysis results are defined if-and-only-if the original
888/// memory access was defined. If that access was dead, or UB, then the
889/// result of this function is undefined.
890LLVM_ABI std::optional<int64_t>
891getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr,
892 const Loop *Lp, const DominatorTree &DT,
893 const DenseMap<Value *, const SCEV *> &StridesMap =
894 DenseMap<Value *, const SCEV *>(),
895 bool Assume = false, bool ShouldCheckWrap = true);
896
897/// Returns the distance between the pointers \p PtrA and \p PtrB iff they are
898/// compatible and it is possible to calculate the distance between them. This
899/// is a simple API that does not depend on the analysis pass.
900/// \param StrictCheck Ensure that the calculated distance matches the
901/// type-based one after all the bitcasts removal in the provided pointers.
902LLVM_ABI std::optional<int64_t>
903getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB, Value *PtrB,
904 const DataLayout &DL, ScalarEvolution &SE,
905 bool StrictCheck = false, bool CheckType = true);
906
907/// Attempt to sort the pointers in \p VL and return the sorted indices
908/// in \p SortedIndices, if reordering is required.
909///
910/// Returns 'true' if sorting is legal, otherwise returns 'false'.
911///
912/// For example, for a given \p VL of memory accesses in program order, a[i+4],
913/// a[i+0], a[i+1] and a[i+7], this function will sort the \p VL and save the
914/// sorted indices in \p SortedIndices as a[i+0], a[i+1], a[i+4], a[i+7] and
915/// saves the mask for actual memory accesses in program order in
916/// \p SortedIndices as <1,2,0,3>
917LLVM_ABI bool sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
918 const DataLayout &DL, ScalarEvolution &SE,
919 SmallVectorImpl<unsigned> &SortedIndices);
920
921/// Returns true if the memory operations \p A and \p B are consecutive.
922/// This is a simple API that does not depend on the analysis pass.
923LLVM_ABI bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
924 ScalarEvolution &SE, bool CheckType = true);
925
926/// Calculate Start and End points of memory access using exact backedge taken
927/// count \p BTC if computable or maximum backedge taken count \p MaxBTC
928/// otherwise.
929///
930/// Let's assume A is the first access and B is a memory access on N-th loop
931/// iteration. Then B is calculated as:
932/// B = A + Step*N .
933/// Step value may be positive or negative.
934/// N is a calculated back-edge taken count:
935/// N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
936/// Start and End points are calculated in the following way:
937/// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
938/// where SizeOfElt is the size of single memory access in bytes.
939///
940/// There is no conflict when the intervals are disjoint:
941/// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
942LLVM_ABI std::pair<const SCEV *, const SCEV *> getStartAndEndForAccess(
943 const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *BTC,
944 const SCEV *MaxBTC, ScalarEvolution *SE,
945 DenseMap<std::pair<const SCEV *, const SCEV *>,
946 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
947 DominatorTree *DT, AssumptionCache *AC,
948 std::optional<ScalarEvolution::LoopGuards> &LoopGuards);
949LLVM_ABI std::pair<const SCEV *, const SCEV *> getStartAndEndForAccess(
950 const Loop *Lp, const SCEV *PtrExpr, const SCEV *EltSizeSCEV,
951 const SCEV *BTC, const SCEV *MaxBTC, ScalarEvolution *SE,
952 DenseMap<std::pair<const SCEV *, const SCEV *>,
953 std::pair<const SCEV *, const SCEV *>> *PointerBounds,
954 DominatorTree *DT, AssumptionCache *AC,
955 std::optional<ScalarEvolution::LoopGuards> &LoopGuards);
956
958 /// The cache.
960
961 // The used analysis passes.
962 ScalarEvolution &SE;
963 AAResults &AA;
964 DominatorTree &DT;
965 LoopInfo &LI;
967 const TargetLibraryInfo *TLI = nullptr;
968 AssumptionCache *AC;
969
970public:
973 const TargetLibraryInfo *TLI, AssumptionCache *AC)
974 : SE(SE), AA(AA), DT(DT), LI(LI), TTI(TTI), TLI(TLI), AC(AC) {}
975
976 LLVM_ABI const LoopAccessInfo &getInfo(Loop &L, bool AllowPartial = false);
977
978 LLVM_ABI void clear();
979
981 FunctionAnalysisManager::Invalidator &Inv);
982};
983
984/// This analysis provides dependence information for the memory
985/// accesses of a loop.
986///
987/// It runs the analysis for a loop on demand. This can be initiated by
988/// querying the loop access info via AM.getResult<LoopAccessAnalysis>.
989/// getResult return a LoopAccessInfo object. See this class for the
990/// specifics of what information is provided.
992 : public AnalysisInfoMixin<LoopAccessAnalysis> {
994 LLVM_ABI static AnalysisKey Key;
995
996public:
998
1000};
1001
1003 const MemoryDepChecker &DepChecker) const {
1004 return DepChecker.getMemoryInstructions()[Source];
1005}
1006
1008 const MemoryDepChecker &DepChecker) const {
1009 return DepChecker.getMemoryInstructions()[Destination];
1010}
1011
1012} // End llvm namespace
1013
1014#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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:213
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)
ArrayRef - 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:159
EquivalenceClasses - This represents a collection of equivalence classes and supports three efficient...
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.
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.
const DenseMap< Value *, const SCEV * > & getSymbolicStrides() const
If an access has a symbolic strides, this maps the pointer value to the stride symbol.
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.
DenseMap< std::pair< const SCEV *, const SCEV * >, std::pair< const SCEV *, const SCEV * > > & getPointerBounds()
MemoryDepChecker(PredicatedScalarEvolution &PSE, AssumptionCache *AC, DominatorTree *DT, const Loop *L, const DenseMap< Value *, const SCEV * > &SymbolicStrides, unsigned MaxTargetVectorWidthInBits, std::optional< ScalarEvolution::LoopGuards > &LoopGuards)
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.
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 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
LLVM_ABI void 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.
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
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.
Definition Types.h:26
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...
std::pair< const RuntimeCheckingPtrGroup *, const RuntimeCheckingPtrGroup * > RuntimePointerCheck
A memcheck which made up of a pair of grouped pointers.
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 const SCEV * replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, const DenseMap< Value *, const SCEV * > &PtrToStride, Value *Ptr)
Return the SCEV corresponding to a pointer with the symbolic stride replaced with constant one,...
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 > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DominatorTree &DT, const DenseMap< Value *, const SCEV * > &StridesMap=DenseMap< Value *, const SCEV * >(), bool Assume=false, bool ShouldCheckWrap=true)
If the pointer has a constant stride return it in units of the access type size.
#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.
Definition PassManager.h:93
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 VectorizationFactor
VF as overridden by the user.
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 bool HoistRuntimeChecks