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