[LoopAccesses 2/3] Allow querying of interesting dependences
[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   /// \brief Dependece between memory access instructions.
131   struct Dependence {
132     /// \brief The type of the dependence.
133     enum DepType {
134       // No dependence.
135       NoDep,
136       // We couldn't determine the direction or the distance.
137       Unknown,
138       // Lexically forward.
139       Forward,
140       // Forward, but if vectorized, is likely to prevent store-to-load
141       // forwarding.
142       ForwardButPreventsForwarding,
143       // Lexically backward.
144       Backward,
145       // Backward, but the distance allows a vectorization factor of
146       // MaxSafeDepDistBytes.
147       BackwardVectorizable,
148       // Same, but may prevent store-to-load forwarding.
149       BackwardVectorizableButPreventsForwarding
150     };
151
152     /// \brief Index of the source of the dependence in the InstMap vector.
153     unsigned Source;
154     /// \brief Index of the destination of the dependence in the InstMap vector.
155     unsigned Destination;
156     /// \brief The type of the dependence.
157     DepType Type;
158
159     Dependence(unsigned Source, unsigned Destination, DepType Type)
160         : Source(Source), Destination(Destination), Type(Type) {}
161
162     /// \brief Dependence types that don't prevent vectorization.
163     static bool isSafeForVectorization(DepType Type);
164
165     /// \brief Dependence types that can be queried from the analysis.
166     static bool isInterestingDependence(DepType Type);
167
168     /// \brief Lexically backward dependence types.
169     bool isPossiblyBackward() const;
170   };
171
172   MemoryDepChecker(ScalarEvolution *Se, const Loop *L)
173       : SE(Se), InnermostLoop(L), AccessIdx(0),
174         ShouldRetryWithRuntimeCheck(false), SafeForVectorization(true),
175         RecordInterestingDependences(true) {}
176
177   /// \brief Register the location (instructions are given increasing numbers)
178   /// of a write access.
179   void addAccess(StoreInst *SI) {
180     Value *Ptr = SI->getPointerOperand();
181     Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
182     InstMap.push_back(SI);
183     ++AccessIdx;
184   }
185
186   /// \brief Register the location (instructions are given increasing numbers)
187   /// of a write access.
188   void addAccess(LoadInst *LI) {
189     Value *Ptr = LI->getPointerOperand();
190     Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
191     InstMap.push_back(LI);
192     ++AccessIdx;
193   }
194
195   /// \brief Check whether the dependencies between the accesses are safe.
196   ///
197   /// Only checks sets with elements in \p CheckDeps.
198   bool areDepsSafe(DepCandidates &AccessSets, MemAccessInfoSet &CheckDeps,
199                    const ValueToValueMap &Strides);
200
201   /// \brief No memory dependence was encountered that would inhibit
202   /// vectorization.
203   bool isSafeForVectorization() const { return SafeForVectorization; }
204
205   /// \brief The maximum number of bytes of a vector register we can vectorize
206   /// the accesses safely with.
207   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
208
209   /// \brief In same cases when the dependency check fails we can still
210   /// vectorize the loop with a dynamic array access check.
211   bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
212
213   /// \brief Returns the interesting dependences.  If null is returned we
214   /// exceeded the MaxInterestingDependence threshold and this information is
215   /// not available.
216   const SmallVectorImpl<Dependence> *getInterestingDependences() const {
217     return RecordInterestingDependences ? &InterestingDependences : nullptr;
218   }
219
220   /// \brief The vector of memory access instructions.  The indices are used as
221   /// instruction identifiers in the Dependence class.
222   const SmallVectorImpl<Instruction *> &getMemoryInstructions() const {
223     return InstMap;
224   }
225
226 private:
227   ScalarEvolution *SE;
228   const Loop *InnermostLoop;
229
230   /// \brief Maps access locations (ptr, read/write) to program order.
231   DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
232
233   /// \brief Memory access instructions in program order.
234   SmallVector<Instruction *, 16> InstMap;
235
236   /// \brief The program order index to be used for the next instruction.
237   unsigned AccessIdx;
238
239   // We can access this many bytes in parallel safely.
240   unsigned MaxSafeDepDistBytes;
241
242   /// \brief If we see a non-constant dependence distance we can still try to
243   /// vectorize this loop with runtime checks.
244   bool ShouldRetryWithRuntimeCheck;
245
246   /// \brief No memory dependence was encountered that would inhibit
247   /// vectorization.
248   bool SafeForVectorization;
249
250   //// \brief True if InterestingDependences reflects the dependences in the
251   //// loop.  If false we exceeded MaxInterestingDependence and
252   //// InterestingDependences is invalid.
253   bool RecordInterestingDependences;
254
255   /// \brief Interesting memory dependences collected during the analysis as
256   /// defined by isInterestingDependence.  Only valid if
257   /// RecordInterestingDependences is true.
258   SmallVector<Dependence, 8> InterestingDependences;
259
260   /// \brief Check whether there is a plausible dependence between the two
261   /// accesses.
262   ///
263   /// Access \p A must happen before \p B in program order. The two indices
264   /// identify the index into the program order map.
265   ///
266   /// This function checks  whether there is a plausible dependence (or the
267   /// absence of such can't be proved) between the two accesses. If there is a
268   /// plausible dependence but the dependence distance is bigger than one
269   /// element access it records this distance in \p MaxSafeDepDistBytes (if this
270   /// distance is smaller than any other distance encountered so far).
271   /// Otherwise, this function returns true signaling a possible dependence.
272   Dependence::DepType isDependent(const MemAccessInfo &A, unsigned AIdx,
273                                   const MemAccessInfo &B, unsigned BIdx,
274                                   const ValueToValueMap &Strides);
275
276   /// \brief Check whether the data dependence could prevent store-load
277   /// forwarding.
278   bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
279 };
280
281 /// \brief Drive the analysis of memory accesses in the loop
282 ///
283 /// This class is responsible for analyzing the memory accesses of a loop.  It
284 /// collects the accesses and then its main helper the AccessAnalysis class
285 /// finds and categorizes the dependences in buildDependenceSets.
286 ///
287 /// For memory dependences that can be analyzed at compile time, it determines
288 /// whether the dependence is part of cycle inhibiting vectorization.  This work
289 /// is delegated to the MemoryDepChecker class.
290 ///
291 /// For memory dependences that cannot be determined at compile time, it
292 /// generates run-time checks to prove independence.  This is done by
293 /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
294 /// RuntimePointerCheck class.
295 class LoopAccessInfo {
296 public:
297   /// This struct holds information about the memory runtime legality check that
298   /// a group of pointers do not overlap.
299   struct RuntimePointerCheck {
300     RuntimePointerCheck() : Need(false) {}
301
302     /// Reset the state of the pointer runtime information.
303     void reset() {
304       Need = false;
305       Pointers.clear();
306       Starts.clear();
307       Ends.clear();
308       IsWritePtr.clear();
309       DependencySetId.clear();
310       AliasSetId.clear();
311     }
312
313     /// Insert a pointer and calculate the start and end SCEVs.
314     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
315                 unsigned DepSetId, unsigned ASId,
316                 const ValueToValueMap &Strides);
317
318     /// \brief No run-time memory checking is necessary.
319     bool empty() const { return Pointers.empty(); }
320
321     /// \brief Decide whether we need to issue a run-time check for pointer at
322     /// index \p I and \p J to prove their independence.
323     bool needsChecking(unsigned I, unsigned J) const;
324
325     /// \brief Print the list run-time memory checks necessary.
326     void print(raw_ostream &OS, unsigned Depth = 0) const;
327
328     /// This flag indicates if we need to add the runtime check.
329     bool Need;
330     /// Holds the pointers that we need to check.
331     SmallVector<TrackingVH<Value>, 2> Pointers;
332     /// Holds the pointer value at the beginning of the loop.
333     SmallVector<const SCEV*, 2> Starts;
334     /// Holds the pointer value at the end of the loop.
335     SmallVector<const SCEV*, 2> Ends;
336     /// Holds the information if this pointer is used for writing to memory.
337     SmallVector<bool, 2> IsWritePtr;
338     /// Holds the id of the set of pointers that could be dependent because of a
339     /// shared underlying object.
340     SmallVector<unsigned, 2> DependencySetId;
341     /// Holds the id of the disjoint alias set to which this pointer belongs.
342     SmallVector<unsigned, 2> AliasSetId;
343   };
344
345   LoopAccessInfo(Loop *L, ScalarEvolution *SE, const DataLayout &DL,
346                  const TargetLibraryInfo *TLI, AliasAnalysis *AA,
347                  DominatorTree *DT, const ValueToValueMap &Strides);
348
349   /// Return true we can analyze the memory accesses in the loop and there are
350   /// no memory dependence cycles.
351   bool canVectorizeMemory() const { return CanVecMem; }
352
353   const RuntimePointerCheck *getRuntimePointerCheck() const {
354     return &PtrRtCheck;
355   }
356
357   /// Return true if the block BB needs to be predicated in order for the loop
358   /// to be vectorized.
359   static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
360                                     DominatorTree *DT);
361
362   /// Returns true if the value V is uniform within the loop.
363   bool isUniform(Value *V) const;
364
365   unsigned getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
366   unsigned getNumStores() const { return NumStores; }
367   unsigned getNumLoads() const { return NumLoads;}
368
369   /// \brief Add code that checks at runtime if the accessed arrays overlap.
370   ///
371   /// Returns a pair of instructions where the first element is the first
372   /// instruction generated in possibly a sequence of instructions and the
373   /// second value is the final comparator value or NULL if no check is needed.
374   std::pair<Instruction *, Instruction *>
375     addRuntimeCheck(Instruction *Loc) const;
376
377   /// \brief The diagnostics report generated for the analysis.  E.g. why we
378   /// couldn't analyze the loop.
379   const Optional<LoopAccessReport> &getReport() const { return Report; }
380
381   /// \brief the Memory Dependence Checker which can determine the
382   /// loop-independent and loop-carried dependences between memory accesses.
383   const MemoryDepChecker &getDepChecker() const { return DepChecker; }
384
385   /// \brief Print the information about the memory accesses in the loop.
386   void print(raw_ostream &OS, unsigned Depth = 0) const;
387
388   /// \brief Used to ensure that if the analysis was run with speculating the
389   /// value of symbolic strides, the client queries it with the same assumption.
390   /// Only used in DEBUG build but we don't want NDEBUG-dependent ABI.
391   unsigned NumSymbolicStrides;
392
393 private:
394   /// \brief Analyze the loop.  Substitute symbolic strides using Strides.
395   void analyzeLoop(const ValueToValueMap &Strides);
396
397   /// \brief Check if the structure of the loop allows it to be analyzed by this
398   /// pass.
399   bool canAnalyzeLoop();
400
401   void emitAnalysis(LoopAccessReport &Message);
402
403   /// We need to check that all of the pointers in this list are disjoint
404   /// at runtime.
405   RuntimePointerCheck PtrRtCheck;
406
407   /// \brief the Memory Dependence Checker which can determine the
408   /// loop-independent and loop-carried dependences between memory accesses.
409   MemoryDepChecker DepChecker;
410
411   Loop *TheLoop;
412   ScalarEvolution *SE;
413   const DataLayout &DL;
414   const TargetLibraryInfo *TLI;
415   AliasAnalysis *AA;
416   DominatorTree *DT;
417
418   unsigned NumLoads;
419   unsigned NumStores;
420
421   unsigned MaxSafeDepDistBytes;
422
423   /// \brief Cache the result of analyzeLoop.
424   bool CanVecMem;
425
426   /// \brief The diagnostics report generated for the analysis.  E.g. why we
427   /// couldn't analyze the loop.
428   Optional<LoopAccessReport> Report;
429 };
430
431 Value *stripIntegerCast(Value *V);
432
433 ///\brief Return the SCEV corresponding to a pointer with the symbolic stride
434 ///replaced with constant one.
435 ///
436 /// If \p OrigPtr is not null, use it to look up the stride value instead of \p
437 /// Ptr.  \p PtrToStride provides the mapping between the pointer value and its
438 /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
439 const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
440                                       const ValueToValueMap &PtrToStride,
441                                       Value *Ptr, Value *OrigPtr = nullptr);
442
443 /// \brief This analysis provides dependence information for the memory accesses
444 /// of a loop.
445 ///
446 /// It runs the analysis for a loop on demand.  This can be initiated by
447 /// querying the loop access info via LAA::getInfo.  getInfo return a
448 /// LoopAccessInfo object.  See this class for the specifics of what information
449 /// is provided.
450 class LoopAccessAnalysis : public FunctionPass {
451 public:
452   static char ID;
453
454   LoopAccessAnalysis() : FunctionPass(ID) {
455     initializeLoopAccessAnalysisPass(*PassRegistry::getPassRegistry());
456   }
457
458   bool runOnFunction(Function &F) override;
459
460   void getAnalysisUsage(AnalysisUsage &AU) const override;
461
462   /// \brief Query the result of the loop access information for the loop \p L.
463   ///
464   /// If the client speculates (and then issues run-time checks) for the values
465   /// of symbolic strides, \p Strides provides the mapping (see
466   /// replaceSymbolicStrideSCEV).  If there is no cached result available run
467   /// the analysis.
468   const LoopAccessInfo &getInfo(Loop *L, const ValueToValueMap &Strides);
469
470   void releaseMemory() override {
471     // Invalidate the cache when the pass is freed.
472     LoopAccessInfoMap.clear();
473   }
474
475   /// \brief Print the result of the analysis when invoked with -analyze.
476   void print(raw_ostream &OS, const Module *M = nullptr) const override;
477
478 private:
479   /// \brief The cache.
480   DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
481
482   // The used analysis passes.
483   ScalarEvolution *SE;
484   const TargetLibraryInfo *TLI;
485   AliasAnalysis *AA;
486   DominatorTree *DT;
487 };
488 } // End llvm namespace
489
490 #endif