1 //===- llvm/Analysis/LoopAccessAnalysis.h -----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interface for the loop memory dependence framework that
11 // was originally developed for the Loop Vectorizer.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
16 #define LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
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"
33 class ScalarEvolution;
37 /// Optimization analysis message produced during vectorization. Messages inform
38 /// the user why vectorization did not occur.
39 class LoopAccessReport {
41 const Instruction *Instr;
44 LoopAccessReport(const Twine &Message, const Instruction *I)
45 : Message(Message.str()), Instr(I) {}
48 LoopAccessReport(const Instruction *I = nullptr) : Instr(I) {}
50 template <typename A> LoopAccessReport &operator<<(const A &Value) {
51 raw_string_ostream Out(Message);
56 const Instruction *getInstr() const { return Instr; }
58 std::string &str() { return Message; }
59 const std::string &str() const { return Message; }
60 operator Twine() { return Message; }
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
65 static void emitAnalysis(const LoopAccessReport &Message,
66 const Function *TheFunction,
68 const char *PassName);
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;
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();
84 /// \\brief When performing memory disambiguation checks at runtime do not
85 /// make more than this number of comparisons.
86 static unsigned RuntimeMemoryCheckThreshold;
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).
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.
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.
103 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
104 /// a[i] = tmp; y = a[i];
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).
113 /// * A positive constant distance assuming program order that is bigger
114 /// than the biggest memory access.
116 /// tmp = a[i] OR b[i] = x
117 /// a[i+2] = tmp y = b[i+2];
119 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
121 /// * Zero distances and all accesses have the same size.
123 class MemoryDepChecker {
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;
130 MemoryDepChecker(ScalarEvolution *Se, const Loop *L)
131 : SE(Se), InnermostLoop(L), AccessIdx(0),
132 ShouldRetryWithRuntimeCheck(false) {}
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);
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);
152 /// \brief Check whether the dependencies between the accesses are safe.
154 /// Only checks sets with elements in \p CheckDeps.
155 bool areDepsSafe(DepCandidates &AccessSets, MemAccessInfoSet &CheckDeps,
156 const ValueToValueMap &Strides);
158 /// \brief The maximum number of bytes of a vector register we can vectorize
159 /// the accesses safely with.
160 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
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; }
168 const Loop *InnermostLoop;
170 /// \brief Maps access locations (ptr, read/write) to program order.
171 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
173 /// \brief Memory access instructions in program order.
174 SmallVector<Instruction *, 16> InstMap;
176 /// \brief The program order index to be used for the next instruction.
179 // We can access this many bytes in parallel safely.
180 unsigned MaxSafeDepDistBytes;
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;
186 /// \brief Check whether there is a plausible dependence between the two
189 /// Access \p A must happen before \p B in program order. The two indices
190 /// identify the index into the program order map.
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);
202 /// \brief Check whether the data dependence could prevent store-load
204 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
207 /// \brief Drive the analysis of memory accesses in the loop
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.
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.
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 {
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) {}
228 /// Reset the state of the pointer runtime information.
235 DependencySetId.clear();
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);
244 /// \brief No run-time memory checking is necessary.
245 bool empty() const { return Pointers.empty(); }
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;
251 /// \brief Print the list run-time memory checks necessary.
252 void print(raw_ostream &OS, unsigned Depth = 0) const;
254 /// This flag indicates if we need to add the runtime check.
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;
271 LoopAccessInfo(Loop *L, ScalarEvolution *SE, const DataLayout &DL,
272 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
273 DominatorTree *DT, const ValueToValueMap &Strides);
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; }
279 const RuntimePointerCheck *getRuntimePointerCheck() const {
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,
288 /// Returns true if the value V is uniform within the loop.
289 bool isUniform(Value *V) const;
291 unsigned getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
292 unsigned getNumStores() const { return NumStores; }
293 unsigned getNumLoads() const { return NumLoads;}
295 /// \brief Add code that checks at runtime if the accessed arrays overlap.
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;
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; }
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; }
311 /// \brief Print the information about the memory accesses in the loop.
312 void print(raw_ostream &OS, unsigned Depth = 0) const;
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;
320 /// \brief Analyze the loop. Substitute symbolic strides using Strides.
321 void analyzeLoop(const ValueToValueMap &Strides);
323 /// \brief Check if the structure of the loop allows it to be analyzed by this
325 bool canAnalyzeLoop();
327 void emitAnalysis(LoopAccessReport &Message);
329 /// We need to check that all of the pointers in this list are disjoint
331 RuntimePointerCheck PtrRtCheck;
333 /// \brief the Memory Dependence Checker which can determine the
334 /// loop-independent and loop-carried dependences between memory accesses.
335 MemoryDepChecker DepChecker;
339 const DataLayout &DL;
340 const TargetLibraryInfo *TLI;
347 unsigned MaxSafeDepDistBytes;
349 /// \brief Cache the result of analyzeLoop.
352 /// \brief The diagnostics report generated for the analysis. E.g. why we
353 /// couldn't analyze the loop.
354 Optional<LoopAccessReport> Report;
357 Value *stripIntegerCast(Value *V);
359 ///\brief Return the SCEV corresponding to a pointer with the symbolic stride
360 ///replaced with constant one.
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);
369 /// \brief This analysis provides dependence information for the memory accesses
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
376 class LoopAccessAnalysis : public FunctionPass {
380 LoopAccessAnalysis() : FunctionPass(ID) {
381 initializeLoopAccessAnalysisPass(*PassRegistry::getPassRegistry());
384 bool runOnFunction(Function &F) override;
386 void getAnalysisUsage(AnalysisUsage &AU) const override;
388 /// \brief Query the result of the loop access information for the loop \p L.
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
394 const LoopAccessInfo &getInfo(Loop *L, const ValueToValueMap &Strides);
396 void releaseMemory() override {
397 // Invalidate the cache when the pass is freed.
398 LoopAccessInfoMap.clear();
401 /// \brief Print the result of the analysis when invoked with -analyze.
402 void print(raw_ostream &OS, const Module *M = nullptr) const override;
405 /// \brief The cache.
406 DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
408 // The used analysis passes.
410 const TargetLibraryInfo *TLI;
414 } // End llvm namespace