[LoopAccesses] Add missing const to APIs in VectorizationReport
[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 AliasAnalysis;
33 class ScalarEvolution;
34 class Loop;
35 class SCEV;
36
37 /// Optimization analysis message produced during vectorization. Messages inform
38 /// the user why vectorization did not occur.
39 class VectorizationReport {
40   std::string Message;
41   const Instruction *Instr;
42
43 public:
44   VectorizationReport(const Instruction *I = nullptr)
45       : Message("loop not vectorized: "), Instr(I) {}
46
47   template <typename A> VectorizationReport &operator<<(const A &Value) {
48     raw_string_ostream Out(Message);
49     Out << Value;
50     return *this;
51   }
52
53   const Instruction *getInstr() const { return Instr; }
54
55   std::string &str() { return Message; }
56   const std::string &str() const { return Message; }
57   operator Twine() { return Message; }
58
59   /// \brief Emit an analysis note for \p PassName with the debug location from
60   /// the instruction in \p Message if available.  Otherwise use the location of
61   /// \p TheLoop.
62   static void emitAnalysis(const VectorizationReport &Message,
63                            const Function *TheFunction,
64                            const Loop *TheLoop,
65                            const char *PassName);
66 };
67
68 /// \brief Collection of parameters shared beetween the Loop Vectorizer and the
69 /// Loop Access Analysis.
70 struct VectorizerParams {
71   /// \brief Maximum SIMD width.
72   static const unsigned MaxVectorWidth;
73
74   /// \brief VF as overridden by the user.
75   static unsigned VectorizationFactor;
76   /// \brief Interleave factor as overridden by the user.
77   static unsigned VectorizationInterleave;
78   /// \brief True if force-vector-interleave was specified by the user.
79   static bool isInterleaveForced();
80
81   /// \\brief When performing memory disambiguation checks at runtime do not
82   /// make more than this number of comparisons.
83   static const unsigned RuntimeMemoryCheckThreshold;
84 };
85
86 /// \brief Drive the analysis of memory accesses in the loop
87 ///
88 /// This class is responsible for analyzing the memory accesses of a loop.  It
89 /// collects the accesses and then its main helper the AccessAnalysis class
90 /// finds and categorizes the dependences in buildDependenceSets.
91 ///
92 /// For memory dependences that can be analyzed at compile time, it determines
93 /// whether the dependence is part of cycle inhibiting vectorization.  This work
94 /// is delegated to the MemoryDepChecker class.
95 ///
96 /// For memory dependences that cannot be determined at compile time, it
97 /// generates run-time checks to prove independence.  This is done by
98 /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
99 /// RuntimePointerCheck class.
100 class LoopAccessInfo {
101 public:
102   /// This struct holds information about the memory runtime legality check that
103   /// a group of pointers do not overlap.
104   struct RuntimePointerCheck {
105     RuntimePointerCheck() : Need(false) {}
106
107     /// Reset the state of the pointer runtime information.
108     void reset() {
109       Need = false;
110       Pointers.clear();
111       Starts.clear();
112       Ends.clear();
113       IsWritePtr.clear();
114       DependencySetId.clear();
115       AliasSetId.clear();
116     }
117
118     /// Insert a pointer and calculate the start and end SCEVs.
119     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
120                 unsigned DepSetId, unsigned ASId, ValueToValueMap &Strides);
121
122     /// \brief Decide whether we need to issue a run-time check for pointer at
123     /// index \p I and \p J to prove their independence.
124     bool needsChecking(unsigned I, unsigned J) const;
125
126     /// This flag indicates if we need to add the runtime check.
127     bool Need;
128     /// Holds the pointers that we need to check.
129     SmallVector<TrackingVH<Value>, 2> Pointers;
130     /// Holds the pointer value at the beginning of the loop.
131     SmallVector<const SCEV*, 2> Starts;
132     /// Holds the pointer value at the end of the loop.
133     SmallVector<const SCEV*, 2> Ends;
134     /// Holds the information if this pointer is used for writing to memory.
135     SmallVector<bool, 2> IsWritePtr;
136     /// Holds the id of the set of pointers that could be dependent because of a
137     /// shared underlying object.
138     SmallVector<unsigned, 2> DependencySetId;
139     /// Holds the id of the disjoint alias set to which this pointer belongs.
140     SmallVector<unsigned, 2> AliasSetId;
141   };
142
143   LoopAccessInfo(Loop *L, ScalarEvolution *SE, const DataLayout *DL,
144                  const TargetLibraryInfo *TLI, AliasAnalysis *AA,
145                  DominatorTree *DT, ValueToValueMap &Strides);
146
147   /// Return true we can analyze the memory accesses in the loop and there are
148   /// no memory dependence cycles.
149   bool canVectorizeMemory() { return CanVecMem; }
150
151   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
152
153   /// Return true if the block BB needs to be predicated in order for the loop
154   /// to be vectorized.
155   static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
156                                     DominatorTree *DT);
157
158   /// Returns true if the value V is uniform within the loop.
159   bool isUniform(Value *V);
160
161   unsigned getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
162   unsigned getNumStores() const { return NumStores; }
163   unsigned getNumLoads() const { return NumLoads;}
164
165   /// \brief Add code that checks at runtime if the accessed arrays overlap.
166   ///
167   /// Returns a pair of instructions where the first element is the first
168   /// instruction generated in possibly a sequence of instructions and the
169   /// second value is the final comparator value or NULL if no check is needed.
170   std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
171
172   /// \brief The diagnostics report generated for the analysis.  E.g. why we
173   /// couldn't analyze the loop.
174   Optional<VectorizationReport> &getReport() { return Report; }
175
176   /// \brief Used to ensure that if the analysis was run with speculating the
177   /// value of symbolic strides, the client queries it with the same assumption.
178   /// Only used in DEBUG build but we don't want NDEBUG-depedent ABI.
179   unsigned NumSymbolicStrides;
180
181 private:
182   /// \brief Analyze the loop.  Substitute symbolic strides using Strides.
183   void analyzeLoop(ValueToValueMap &Strides);
184
185   /// \brief Check if the structure of the loop allows it to be analyzed by this
186   /// pass.
187   bool canAnalyzeLoop();
188
189   void emitAnalysis(VectorizationReport &Message);
190
191   /// We need to check that all of the pointers in this list are disjoint
192   /// at runtime.
193   RuntimePointerCheck PtrRtCheck;
194   Loop *TheLoop;
195   ScalarEvolution *SE;
196   const DataLayout *DL;
197   const TargetLibraryInfo *TLI;
198   AliasAnalysis *AA;
199   DominatorTree *DT;
200
201   unsigned NumLoads;
202   unsigned NumStores;
203
204   unsigned MaxSafeDepDistBytes;
205
206   /// \brief Cache the result of analyzeLoop.
207   bool CanVecMem;
208
209   /// \brief The diagnostics report generated for the analysis.  E.g. why we
210   /// couldn't analyze the loop.
211   Optional<VectorizationReport> Report;
212 };
213
214 Value *stripIntegerCast(Value *V);
215
216 ///\brief Return the SCEV corresponding to a pointer with the symbolic stride
217 ///replaced with constant one.
218 ///
219 /// If \p OrigPtr is not null, use it to look up the stride value instead of \p
220 /// Ptr.  \p PtrToStride provides the mapping between the pointer value and its
221 /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
222 const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
223                                       ValueToValueMap &PtrToStride,
224                                       Value *Ptr, Value *OrigPtr = nullptr);
225
226 /// \brief This analysis provides dependence information for the memory accesses
227 /// of a loop.
228 ///
229 /// It runs the analysis for a loop on demand.  This can be initiated by
230 /// querying the loop access info via LAA::getInfo.  getInfo return a
231 /// LoopAccessInfo object.  See this class for the specifics of what information
232 /// is provided.
233 class LoopAccessAnalysis : public FunctionPass {
234 public:
235   static char ID;
236
237   LoopAccessAnalysis() : FunctionPass(ID) {
238     initializeLoopAccessAnalysisPass(*PassRegistry::getPassRegistry());
239   }
240
241   bool runOnFunction(Function &F) override;
242
243   void getAnalysisUsage(AnalysisUsage &AU) const override;
244
245   /// \brief Query the result of the loop access information for the loop \p L.
246   ///
247   /// If the client speculates (and then issues run-time checks) for the values
248   /// of symbolic strides, \p Strides provides the mapping (see
249   /// replaceSymbolicStrideSCEV).  If there is no cached result available run
250   /// the analysis.
251   LoopAccessInfo &getInfo(Loop *L, ValueToValueMap &Strides);
252
253   void releaseMemory() override {
254     // Invalidate the cache when the pass is freed.
255     LoopAccessInfoMap.clear();
256   }
257
258 private:
259   /// \brief The cache.
260   DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
261
262   // The used analysis passes.
263   ScalarEvolution *SE;
264   const DataLayout *DL;
265   const TargetLibraryInfo *TLI;
266   AliasAnalysis *AA;
267   DominatorTree *DT;
268 };
269 } // End llvm namespace
270
271 #endif