9d9b48d6f1abe3def5d1d983b76298cd98eded03
[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 unsigned RuntimeMemoryCheckThreshold;
87 };
88
89 /// \brief Checks memory dependences among accesses to the same underlying
90 /// object to determine whether there vectorization is legal or not (and at
91 /// which vectorization factor).
92 ///
93 /// Note: This class will compute a conservative dependence for access to
94 /// different underlying pointers. Clients, such as the loop vectorizer, will
95 /// sometimes deal these potential dependencies by emitting runtime checks.
96 ///
97 /// We use the ScalarEvolution framework to symbolically evalutate access
98 /// functions pairs. Since we currently don't restructure the loop we can rely
99 /// on the program order of memory accesses to determine their safety.
100 /// At the moment we will only deem accesses as safe for:
101 ///  * A negative constant distance assuming program order.
102 ///
103 ///      Safe: tmp = a[i + 1];     OR     a[i + 1] = x;
104 ///            a[i] = tmp;                y = a[i];
105 ///
106 ///   The latter case is safe because later checks guarantuee that there can't
107 ///   be a cycle through a phi node (that is, we check that "x" and "y" is not
108 ///   the same variable: a header phi can only be an induction or a reduction, a
109 ///   reduction can't have a memory sink, an induction can't have a memory
110 ///   source). This is important and must not be violated (or we have to
111 ///   resort to checking for cycles through memory).
112 ///
113 ///  * A positive constant distance assuming program order that is bigger
114 ///    than the biggest memory access.
115 ///
116 ///     tmp = a[i]        OR              b[i] = x
117 ///     a[i+2] = tmp                      y = b[i+2];
118 ///
119 ///     Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
120 ///
121 ///  * Zero distances and all accesses have the same size.
122 ///
123 class MemoryDepChecker {
124 public:
125   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
126   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
127   /// \brief Set of potential dependent memory accesses.
128   typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
129
130   MemoryDepChecker(ScalarEvolution *Se, const Loop *L)
131       : SE(Se), InnermostLoop(L), AccessIdx(0),
132         ShouldRetryWithRuntimeCheck(false) {}
133
134   /// \brief Register the location (instructions are given increasing numbers)
135   /// of a write access.
136   void addAccess(StoreInst *SI) {
137     Value *Ptr = SI->getPointerOperand();
138     Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
139     InstMap.push_back(SI);
140     ++AccessIdx;
141   }
142
143   /// \brief Register the location (instructions are given increasing numbers)
144   /// of a write access.
145   void addAccess(LoadInst *LI) {
146     Value *Ptr = LI->getPointerOperand();
147     Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
148     InstMap.push_back(LI);
149     ++AccessIdx;
150   }
151
152   /// \brief Check whether the dependencies between the accesses are safe.
153   ///
154   /// Only checks sets with elements in \p CheckDeps.
155   bool areDepsSafe(DepCandidates &AccessSets, MemAccessInfoSet &CheckDeps,
156                    const ValueToValueMap &Strides);
157
158   /// \brief The maximum number of bytes of a vector register we can vectorize
159   /// the accesses safely with.
160   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
161
162   /// \brief In same cases when the dependency check fails we can still
163   /// vectorize the loop with a dynamic array access check.
164   bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
165
166 private:
167   ScalarEvolution *SE;
168   const Loop *InnermostLoop;
169
170   /// \brief Maps access locations (ptr, read/write) to program order.
171   DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
172
173   /// \brief Memory access instructions in program order.
174   SmallVector<Instruction *, 16> InstMap;
175
176   /// \brief The program order index to be used for the next instruction.
177   unsigned AccessIdx;
178
179   // We can access this many bytes in parallel safely.
180   unsigned MaxSafeDepDistBytes;
181
182   /// \brief If we see a non-constant dependence distance we can still try to
183   /// vectorize this loop with runtime checks.
184   bool ShouldRetryWithRuntimeCheck;
185
186   /// \brief Check whether there is a plausible dependence between the two
187   /// accesses.
188   ///
189   /// Access \p A must happen before \p B in program order. The two indices
190   /// identify the index into the program order map.
191   ///
192   /// This function checks  whether there is a plausible dependence (or the
193   /// absence of such can't be proved) between the two accesses. If there is a
194   /// plausible dependence but the dependence distance is bigger than one
195   /// element access it records this distance in \p MaxSafeDepDistBytes (if this
196   /// distance is smaller than any other distance encountered so far).
197   /// Otherwise, this function returns true signaling a possible dependence.
198   bool isDependent(const MemAccessInfo &A, unsigned AIdx,
199                    const MemAccessInfo &B, unsigned BIdx,
200                    const ValueToValueMap &Strides);
201
202   /// \brief Check whether the data dependence could prevent store-load
203   /// forwarding.
204   bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
205 };
206
207 /// \brief Drive the analysis of memory accesses in the loop
208 ///
209 /// This class is responsible for analyzing the memory accesses of a loop.  It
210 /// collects the accesses and then its main helper the AccessAnalysis class
211 /// finds and categorizes the dependences in buildDependenceSets.
212 ///
213 /// For memory dependences that can be analyzed at compile time, it determines
214 /// whether the dependence is part of cycle inhibiting vectorization.  This work
215 /// is delegated to the MemoryDepChecker class.
216 ///
217 /// For memory dependences that cannot be determined at compile time, it
218 /// generates run-time checks to prove independence.  This is done by
219 /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
220 /// RuntimePointerCheck class.
221 class LoopAccessInfo {
222 public:
223   /// This struct holds information about the memory runtime legality check that
224   /// a group of pointers do not overlap.
225   struct RuntimePointerCheck {
226     RuntimePointerCheck() : Need(false) {}
227
228     /// Reset the state of the pointer runtime information.
229     void reset() {
230       Need = false;
231       Pointers.clear();
232       Starts.clear();
233       Ends.clear();
234       IsWritePtr.clear();
235       DependencySetId.clear();
236       AliasSetId.clear();
237     }
238
239     /// Insert a pointer and calculate the start and end SCEVs.
240     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
241                 unsigned DepSetId, unsigned ASId,
242                 const ValueToValueMap &Strides);
243
244     /// \brief No run-time memory checking is necessary.
245     bool empty() const { return Pointers.empty(); }
246
247     /// \brief Decide whether we need to issue a run-time check for pointer at
248     /// index \p I and \p J to prove their independence.
249     bool needsChecking(unsigned I, unsigned J) const;
250
251     /// \brief Print the list run-time memory checks necessary.
252     void print(raw_ostream &OS, unsigned Depth = 0) const;
253
254     /// This flag indicates if we need to add the runtime check.
255     bool Need;
256     /// Holds the pointers that we need to check.
257     SmallVector<TrackingVH<Value>, 2> Pointers;
258     /// Holds the pointer value at the beginning of the loop.
259     SmallVector<const SCEV*, 2> Starts;
260     /// Holds the pointer value at the end of the loop.
261     SmallVector<const SCEV*, 2> Ends;
262     /// Holds the information if this pointer is used for writing to memory.
263     SmallVector<bool, 2> IsWritePtr;
264     /// Holds the id of the set of pointers that could be dependent because of a
265     /// shared underlying object.
266     SmallVector<unsigned, 2> DependencySetId;
267     /// Holds the id of the disjoint alias set to which this pointer belongs.
268     SmallVector<unsigned, 2> AliasSetId;
269   };
270
271   LoopAccessInfo(Loop *L, ScalarEvolution *SE, const DataLayout &DL,
272                  const TargetLibraryInfo *TLI, AliasAnalysis *AA,
273                  DominatorTree *DT, const ValueToValueMap &Strides);
274
275   /// Return true we can analyze the memory accesses in the loop and there are
276   /// no memory dependence cycles.
277   bool canVectorizeMemory() const { return CanVecMem; }
278
279   const RuntimePointerCheck *getRuntimePointerCheck() const {
280     return &PtrRtCheck;
281   }
282
283   /// Return true if the block BB needs to be predicated in order for the loop
284   /// to be vectorized.
285   static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
286                                     DominatorTree *DT);
287
288   /// Returns true if the value V is uniform within the loop.
289   bool isUniform(Value *V) const;
290
291   unsigned getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
292   unsigned getNumStores() const { return NumStores; }
293   unsigned getNumLoads() const { return NumLoads;}
294
295   /// \brief Add code that checks at runtime if the accessed arrays overlap.
296   ///
297   /// Returns a pair of instructions where the first element is the first
298   /// instruction generated in possibly a sequence of instructions and the
299   /// second value is the final comparator value or NULL if no check is needed.
300   std::pair<Instruction *, Instruction *>
301     addRuntimeCheck(Instruction *Loc) const;
302
303   /// \brief The diagnostics report generated for the analysis.  E.g. why we
304   /// couldn't analyze the loop.
305   const Optional<LoopAccessReport> &getReport() const { return Report; }
306
307   /// \brief the Memory Dependence Checker which can determine the
308   /// loop-independent and loop-carried dependences between memory accesses.
309   const MemoryDepChecker &getDepChecker() const { return DepChecker; }
310
311   /// \brief Print the information about the memory accesses in the loop.
312   void print(raw_ostream &OS, unsigned Depth = 0) const;
313
314   /// \brief Used to ensure that if the analysis was run with speculating the
315   /// value of symbolic strides, the client queries it with the same assumption.
316   /// Only used in DEBUG build but we don't want NDEBUG-dependent ABI.
317   unsigned NumSymbolicStrides;
318
319 private:
320   /// \brief Analyze the loop.  Substitute symbolic strides using Strides.
321   void analyzeLoop(const ValueToValueMap &Strides);
322
323   /// \brief Check if the structure of the loop allows it to be analyzed by this
324   /// pass.
325   bool canAnalyzeLoop();
326
327   void emitAnalysis(LoopAccessReport &Message);
328
329   /// We need to check that all of the pointers in this list are disjoint
330   /// at runtime.
331   RuntimePointerCheck PtrRtCheck;
332
333   /// \brief the Memory Dependence Checker which can determine the
334   /// loop-independent and loop-carried dependences between memory accesses.
335   MemoryDepChecker DepChecker;
336
337   Loop *TheLoop;
338   ScalarEvolution *SE;
339   const DataLayout &DL;
340   const TargetLibraryInfo *TLI;
341   AliasAnalysis *AA;
342   DominatorTree *DT;
343
344   unsigned NumLoads;
345   unsigned NumStores;
346
347   unsigned MaxSafeDepDistBytes;
348
349   /// \brief Cache the result of analyzeLoop.
350   bool CanVecMem;
351
352   /// \brief The diagnostics report generated for the analysis.  E.g. why we
353   /// couldn't analyze the loop.
354   Optional<LoopAccessReport> Report;
355 };
356
357 Value *stripIntegerCast(Value *V);
358
359 ///\brief Return the SCEV corresponding to a pointer with the symbolic stride
360 ///replaced with constant one.
361 ///
362 /// If \p OrigPtr is not null, use it to look up the stride value instead of \p
363 /// Ptr.  \p PtrToStride provides the mapping between the pointer value and its
364 /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
365 const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
366                                       const ValueToValueMap &PtrToStride,
367                                       Value *Ptr, Value *OrigPtr = nullptr);
368
369 /// \brief This analysis provides dependence information for the memory accesses
370 /// of a loop.
371 ///
372 /// It runs the analysis for a loop on demand.  This can be initiated by
373 /// querying the loop access info via LAA::getInfo.  getInfo return a
374 /// LoopAccessInfo object.  See this class for the specifics of what information
375 /// is provided.
376 class LoopAccessAnalysis : public FunctionPass {
377 public:
378   static char ID;
379
380   LoopAccessAnalysis() : FunctionPass(ID) {
381     initializeLoopAccessAnalysisPass(*PassRegistry::getPassRegistry());
382   }
383
384   bool runOnFunction(Function &F) override;
385
386   void getAnalysisUsage(AnalysisUsage &AU) const override;
387
388   /// \brief Query the result of the loop access information for the loop \p L.
389   ///
390   /// If the client speculates (and then issues run-time checks) for the values
391   /// of symbolic strides, \p Strides provides the mapping (see
392   /// replaceSymbolicStrideSCEV).  If there is no cached result available run
393   /// the analysis.
394   const LoopAccessInfo &getInfo(Loop *L, const ValueToValueMap &Strides);
395
396   void releaseMemory() override {
397     // Invalidate the cache when the pass is freed.
398     LoopAccessInfoMap.clear();
399   }
400
401   /// \brief Print the result of the analysis when invoked with -analyze.
402   void print(raw_ostream &OS, const Module *M = nullptr) const override;
403
404 private:
405   /// \brief The cache.
406   DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
407
408   // The used analysis passes.
409   ScalarEvolution *SE;
410   const TargetLibraryInfo *TLI;
411   AliasAnalysis *AA;
412   DominatorTree *DT;
413 };
414 } // End llvm namespace
415
416 #endif