blob: fa34afaf9589ba73307147eb375b30602c65f260 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- llvm/Analysis/LoopAccessAnalysis.h -----------------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interface for the loop memory dependence framework that
10// was originally developed for the Loop Vectorizer.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
15#define LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
16
17#include "llvm/ADT/EquivalenceClasses.h"
18#include "llvm/ADT/Optional.h"
19#include "llvm/ADT/SetVector.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/Analysis/AliasSetTracker.h"
22#include "llvm/Analysis/LoopAnalysisManager.h"
23#include "llvm/Analysis/ScalarEvolutionExpressions.h"
24#include "llvm/IR/DiagnosticInfo.h"
25#include "llvm/IR/ValueHandle.h"
26#include "llvm/Pass.h"
27#include "llvm/Support/raw_ostream.h"
28
29namespace llvm {
30
31class Value;
32class DataLayout;
33class ScalarEvolution;
34class Loop;
35class SCEV;
36class SCEVUnionPredicate;
37class LoopAccessInfo;
38class OptimizationRemarkEmitter;
39
Andrew Scullcdfcccc2018-10-05 20:58:37 +010040/// Collection of parameters shared beetween the Loop Vectorizer and the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010041/// Loop Access Analysis.
42struct VectorizerParams {
Andrew Scullcdfcccc2018-10-05 20:58:37 +010043 /// Maximum SIMD width.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010044 static const unsigned MaxVectorWidth;
45
Andrew Scullcdfcccc2018-10-05 20:58:37 +010046 /// VF as overridden by the user.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010047 static unsigned VectorizationFactor;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010048 /// Interleave factor as overridden by the user.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010049 static unsigned VectorizationInterleave;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010050 /// True if force-vector-interleave was specified by the user.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010051 static bool isInterleaveForced();
52
Andrew Scullcdfcccc2018-10-05 20:58:37 +010053 /// \When performing memory disambiguation checks at runtime do not
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010054 /// make more than this number of comparisons.
55 static unsigned RuntimeMemoryCheckThreshold;
56};
57
Andrew Scullcdfcccc2018-10-05 20:58:37 +010058/// Checks memory dependences among accesses to the same underlying
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010059/// object to determine whether there vectorization is legal or not (and at
60/// which vectorization factor).
61///
62/// Note: This class will compute a conservative dependence for access to
63/// different underlying pointers. Clients, such as the loop vectorizer, will
64/// sometimes deal these potential dependencies by emitting runtime checks.
65///
66/// We use the ScalarEvolution framework to symbolically evalutate access
67/// functions pairs. Since we currently don't restructure the loop we can rely
68/// on the program order of memory accesses to determine their safety.
69/// At the moment we will only deem accesses as safe for:
70/// * A negative constant distance assuming program order.
71///
72/// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
73/// a[i] = tmp; y = a[i];
74///
75/// The latter case is safe because later checks guarantuee that there can't
76/// be a cycle through a phi node (that is, we check that "x" and "y" is not
77/// the same variable: a header phi can only be an induction or a reduction, a
78/// reduction can't have a memory sink, an induction can't have a memory
79/// source). This is important and must not be violated (or we have to
80/// resort to checking for cycles through memory).
81///
82/// * A positive constant distance assuming program order that is bigger
83/// than the biggest memory access.
84///
85/// tmp = a[i] OR b[i] = x
86/// a[i+2] = tmp y = b[i+2];
87///
88/// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
89///
90/// * Zero distances and all accesses have the same size.
91///
92class MemoryDepChecker {
93public:
94 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
95 typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010096 /// Set of potential dependent memory accesses.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010097 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
98
Andrew Walbran16937d02019-10-22 13:54:20 +010099 /// Type to keep track of the status of the dependence check. The order of
100 /// the elements is important and has to be from most permissive to least
101 /// permissive.
102 enum class VectorizationSafetyStatus {
103 // Can vectorize safely without RT checks. All dependences are known to be
104 // safe.
105 Safe,
106 // Can possibly vectorize with RT checks to overcome unknown dependencies.
107 PossiblySafeWithRtChecks,
108 // Cannot vectorize due to known unsafe dependencies.
109 Unsafe,
110 };
111
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100112 /// Dependece between memory access instructions.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100113 struct Dependence {
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100114 /// The type of the dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100115 enum DepType {
116 // No dependence.
117 NoDep,
118 // We couldn't determine the direction or the distance.
119 Unknown,
120 // Lexically forward.
121 //
122 // FIXME: If we only have loop-independent forward dependences (e.g. a
123 // read and write of A[i]), LAA will locally deem the dependence "safe"
124 // without querying the MemoryDepChecker. Therefore we can miss
125 // enumerating loop-independent forward dependences in
126 // getDependences. Note that as soon as there are different
127 // indices used to access the same array, the MemoryDepChecker *is*
128 // queried and the dependence list is complete.
129 Forward,
130 // Forward, but if vectorized, is likely to prevent store-to-load
131 // forwarding.
132 ForwardButPreventsForwarding,
133 // Lexically backward.
134 Backward,
135 // Backward, but the distance allows a vectorization factor of
136 // MaxSafeDepDistBytes.
137 BackwardVectorizable,
138 // Same, but may prevent store-to-load forwarding.
139 BackwardVectorizableButPreventsForwarding
140 };
141
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100142 /// String version of the types.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100143 static const char *DepName[];
144
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100145 /// Index of the source of the dependence in the InstMap vector.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100146 unsigned Source;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100147 /// Index of the destination of the dependence in the InstMap vector.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100148 unsigned Destination;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100149 /// The type of the dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100150 DepType Type;
151
152 Dependence(unsigned Source, unsigned Destination, DepType Type)
153 : Source(Source), Destination(Destination), Type(Type) {}
154
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100155 /// Return the source instruction of the dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100156 Instruction *getSource(const LoopAccessInfo &LAI) const;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100157 /// Return the destination instruction of the dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100158 Instruction *getDestination(const LoopAccessInfo &LAI) const;
159
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100160 /// Dependence types that don't prevent vectorization.
Andrew Walbran16937d02019-10-22 13:54:20 +0100161 static VectorizationSafetyStatus isSafeForVectorization(DepType Type);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100162
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100163 /// Lexically forward dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100164 bool isForward() const;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100165 /// Lexically backward dependence.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100166 bool isBackward() const;
167
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100168 /// May be a lexically backward dependence type (includes Unknown).
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100169 bool isPossiblyBackward() const;
170
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100171 /// Print the dependence. \p Instr is used to map the instruction
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100172 /// indices to instructions.
173 void print(raw_ostream &OS, unsigned Depth,
174 const SmallVectorImpl<Instruction *> &Instrs) const;
175 };
176
177 MemoryDepChecker(PredicatedScalarEvolution &PSE, const Loop *L)
178 : PSE(PSE), InnermostLoop(L), AccessIdx(0), MaxSafeRegisterWidth(-1U),
Andrew Walbran16937d02019-10-22 13:54:20 +0100179 FoundNonConstantDistanceDependence(false),
180 Status(VectorizationSafetyStatus::Safe), RecordDependences(true) {}
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100181
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100182 /// Register the location (instructions are given increasing numbers)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100183 /// of a write access.
184 void addAccess(StoreInst *SI) {
185 Value *Ptr = SI->getPointerOperand();
186 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
187 InstMap.push_back(SI);
188 ++AccessIdx;
189 }
190
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100191 /// Register the location (instructions are given increasing numbers)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100192 /// of a write access.
193 void addAccess(LoadInst *LI) {
194 Value *Ptr = LI->getPointerOperand();
195 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
196 InstMap.push_back(LI);
197 ++AccessIdx;
198 }
199
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100200 /// Check whether the dependencies between the accesses are safe.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100201 ///
202 /// Only checks sets with elements in \p CheckDeps.
203 bool areDepsSafe(DepCandidates &AccessSets, MemAccessInfoList &CheckDeps,
204 const ValueToValueMap &Strides);
205
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100206 /// No memory dependence was encountered that would inhibit
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100207 /// vectorization.
Andrew Walbran16937d02019-10-22 13:54:20 +0100208 bool isSafeForVectorization() const {
209 return Status == VectorizationSafetyStatus::Safe;
210 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100211
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100212 /// The maximum number of bytes of a vector register we can vectorize
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100213 /// the accesses safely with.
214 uint64_t getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
215
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100216 /// Return the number of elements that are safe to operate on
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100217 /// simultaneously, multiplied by the size of the element in bits.
218 uint64_t getMaxSafeRegisterWidth() const { return MaxSafeRegisterWidth; }
219
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100220 /// In same cases when the dependency check fails we can still
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100221 /// vectorize the loop with a dynamic array access check.
Andrew Walbran16937d02019-10-22 13:54:20 +0100222 bool shouldRetryWithRuntimeCheck() const {
223 return FoundNonConstantDistanceDependence &&
224 Status == VectorizationSafetyStatus::PossiblySafeWithRtChecks;
225 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100226
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100227 /// Returns the memory dependences. If null is returned we exceeded
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100228 /// the MaxDependences threshold and this information is not
229 /// available.
230 const SmallVectorImpl<Dependence> *getDependences() const {
231 return RecordDependences ? &Dependences : nullptr;
232 }
233
234 void clearDependences() { Dependences.clear(); }
235
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100236 /// The vector of memory access instructions. The indices are used as
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100237 /// instruction identifiers in the Dependence class.
238 const SmallVectorImpl<Instruction *> &getMemoryInstructions() const {
239 return InstMap;
240 }
241
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100242 /// Generate a mapping between the memory instructions and their
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100243 /// indices according to program order.
244 DenseMap<Instruction *, unsigned> generateInstructionOrderMap() const {
245 DenseMap<Instruction *, unsigned> OrderMap;
246
247 for (unsigned I = 0; I < InstMap.size(); ++I)
248 OrderMap[InstMap[I]] = I;
249
250 return OrderMap;
251 }
252
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100253 /// Find the set of instructions that read or write via \p Ptr.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100254 SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
255 bool isWrite) const;
256
257private:
258 /// A wrapper around ScalarEvolution, used to add runtime SCEV checks, and
259 /// applies dynamic knowledge to simplify SCEV expressions and convert them
260 /// to a more usable form. We need this in case assumptions about SCEV
261 /// expressions need to be made in order to avoid unknown dependences. For
262 /// example we might assume a unit stride for a pointer in order to prove
263 /// that a memory access is strided and doesn't wrap.
264 PredicatedScalarEvolution &PSE;
265 const Loop *InnermostLoop;
266
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100267 /// Maps access locations (ptr, read/write) to program order.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100268 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
269
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100270 /// Memory access instructions in program order.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100271 SmallVector<Instruction *, 16> InstMap;
272
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100273 /// The program order index to be used for the next instruction.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100274 unsigned AccessIdx;
275
276 // We can access this many bytes in parallel safely.
277 uint64_t MaxSafeDepDistBytes;
278
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100279 /// Number of elements (from consecutive iterations) that are safe to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100280 /// operate on simultaneously, multiplied by the size of the element in bits.
281 /// The size of the element is taken from the memory access that is most
282 /// restrictive.
283 uint64_t MaxSafeRegisterWidth;
284
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100285 /// If we see a non-constant dependence distance we can still try to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100286 /// vectorize this loop with runtime checks.
Andrew Walbran16937d02019-10-22 13:54:20 +0100287 bool FoundNonConstantDistanceDependence;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100288
Andrew Walbran16937d02019-10-22 13:54:20 +0100289 /// Result of the dependence checks, indicating whether the checked
290 /// dependences are safe for vectorization, require RT checks or are known to
291 /// be unsafe.
292 VectorizationSafetyStatus Status;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100293
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100294 //// True if Dependences reflects the dependences in the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100295 //// loop. If false we exceeded MaxDependences and
296 //// Dependences is invalid.
297 bool RecordDependences;
298
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100299 /// Memory dependences collected during the analysis. Only valid if
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100300 /// RecordDependences is true.
301 SmallVector<Dependence, 8> Dependences;
302
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100303 /// Check whether there is a plausible dependence between the two
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100304 /// accesses.
305 ///
306 /// Access \p A must happen before \p B in program order. The two indices
307 /// identify the index into the program order map.
308 ///
309 /// This function checks whether there is a plausible dependence (or the
310 /// absence of such can't be proved) between the two accesses. If there is a
311 /// plausible dependence but the dependence distance is bigger than one
312 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
313 /// distance is smaller than any other distance encountered so far).
314 /// Otherwise, this function returns true signaling a possible dependence.
315 Dependence::DepType isDependent(const MemAccessInfo &A, unsigned AIdx,
316 const MemAccessInfo &B, unsigned BIdx,
317 const ValueToValueMap &Strides);
318
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100319 /// Check whether the data dependence could prevent store-load
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100320 /// forwarding.
321 ///
322 /// \return false if we shouldn't vectorize at all or avoid larger
323 /// vectorization factors by limiting MaxSafeDepDistBytes.
324 bool couldPreventStoreLoadForward(uint64_t Distance, uint64_t TypeByteSize);
Andrew Walbran16937d02019-10-22 13:54:20 +0100325
326 /// Updates the current safety status with \p S. We can go from Safe to
327 /// either PossiblySafeWithRtChecks or Unsafe and from
328 /// PossiblySafeWithRtChecks to Unsafe.
329 void mergeInStatus(VectorizationSafetyStatus S);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100330};
331
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100332/// Holds information about the memory runtime legality checks to verify
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100333/// that a group of pointers do not overlap.
334class RuntimePointerChecking {
335public:
336 struct PointerInfo {
337 /// Holds the pointer value that we need to check.
338 TrackingVH<Value> PointerValue;
339 /// Holds the smallest byte address accessed by the pointer throughout all
340 /// iterations of the loop.
341 const SCEV *Start;
342 /// Holds the largest byte address accessed by the pointer throughout all
343 /// iterations of the loop, plus 1.
344 const SCEV *End;
345 /// Holds the information if this pointer is used for writing to memory.
346 bool IsWritePtr;
347 /// Holds the id of the set of pointers that could be dependent because of a
348 /// shared underlying object.
349 unsigned DependencySetId;
350 /// Holds the id of the disjoint alias set to which this pointer belongs.
351 unsigned AliasSetId;
352 /// SCEV for the access.
353 const SCEV *Expr;
354
355 PointerInfo(Value *PointerValue, const SCEV *Start, const SCEV *End,
356 bool IsWritePtr, unsigned DependencySetId, unsigned AliasSetId,
357 const SCEV *Expr)
358 : PointerValue(PointerValue), Start(Start), End(End),
359 IsWritePtr(IsWritePtr), DependencySetId(DependencySetId),
360 AliasSetId(AliasSetId), Expr(Expr) {}
361 };
362
363 RuntimePointerChecking(ScalarEvolution *SE) : Need(false), SE(SE) {}
364
365 /// Reset the state of the pointer runtime information.
366 void reset() {
367 Need = false;
368 Pointers.clear();
369 Checks.clear();
370 }
371
372 /// Insert a pointer and calculate the start and end SCEVs.
373 /// We need \p PSE in order to compute the SCEV expression of the pointer
374 /// according to the assumptions that we've made during the analysis.
375 /// The method might also version the pointer stride according to \p Strides,
376 /// and add new predicates to \p PSE.
377 void insert(Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
378 unsigned ASId, const ValueToValueMap &Strides,
379 PredicatedScalarEvolution &PSE);
380
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100381 /// No run-time memory checking is necessary.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100382 bool empty() const { return Pointers.empty(); }
383
384 /// A grouping of pointers. A single memcheck is required between
385 /// two groups.
386 struct CheckingPtrGroup {
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100387 /// Create a new pointer checking group containing a single
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100388 /// pointer, with index \p Index in RtCheck.
389 CheckingPtrGroup(unsigned Index, RuntimePointerChecking &RtCheck)
390 : RtCheck(RtCheck), High(RtCheck.Pointers[Index].End),
391 Low(RtCheck.Pointers[Index].Start) {
392 Members.push_back(Index);
393 }
394
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100395 /// Tries to add the pointer recorded in RtCheck at index
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100396 /// \p Index to this pointer checking group. We can only add a pointer
397 /// to a checking group if we will still be able to get
398 /// the upper and lower bounds of the check. Returns true in case
399 /// of success, false otherwise.
400 bool addPointer(unsigned Index);
401
402 /// Constitutes the context of this pointer checking group. For each
403 /// pointer that is a member of this group we will retain the index
404 /// at which it appears in RtCheck.
405 RuntimePointerChecking &RtCheck;
406 /// The SCEV expression which represents the upper bound of all the
407 /// pointers in this group.
408 const SCEV *High;
409 /// The SCEV expression which represents the lower bound of all the
410 /// pointers in this group.
411 const SCEV *Low;
412 /// Indices of all the pointers that constitute this grouping.
413 SmallVector<unsigned, 2> Members;
414 };
415
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100416 /// A memcheck which made up of a pair of grouped pointers.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100417 ///
418 /// These *have* to be const for now, since checks are generated from
419 /// CheckingPtrGroups in LAI::addRuntimeChecks which is a const member
420 /// function. FIXME: once check-generation is moved inside this class (after
421 /// the PtrPartition hack is removed), we could drop const.
422 typedef std::pair<const CheckingPtrGroup *, const CheckingPtrGroup *>
423 PointerCheck;
424
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100425 /// Generate the checks and store it. This also performs the grouping
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100426 /// of pointers to reduce the number of memchecks necessary.
427 void generateChecks(MemoryDepChecker::DepCandidates &DepCands,
428 bool UseDependencies);
429
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100430 /// Returns the checks that generateChecks created.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100431 const SmallVector<PointerCheck, 4> &getChecks() const { return Checks; }
432
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100433 /// Decide if we need to add a check between two groups of pointers,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100434 /// according to needsChecking.
435 bool needsChecking(const CheckingPtrGroup &M,
436 const CheckingPtrGroup &N) const;
437
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100438 /// Returns the number of run-time checks required according to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100439 /// needsChecking.
440 unsigned getNumberOfChecks() const { return Checks.size(); }
441
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100442 /// Print the list run-time memory checks necessary.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100443 void print(raw_ostream &OS, unsigned Depth = 0) const;
444
445 /// Print \p Checks.
446 void printChecks(raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
447 unsigned Depth = 0) const;
448
449 /// This flag indicates if we need to add the runtime check.
450 bool Need;
451
452 /// Information about the pointers that may require checking.
453 SmallVector<PointerInfo, 2> Pointers;
454
455 /// Holds a partitioning of pointers into "check groups".
456 SmallVector<CheckingPtrGroup, 2> CheckingGroups;
457
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100458 /// Check if pointers are in the same partition
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100459 ///
460 /// \p PtrToPartition contains the partition number for pointers (-1 if the
461 /// pointer belongs to multiple partitions).
462 static bool
463 arePointersInSamePartition(const SmallVectorImpl<int> &PtrToPartition,
464 unsigned PtrIdx1, unsigned PtrIdx2);
465
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100466 /// Decide whether we need to issue a run-time check for pointer at
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100467 /// index \p I and \p J to prove their independence.
468 bool needsChecking(unsigned I, unsigned J) const;
469
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100470 /// Return PointerInfo for pointer at index \p PtrIdx.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100471 const PointerInfo &getPointerInfo(unsigned PtrIdx) const {
472 return Pointers[PtrIdx];
473 }
474
475private:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100476 /// Groups pointers such that a single memcheck is required
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100477 /// between two different groups. This will clear the CheckingGroups vector
478 /// and re-compute it. We will only group dependecies if \p UseDependencies
479 /// is true, otherwise we will create a separate group for each pointer.
480 void groupChecks(MemoryDepChecker::DepCandidates &DepCands,
481 bool UseDependencies);
482
483 /// Generate the checks and return them.
484 SmallVector<PointerCheck, 4>
485 generateChecks() const;
486
487 /// Holds a pointer to the ScalarEvolution analysis.
488 ScalarEvolution *SE;
489
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100490 /// Set of run-time checks required to establish independence of
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100491 /// otherwise may-aliasing pointers in the loop.
492 SmallVector<PointerCheck, 4> Checks;
493};
494
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100495/// Drive the analysis of memory accesses in the loop
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100496///
497/// This class is responsible for analyzing the memory accesses of a loop. It
498/// collects the accesses and then its main helper the AccessAnalysis class
499/// finds and categorizes the dependences in buildDependenceSets.
500///
501/// For memory dependences that can be analyzed at compile time, it determines
502/// whether the dependence is part of cycle inhibiting vectorization. This work
503/// is delegated to the MemoryDepChecker class.
504///
505/// For memory dependences that cannot be determined at compile time, it
506/// generates run-time checks to prove independence. This is done by
507/// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
508/// RuntimePointerCheck class.
509///
510/// If pointers can wrap or can't be expressed as affine AddRec expressions by
511/// ScalarEvolution, we will generate run-time checks by emitting a
512/// SCEVUnionPredicate.
513///
514/// Checks for both memory dependences and the SCEV predicates contained in the
515/// PSE must be emitted in order for the results of this analysis to be valid.
516class LoopAccessInfo {
517public:
518 LoopAccessInfo(Loop *L, ScalarEvolution *SE, const TargetLibraryInfo *TLI,
519 AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI);
520
521 /// Return true we can analyze the memory accesses in the loop and there are
522 /// no memory dependence cycles.
523 bool canVectorizeMemory() const { return CanVecMem; }
524
525 const RuntimePointerChecking *getRuntimePointerChecking() const {
526 return PtrRtChecking.get();
527 }
528
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100529 /// Number of memchecks required to prove independence of otherwise
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100530 /// may-alias pointers.
531 unsigned getNumRuntimePointerChecks() const {
532 return PtrRtChecking->getNumberOfChecks();
533 }
534
535 /// Return true if the block BB needs to be predicated in order for the loop
536 /// to be vectorized.
537 static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
538 DominatorTree *DT);
539
540 /// Returns true if the value V is uniform within the loop.
541 bool isUniform(Value *V) const;
542
543 uint64_t getMaxSafeDepDistBytes() const { return MaxSafeDepDistBytes; }
544 unsigned getNumStores() const { return NumStores; }
545 unsigned getNumLoads() const { return NumLoads;}
546
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100547 /// Add code that checks at runtime if the accessed arrays overlap.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100548 ///
549 /// Returns a pair of instructions where the first element is the first
550 /// instruction generated in possibly a sequence of instructions and the
551 /// second value is the final comparator value or NULL if no check is needed.
552 std::pair<Instruction *, Instruction *>
553 addRuntimeChecks(Instruction *Loc) const;
554
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100555 /// Generete the instructions for the checks in \p PointerChecks.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100556 ///
557 /// Returns a pair of instructions where the first element is the first
558 /// instruction generated in possibly a sequence of instructions and the
559 /// second value is the final comparator value or NULL if no check is needed.
560 std::pair<Instruction *, Instruction *>
561 addRuntimeChecks(Instruction *Loc,
562 const SmallVectorImpl<RuntimePointerChecking::PointerCheck>
563 &PointerChecks) const;
564
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100565 /// The diagnostics report generated for the analysis. E.g. why we
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100566 /// couldn't analyze the loop.
567 const OptimizationRemarkAnalysis *getReport() const { return Report.get(); }
568
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100569 /// the Memory Dependence Checker which can determine the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100570 /// loop-independent and loop-carried dependences between memory accesses.
571 const MemoryDepChecker &getDepChecker() const { return *DepChecker; }
572
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100573 /// Return the list of instructions that use \p Ptr to read or write
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100574 /// memory.
575 SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
576 bool isWrite) const {
577 return DepChecker->getInstructionsForAccess(Ptr, isWrite);
578 }
579
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100580 /// If an access has a symbolic strides, this maps the pointer value to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100581 /// the stride symbol.
582 const ValueToValueMap &getSymbolicStrides() const { return SymbolicStrides; }
583
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100584 /// Pointer has a symbolic stride.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100585 bool hasStride(Value *V) const { return StrideSet.count(V); }
586
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100587 /// Print the information about the memory accesses in the loop.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100588 void print(raw_ostream &OS, unsigned Depth = 0) const;
589
Andrew Walbran16937d02019-10-22 13:54:20 +0100590 /// If the loop has memory dependence involving an invariant address, i.e. two
591 /// stores or a store and a load, then return true, else return false.
592 bool hasDependenceInvolvingLoopInvariantAddress() const {
593 return HasDependenceInvolvingLoopInvariantAddress;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100594 }
595
596 /// Used to add runtime SCEV checks. Simplifies SCEV expressions and converts
597 /// them to a more usable form. All SCEV expressions during the analysis
598 /// should be re-written (and therefore simplified) according to PSE.
599 /// A user of LoopAccessAnalysis will need to emit the runtime checks
600 /// associated with this predicate.
601 const PredicatedScalarEvolution &getPSE() const { return *PSE; }
602
603private:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100604 /// Analyze the loop.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100605 void analyzeLoop(AliasAnalysis *AA, LoopInfo *LI,
606 const TargetLibraryInfo *TLI, DominatorTree *DT);
607
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100608 /// Check if the structure of the loop allows it to be analyzed by this
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100609 /// pass.
610 bool canAnalyzeLoop();
611
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100612 /// Save the analysis remark.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100613 ///
614 /// LAA does not directly emits the remarks. Instead it stores it which the
615 /// client can retrieve and presents as its own analysis
616 /// (e.g. -Rpass-analysis=loop-vectorize).
617 OptimizationRemarkAnalysis &recordAnalysis(StringRef RemarkName,
618 Instruction *Instr = nullptr);
619
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100620 /// Collect memory access with loop invariant strides.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100621 ///
622 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
623 /// invariant.
624 void collectStridedAccess(Value *LoadOrStoreInst);
625
626 std::unique_ptr<PredicatedScalarEvolution> PSE;
627
628 /// We need to check that all of the pointers in this list are disjoint
629 /// at runtime. Using std::unique_ptr to make using move ctor simpler.
630 std::unique_ptr<RuntimePointerChecking> PtrRtChecking;
631
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100632 /// the Memory Dependence Checker which can determine the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100633 /// loop-independent and loop-carried dependences between memory accesses.
634 std::unique_ptr<MemoryDepChecker> DepChecker;
635
636 Loop *TheLoop;
637
638 unsigned NumLoads;
639 unsigned NumStores;
640
641 uint64_t MaxSafeDepDistBytes;
642
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100643 /// Cache the result of analyzeLoop.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100644 bool CanVecMem;
645
Andrew Walbran16937d02019-10-22 13:54:20 +0100646 /// Indicator that there are non vectorizable stores to a uniform address.
647 bool HasDependenceInvolvingLoopInvariantAddress;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100648
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100649 /// The diagnostics report generated for the analysis. E.g. why we
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100650 /// couldn't analyze the loop.
651 std::unique_ptr<OptimizationRemarkAnalysis> Report;
652
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100653 /// If an access has a symbolic strides, this maps the pointer value to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100654 /// the stride symbol.
655 ValueToValueMap SymbolicStrides;
656
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100657 /// Set of symbolic strides values.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100658 SmallPtrSet<Value *, 8> StrideSet;
659};
660
661Value *stripIntegerCast(Value *V);
662
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100663/// Return the SCEV corresponding to a pointer with the symbolic stride
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100664/// replaced with constant one, assuming the SCEV predicate associated with
665/// \p PSE is true.
666///
667/// If necessary this method will version the stride of the pointer according
668/// to \p PtrToStride and therefore add further predicates to \p PSE.
669///
670/// If \p OrigPtr is not null, use it to look up the stride value instead of \p
671/// Ptr. \p PtrToStride provides the mapping between the pointer value and its
672/// stride as collected by LoopVectorizationLegality::collectStridedAccess.
673const SCEV *replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
674 const ValueToValueMap &PtrToStride,
675 Value *Ptr, Value *OrigPtr = nullptr);
676
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100677/// If the pointer has a constant stride return it in units of its
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100678/// element size. Otherwise return zero.
679///
680/// Ensure that it does not wrap in the address space, assuming the predicate
681/// associated with \p PSE is true.
682///
683/// If necessary this method will version the stride of the pointer according
684/// to \p PtrToStride and therefore add further predicates to \p PSE.
685/// The \p Assume parameter indicates if we are allowed to make additional
686/// run-time assumptions.
687int64_t getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr, const Loop *Lp,
688 const ValueToValueMap &StridesMap = ValueToValueMap(),
689 bool Assume = false, bool ShouldCheckWrap = true);
690
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100691/// Attempt to sort the pointers in \p VL and return the sorted indices
692/// in \p SortedIndices, if reordering is required.
693///
694/// Returns 'true' if sorting is legal, otherwise returns 'false'.
695///
696/// For example, for a given \p VL of memory accesses in program order, a[i+4],
697/// a[i+0], a[i+1] and a[i+7], this function will sort the \p VL and save the
698/// sorted indices in \p SortedIndices as a[i+0], a[i+1], a[i+4], a[i+7] and
699/// saves the mask for actual memory accesses in program order in
700/// \p SortedIndices as <1,2,0,3>
701bool sortPtrAccesses(ArrayRef<Value *> VL, const DataLayout &DL,
702 ScalarEvolution &SE,
703 SmallVectorImpl<unsigned> &SortedIndices);
704
705/// Returns true if the memory operations \p A and \p B are consecutive.
706/// This is a simple API that does not depend on the analysis pass.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100707bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
708 ScalarEvolution &SE, bool CheckType = true);
709
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100710/// This analysis provides dependence information for the memory accesses
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100711/// of a loop.
712///
713/// It runs the analysis for a loop on demand. This can be initiated by
714/// querying the loop access info via LAA::getInfo. getInfo return a
715/// LoopAccessInfo object. See this class for the specifics of what information
716/// is provided.
717class LoopAccessLegacyAnalysis : public FunctionPass {
718public:
719 static char ID;
720
721 LoopAccessLegacyAnalysis() : FunctionPass(ID) {
722 initializeLoopAccessLegacyAnalysisPass(*PassRegistry::getPassRegistry());
723 }
724
725 bool runOnFunction(Function &F) override;
726
727 void getAnalysisUsage(AnalysisUsage &AU) const override;
728
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100729 /// Query the result of the loop access information for the loop \p L.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100730 ///
731 /// If there is no cached result available run the analysis.
732 const LoopAccessInfo &getInfo(Loop *L);
733
734 void releaseMemory() override {
735 // Invalidate the cache when the pass is freed.
736 LoopAccessInfoMap.clear();
737 }
738
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100739 /// Print the result of the analysis when invoked with -analyze.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100740 void print(raw_ostream &OS, const Module *M = nullptr) const override;
741
742private:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100743 /// The cache.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100744 DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
745
746 // The used analysis passes.
747 ScalarEvolution *SE;
748 const TargetLibraryInfo *TLI;
749 AliasAnalysis *AA;
750 DominatorTree *DT;
751 LoopInfo *LI;
752};
753
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100754/// This analysis provides dependence information for the memory
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100755/// accesses of a loop.
756///
757/// It runs the analysis for a loop on demand. This can be initiated by
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100758/// querying the loop access info via AM.getResult<LoopAccessAnalysis>.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100759/// getResult return a LoopAccessInfo object. See this class for the
760/// specifics of what information is provided.
761class LoopAccessAnalysis
762 : public AnalysisInfoMixin<LoopAccessAnalysis> {
763 friend AnalysisInfoMixin<LoopAccessAnalysis>;
764 static AnalysisKey Key;
765
766public:
767 typedef LoopAccessInfo Result;
768
769 Result run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR);
770};
771
772inline Instruction *MemoryDepChecker::Dependence::getSource(
773 const LoopAccessInfo &LAI) const {
774 return LAI.getDepChecker().getMemoryInstructions()[Source];
775}
776
777inline Instruction *MemoryDepChecker::Dependence::getDestination(
778 const LoopAccessInfo &LAI) const {
779 return LAI.getDepChecker().getMemoryInstructions()[Destination];
780}
781
782} // End llvm namespace
783
784#endif