[LoopAccesses] Cache the result of canVectorizeMemory
[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/Support/raw_ostream.h"
26
27 namespace llvm {
28
29 class Value;
30 class DataLayout;
31 class AliasAnalysis;
32 class ScalarEvolution;
33 class Loop;
34 class SCEV;
35
36 /// Optimization analysis message produced during vectorization. Messages inform
37 /// the user why vectorization did not occur.
38 class VectorizationReport {
39   std::string Message;
40   Instruction *Instr;
41
42 public:
43   VectorizationReport(Instruction *I = nullptr)
44       : Message("loop not vectorized: "), Instr(I) {}
45
46   template <typename A> VectorizationReport &operator<<(const A &Value) {
47     raw_string_ostream Out(Message);
48     Out << Value;
49     return *this;
50   }
51
52   Instruction *getInstr() { return Instr; }
53
54   std::string &str() { return Message; }
55   operator Twine() { return Message; }
56
57   /// \brief Emit an analysis note with the debug location from the instruction
58   /// in \p Message if available.  Otherwise use the location of \p TheLoop.
59   static void emitAnalysis(VectorizationReport &Message,
60                            const Function *TheFunction,
61                            const Loop *TheLoop);
62 };
63
64 /// \brief Collection of parameters shared beetween the Loop Vectorizer and the
65 /// Loop Access Analysis.
66 struct VectorizerParams {
67   /// \brief Maximum SIMD width.
68   static const unsigned MaxVectorWidth;
69
70   /// \brief VF as overridden by the user.
71   static unsigned VectorizationFactor;
72   /// \brief Interleave factor as overridden by the user.
73   static unsigned VectorizationInterleave;
74   /// \brief True if force-vector-interleave was specified by the user.
75   static bool isInterleaveForced();
76
77   /// \\brief When performing memory disambiguation checks at runtime do not
78   /// make more than this number of comparisons.
79   static const unsigned RuntimeMemoryCheckThreshold;
80 };
81
82 /// \brief Drive the analysis of memory accesses in the loop
83 ///
84 /// This class is responsible for analyzing the memory accesses of a loop.  It
85 /// collects the accesses and then its main helper the AccessAnalysis class
86 /// finds and categorizes the dependences in buildDependenceSets.
87 ///
88 /// For memory dependences that can be analyzed at compile time, it determines
89 /// whether the dependence is part of cycle inhibiting vectorization.  This work
90 /// is delegated to the MemoryDepChecker class.
91 ///
92 /// For memory dependences that cannot be determined at compile time, it
93 /// generates run-time checks to prove independence.  This is done by
94 /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
95 /// RuntimePointerCheck class.
96 class LoopAccessInfo {
97 public:
98   /// This struct holds information about the memory runtime legality check that
99   /// a group of pointers do not overlap.
100   struct RuntimePointerCheck {
101     RuntimePointerCheck() : Need(false) {}
102
103     /// Reset the state of the pointer runtime information.
104     void reset() {
105       Need = false;
106       Pointers.clear();
107       Starts.clear();
108       Ends.clear();
109       IsWritePtr.clear();
110       DependencySetId.clear();
111       AliasSetId.clear();
112     }
113
114     /// Insert a pointer and calculate the start and end SCEVs.
115     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
116                 unsigned DepSetId, unsigned ASId, ValueToValueMap &Strides);
117
118     /// \brief Decide whether we need to issue a run-time check for pointer at
119     /// index \p I and \p J to prove their independence.
120     bool needsChecking(unsigned I, unsigned J) const;
121
122     /// This flag indicates if we need to add the runtime check.
123     bool Need;
124     /// Holds the pointers that we need to check.
125     SmallVector<TrackingVH<Value>, 2> Pointers;
126     /// Holds the pointer value at the beginning of the loop.
127     SmallVector<const SCEV*, 2> Starts;
128     /// Holds the pointer value at the end of the loop.
129     SmallVector<const SCEV*, 2> Ends;
130     /// Holds the information if this pointer is used for writing to memory.
131     SmallVector<bool, 2> IsWritePtr;
132     /// Holds the id of the set of pointers that could be dependent because of a
133     /// shared underlying object.
134     SmallVector<unsigned, 2> DependencySetId;
135     /// Holds the id of the disjoint alias set to which this pointer belongs.
136     SmallVector<unsigned, 2> AliasSetId;
137   };
138
139   LoopAccessInfo(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
140                  const TargetLibraryInfo *TLI, AliasAnalysis *AA,
141                  DominatorTree *DT) :
142       TheLoop(L), SE(SE), DL(DL), TLI(TLI), AA(AA), DT(DT), NumLoads(0),
143       NumStores(0), MaxSafeDepDistBytes(-1U), CanVecMem(false) {}
144
145   /// \brief Analyze the loop.  Replaces symbolic strides using Strides.
146   void analyzeLoop(ValueToValueMap &Strides);
147
148   /// Return true we can analyze the memory accesses in the loop and there are
149   /// no memory dependence cycles.
150   bool canVectorizeMemory() { return CanVecMem; }
151
152   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
153
154   /// Return true if the block BB needs to be predicated in order for the loop
155   /// to be vectorized.
156   static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
157                                     DominatorTree *DT);
158
159   /// Returns true if the value V is uniform within the loop.
160   bool isUniform(Value *V);
161
162   unsigned getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
163   unsigned getNumStores() const { return NumStores; }
164   unsigned getNumLoads() const { return NumLoads;}
165
166   /// \brief Add code that checks at runtime if the accessed arrays overlap.
167   ///
168   /// Returns a pair of instructions where the first element is the first
169   /// instruction generated in possibly a sequence of instructions and the
170   /// second value is the final comparator value or NULL if no check is needed.
171   std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
172
173   /// \brief The diagnostics report generated for the analysis.  E.g. why we
174   /// couldn't analyze the loop.
175   Optional<VectorizationReport> &getReport() { return Report; }
176
177 private:
178   void emitAnalysis(VectorizationReport &Message);
179
180   /// We need to check that all of the pointers in this list are disjoint
181   /// at runtime.
182   RuntimePointerCheck PtrRtCheck;
183   Loop *TheLoop;
184   ScalarEvolution *SE;
185   const DataLayout *DL;
186   const TargetLibraryInfo *TLI;
187   AliasAnalysis *AA;
188   DominatorTree *DT;
189
190   unsigned NumLoads;
191   unsigned NumStores;
192
193   unsigned MaxSafeDepDistBytes;
194
195   /// \brief Cache the result of analyzeLoop.
196   bool CanVecMem;
197
198   /// \brief The diagnostics report generated for the analysis.  E.g. why we
199   /// couldn't analyze the loop.
200   Optional<VectorizationReport> Report;
201 };
202
203 Value *stripIntegerCast(Value *V);
204
205 ///\brief Return the SCEV corresponding to a pointer with the symbolic stride
206 ///replaced with constant one.
207 ///
208 /// If \p OrigPtr is not null, use it to look up the stride value instead of \p
209 /// Ptr.  \p PtrToStride provides the mapping between the pointer value and its
210 /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
211 const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
212                                       ValueToValueMap &PtrToStride,
213                                       Value *Ptr, Value *OrigPtr = nullptr);
214
215 } // End llvm namespace
216
217 #endif