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