1 //===- llvm/Analysis/LoopAccessAnalysis.h -----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interface for the loop memory dependence framework that
11 // was originally developed for the Loop Vectorizer.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
16 #define LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
18 #include "llvm/ADT/EquivalenceClasses.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/AliasSetTracker.h"
23 #include "llvm/Analysis/LoopAnalysisManager.h"
24 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
25 #include "llvm/IR/DiagnosticInfo.h"
26 #include "llvm/IR/ValueHandle.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/raw_ostream.h"
34 class ScalarEvolution;
37 class SCEVUnionPredicate;
39 class OptimizationRemarkEmitter;
41 /// Optimization analysis message produced during vectorization. Messages inform
42 /// the user why vectorization did not occur.
43 class LoopAccessReport {
45 const Instruction *Instr;
48 LoopAccessReport(const Twine &Message, const Instruction *I)
49 : Message(Message.str()), Instr(I) {}
52 LoopAccessReport(const Instruction *I = nullptr) : Instr(I) {}
54 template <typename A> LoopAccessReport &operator<<(const A &Value) {
55 raw_string_ostream Out(Message);
60 const Instruction *getInstr() const { return Instr; }
62 std::string &str() { return Message; }
63 const std::string &str() const { return Message; }
64 operator Twine() { return Message; }
66 /// \brief Emit an analysis note for \p PassName with the debug location from
67 /// the instruction in \p Message if available. Otherwise use the location of
69 static void emitAnalysis(const LoopAccessReport &Message, const Loop *TheLoop,
71 OptimizationRemarkEmitter &ORE);
74 /// \brief Collection of parameters shared beetween the Loop Vectorizer and the
75 /// Loop Access Analysis.
76 struct VectorizerParams {
77 /// \brief Maximum SIMD width.
78 static const unsigned MaxVectorWidth;
80 /// \brief VF as overridden by the user.
81 static unsigned VectorizationFactor;
82 /// \brief Interleave factor as overridden by the user.
83 static unsigned VectorizationInterleave;
84 /// \brief True if force-vector-interleave was specified by the user.
85 static bool isInterleaveForced();
87 /// \\brief When performing memory disambiguation checks at runtime do not
88 /// make more than this number of comparisons.
89 static unsigned RuntimeMemoryCheckThreshold;
92 /// \brief Checks memory dependences among accesses to the same underlying
93 /// object to determine whether there vectorization is legal or not (and at
94 /// which vectorization factor).
96 /// Note: This class will compute a conservative dependence for access to
97 /// different underlying pointers. Clients, such as the loop vectorizer, will
98 /// sometimes deal these potential dependencies by emitting runtime checks.
100 /// We use the ScalarEvolution framework to symbolically evalutate access
101 /// functions pairs. Since we currently don't restructure the loop we can rely
102 /// on the program order of memory accesses to determine their safety.
103 /// At the moment we will only deem accesses as safe for:
104 /// * A negative constant distance assuming program order.
106 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
107 /// a[i] = tmp; y = a[i];
109 /// The latter case is safe because later checks guarantuee that there can't
110 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
111 /// the same variable: a header phi can only be an induction or a reduction, a
112 /// reduction can't have a memory sink, an induction can't have a memory
113 /// source). This is important and must not be violated (or we have to
114 /// resort to checking for cycles through memory).
116 /// * A positive constant distance assuming program order that is bigger
117 /// than the biggest memory access.
119 /// tmp = a[i] OR b[i] = x
120 /// a[i+2] = tmp y = b[i+2];
122 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
124 /// * Zero distances and all accesses have the same size.
126 class MemoryDepChecker {
128 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
129 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
130 /// \brief Set of potential dependent memory accesses.
131 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
133 /// \brief Dependece between memory access instructions.
135 /// \brief The type of the dependence.
139 // We couldn't determine the direction or the distance.
141 // Lexically forward.
143 // FIXME: If we only have loop-independent forward dependences (e.g. a
144 // read and write of A[i]), LAA will locally deem the dependence "safe"
145 // without querying the MemoryDepChecker. Therefore we can miss
146 // enumerating loop-independent forward dependences in
147 // getDependences. Note that as soon as there are different
148 // indices used to access the same array, the MemoryDepChecker *is*
149 // queried and the dependence list is complete.
151 // Forward, but if vectorized, is likely to prevent store-to-load
153 ForwardButPreventsForwarding,
154 // Lexically backward.
156 // Backward, but the distance allows a vectorization factor of
157 // MaxSafeDepDistBytes.
158 BackwardVectorizable,
159 // Same, but may prevent store-to-load forwarding.
160 BackwardVectorizableButPreventsForwarding
163 /// \brief String version of the types.
164 static const char *DepName[];
166 /// \brief Index of the source of the dependence in the InstMap vector.
168 /// \brief Index of the destination of the dependence in the InstMap vector.
169 unsigned Destination;
170 /// \brief The type of the dependence.
173 Dependence(unsigned Source, unsigned Destination, DepType Type)
174 : Source(Source), Destination(Destination), Type(Type) {}
176 /// \brief Return the source instruction of the dependence.
177 Instruction *getSource(const LoopAccessInfo &LAI) const;
178 /// \brief Return the destination instruction of the dependence.
179 Instruction *getDestination(const LoopAccessInfo &LAI) const;
181 /// \brief Dependence types that don't prevent vectorization.
182 static bool isSafeForVectorization(DepType Type);
184 /// \brief Lexically forward dependence.
185 bool isForward() const;
186 /// \brief Lexically backward dependence.
187 bool isBackward() const;
189 /// \brief May be a lexically backward dependence type (includes Unknown).
190 bool isPossiblyBackward() const;
192 /// \brief Print the dependence. \p Instr is used to map the instruction
193 /// indices to instructions.
194 void print(raw_ostream &OS, unsigned Depth,
195 const SmallVectorImpl<Instruction *> &Instrs) const;
198 MemoryDepChecker(PredicatedScalarEvolution &PSE, const Loop *L)
199 : PSE(PSE), InnermostLoop(L), AccessIdx(0),
200 ShouldRetryWithRuntimeCheck(false), SafeForVectorization(true),
201 RecordDependences(true) {}
203 /// \brief Register the location (instructions are given increasing numbers)
204 /// of a write access.
205 void addAccess(StoreInst *SI) {
206 Value *Ptr = SI->getPointerOperand();
207 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
208 InstMap.push_back(SI);
212 /// \brief Register the location (instructions are given increasing numbers)
213 /// of a write access.
214 void addAccess(LoadInst *LI) {
215 Value *Ptr = LI->getPointerOperand();
216 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
217 InstMap.push_back(LI);
221 /// \brief Check whether the dependencies between the accesses are safe.
223 /// Only checks sets with elements in \p CheckDeps.
224 bool areDepsSafe(DepCandidates &AccessSets, MemAccessInfoSet &CheckDeps,
225 const ValueToValueMap &Strides);
227 /// \brief No memory dependence was encountered that would inhibit
229 bool isSafeForVectorization() const { return SafeForVectorization; }
231 /// \brief The maximum number of bytes of a vector register we can vectorize
232 /// the accesses safely with.
233 uint64_t getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
235 /// \brief In same cases when the dependency check fails we can still
236 /// vectorize the loop with a dynamic array access check.
237 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
239 /// \brief Returns the memory dependences. If null is returned we exceeded
240 /// the MaxDependences threshold and this information is not
242 const SmallVectorImpl<Dependence> *getDependences() const {
243 return RecordDependences ? &Dependences : nullptr;
246 void clearDependences() { Dependences.clear(); }
248 /// \brief The vector of memory access instructions. The indices are used as
249 /// instruction identifiers in the Dependence class.
250 const SmallVectorImpl<Instruction *> &getMemoryInstructions() const {
254 /// \brief Generate a mapping between the memory instructions and their
255 /// indices according to program order.
256 DenseMap<Instruction *, unsigned> generateInstructionOrderMap() const {
257 DenseMap<Instruction *, unsigned> OrderMap;
259 for (unsigned I = 0; I < InstMap.size(); ++I)
260 OrderMap[InstMap[I]] = I;
265 /// \brief Find the set of instructions that read or write via \p Ptr.
266 SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
270 /// A wrapper around ScalarEvolution, used to add runtime SCEV checks, and
271 /// applies dynamic knowledge to simplify SCEV expressions and convert them
272 /// to a more usable form. We need this in case assumptions about SCEV
273 /// expressions need to be made in order to avoid unknown dependences. For
274 /// example we might assume a unit stride for a pointer in order to prove
275 /// that a memory access is strided and doesn't wrap.
276 PredicatedScalarEvolution &PSE;
277 const Loop *InnermostLoop;
279 /// \brief Maps access locations (ptr, read/write) to program order.
280 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
282 /// \brief Memory access instructions in program order.
283 SmallVector<Instruction *, 16> InstMap;
285 /// \brief The program order index to be used for the next instruction.
288 // We can access this many bytes in parallel safely.
289 uint64_t MaxSafeDepDistBytes;
291 /// \brief If we see a non-constant dependence distance we can still try to
292 /// vectorize this loop with runtime checks.
293 bool ShouldRetryWithRuntimeCheck;
295 /// \brief No memory dependence was encountered that would inhibit
297 bool SafeForVectorization;
299 //// \brief True if Dependences reflects the dependences in the
300 //// loop. If false we exceeded MaxDependences and
301 //// Dependences is invalid.
302 bool RecordDependences;
304 /// \brief Memory dependences collected during the analysis. Only valid if
305 /// RecordDependences is true.
306 SmallVector<Dependence, 8> Dependences;
308 /// \brief Check whether there is a plausible dependence between the two
311 /// Access \p A must happen before \p B in program order. The two indices
312 /// identify the index into the program order map.
314 /// This function checks whether there is a plausible dependence (or the
315 /// absence of such can't be proved) between the two accesses. If there is a
316 /// plausible dependence but the dependence distance is bigger than one
317 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
318 /// distance is smaller than any other distance encountered so far).
319 /// Otherwise, this function returns true signaling a possible dependence.
320 Dependence::DepType isDependent(const MemAccessInfo &A, unsigned AIdx,
321 const MemAccessInfo &B, unsigned BIdx,
322 const ValueToValueMap &Strides);
324 /// \brief Check whether the data dependence could prevent store-load
327 /// \return false if we shouldn't vectorize at all or avoid larger
328 /// vectorization factors by limiting MaxSafeDepDistBytes.
329 bool couldPreventStoreLoadForward(uint64_t Distance, uint64_t TypeByteSize);
332 /// \brief Holds information about the memory runtime legality checks to verify
333 /// that a group of pointers do not overlap.
334 class RuntimePointerChecking {
337 /// Holds the pointer value that we need to check.
338 TrackingVH<Value> PointerValue;
339 /// Holds the smallest byte address accessed by the pointer throughout all
340 /// iterations of the loop.
342 /// Holds the largest byte address accessed by the pointer throughout all
343 /// iterations of the loop, plus 1.
345 /// Holds the information if this pointer is used for writing to memory.
347 /// Holds the id of the set of pointers that could be dependent because of a
348 /// shared underlying object.
349 unsigned DependencySetId;
350 /// Holds the id of the disjoint alias set to which this pointer belongs.
352 /// SCEV for the access.
355 PointerInfo(Value *PointerValue, const SCEV *Start, const SCEV *End,
356 bool IsWritePtr, unsigned DependencySetId, unsigned AliasSetId,
358 : PointerValue(PointerValue), Start(Start), End(End),
359 IsWritePtr(IsWritePtr), DependencySetId(DependencySetId),
360 AliasSetId(AliasSetId), Expr(Expr) {}
363 RuntimePointerChecking(ScalarEvolution *SE) : Need(false), SE(SE) {}
365 /// Reset the state of the pointer runtime information.
372 /// Insert a pointer and calculate the start and end SCEVs.
373 /// We need \p PSE in order to compute the SCEV expression of the pointer
374 /// according to the assumptions that we've made during the analysis.
375 /// The method might also version the pointer stride according to \p Strides,
376 /// and add new predicates to \p PSE.
377 void insert(Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
378 unsigned ASId, const ValueToValueMap &Strides,
379 PredicatedScalarEvolution &PSE);
381 /// \brief No run-time memory checking is necessary.
382 bool empty() const { return Pointers.empty(); }
384 /// A grouping of pointers. A single memcheck is required between
386 struct CheckingPtrGroup {
387 /// \brief Create a new pointer checking group containing a single
388 /// pointer, with index \p Index in RtCheck.
389 CheckingPtrGroup(unsigned Index, RuntimePointerChecking &RtCheck)
390 : RtCheck(RtCheck), High(RtCheck.Pointers[Index].End),
391 Low(RtCheck.Pointers[Index].Start) {
392 Members.push_back(Index);
395 /// \brief Tries to add the pointer recorded in RtCheck at index
396 /// \p Index to this pointer checking group. We can only add a pointer
397 /// to a checking group if we will still be able to get
398 /// the upper and lower bounds of the check. Returns true in case
399 /// of success, false otherwise.
400 bool addPointer(unsigned Index);
402 /// Constitutes the context of this pointer checking group. For each
403 /// pointer that is a member of this group we will retain the index
404 /// at which it appears in RtCheck.
405 RuntimePointerChecking &RtCheck;
406 /// The SCEV expression which represents the upper bound of all the
407 /// pointers in this group.
409 /// The SCEV expression which represents the lower bound of all the
410 /// pointers in this group.
412 /// Indices of all the pointers that constitute this grouping.
413 SmallVector<unsigned, 2> Members;
416 /// \brief A memcheck which made up of a pair of grouped pointers.
418 /// These *have* to be const for now, since checks are generated from
419 /// CheckingPtrGroups in LAI::addRuntimeChecks which is a const member
420 /// function. FIXME: once check-generation is moved inside this class (after
421 /// the PtrPartition hack is removed), we could drop const.
422 typedef std::pair<const CheckingPtrGroup *, const CheckingPtrGroup *>
425 /// \brief Generate the checks and store it. This also performs the grouping
426 /// of pointers to reduce the number of memchecks necessary.
427 void generateChecks(MemoryDepChecker::DepCandidates &DepCands,
428 bool UseDependencies);
430 /// \brief Returns the checks that generateChecks created.
431 const SmallVector<PointerCheck, 4> &getChecks() const { return Checks; }
433 /// \brief Decide if we need to add a check between two groups of pointers,
434 /// according to needsChecking.
435 bool needsChecking(const CheckingPtrGroup &M,
436 const CheckingPtrGroup &N) const;
438 /// \brief Returns the number of run-time checks required according to
440 unsigned getNumberOfChecks() const { return Checks.size(); }
442 /// \brief Print the list run-time memory checks necessary.
443 void print(raw_ostream &OS, unsigned Depth = 0) const;
446 void printChecks(raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
447 unsigned Depth = 0) const;
449 /// This flag indicates if we need to add the runtime check.
452 /// Information about the pointers that may require checking.
453 SmallVector<PointerInfo, 2> Pointers;
455 /// Holds a partitioning of pointers into "check groups".
456 SmallVector<CheckingPtrGroup, 2> CheckingGroups;
458 /// \brief Check if pointers are in the same partition
460 /// \p PtrToPartition contains the partition number for pointers (-1 if the
461 /// pointer belongs to multiple partitions).
463 arePointersInSamePartition(const SmallVectorImpl<int> &PtrToPartition,
464 unsigned PtrIdx1, unsigned PtrIdx2);
466 /// \brief Decide whether we need to issue a run-time check for pointer at
467 /// index \p I and \p J to prove their independence.
468 bool needsChecking(unsigned I, unsigned J) const;
470 /// \brief Return PointerInfo for pointer at index \p PtrIdx.
471 const PointerInfo &getPointerInfo(unsigned PtrIdx) const {
472 return Pointers[PtrIdx];
476 /// \brief Groups pointers such that a single memcheck is required
477 /// between two different groups. This will clear the CheckingGroups vector
478 /// and re-compute it. We will only group dependecies if \p UseDependencies
479 /// is true, otherwise we will create a separate group for each pointer.
480 void groupChecks(MemoryDepChecker::DepCandidates &DepCands,
481 bool UseDependencies);
483 /// Generate the checks and return them.
484 SmallVector<PointerCheck, 4>
485 generateChecks() const;
487 /// Holds a pointer to the ScalarEvolution analysis.
490 /// \brief Set of run-time checks required to establish independence of
491 /// otherwise may-aliasing pointers in the loop.
492 SmallVector<PointerCheck, 4> Checks;
495 /// \brief Drive the analysis of memory accesses in the loop
497 /// This class is responsible for analyzing the memory accesses of a loop. It
498 /// collects the accesses and then its main helper the AccessAnalysis class
499 /// finds and categorizes the dependences in buildDependenceSets.
501 /// For memory dependences that can be analyzed at compile time, it determines
502 /// whether the dependence is part of cycle inhibiting vectorization. This work
503 /// is delegated to the MemoryDepChecker class.
505 /// For memory dependences that cannot be determined at compile time, it
506 /// generates run-time checks to prove independence. This is done by
507 /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
508 /// RuntimePointerCheck class.
510 /// If pointers can wrap or can't be expressed as affine AddRec expressions by
511 /// ScalarEvolution, we will generate run-time checks by emitting a
512 /// SCEVUnionPredicate.
514 /// Checks for both memory dependences and the SCEV predicates contained in the
515 /// PSE must be emitted in order for the results of this analysis to be valid.
516 class LoopAccessInfo {
518 LoopAccessInfo(Loop *L, ScalarEvolution *SE, const TargetLibraryInfo *TLI,
519 AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI);
521 /// Return true we can analyze the memory accesses in the loop and there are
522 /// no memory dependence cycles.
523 bool canVectorizeMemory() const { return CanVecMem; }
525 const RuntimePointerChecking *getRuntimePointerChecking() const {
526 return PtrRtChecking.get();
529 /// \brief Number of memchecks required to prove independence of otherwise
530 /// may-alias pointers.
531 unsigned getNumRuntimePointerChecks() const {
532 return PtrRtChecking->getNumberOfChecks();
535 /// Return true if the block BB needs to be predicated in order for the loop
536 /// to be vectorized.
537 static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
540 /// Returns true if the value V is uniform within the loop.
541 bool isUniform(Value *V) const;
543 uint64_t getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
544 unsigned getNumStores() const { return NumStores; }
545 unsigned getNumLoads() const { return NumLoads;}
547 /// \brief Add code that checks at runtime if the accessed arrays overlap.
549 /// Returns a pair of instructions where the first element is the first
550 /// instruction generated in possibly a sequence of instructions and the
551 /// second value is the final comparator value or NULL if no check is needed.
552 std::pair<Instruction *, Instruction *>
553 addRuntimeChecks(Instruction *Loc) const;
555 /// \brief Generete the instructions for the checks in \p PointerChecks.
557 /// Returns a pair of instructions where the first element is the first
558 /// instruction generated in possibly a sequence of instructions and the
559 /// second value is the final comparator value or NULL if no check is needed.
560 std::pair<Instruction *, Instruction *>
561 addRuntimeChecks(Instruction *Loc,
562 const SmallVectorImpl<RuntimePointerChecking::PointerCheck>
563 &PointerChecks) const;
565 /// \brief The diagnostics report generated for the analysis. E.g. why we
566 /// couldn't analyze the loop.
567 const OptimizationRemarkAnalysis *getReport() const { return Report.get(); }
569 /// \brief the Memory Dependence Checker which can determine the
570 /// loop-independent and loop-carried dependences between memory accesses.
571 const MemoryDepChecker &getDepChecker() const { return *DepChecker; }
573 /// \brief Return the list of instructions that use \p Ptr to read or write
575 SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
576 bool isWrite) const {
577 return DepChecker->getInstructionsForAccess(Ptr, isWrite);
580 /// \brief If an access has a symbolic strides, this maps the pointer value to
581 /// the stride symbol.
582 const ValueToValueMap &getSymbolicStrides() const { return SymbolicStrides; }
584 /// \brief Pointer has a symbolic stride.
585 bool hasStride(Value *V) const { return StrideSet.count(V); }
587 /// \brief Print the information about the memory accesses in the loop.
588 void print(raw_ostream &OS, unsigned Depth = 0) const;
590 /// \brief Checks existence of store to invariant address inside loop.
591 /// If the loop has any store to invariant address, then it returns true,
592 /// else returns false.
593 bool hasStoreToLoopInvariantAddress() const {
594 return StoreToLoopInvariantAddress;
597 /// Used to add runtime SCEV checks. Simplifies SCEV expressions and converts
598 /// them to a more usable form. All SCEV expressions during the analysis
599 /// should be re-written (and therefore simplified) according to PSE.
600 /// A user of LoopAccessAnalysis will need to emit the runtime checks
601 /// associated with this predicate.
602 const PredicatedScalarEvolution &getPSE() const { return *PSE; }
605 /// \brief Analyze the loop.
606 void analyzeLoop(AliasAnalysis *AA, LoopInfo *LI,
607 const TargetLibraryInfo *TLI, DominatorTree *DT);
609 /// \brief Check if the structure of the loop allows it to be analyzed by this
611 bool canAnalyzeLoop();
613 /// \brief Save the analysis remark.
615 /// LAA does not directly emits the remarks. Instead it stores it which the
616 /// client can retrieve and presents as its own analysis
617 /// (e.g. -Rpass-analysis=loop-vectorize).
618 OptimizationRemarkAnalysis &recordAnalysis(StringRef RemarkName,
619 Instruction *Instr = nullptr);
621 /// \brief Collect memory access with loop invariant strides.
623 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
625 void collectStridedAccess(Value *LoadOrStoreInst);
627 std::unique_ptr<PredicatedScalarEvolution> PSE;
629 /// We need to check that all of the pointers in this list are disjoint
630 /// at runtime. Using std::unique_ptr to make using move ctor simpler.
631 std::unique_ptr<RuntimePointerChecking> PtrRtChecking;
633 /// \brief the Memory Dependence Checker which can determine the
634 /// loop-independent and loop-carried dependences between memory accesses.
635 std::unique_ptr<MemoryDepChecker> DepChecker;
642 uint64_t MaxSafeDepDistBytes;
644 /// \brief Cache the result of analyzeLoop.
647 /// \brief Indicator for storing to uniform addresses.
648 /// If a loop has write to a loop invariant address then it should be true.
649 bool StoreToLoopInvariantAddress;
651 /// \brief The diagnostics report generated for the analysis. E.g. why we
652 /// couldn't analyze the loop.
653 std::unique_ptr<OptimizationRemarkAnalysis> Report;
655 /// \brief If an access has a symbolic strides, this maps the pointer value to
656 /// the stride symbol.
657 ValueToValueMap SymbolicStrides;
659 /// \brief Set of symbolic strides values.
660 SmallPtrSet<Value *, 8> StrideSet;
663 Value *stripIntegerCast(Value *V);
665 /// \brief Return the SCEV corresponding to a pointer with the symbolic stride
666 /// replaced with constant one, assuming the SCEV predicate associated with
669 /// If necessary this method will version the stride of the pointer according
670 /// to \p PtrToStride and therefore add further predicates to \p PSE.
672 /// If \p OrigPtr is not null, use it to look up the stride value instead of \p
673 /// Ptr. \p PtrToStride provides the mapping between the pointer value and its
674 /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
675 const SCEV *replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
676 const ValueToValueMap &PtrToStride,
677 Value *Ptr, Value *OrigPtr = nullptr);
679 /// \brief If the pointer has a constant stride return it in units of its
680 /// element size. Otherwise return zero.
682 /// Ensure that it does not wrap in the address space, assuming the predicate
683 /// associated with \p PSE is true.
685 /// If necessary this method will version the stride of the pointer according
686 /// to \p PtrToStride and therefore add further predicates to \p PSE.
687 /// The \p Assume parameter indicates if we are allowed to make additional
688 /// run-time assumptions.
689 int64_t getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr, const Loop *Lp,
690 const ValueToValueMap &StridesMap = ValueToValueMap(),
691 bool Assume = false, bool ShouldCheckWrap = true);
693 /// \brief Returns true if the memory operations \p A and \p B are consecutive.
694 /// This is a simple API that does not depend on the analysis pass.
695 bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
696 ScalarEvolution &SE, bool CheckType = true);
698 /// \brief This analysis provides dependence information for the memory accesses
701 /// It runs the analysis for a loop on demand. This can be initiated by
702 /// querying the loop access info via LAA::getInfo. getInfo return a
703 /// LoopAccessInfo object. See this class for the specifics of what information
705 class LoopAccessLegacyAnalysis : public FunctionPass {
709 LoopAccessLegacyAnalysis() : FunctionPass(ID) {
710 initializeLoopAccessLegacyAnalysisPass(*PassRegistry::getPassRegistry());
713 bool runOnFunction(Function &F) override;
715 void getAnalysisUsage(AnalysisUsage &AU) const override;
717 /// \brief Query the result of the loop access information for the loop \p L.
719 /// If there is no cached result available run the analysis.
720 const LoopAccessInfo &getInfo(Loop *L);
722 void releaseMemory() override {
723 // Invalidate the cache when the pass is freed.
724 LoopAccessInfoMap.clear();
727 /// \brief Print the result of the analysis when invoked with -analyze.
728 void print(raw_ostream &OS, const Module *M = nullptr) const override;
731 /// \brief The cache.
732 DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
734 // The used analysis passes.
736 const TargetLibraryInfo *TLI;
742 /// \brief This analysis provides dependence information for the memory
743 /// accesses of a loop.
745 /// It runs the analysis for a loop on demand. This can be initiated by
746 /// querying the loop access info via AM.getResult<LoopAccessAnalysis>.
747 /// getResult return a LoopAccessInfo object. See this class for the
748 /// specifics of what information is provided.
749 class LoopAccessAnalysis
750 : public AnalysisInfoMixin<LoopAccessAnalysis> {
751 friend AnalysisInfoMixin<LoopAccessAnalysis>;
752 static AnalysisKey Key;
755 typedef LoopAccessInfo Result;
757 Result run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR);
760 inline Instruction *MemoryDepChecker::Dependence::getSource(
761 const LoopAccessInfo &LAI) const {
762 return LAI.getDepChecker().getMemoryInstructions()[Source];
765 inline Instruction *MemoryDepChecker::Dependence::getDestination(
766 const LoopAccessInfo &LAI) const {
767 return LAI.getDepChecker().getMemoryInstructions()[Destination];
770 } // End llvm namespace