77d412a4f9271767201932f0d74e65c6f50e70c4
[oota-llvm.git] / include / llvm / Analysis / LoopAccessAnalysis.h
1 //===- llvm/Analysis/LoopAccessAnalysis.h -----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interface for the loop memory dependence framework that
11 // was originally developed for the Loop Vectorizer.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
16 #define LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
17
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/ScalarEvolutionExpressions.h"
24 #include "llvm/IR/ValueHandle.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/raw_ostream.h"
27
28 namespace llvm {
29
30 class Value;
31 class DataLayout;
32 class ScalarEvolution;
33 class Loop;
34 class SCEV;
35 class SCEVUnionPredicate;
36 class LoopAccessInfo;
37
38 /// Optimization analysis message produced during vectorization. Messages inform
39 /// the user why vectorization did not occur.
40 class LoopAccessReport {
41   std::string Message;
42   const Instruction *Instr;
43
44 protected:
45   LoopAccessReport(const Twine &Message, const Instruction *I)
46       : Message(Message.str()), Instr(I) {}
47
48 public:
49   LoopAccessReport(const Instruction *I = nullptr) : Instr(I) {}
50
51   template <typename A> LoopAccessReport &operator<<(const A &Value) {
52     raw_string_ostream Out(Message);
53     Out << Value;
54     return *this;
55   }
56
57   const Instruction *getInstr() const { return Instr; }
58
59   std::string &str() { return Message; }
60   const std::string &str() const { return Message; }
61   operator Twine() { return Message; }
62
63   /// \brief Emit an analysis note for \p PassName with the debug location from
64   /// the instruction in \p Message if available.  Otherwise use the location of
65   /// \p TheLoop.
66   static void emitAnalysis(const LoopAccessReport &Message,
67                            const Function *TheFunction,
68                            const Loop *TheLoop,
69                            const char *PassName);
70 };
71
72 /// \brief Collection of parameters shared beetween the Loop Vectorizer and the
73 /// Loop Access Analysis.
74 struct VectorizerParams {
75   /// \brief Maximum SIMD width.
76   static const unsigned MaxVectorWidth;
77
78   /// \brief VF as overridden by the user.
79   static unsigned VectorizationFactor;
80   /// \brief Interleave factor as overridden by the user.
81   static unsigned VectorizationInterleave;
82   /// \brief True if force-vector-interleave was specified by the user.
83   static bool isInterleaveForced();
84
85   /// \\brief When performing memory disambiguation checks at runtime do not
86   /// make more than this number of comparisons.
87   static unsigned RuntimeMemoryCheckThreshold;
88 };
89
90 /// \brief Checks memory dependences among accesses to the same underlying
91 /// object to determine whether there vectorization is legal or not (and at
92 /// which vectorization factor).
93 ///
94 /// Note: This class will compute a conservative dependence for access to
95 /// different underlying pointers. Clients, such as the loop vectorizer, will
96 /// sometimes deal these potential dependencies by emitting runtime checks.
97 ///
98 /// We use the ScalarEvolution framework to symbolically evalutate access
99 /// functions pairs. Since we currently don't restructure the loop we can rely
100 /// on the program order of memory accesses to determine their safety.
101 /// At the moment we will only deem accesses as safe for:
102 ///  * A negative constant distance assuming program order.
103 ///
104 ///      Safe: tmp = a[i + 1];     OR     a[i + 1] = x;
105 ///            a[i] = tmp;                y = a[i];
106 ///
107 ///   The latter case is safe because later checks guarantuee that there can't
108 ///   be a cycle through a phi node (that is, we check that "x" and "y" is not
109 ///   the same variable: a header phi can only be an induction or a reduction, a
110 ///   reduction can't have a memory sink, an induction can't have a memory
111 ///   source). This is important and must not be violated (or we have to
112 ///   resort to checking for cycles through memory).
113 ///
114 ///  * A positive constant distance assuming program order that is bigger
115 ///    than the biggest memory access.
116 ///
117 ///     tmp = a[i]        OR              b[i] = x
118 ///     a[i+2] = tmp                      y = b[i+2];
119 ///
120 ///     Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
121 ///
122 ///  * Zero distances and all accesses have the same size.
123 ///
124 class MemoryDepChecker {
125 public:
126   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
127   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
128   /// \brief Set of potential dependent memory accesses.
129   typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
130
131   /// \brief Dependece between memory access instructions.
132   struct Dependence {
133     /// \brief The type of the dependence.
134     enum DepType {
135       // No dependence.
136       NoDep,
137       // We couldn't determine the direction or the distance.
138       Unknown,
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.
148       Forward,
149       // Forward, but if vectorized, is likely to prevent store-to-load
150       // forwarding.
151       ForwardButPreventsForwarding,
152       // Lexically backward.
153       Backward,
154       // Backward, but the distance allows a vectorization factor of
155       // MaxSafeDepDistBytes.
156       BackwardVectorizable,
157       // Same, but may prevent store-to-load forwarding.
158       BackwardVectorizableButPreventsForwarding
159     };
160
161     /// \brief String version of the types.
162     static const char *DepName[];
163
164     /// \brief Index of the source of the dependence in the InstMap vector.
165     unsigned Source;
166     /// \brief Index of the destination of the dependence in the InstMap vector.
167     unsigned Destination;
168     /// \brief The type of the dependence.
169     DepType Type;
170
171     Dependence(unsigned Source, unsigned Destination, DepType Type)
172         : Source(Source), Destination(Destination), Type(Type) {}
173
174     /// \brief Return the source instruction of the dependence.
175     Instruction *getSource(const LoopAccessInfo &LAI) const;
176     /// \brief Return the destination instruction of the dependence.
177     Instruction *getDestination(const LoopAccessInfo &LAI) const;
178
179     /// \brief Dependence types that don't prevent vectorization.
180     static bool isSafeForVectorization(DepType Type);
181
182     /// \brief Lexically forward dependence.
183     bool isForward() const;
184     /// \brief Lexically backward dependence.
185     bool isBackward() const;
186
187     /// \brief May be a lexically backward dependence type (includes Unknown).
188     bool isPossiblyBackward() const;
189
190     /// \brief Print the dependence.  \p Instr is used to map the instruction
191     /// indices to instructions.
192     void print(raw_ostream &OS, unsigned Depth,
193                const SmallVectorImpl<Instruction *> &Instrs) const;
194   };
195
196   MemoryDepChecker(ScalarEvolution *Se, const Loop *L,
197                    SCEVUnionPredicate &Preds)
198       : SE(Se), InnermostLoop(L), AccessIdx(0),
199         ShouldRetryWithRuntimeCheck(false), SafeForVectorization(true),
200         RecordDependences(true), Preds(Preds) {}
201
202   /// \brief Register the location (instructions are given increasing numbers)
203   /// of a write access.
204   void addAccess(StoreInst *SI) {
205     Value *Ptr = SI->getPointerOperand();
206     Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
207     InstMap.push_back(SI);
208     ++AccessIdx;
209   }
210
211   /// \brief Register the location (instructions are given increasing numbers)
212   /// of a write access.
213   void addAccess(LoadInst *LI) {
214     Value *Ptr = LI->getPointerOperand();
215     Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
216     InstMap.push_back(LI);
217     ++AccessIdx;
218   }
219
220   /// \brief Check whether the dependencies between the accesses are safe.
221   ///
222   /// Only checks sets with elements in \p CheckDeps.
223   bool areDepsSafe(DepCandidates &AccessSets, MemAccessInfoSet &CheckDeps,
224                    const ValueToValueMap &Strides);
225
226   /// \brief No memory dependence was encountered that would inhibit
227   /// vectorization.
228   bool isSafeForVectorization() const { return SafeForVectorization; }
229
230   /// \brief The maximum number of bytes of a vector register we can vectorize
231   /// the accesses safely with.
232   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
233
234   /// \brief In same cases when the dependency check fails we can still
235   /// vectorize the loop with a dynamic array access check.
236   bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
237
238   /// \brief Returns the memory dependences.  If null is returned we exceeded
239   /// the MaxDependences threshold and this information is not
240   /// available.
241   const SmallVectorImpl<Dependence> *getDependences() const {
242     return RecordDependences ? &Dependences : nullptr;
243   }
244
245   void clearDependences() { Dependences.clear(); }
246
247   /// \brief The vector of memory access instructions.  The indices are used as
248   /// instruction identifiers in the Dependence class.
249   const SmallVectorImpl<Instruction *> &getMemoryInstructions() const {
250     return InstMap;
251   }
252
253   /// \brief Generate a mapping between the memory instructions and their
254   /// indices according to program order.
255   DenseMap<Instruction *, unsigned> generateInstructionOrderMap() const {
256     DenseMap<Instruction *, unsigned> OrderMap;
257
258     for (unsigned I = 0; I < InstMap.size(); ++I)
259       OrderMap[InstMap[I]] = I;
260
261     return OrderMap;
262   }
263
264   /// \brief Find the set of instructions that read or write via \p Ptr.
265   SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
266                                                          bool isWrite) const;
267
268 private:
269   ScalarEvolution *SE;
270   const Loop *InnermostLoop;
271
272   /// \brief Maps access locations (ptr, read/write) to program order.
273   DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
274
275   /// \brief Memory access instructions in program order.
276   SmallVector<Instruction *, 16> InstMap;
277
278   /// \brief The program order index to be used for the next instruction.
279   unsigned AccessIdx;
280
281   // We can access this many bytes in parallel safely.
282   unsigned MaxSafeDepDistBytes;
283
284   /// \brief If we see a non-constant dependence distance we can still try to
285   /// vectorize this loop with runtime checks.
286   bool ShouldRetryWithRuntimeCheck;
287
288   /// \brief No memory dependence was encountered that would inhibit
289   /// vectorization.
290   bool SafeForVectorization;
291
292   //// \brief True if Dependences reflects the dependences in the
293   //// loop.  If false we exceeded MaxDependences and
294   //// Dependences is invalid.
295   bool RecordDependences;
296
297   /// \brief Memory dependences collected during the analysis.  Only valid if
298   /// RecordDependences is true.
299   SmallVector<Dependence, 8> Dependences;
300
301   /// \brief Check whether there is a plausible dependence between the two
302   /// accesses.
303   ///
304   /// Access \p A must happen before \p B in program order. The two indices
305   /// identify the index into the program order map.
306   ///
307   /// This function checks  whether there is a plausible dependence (or the
308   /// absence of such can't be proved) between the two accesses. If there is a
309   /// plausible dependence but the dependence distance is bigger than one
310   /// element access it records this distance in \p MaxSafeDepDistBytes (if this
311   /// distance is smaller than any other distance encountered so far).
312   /// Otherwise, this function returns true signaling a possible dependence.
313   Dependence::DepType isDependent(const MemAccessInfo &A, unsigned AIdx,
314                                   const MemAccessInfo &B, unsigned BIdx,
315                                   const ValueToValueMap &Strides);
316
317   /// \brief Check whether the data dependence could prevent store-load
318   /// forwarding.
319   bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
320
321   /// The SCEV predicate containing all the SCEV-related assumptions.
322   /// The dependence checker needs this in order to convert SCEVs of pointers
323   /// to more accurate expressions in the context of existing assumptions.
324   /// We also need this in case assumptions about SCEV expressions need to
325   /// be made in order to avoid unknown dependences. For example we might
326   /// assume a unit stride for a pointer in order to prove that a memory access
327   /// is strided and doesn't wrap.
328   SCEVUnionPredicate &Preds;
329 };
330
331 /// \brief Holds information about the memory runtime legality checks to verify
332 /// that a group of pointers do not overlap.
333 class RuntimePointerChecking {
334 public:
335   struct PointerInfo {
336     /// Holds the pointer value that we need to check.
337     TrackingVH<Value> PointerValue;
338     /// Holds the pointer value at the beginning of the loop.
339     const SCEV *Start;
340     /// Holds the pointer value at the end of the loop.
341     const SCEV *End;
342     /// Holds the information if this pointer is used for writing to memory.
343     bool IsWritePtr;
344     /// Holds the id of the set of pointers that could be dependent because of a
345     /// shared underlying object.
346     unsigned DependencySetId;
347     /// Holds the id of the disjoint alias set to which this pointer belongs.
348     unsigned AliasSetId;
349     /// SCEV for the access.
350     const SCEV *Expr;
351
352     PointerInfo(Value *PointerValue, const SCEV *Start, const SCEV *End,
353                 bool IsWritePtr, unsigned DependencySetId, unsigned AliasSetId,
354                 const SCEV *Expr)
355         : PointerValue(PointerValue), Start(Start), End(End),
356           IsWritePtr(IsWritePtr), DependencySetId(DependencySetId),
357           AliasSetId(AliasSetId), Expr(Expr) {}
358   };
359
360   RuntimePointerChecking(ScalarEvolution *SE) : Need(false), SE(SE) {}
361
362   /// Reset the state of the pointer runtime information.
363   void reset() {
364     Need = false;
365     Pointers.clear();
366     Checks.clear();
367   }
368
369   /// Insert a pointer and calculate the start and end SCEVs.
370   /// \p We need Preds in order to compute the SCEV expression of the pointer
371   /// according to the assumptions that we've made during the analysis.
372   /// The method might also version the pointer stride according to \p Strides,
373   /// and change \p Preds.
374   void insert(Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
375               unsigned ASId, const ValueToValueMap &Strides,
376               SCEVUnionPredicate &Preds);
377
378   /// \brief No run-time memory checking is necessary.
379   bool empty() const { return Pointers.empty(); }
380
381   /// A grouping of pointers. A single memcheck is required between
382   /// two groups.
383   struct CheckingPtrGroup {
384     /// \brief Create a new pointer checking group containing a single
385     /// pointer, with index \p Index in RtCheck.
386     CheckingPtrGroup(unsigned Index, RuntimePointerChecking &RtCheck)
387         : RtCheck(RtCheck), High(RtCheck.Pointers[Index].End),
388           Low(RtCheck.Pointers[Index].Start) {
389       Members.push_back(Index);
390     }
391
392     /// \brief Tries to add the pointer recorded in RtCheck at index
393     /// \p Index to this pointer checking group. We can only add a pointer
394     /// to a checking group if we will still be able to get
395     /// the upper and lower bounds of the check. Returns true in case
396     /// of success, false otherwise.
397     bool addPointer(unsigned Index);
398
399     /// Constitutes the context of this pointer checking group. For each
400     /// pointer that is a member of this group we will retain the index
401     /// at which it appears in RtCheck.
402     RuntimePointerChecking &RtCheck;
403     /// The SCEV expression which represents the upper bound of all the
404     /// pointers in this group.
405     const SCEV *High;
406     /// The SCEV expression which represents the lower bound of all the
407     /// pointers in this group.
408     const SCEV *Low;
409     /// Indices of all the pointers that constitute this grouping.
410     SmallVector<unsigned, 2> Members;
411   };
412
413   /// \brief A memcheck which made up of a pair of grouped pointers.
414   ///
415   /// These *have* to be const for now, since checks are generated from
416   /// CheckingPtrGroups in LAI::addRuntimeChecks which is a const member
417   /// function.  FIXME: once check-generation is moved inside this class (after
418   /// the PtrPartition hack is removed), we could drop const.
419   typedef std::pair<const CheckingPtrGroup *, const CheckingPtrGroup *>
420       PointerCheck;
421
422   /// \brief Generate the checks and store it.  This also performs the grouping
423   /// of pointers to reduce the number of memchecks necessary.
424   void generateChecks(MemoryDepChecker::DepCandidates &DepCands,
425                       bool UseDependencies);
426
427   /// \brief Returns the checks that generateChecks created.
428   const SmallVector<PointerCheck, 4> &getChecks() const { return Checks; }
429
430   /// \brief Decide if we need to add a check between two groups of pointers,
431   /// according to needsChecking.
432   bool needsChecking(const CheckingPtrGroup &M,
433                      const CheckingPtrGroup &N) const;
434
435   /// \brief Returns the number of run-time checks required according to
436   /// needsChecking.
437   unsigned getNumberOfChecks() const { return Checks.size(); }
438
439   /// \brief Print the list run-time memory checks necessary.
440   void print(raw_ostream &OS, unsigned Depth = 0) const;
441
442   /// Print \p Checks.
443   void printChecks(raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
444                    unsigned Depth = 0) const;
445
446   /// This flag indicates if we need to add the runtime check.
447   bool Need;
448
449   /// Information about the pointers that may require checking.
450   SmallVector<PointerInfo, 2> Pointers;
451
452   /// Holds a partitioning of pointers into "check groups".
453   SmallVector<CheckingPtrGroup, 2> CheckingGroups;
454
455   /// \brief Check if pointers are in the same partition
456   ///
457   /// \p PtrToPartition contains the partition number for pointers (-1 if the
458   /// pointer belongs to multiple partitions).
459   static bool
460   arePointersInSamePartition(const SmallVectorImpl<int> &PtrToPartition,
461                              unsigned PtrIdx1, unsigned PtrIdx2);
462
463   /// \brief Decide whether we need to issue a run-time check for pointer at
464   /// index \p I and \p J to prove their independence.
465   bool needsChecking(unsigned I, unsigned J) const;
466
467   /// \brief Return PointerInfo for pointer at index \p PtrIdx.
468   const PointerInfo &getPointerInfo(unsigned PtrIdx) const {
469     return Pointers[PtrIdx];
470   }
471
472 private:
473   /// \brief Groups pointers such that a single memcheck is required
474   /// between two different groups. This will clear the CheckingGroups vector
475   /// and re-compute it. We will only group dependecies if \p UseDependencies
476   /// is true, otherwise we will create a separate group for each pointer.
477   void groupChecks(MemoryDepChecker::DepCandidates &DepCands,
478                    bool UseDependencies);
479
480   /// Generate the checks and return them.
481   SmallVector<PointerCheck, 4>
482   generateChecks() const;
483
484   /// Holds a pointer to the ScalarEvolution analysis.
485   ScalarEvolution *SE;
486
487   /// \brief Set of run-time checks required to establish independence of
488   /// otherwise may-aliasing pointers in the loop.
489   SmallVector<PointerCheck, 4> Checks;
490 };
491
492 /// \brief Drive the analysis of memory accesses in the loop
493 ///
494 /// This class is responsible for analyzing the memory accesses of a loop.  It
495 /// collects the accesses and then its main helper the AccessAnalysis class
496 /// finds and categorizes the dependences in buildDependenceSets.
497 ///
498 /// For memory dependences that can be analyzed at compile time, it determines
499 /// whether the dependence is part of cycle inhibiting vectorization.  This work
500 /// is delegated to the MemoryDepChecker class.
501 ///
502 /// For memory dependences that cannot be determined at compile time, it
503 /// generates run-time checks to prove independence.  This is done by
504 /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
505 /// RuntimePointerCheck class.
506 ///
507 /// If pointers can wrap or can't be expressed as affine AddRec expressions by
508 /// ScalarEvolution, we will generate run-time checks by emitting a
509 /// SCEVUnionPredicate.
510 ///
511 /// Checks for both memory dependences and SCEV predicates must be emitted in
512 /// order for the results of this analysis to be valid.
513 class LoopAccessInfo {
514 public:
515   LoopAccessInfo(Loop *L, ScalarEvolution *SE, const DataLayout &DL,
516                  const TargetLibraryInfo *TLI, AliasAnalysis *AA,
517                  DominatorTree *DT, LoopInfo *LI,
518                  const ValueToValueMap &Strides);
519
520   /// Return true we can analyze the memory accesses in the loop and there are
521   /// no memory dependence cycles.
522   bool canVectorizeMemory() const { return CanVecMem; }
523
524   const RuntimePointerChecking *getRuntimePointerChecking() const {
525     return &PtrRtChecking;
526   }
527
528   /// \brief Number of memchecks required to prove independence of otherwise
529   /// may-alias pointers.
530   unsigned getNumRuntimePointerChecks() const {
531     return PtrRtChecking.getNumberOfChecks();
532   }
533
534   /// Return true if the block BB needs to be predicated in order for the loop
535   /// to be vectorized.
536   static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
537                                     DominatorTree *DT);
538
539   /// Returns true if the value V is uniform within the loop.
540   bool isUniform(Value *V) const;
541
542   unsigned getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
543   unsigned getNumStores() const { return NumStores; }
544   unsigned getNumLoads() const { return NumLoads;}
545
546   /// \brief Add code that checks at runtime if the accessed arrays overlap.
547   ///
548   /// Returns a pair of instructions where the first element is the first
549   /// instruction generated in possibly a sequence of instructions and the
550   /// second value is the final comparator value or NULL if no check is needed.
551   std::pair<Instruction *, Instruction *>
552   addRuntimeChecks(Instruction *Loc) const;
553
554   /// \brief Generete the instructions for the checks in \p PointerChecks.
555   ///
556   /// Returns a pair of instructions where the first element is the first
557   /// instruction generated in possibly a sequence of instructions and the
558   /// second value is the final comparator value or NULL if no check is needed.
559   std::pair<Instruction *, Instruction *>
560   addRuntimeChecks(Instruction *Loc,
561                    const SmallVectorImpl<RuntimePointerChecking::PointerCheck>
562                        &PointerChecks) const;
563
564   /// \brief The diagnostics report generated for the analysis.  E.g. why we
565   /// couldn't analyze the loop.
566   const Optional<LoopAccessReport> &getReport() const { return Report; }
567
568   /// \brief the Memory Dependence Checker which can determine the
569   /// loop-independent and loop-carried dependences between memory accesses.
570   const MemoryDepChecker &getDepChecker() const { return DepChecker; }
571
572   /// \brief Return the list of instructions that use \p Ptr to read or write
573   /// memory.
574   SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
575                                                          bool isWrite) const {
576     return DepChecker.getInstructionsForAccess(Ptr, isWrite);
577   }
578
579   /// \brief Print the information about the memory accesses in the loop.
580   void print(raw_ostream &OS, unsigned Depth = 0) const;
581
582   /// \brief Used to ensure that if the analysis was run with speculating the
583   /// value of symbolic strides, the client queries it with the same assumption.
584   /// Only used in DEBUG build but we don't want NDEBUG-dependent ABI.
585   unsigned NumSymbolicStrides;
586
587   /// \brief Checks existence of store to invariant address inside loop.
588   /// If the loop has any store to invariant address, then it returns true,
589   /// else returns false.
590   bool hasStoreToLoopInvariantAddress() const {
591     return StoreToLoopInvariantAddress;
592   }
593
594   /// The SCEV predicate contains all the SCEV-related assumptions.
595   /// The is used to keep track of the minimal set of assumptions on SCEV
596   /// expressions that the analysis needs to make in order to return a
597   /// meaningful result. All SCEV expressions during the analysis should be
598   /// re-written (and therefore simplified) according to Preds.
599   /// A user of LoopAccessAnalysis will need to emit the runtime checks
600   /// associated with this predicate.
601   SCEVUnionPredicate Preds;
602
603 private:
604   /// \brief Analyze the loop.  Substitute symbolic strides using Strides.
605   void analyzeLoop(const ValueToValueMap &Strides);
606
607   /// \brief Check if the structure of the loop allows it to be analyzed by this
608   /// pass.
609   bool canAnalyzeLoop();
610
611   void emitAnalysis(LoopAccessReport &Message);
612
613   /// We need to check that all of the pointers in this list are disjoint
614   /// at runtime.
615   RuntimePointerChecking PtrRtChecking;
616
617   /// \brief the Memory Dependence Checker which can determine the
618   /// loop-independent and loop-carried dependences between memory accesses.
619   MemoryDepChecker DepChecker;
620
621   Loop *TheLoop;
622   ScalarEvolution *SE;
623   const DataLayout &DL;
624   const TargetLibraryInfo *TLI;
625   AliasAnalysis *AA;
626   DominatorTree *DT;
627   LoopInfo *LI;
628
629   unsigned NumLoads;
630   unsigned NumStores;
631
632   unsigned MaxSafeDepDistBytes;
633
634   /// \brief Cache the result of analyzeLoop.
635   bool CanVecMem;
636
637   /// \brief Indicator for storing to uniform addresses.
638   /// If a loop has write to a loop invariant address then it should be true.
639   bool StoreToLoopInvariantAddress;
640
641   /// \brief The diagnostics report generated for the analysis.  E.g. why we
642   /// couldn't analyze the loop.
643   Optional<LoopAccessReport> Report;
644 };
645
646 Value *stripIntegerCast(Value *V);
647
648 ///\brief Return the SCEV corresponding to a pointer with the symbolic stride
649 /// replaced with constant one, assuming \p Preds is true.
650 ///
651 /// If necessary this method will version the stride of the pointer according
652 /// to \p PtrToStride and therefore add a new predicate to \p Preds.
653 ///
654 /// If \p OrigPtr is not null, use it to look up the stride value instead of \p
655 /// Ptr.  \p PtrToStride provides the mapping between the pointer value and its
656 /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
657 const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
658                                       const ValueToValueMap &PtrToStride,
659                                       SCEVUnionPredicate &Preds, Value *Ptr,
660                                       Value *OrigPtr = nullptr);
661
662 /// \brief Check the stride of the pointer and ensure that it does not wrap in
663 /// the address space, assuming \p Preds is true.
664 ///
665 /// If necessary this method will version the stride of the pointer according
666 /// to \p PtrToStride and therefore add a new predicate to \p Preds.
667 int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
668                  const ValueToValueMap &StridesMap, SCEVUnionPredicate &Preds);
669
670 /// \brief This analysis provides dependence information for the memory accesses
671 /// of a loop.
672 ///
673 /// It runs the analysis for a loop on demand.  This can be initiated by
674 /// querying the loop access info via LAA::getInfo.  getInfo return a
675 /// LoopAccessInfo object.  See this class for the specifics of what information
676 /// is provided.
677 class LoopAccessAnalysis : public FunctionPass {
678 public:
679   static char ID;
680
681   LoopAccessAnalysis() : FunctionPass(ID) {
682     initializeLoopAccessAnalysisPass(*PassRegistry::getPassRegistry());
683   }
684
685   bool runOnFunction(Function &F) override;
686
687   void getAnalysisUsage(AnalysisUsage &AU) const override;
688
689   /// \brief Query the result of the loop access information for the loop \p L.
690   ///
691   /// If the client speculates (and then issues run-time checks) for the values
692   /// of symbolic strides, \p Strides provides the mapping (see
693   /// replaceSymbolicStrideSCEV).  If there is no cached result available run
694   /// the analysis.
695   const LoopAccessInfo &getInfo(Loop *L, const ValueToValueMap &Strides);
696
697   void releaseMemory() override {
698     // Invalidate the cache when the pass is freed.
699     LoopAccessInfoMap.clear();
700   }
701
702   /// \brief Print the result of the analysis when invoked with -analyze.
703   void print(raw_ostream &OS, const Module *M = nullptr) const override;
704
705 private:
706   /// \brief The cache.
707   DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
708
709   // The used analysis passes.
710   ScalarEvolution *SE;
711   const TargetLibraryInfo *TLI;
712   AliasAnalysis *AA;
713   DominatorTree *DT;
714   LoopInfo *LI;
715 };
716
717 inline Instruction *MemoryDepChecker::Dependence::getSource(
718     const LoopAccessInfo &LAI) const {
719   return LAI.getDepChecker().getMemoryInstructions()[Source];
720 }
721
722 inline Instruction *MemoryDepChecker::Dependence::getDestination(
723     const LoopAccessInfo &LAI) const {
724   return LAI.getDepChecker().getMemoryInstructions()[Destination];
725 }
726
727 } // End llvm namespace
728
729 #endif