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