blob: a775f15ced956aa75069e7ac72719a270a717b5a [file] [log] [blame]
Adam Nemet04563272015-02-01 16:56:15 +00001//===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
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// The implementation for the loop memory dependence that was originally
11// developed for the loop vectorizer.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LoopAccessAnalysis.h"
16#include "llvm/Analysis/LoopInfo.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000017#include "llvm/Analysis/LoopPassManager.h"
Adam Nemet5b3a5cf2016-07-20 21:44:26 +000018#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000019#include "llvm/Analysis/ScalarEvolutionExpander.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
Adam Nemet04563272015-02-01 16:56:15 +000021#include "llvm/Analysis/ValueTracking.h"
Adam Nemetf45594c2016-07-01 00:09:02 +000022#include "llvm/Analysis/VectorUtils.h"
Adam Nemet04563272015-02-01 16:56:15 +000023#include "llvm/IR/Dominators.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000024#include "llvm/IR/IRBuilder.h"
Xinliang David Li8a021312016-07-02 21:18:40 +000025#include "llvm/IR/PassManager.h"
Adam Nemet04563272015-02-01 16:56:15 +000026#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000027#include "llvm/Support/raw_ostream.h"
Adam Nemet04563272015-02-01 16:56:15 +000028using namespace llvm;
29
Adam Nemet339f42b2015-02-19 19:15:07 +000030#define DEBUG_TYPE "loop-accesses"
Adam Nemet04563272015-02-01 16:56:15 +000031
Adam Nemetf219c642015-02-19 19:14:52 +000032static cl::opt<unsigned, true>
33VectorizationFactor("force-vector-width", cl::Hidden,
34 cl::desc("Sets the SIMD width. Zero is autoselect."),
35 cl::location(VectorizerParams::VectorizationFactor));
Adam Nemet1d862af2015-02-26 04:39:09 +000036unsigned VectorizerParams::VectorizationFactor;
Adam Nemetf219c642015-02-19 19:14:52 +000037
38static cl::opt<unsigned, true>
39VectorizationInterleave("force-vector-interleave", cl::Hidden,
40 cl::desc("Sets the vectorization interleave count. "
41 "Zero is autoselect."),
42 cl::location(
43 VectorizerParams::VectorizationInterleave));
Adam Nemet1d862af2015-02-26 04:39:09 +000044unsigned VectorizerParams::VectorizationInterleave;
Adam Nemetf219c642015-02-19 19:14:52 +000045
Adam Nemet1d862af2015-02-26 04:39:09 +000046static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
47 "runtime-memory-check-threshold", cl::Hidden,
48 cl::desc("When performing memory disambiguation checks at runtime do not "
49 "generate more than this number of comparisons (default = 8)."),
50 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
51unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
Adam Nemetf219c642015-02-19 19:14:52 +000052
Silviu Baranga1b6b50a2015-07-08 09:16:33 +000053/// \brief The maximum iterations used to merge memory checks
54static cl::opt<unsigned> MemoryCheckMergeThreshold(
55 "memory-check-merge-threshold", cl::Hidden,
56 cl::desc("Maximum number of comparisons done when trying to merge "
57 "runtime memory checks. (default = 100)"),
58 cl::init(100));
59
Adam Nemetf219c642015-02-19 19:14:52 +000060/// Maximum SIMD width.
61const unsigned VectorizerParams::MaxVectorWidth = 64;
62
Adam Nemeta2df7502015-11-03 21:39:52 +000063/// \brief We collect dependences up to this threshold.
64static cl::opt<unsigned>
65 MaxDependences("max-dependences", cl::Hidden,
66 cl::desc("Maximum number of dependences collected by "
67 "loop-access analysis (default = 100)"),
68 cl::init(100));
Adam Nemet9c926572015-03-10 17:40:37 +000069
Adam Nemeta9f09c62016-06-17 22:35:41 +000070/// This enables versioning on the strides of symbolically striding memory
71/// accesses in code like the following.
72/// for (i = 0; i < N; ++i)
73/// A[i * Stride1] += B[i * Stride2] ...
74///
75/// Will be roughly translated to
76/// if (Stride1 == 1 && Stride2 == 1) {
77/// for (i = 0; i < N; i+=4)
78/// A[i:i+3] += ...
79/// } else
80/// ...
81static cl::opt<bool> EnableMemAccessVersioning(
82 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
83 cl::desc("Enable symbolic stride memory access versioning"));
84
Matthew Simpson37ec5f92016-05-16 17:00:56 +000085/// \brief Enable store-to-load forwarding conflict detection. This option can
86/// be disabled for correctness testing.
87static cl::opt<bool> EnableForwardingConflictDetection(
88 "store-to-load-forwarding-conflict-detection", cl::Hidden,
Matthew Simpsona250dc92016-05-16 14:14:49 +000089 cl::desc("Enable conflict detection in loop-access analysis"),
90 cl::init(true));
91
Adam Nemetf219c642015-02-19 19:14:52 +000092bool VectorizerParams::isInterleaveForced() {
93 return ::VectorizationInterleave.getNumOccurrences() > 0;
94}
95
Adam Nemet2bd6e982015-02-19 19:15:15 +000096void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
Adam Nemet5b3a5cf2016-07-20 21:44:26 +000097 const Loop *TheLoop, const char *PassName,
98 OptimizationRemarkEmitter &ORE) {
Adam Nemet04563272015-02-01 16:56:15 +000099 DebugLoc DL = TheLoop->getStartLoc();
Adam Nemet5b3a5cf2016-07-20 21:44:26 +0000100 const Value *V = TheLoop->getHeader();
101 if (const Instruction *I = Message.getInstr()) {
Adam Nemete3cef932016-09-21 03:14:20 +0000102 // If there is no debug location attached to the instruction, revert back to
103 // using the loop's.
104 if (I->getDebugLoc())
105 DL = I->getDebugLoc();
Adam Nemet5b3a5cf2016-07-20 21:44:26 +0000106 V = I->getParent();
107 }
108 ORE.emitOptimizationRemarkAnalysis(PassName, DL, V, Message.str());
Adam Nemet04563272015-02-01 16:56:15 +0000109}
110
111Value *llvm::stripIntegerCast(Value *V) {
David Majnemer8b401012016-07-12 20:31:46 +0000112 if (auto *CI = dyn_cast<CastInst>(V))
Adam Nemet04563272015-02-01 16:56:15 +0000113 if (CI->getOperand(0)->getType()->isIntegerTy())
114 return CI->getOperand(0);
115 return V;
116}
117
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000118const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000119 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +0000120 Value *Ptr, Value *OrigPtr) {
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000121 const SCEV *OrigSCEV = PSE.getSCEV(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000122
123 // If there is an entry in the map return the SCEV of the pointer with the
124 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000125 ValueToValueMap::const_iterator SI =
126 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000127 if (SI != PtrToStride.end()) {
128 Value *StrideVal = SI->second;
129
130 // Strip casts.
131 StrideVal = stripIntegerCast(StrideVal);
132
133 // Replace symbolic stride by one.
134 Value *One = ConstantInt::get(StrideVal->getType(), 1);
135 ValueToValueMap RewriteMap;
136 RewriteMap[StrideVal] = One;
137
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000138 ScalarEvolution *SE = PSE.getSE();
Silviu Barangae3c05342015-11-02 14:41:02 +0000139 const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
140 const auto *CT =
141 static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
142
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000143 PSE.addPredicate(*SE->getEqualPredicate(U, CT));
144 auto *Expr = PSE.getSCEV(Ptr);
Silviu Barangae3c05342015-11-02 14:41:02 +0000145
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000146 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *Expr
Adam Nemet04563272015-02-01 16:56:15 +0000147 << "\n");
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000148 return Expr;
Adam Nemet04563272015-02-01 16:56:15 +0000149 }
150
151 // Otherwise, just return the SCEV of the original pointer.
Silviu Barangae3c05342015-11-02 14:41:02 +0000152 return OrigSCEV;
Adam Nemet04563272015-02-01 16:56:15 +0000153}
154
Elena Demikhovsky3622fbf2016-08-28 08:53:53 +0000155/// Calculate Start and End points of memory access.
156/// Let's assume A is the first access and B is a memory access on N-th loop
157/// iteration. Then B is calculated as:
158/// B = A + Step*N .
159/// Step value may be positive or negative.
160/// N is a calculated back-edge taken count:
161/// N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
162/// Start and End points are calculated in the following way:
163/// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
164/// where SizeOfElt is the size of single memory access in bytes.
165///
166/// There is no conflict when the intervals are disjoint:
167/// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
Adam Nemet7cdebac2015-07-14 22:32:44 +0000168void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
169 unsigned DepSetId, unsigned ASId,
Silviu Barangae3c05342015-11-02 14:41:02 +0000170 const ValueToValueMap &Strides,
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000171 PredicatedScalarEvolution &PSE) {
Adam Nemet04563272015-02-01 16:56:15 +0000172 // Get the stride replaced scev.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000173 const SCEV *Sc = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000174 ScalarEvolution *SE = PSE.getSE();
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000175
Adam Nemet279784f2016-03-24 04:28:47 +0000176 const SCEV *ScStart;
177 const SCEV *ScEnd;
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000178
Adam Nemet59a65502016-03-24 05:15:24 +0000179 if (SE->isLoopInvariant(Sc, Lp))
Adam Nemet279784f2016-03-24 04:28:47 +0000180 ScStart = ScEnd = Sc;
Adam Nemet279784f2016-03-24 04:28:47 +0000181 else {
182 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
183 assert(AR && "Invalid addrec expression");
Silviu Baranga6f444df2016-04-08 14:29:09 +0000184 const SCEV *Ex = PSE.getBackedgeTakenCount();
Adam Nemet279784f2016-03-24 04:28:47 +0000185
186 ScStart = AR->getStart();
187 ScEnd = AR->evaluateAtIteration(Ex, *SE);
188 const SCEV *Step = AR->getStepRecurrence(*SE);
189
190 // For expressions with negative step, the upper bound is ScStart and the
191 // lower bound is ScEnd.
David Majnemer8b401012016-07-12 20:31:46 +0000192 if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
Adam Nemet279784f2016-03-24 04:28:47 +0000193 if (CStep->getValue()->isNegative())
194 std::swap(ScStart, ScEnd);
195 } else {
Elena Demikhovsky3622fbf2016-08-28 08:53:53 +0000196 // Fallback case: the step is not constant, but we can still
Adam Nemet279784f2016-03-24 04:28:47 +0000197 // get the upper and lower bounds of the interval by using min/max
198 // expressions.
199 ScStart = SE->getUMinExpr(ScStart, ScEnd);
200 ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
201 }
Elena Demikhovsky3622fbf2016-08-28 08:53:53 +0000202 // Add the size of the pointed element to ScEnd.
203 unsigned EltSize =
204 Ptr->getType()->getPointerElementType()->getScalarSizeInBits() / 8;
205 const SCEV *EltSizeSCEV = SE->getConstant(ScEnd->getType(), EltSize);
206 ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV);
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000207 }
208
209 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000210}
211
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000212SmallVector<RuntimePointerChecking::PointerCheck, 4>
Adam Nemet38530882015-08-09 20:06:06 +0000213RuntimePointerChecking::generateChecks() const {
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000214 SmallVector<PointerCheck, 4> Checks;
215
Adam Nemet7c52e052015-07-27 19:38:50 +0000216 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
217 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
218 const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
219 const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000220
Adam Nemet38530882015-08-09 20:06:06 +0000221 if (needsChecking(CGI, CGJ))
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000222 Checks.push_back(std::make_pair(&CGI, &CGJ));
223 }
224 }
225 return Checks;
226}
227
Adam Nemet15840392015-08-07 22:44:15 +0000228void RuntimePointerChecking::generateChecks(
229 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
230 assert(Checks.empty() && "Checks is not empty");
231 groupChecks(DepCands, UseDependencies);
232 Checks = generateChecks();
233}
234
Adam Nemet651a5a22015-08-09 20:06:08 +0000235bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
236 const CheckingPtrGroup &N) const {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000237 for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
238 for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
Adam Nemet651a5a22015-08-09 20:06:08 +0000239 if (needsChecking(M.Members[I], N.Members[J]))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000240 return true;
241 return false;
242}
243
244/// Compare \p I and \p J and return the minimum.
245/// Return nullptr in case we couldn't find an answer.
246static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
247 ScalarEvolution *SE) {
248 const SCEV *Diff = SE->getMinusSCEV(J, I);
249 const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
250
251 if (!C)
252 return nullptr;
253 if (C->getValue()->isNegative())
254 return J;
255 return I;
256}
257
Adam Nemet7cdebac2015-07-14 22:32:44 +0000258bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000259 const SCEV *Start = RtCheck.Pointers[Index].Start;
260 const SCEV *End = RtCheck.Pointers[Index].End;
261
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000262 // Compare the starts and ends with the known minimum and maximum
263 // of this set. We need to know how we compare against the min/max
264 // of the set in order to be able to emit memchecks.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000265 const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000266 if (!Min0)
267 return false;
268
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000269 const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000270 if (!Min1)
271 return false;
272
273 // Update the low bound expression if we've found a new min value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000274 if (Min0 == Start)
275 Low = Start;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000276
277 // Update the high bound expression if we've found a new max value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000278 if (Min1 != End)
279 High = End;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000280
281 Members.push_back(Index);
282 return true;
283}
284
Adam Nemet7cdebac2015-07-14 22:32:44 +0000285void RuntimePointerChecking::groupChecks(
286 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000287 // We build the groups from dependency candidates equivalence classes
288 // because:
289 // - We know that pointers in the same equivalence class share
290 // the same underlying object and therefore there is a chance
291 // that we can compare pointers
292 // - We wouldn't be able to merge two pointers for which we need
293 // to emit a memcheck. The classes in DepCands are already
294 // conveniently built such that no two pointers in the same
295 // class need checking against each other.
296
297 // We use the following (greedy) algorithm to construct the groups
298 // For every pointer in the equivalence class:
299 // For each existing group:
300 // - if the difference between this pointer and the min/max bounds
301 // of the group is a constant, then make the pointer part of the
302 // group and update the min/max bounds of that group as required.
303
304 CheckingGroups.clear();
305
Silviu Baranga48250602015-07-28 13:44:08 +0000306 // If we need to check two pointers to the same underlying object
307 // with a non-constant difference, we shouldn't perform any pointer
308 // grouping with those pointers. This is because we can easily get
309 // into cases where the resulting check would return false, even when
310 // the accesses are safe.
311 //
312 // The following example shows this:
313 // for (i = 0; i < 1000; ++i)
314 // a[5000 + i * m] = a[i] + a[i + 9000]
315 //
316 // Here grouping gives a check of (5000, 5000 + 1000 * m) against
317 // (0, 10000) which is always false. However, if m is 1, there is no
318 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
319 // us to perform an accurate check in this case.
320 //
321 // The above case requires that we have an UnknownDependence between
322 // accesses to the same underlying object. This cannot happen unless
323 // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
324 // is also false. In this case we will use the fallback path and create
325 // separate checking groups for all pointers.
Mehdi Aminiafd13512015-11-05 05:49:43 +0000326
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000327 // If we don't have the dependency partitions, construct a new
Silviu Baranga48250602015-07-28 13:44:08 +0000328 // checking pointer group for each pointer. This is also required
329 // for correctness, because in this case we can have checking between
330 // pointers to the same underlying object.
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000331 if (!UseDependencies) {
332 for (unsigned I = 0; I < Pointers.size(); ++I)
333 CheckingGroups.push_back(CheckingPtrGroup(I, *this));
334 return;
335 }
336
337 unsigned TotalComparisons = 0;
338
339 DenseMap<Value *, unsigned> PositionMap;
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000340 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
341 PositionMap[Pointers[Index].PointerValue] = Index;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000342
Silviu Barangace3877f2015-07-09 15:18:25 +0000343 // We need to keep track of what pointers we've already seen so we
344 // don't process them twice.
345 SmallSet<unsigned, 2> Seen;
346
Sanjay Patele4b9f502015-12-07 19:21:39 +0000347 // Go through all equivalence classes, get the "pointer check groups"
Silviu Barangace3877f2015-07-09 15:18:25 +0000348 // and add them to the overall solution. We use the order in which accesses
349 // appear in 'Pointers' to enforce determinism.
350 for (unsigned I = 0; I < Pointers.size(); ++I) {
351 // We've seen this pointer before, and therefore already processed
352 // its equivalence class.
353 if (Seen.count(I))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000354 continue;
355
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000356 MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
357 Pointers[I].IsWritePtr);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000358
Silviu Barangace3877f2015-07-09 15:18:25 +0000359 SmallVector<CheckingPtrGroup, 2> Groups;
360 auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
361
Silviu Barangaa647c302015-07-13 14:48:24 +0000362 // Because DepCands is constructed by visiting accesses in the order in
363 // which they appear in alias sets (which is deterministic) and the
364 // iteration order within an equivalence class member is only dependent on
365 // the order in which unions and insertions are performed on the
366 // equivalence class, the iteration order is deterministic.
Silviu Barangace3877f2015-07-09 15:18:25 +0000367 for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000368 MI != ME; ++MI) {
369 unsigned Pointer = PositionMap[MI->getPointer()];
370 bool Merged = false;
Silviu Barangace3877f2015-07-09 15:18:25 +0000371 // Mark this pointer as seen.
372 Seen.insert(Pointer);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000373
374 // Go through all the existing sets and see if we can find one
375 // which can include this pointer.
376 for (CheckingPtrGroup &Group : Groups) {
377 // Don't perform more than a certain amount of comparisons.
378 // This should limit the cost of grouping the pointers to something
379 // reasonable. If we do end up hitting this threshold, the algorithm
380 // will create separate groups for all remaining pointers.
381 if (TotalComparisons > MemoryCheckMergeThreshold)
382 break;
383
384 TotalComparisons++;
385
386 if (Group.addPointer(Pointer)) {
387 Merged = true;
388 break;
389 }
390 }
391
392 if (!Merged)
393 // We couldn't add this pointer to any existing set or the threshold
394 // for the number of comparisons has been reached. Create a new group
395 // to hold the current pointer.
396 Groups.push_back(CheckingPtrGroup(Pointer, *this));
397 }
398
399 // We've computed the grouped checks for this partition.
400 // Save the results and continue with the next one.
401 std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
402 }
Adam Nemet04563272015-02-01 16:56:15 +0000403}
404
Adam Nemet041e6de2015-07-16 02:48:05 +0000405bool RuntimePointerChecking::arePointersInSamePartition(
406 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
407 unsigned PtrIdx2) {
408 return (PtrToPartition[PtrIdx1] != -1 &&
409 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
410}
411
Adam Nemet651a5a22015-08-09 20:06:08 +0000412bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000413 const PointerInfo &PointerI = Pointers[I];
414 const PointerInfo &PointerJ = Pointers[J];
415
Adam Nemeta8945b72015-02-18 03:43:58 +0000416 // No need to check if two readonly pointers intersect.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000417 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
Adam Nemeta8945b72015-02-18 03:43:58 +0000418 return false;
419
420 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000421 if (PointerI.DependencySetId == PointerJ.DependencySetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000422 return false;
423
424 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000425 if (PointerI.AliasSetId != PointerJ.AliasSetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000426 return false;
427
428 return true;
429}
430
Adam Nemet54f0b832015-07-27 23:54:41 +0000431void RuntimePointerChecking::printChecks(
432 raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
433 unsigned Depth) const {
434 unsigned N = 0;
435 for (const auto &Check : Checks) {
436 const auto &First = Check.first->Members, &Second = Check.second->Members;
437
438 OS.indent(Depth) << "Check " << N++ << ":\n";
439
440 OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
441 for (unsigned K = 0; K < First.size(); ++K)
442 OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
443
444 OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
445 for (unsigned K = 0; K < Second.size(); ++K)
446 OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
447 }
448}
449
Adam Nemet3a91e942015-08-07 19:44:48 +0000450void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000451
452 OS.indent(Depth) << "Run-time memory checks:\n";
Adam Nemet15840392015-08-07 22:44:15 +0000453 printChecks(OS, Checks, Depth);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000454
455 OS.indent(Depth) << "Grouped accesses:\n";
456 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
Adam Nemet54f0b832015-07-27 23:54:41 +0000457 const auto &CG = CheckingGroups[I];
458
459 OS.indent(Depth + 2) << "Group " << &CG << ":\n";
460 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
461 << ")\n";
462 for (unsigned J = 0; J < CG.Members.size(); ++J) {
463 OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000464 << "\n";
465 }
466 }
Adam Nemete91cc6e2015-02-19 19:15:19 +0000467}
468
Adam Nemet04563272015-02-01 16:56:15 +0000469namespace {
470/// \brief Analyses memory accesses in a loop.
471///
472/// Checks whether run time pointer checks are needed and builds sets for data
473/// dependence checking.
474class AccessAnalysis {
475public:
476 /// \brief Read or write access location.
477 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
478 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
479
Adam Nemete2b885c2015-04-23 20:09:20 +0000480 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000481 MemoryDepChecker::DepCandidates &DA,
482 PredicatedScalarEvolution &PSE)
Silviu Barangae3c05342015-11-02 14:41:02 +0000483 : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckAnalysisNeeded(false),
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000484 PSE(PSE) {}
Adam Nemet04563272015-02-01 16:56:15 +0000485
486 /// \brief Register a load and whether it is only read from.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000487 void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
Adam Nemet04563272015-02-01 16:56:15 +0000488 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000489 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000490 Accesses.insert(MemAccessInfo(Ptr, false));
491 if (IsReadOnly)
492 ReadOnlyPtr.insert(Ptr);
493 }
494
495 /// \brief Register a store.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000496 void addStore(MemoryLocation &Loc) {
Adam Nemet04563272015-02-01 16:56:15 +0000497 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000498 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000499 Accesses.insert(MemAccessInfo(Ptr, true));
500 }
501
502 /// \brief Check whether we can check the pointers at runtime for
Adam Nemetee614742015-07-09 22:17:38 +0000503 /// non-intersection.
504 ///
505 /// Returns true if we need no check or if we do and we can generate them
506 /// (i.e. the pointers have computable bounds).
Adam Nemet7cdebac2015-07-14 22:32:44 +0000507 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
508 Loop *TheLoop, const ValueToValueMap &Strides,
Andrey Turetskiy9f02c582016-06-07 14:55:27 +0000509 bool ShouldCheckWrap = false);
Adam Nemet04563272015-02-01 16:56:15 +0000510
511 /// \brief Goes over all memory accesses, checks whether a RT check is needed
512 /// and builds sets of dependent accesses.
513 void buildDependenceSets() {
514 processMemAccesses();
515 }
516
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000517 /// \brief Initial processing of memory accesses determined that we need to
518 /// perform dependency checking.
519 ///
520 /// Note that this can later be cleared if we retry memcheck analysis without
521 /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
Adam Nemet04563272015-02-01 16:56:15 +0000522 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000523
524 /// We decided that no dependence analysis would be used. Reset the state.
525 void resetDepChecks(MemoryDepChecker &DepChecker) {
526 CheckDeps.clear();
Adam Nemeta2df7502015-11-03 21:39:52 +0000527 DepChecker.clearDependences();
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000528 }
Adam Nemet04563272015-02-01 16:56:15 +0000529
530 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
531
532private:
533 typedef SetVector<MemAccessInfo> PtrAccessSet;
534
535 /// \brief Go over all memory access and check whether runtime pointer checks
Adam Nemetb41d2d32015-07-09 06:47:21 +0000536 /// are needed and build sets of dependency check candidates.
Adam Nemet04563272015-02-01 16:56:15 +0000537 void processMemAccesses();
538
539 /// Set of all accesses.
540 PtrAccessSet Accesses;
541
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000542 const DataLayout &DL;
543
Adam Nemet04563272015-02-01 16:56:15 +0000544 /// Set of accesses that need a further dependence check.
545 MemAccessInfoSet CheckDeps;
546
547 /// Set of pointers that are read only.
548 SmallPtrSet<Value*, 16> ReadOnlyPtr;
549
Adam Nemet04563272015-02-01 16:56:15 +0000550 /// An alias set tracker to partition the access set by underlying object and
551 //intrinsic property (such as TBAA metadata).
552 AliasSetTracker AST;
553
Adam Nemete2b885c2015-04-23 20:09:20 +0000554 LoopInfo *LI;
555
Adam Nemet04563272015-02-01 16:56:15 +0000556 /// Sets of potentially dependent accesses - members of one set share an
557 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
558 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000559 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000560
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000561 /// \brief Initial processing of memory accesses determined that we may need
562 /// to add memchecks. Perform the analysis to determine the necessary checks.
563 ///
564 /// Note that, this is different from isDependencyCheckNeeded. When we retry
565 /// memcheck analysis without dependency checking
566 /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
567 /// while this remains set if we have potentially dependent accesses.
568 bool IsRTCheckAnalysisNeeded;
Silviu Barangae3c05342015-11-02 14:41:02 +0000569
570 /// The SCEV predicate containing all the SCEV-related assumptions.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000571 PredicatedScalarEvolution &PSE;
Adam Nemet04563272015-02-01 16:56:15 +0000572};
573
574} // end anonymous namespace
575
576/// \brief Check whether a pointer can participate in a runtime bounds check.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000577static bool hasComputableBounds(PredicatedScalarEvolution &PSE,
Silviu Barangae3c05342015-11-02 14:41:02 +0000578 const ValueToValueMap &Strides, Value *Ptr,
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000579 Loop *L) {
580 const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
Adam Nemet279784f2016-03-24 04:28:47 +0000581
582 // The bounds for loop-invariant pointer is trivial.
583 if (PSE.getSE()->isLoopInvariant(PtrScev, L))
584 return true;
585
Adam Nemet04563272015-02-01 16:56:15 +0000586 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
587 if (!AR)
588 return false;
589
590 return AR->isAffine();
591}
592
Andrey Turetskiy9f02c582016-06-07 14:55:27 +0000593/// \brief Check whether a pointer address cannot wrap.
594static bool isNoWrap(PredicatedScalarEvolution &PSE,
595 const ValueToValueMap &Strides, Value *Ptr, Loop *L) {
596 const SCEV *PtrScev = PSE.getSCEV(Ptr);
597 if (PSE.getSE()->isLoopInvariant(PtrScev, L))
598 return true;
599
David Majnemer7afb46d2016-07-07 06:24:36 +0000600 int64_t Stride = getPtrStride(PSE, Ptr, L, Strides);
Andrey Turetskiy9f02c582016-06-07 14:55:27 +0000601 return Stride == 1;
602}
603
Adam Nemet7cdebac2015-07-14 22:32:44 +0000604bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
605 ScalarEvolution *SE, Loop *TheLoop,
606 const ValueToValueMap &StridesMap,
Andrey Turetskiy9f02c582016-06-07 14:55:27 +0000607 bool ShouldCheckWrap) {
Adam Nemet04563272015-02-01 16:56:15 +0000608 // Find pointers with computable bounds. We are going to use this information
609 // to place a runtime bound check.
610 bool CanDoRT = true;
611
Adam Nemetee614742015-07-09 22:17:38 +0000612 bool NeedRTCheck = false;
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000613 if (!IsRTCheckAnalysisNeeded) return true;
Silviu Baranga98a13712015-06-08 10:27:06 +0000614
Adam Nemet04563272015-02-01 16:56:15 +0000615 bool IsDepCheckNeeded = isDependencyCheckNeeded();
Adam Nemet04563272015-02-01 16:56:15 +0000616
617 // We assign a consecutive id to access from different alias sets.
618 // Accesses between different groups doesn't need to be checked.
619 unsigned ASId = 1;
620 for (auto &AS : AST) {
Adam Nemet424edc62015-07-08 22:58:48 +0000621 int NumReadPtrChecks = 0;
622 int NumWritePtrChecks = 0;
623
Adam Nemet04563272015-02-01 16:56:15 +0000624 // We assign consecutive id to access from different dependence sets.
625 // Accesses within the same set don't need a runtime check.
626 unsigned RunningDepId = 1;
627 DenseMap<Value *, unsigned> DepSetId;
628
629 for (auto A : AS) {
630 Value *Ptr = A.getValue();
631 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
632 MemAccessInfo Access(Ptr, IsWrite);
633
Adam Nemet424edc62015-07-08 22:58:48 +0000634 if (IsWrite)
635 ++NumWritePtrChecks;
636 else
637 ++NumReadPtrChecks;
638
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000639 if (hasComputableBounds(PSE, StridesMap, Ptr, TheLoop) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000640 // When we run after a failing dependency check we have to make sure
641 // we don't have wrapping pointers.
Andrey Turetskiy9f02c582016-06-07 14:55:27 +0000642 (!ShouldCheckWrap || isNoWrap(PSE, StridesMap, Ptr, TheLoop))) {
Adam Nemet04563272015-02-01 16:56:15 +0000643 // The id of the dependence set.
644 unsigned DepId;
645
646 if (IsDepCheckNeeded) {
647 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
648 unsigned &LeaderId = DepSetId[Leader];
649 if (!LeaderId)
650 LeaderId = RunningDepId++;
651 DepId = LeaderId;
652 } else
653 // Each access has its own dependence set.
654 DepId = RunningDepId++;
655
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000656 RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
Adam Nemet04563272015-02-01 16:56:15 +0000657
Adam Nemet339f42b2015-02-19 19:15:07 +0000658 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000659 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000660 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000661 CanDoRT = false;
662 }
663 }
664
Adam Nemet424edc62015-07-08 22:58:48 +0000665 // If we have at least two writes or one write and a read then we need to
666 // check them. But there is no need to checks if there is only one
667 // dependence set for this alias set.
668 //
669 // Note that this function computes CanDoRT and NeedRTCheck independently.
670 // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
671 // for which we couldn't find the bounds but we don't actually need to emit
672 // any checks so it does not matter.
673 if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
674 NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
675 NumWritePtrChecks >= 1));
676
Adam Nemet04563272015-02-01 16:56:15 +0000677 ++ASId;
678 }
679
680 // If the pointers that we would use for the bounds comparison have different
681 // address spaces, assume the values aren't directly comparable, so we can't
682 // use them for the runtime check. We also have to assume they could
683 // overlap. In the future there should be metadata for whether address spaces
684 // are disjoint.
685 unsigned NumPointers = RtCheck.Pointers.size();
686 for (unsigned i = 0; i < NumPointers; ++i) {
687 for (unsigned j = i + 1; j < NumPointers; ++j) {
688 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000689 if (RtCheck.Pointers[i].DependencySetId ==
690 RtCheck.Pointers[j].DependencySetId)
Adam Nemet04563272015-02-01 16:56:15 +0000691 continue;
692 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000693 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
Adam Nemet04563272015-02-01 16:56:15 +0000694 continue;
695
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000696 Value *PtrI = RtCheck.Pointers[i].PointerValue;
697 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
Adam Nemet04563272015-02-01 16:56:15 +0000698
699 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
700 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
701 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000702 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000703 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000704 return false;
705 }
706 }
707 }
708
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000709 if (NeedRTCheck && CanDoRT)
Adam Nemet15840392015-08-07 22:44:15 +0000710 RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000711
Adam Nemet155e8742015-08-07 22:44:21 +0000712 DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
Adam Nemetee614742015-07-09 22:17:38 +0000713 << " pointer comparisons.\n");
714
715 RtCheck.Need = NeedRTCheck;
716
717 bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
718 if (!CanDoRTIfNeeded)
719 RtCheck.reset();
720 return CanDoRTIfNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000721}
722
723void AccessAnalysis::processMemAccesses() {
724 // We process the set twice: first we process read-write pointers, last we
725 // process read-only pointers. This allows us to skip dependence tests for
726 // read-only pointers.
727
Adam Nemet339f42b2015-02-19 19:15:07 +0000728 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000729 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000730 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000731 DEBUG({
732 for (auto A : Accesses)
733 dbgs() << "\t" << *A.getPointer() << " (" <<
734 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
735 "read-only" : "read")) << ")\n";
736 });
737
738 // The AliasSetTracker has nicely partitioned our pointers by metadata
739 // compatibility and potential for underlying-object overlap. As a result, we
740 // only need to check for potential pointer dependencies within each alias
741 // set.
742 for (auto &AS : AST) {
743 // Note that both the alias-set tracker and the alias sets themselves used
744 // linked lists internally and so the iteration order here is deterministic
745 // (matching the original instruction order within each set).
746
747 bool SetHasWrite = false;
748
749 // Map of pointers to last access encountered.
750 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
751 UnderlyingObjToAccessMap ObjToLastAccess;
752
753 // Set of access to check after all writes have been processed.
754 PtrAccessSet DeferredAccesses;
755
756 // Iterate over each alias set twice, once to process read/write pointers,
757 // and then to process read-only pointers.
758 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
759 bool UseDeferred = SetIteration > 0;
760 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
761
762 for (auto AV : AS) {
763 Value *Ptr = AV.getValue();
764
765 // For a single memory access in AliasSetTracker, Accesses may contain
766 // both read and write, and they both need to be handled for CheckDeps.
767 for (auto AC : S) {
768 if (AC.getPointer() != Ptr)
769 continue;
770
771 bool IsWrite = AC.getInt();
772
773 // If we're using the deferred access set, then it contains only
774 // reads.
775 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
776 if (UseDeferred && !IsReadOnlyPtr)
777 continue;
778 // Otherwise, the pointer must be in the PtrAccessSet, either as a
779 // read or a write.
780 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
781 S.count(MemAccessInfo(Ptr, false))) &&
782 "Alias-set pointer not in the access set?");
783
784 MemAccessInfo Access(Ptr, IsWrite);
785 DepCands.insert(Access);
786
787 // Memorize read-only pointers for later processing and skip them in
788 // the first round (they need to be checked after we have seen all
789 // write pointers). Note: we also mark pointer that are not
790 // consecutive as "read-only" pointers (so that we check
791 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
792 if (!UseDeferred && IsReadOnlyPtr) {
793 DeferredAccesses.insert(Access);
794 continue;
795 }
796
797 // If this is a write - check other reads and writes for conflicts. If
798 // this is a read only check other writes for conflicts (but only if
799 // there is no other write to the ptr - this is an optimization to
800 // catch "a[i] = a[i] + " without having to do a dependence check).
801 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
802 CheckDeps.insert(Access);
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000803 IsRTCheckAnalysisNeeded = true;
Adam Nemet04563272015-02-01 16:56:15 +0000804 }
805
806 if (IsWrite)
807 SetHasWrite = true;
808
809 // Create sets of pointers connected by a shared alias set and
810 // underlying object.
811 typedef SmallVector<Value *, 16> ValueVector;
812 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000813
814 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
815 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000816 for (Value *UnderlyingObj : TempObjects) {
Mehdi Aminiafd13512015-11-05 05:49:43 +0000817 // nullptr never alias, don't join sets for pointer that have "null"
818 // in their UnderlyingObjects list.
819 if (isa<ConstantPointerNull>(UnderlyingObj))
820 continue;
821
Adam Nemet04563272015-02-01 16:56:15 +0000822 UnderlyingObjToAccessMap::iterator Prev =
823 ObjToLastAccess.find(UnderlyingObj);
824 if (Prev != ObjToLastAccess.end())
825 DepCands.unionSets(Access, Prev->second);
826
827 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000828 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000829 }
830 }
831 }
832 }
833 }
834}
835
Adam Nemet04563272015-02-01 16:56:15 +0000836static bool isInBoundsGep(Value *Ptr) {
837 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
838 return GEP->isInBounds();
839 return false;
840}
841
Adam Nemetc4866d22015-06-26 17:25:43 +0000842/// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
843/// i.e. monotonically increasing/decreasing.
844static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000845 PredicatedScalarEvolution &PSE, const Loop *L) {
Adam Nemetc4866d22015-06-26 17:25:43 +0000846 // FIXME: This should probably only return true for NUW.
847 if (AR->getNoWrapFlags(SCEV::NoWrapMask))
848 return true;
849
850 // Scalar evolution does not propagate the non-wrapping flags to values that
851 // are derived from a non-wrapping induction variable because non-wrapping
852 // could be flow-sensitive.
853 //
854 // Look through the potentially overflowing instruction to try to prove
855 // non-wrapping for the *specific* value of Ptr.
856
857 // The arithmetic implied by an inbounds GEP can't overflow.
858 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
859 if (!GEP || !GEP->isInBounds())
860 return false;
861
862 // Make sure there is only one non-const index and analyze that.
863 Value *NonConstIndex = nullptr;
David Majnemer8b401012016-07-12 20:31:46 +0000864 for (Value *Index : make_range(GEP->idx_begin(), GEP->idx_end()))
865 if (!isa<ConstantInt>(Index)) {
Adam Nemetc4866d22015-06-26 17:25:43 +0000866 if (NonConstIndex)
867 return false;
David Majnemer8b401012016-07-12 20:31:46 +0000868 NonConstIndex = Index;
Adam Nemetc4866d22015-06-26 17:25:43 +0000869 }
870 if (!NonConstIndex)
871 // The recurrence is on the pointer, ignore for now.
872 return false;
873
874 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
875 // AddRec using a NSW operation.
876 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
877 if (OBO->hasNoSignedWrap() &&
878 // Assume constant for other the operand so that the AddRec can be
879 // easily found.
880 isa<ConstantInt>(OBO->getOperand(1))) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000881 auto *OpScev = PSE.getSCEV(OBO->getOperand(0));
Adam Nemetc4866d22015-06-26 17:25:43 +0000882
883 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
884 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
885 }
886
887 return false;
888}
889
Adam Nemet04563272015-02-01 16:56:15 +0000890/// \brief Check whether the access through \p Ptr has a constant stride.
David Majnemer7afb46d2016-07-07 06:24:36 +0000891int64_t llvm::getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr,
892 const Loop *Lp, const ValueToValueMap &StridesMap,
Elena Demikhovsky5f8cc0c2016-09-18 13:56:08 +0000893 bool Assume, bool ShouldCheckWrap) {
Craig Toppere3dcce92015-08-01 22:20:21 +0000894 Type *Ty = Ptr->getType();
Adam Nemet04563272015-02-01 16:56:15 +0000895 assert(Ty->isPointerTy() && "Unexpected non-ptr");
896
897 // Make sure that the pointer does not point to aggregate types.
Craig Toppere3dcce92015-08-01 22:20:21 +0000898 auto *PtrTy = cast<PointerType>(Ty);
Adam Nemet04563272015-02-01 16:56:15 +0000899 if (PtrTy->getElementType()->isAggregateType()) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000900 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type" << *Ptr
901 << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000902 return 0;
903 }
904
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000905 const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000906
907 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000908 if (Assume && !AR)
Silviu Barangad68ed852016-03-23 15:29:30 +0000909 AR = PSE.getAsAddRec(Ptr);
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000910
Adam Nemet04563272015-02-01 16:56:15 +0000911 if (!AR) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000912 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
913 << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000914 return 0;
915 }
916
917 // The accesss function must stride over the innermost loop.
918 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000919 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000920 *Ptr << " SCEV: " << *AR << "\n");
Kyle Butta02ce982016-01-08 01:55:13 +0000921 return 0;
Adam Nemet04563272015-02-01 16:56:15 +0000922 }
923
924 // The address calculation must not wrap. Otherwise, a dependence could be
925 // inverted.
926 // An inbounds getelementptr that is a AddRec with a unit stride
927 // cannot wrap per definition. The unit stride requirement is checked later.
928 // An getelementptr without an inbounds attribute and unit stride would have
929 // to access the pointer value "0" which is undefined behavior in address
930 // space 0, therefore we can also vectorize this case.
931 bool IsInBoundsGEP = isInBoundsGep(Ptr);
Elena Demikhovsky5f8cc0c2016-09-18 13:56:08 +0000932 bool IsNoWrapAddRec = !ShouldCheckWrap ||
933 PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) ||
934 isNoWrapAddRec(Ptr, AR, PSE, Lp);
Adam Nemet04563272015-02-01 16:56:15 +0000935 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
936 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000937 if (Assume) {
938 PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
939 IsNoWrapAddRec = true;
940 DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n"
941 << "LAA: Pointer: " << *Ptr << "\n"
942 << "LAA: SCEV: " << *AR << "\n"
943 << "LAA: Added an overflow assumption\n");
944 } else {
945 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
946 << *Ptr << " SCEV: " << *AR << "\n");
947 return 0;
948 }
Adam Nemet04563272015-02-01 16:56:15 +0000949 }
950
951 // Check the step is constant.
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +0000952 const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
Adam Nemet04563272015-02-01 16:56:15 +0000953
Adam Nemet943befe2015-07-09 00:03:22 +0000954 // Calculate the pointer stride and check if it is constant.
Adam Nemet04563272015-02-01 16:56:15 +0000955 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
956 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000957 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000958 " SCEV: " << *AR << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000959 return 0;
960 }
961
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000962 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
963 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000964 const APInt &APStepVal = C->getAPInt();
Adam Nemet04563272015-02-01 16:56:15 +0000965
966 // Huge step value - give up.
967 if (APStepVal.getBitWidth() > 64)
968 return 0;
969
970 int64_t StepVal = APStepVal.getSExtValue();
971
972 // Strided access.
973 int64_t Stride = StepVal / Size;
974 int64_t Rem = StepVal % Size;
975 if (Rem)
976 return 0;
977
978 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
979 // know we can't "wrap around the address space". In case of address space
980 // zero we know that this won't happen without triggering undefined behavior.
981 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
Silviu Barangaea63a7f2016-02-08 17:02:45 +0000982 Stride != 1 && Stride != -1) {
983 if (Assume) {
984 // We can avoid this case by adding a run-time check.
985 DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either "
986 << "inbouds or in address space 0 may wrap:\n"
987 << "LAA: Pointer: " << *Ptr << "\n"
988 << "LAA: SCEV: " << *AR << "\n"
989 << "LAA: Added an overflow assumption\n");
990 PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW);
991 } else
992 return 0;
993 }
Adam Nemet04563272015-02-01 16:56:15 +0000994
995 return Stride;
996}
997
Haicheng Wuf1c00a22016-01-26 02:27:47 +0000998/// Take the pointer operand from the Load/Store instruction.
999/// Returns NULL if this is not a valid Load/Store instruction.
1000static Value *getPointerOperand(Value *I) {
David Majnemer8b401012016-07-12 20:31:46 +00001001 if (auto *LI = dyn_cast<LoadInst>(I))
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001002 return LI->getPointerOperand();
David Majnemer8b401012016-07-12 20:31:46 +00001003 if (auto *SI = dyn_cast<StoreInst>(I))
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001004 return SI->getPointerOperand();
1005 return nullptr;
1006}
1007
1008/// Take the address space operand from the Load/Store instruction.
1009/// Returns -1 if this is not a valid Load/Store instruction.
1010static unsigned getAddressSpaceOperand(Value *I) {
1011 if (LoadInst *L = dyn_cast<LoadInst>(I))
1012 return L->getPointerAddressSpace();
1013 if (StoreInst *S = dyn_cast<StoreInst>(I))
1014 return S->getPointerAddressSpace();
1015 return -1;
1016}
1017
1018/// Returns true if the memory operations \p A and \p B are consecutive.
1019bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
1020 ScalarEvolution &SE, bool CheckType) {
1021 Value *PtrA = getPointerOperand(A);
1022 Value *PtrB = getPointerOperand(B);
1023 unsigned ASA = getAddressSpaceOperand(A);
1024 unsigned ASB = getAddressSpaceOperand(B);
1025
1026 // Check that the address spaces match and that the pointers are valid.
1027 if (!PtrA || !PtrB || (ASA != ASB))
1028 return false;
1029
1030 // Make sure that A and B are different pointers.
1031 if (PtrA == PtrB)
1032 return false;
1033
1034 // Make sure that A and B have the same type if required.
Chad Rosier83a12032016-08-31 18:37:52 +00001035 if (CheckType && PtrA->getType() != PtrB->getType())
1036 return false;
Haicheng Wuf1c00a22016-01-26 02:27:47 +00001037
1038 unsigned PtrBitWidth = DL.getPointerSizeInBits(ASA);
1039 Type *Ty = cast<PointerType>(PtrA->getType())->getElementType();
1040 APInt Size(PtrBitWidth, DL.getTypeStoreSize(Ty));
1041
1042 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1043 PtrA = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA);
1044 PtrB = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB);
1045
1046 // OffsetDelta = OffsetB - OffsetA;
1047 const SCEV *OffsetSCEVA = SE.getConstant(OffsetA);
1048 const SCEV *OffsetSCEVB = SE.getConstant(OffsetB);
1049 const SCEV *OffsetDeltaSCEV = SE.getMinusSCEV(OffsetSCEVB, OffsetSCEVA);
1050 const SCEVConstant *OffsetDeltaC = dyn_cast<SCEVConstant>(OffsetDeltaSCEV);
1051 const APInt &OffsetDelta = OffsetDeltaC->getAPInt();
1052 // Check if they are based on the same pointer. That makes the offsets
1053 // sufficient.
1054 if (PtrA == PtrB)
1055 return OffsetDelta == Size;
1056
1057 // Compute the necessary base pointer delta to have the necessary final delta
1058 // equal to the size.
1059 // BaseDelta = Size - OffsetDelta;
1060 const SCEV *SizeSCEV = SE.getConstant(Size);
1061 const SCEV *BaseDelta = SE.getMinusSCEV(SizeSCEV, OffsetDeltaSCEV);
1062
1063 // Otherwise compute the distance with SCEV between the base pointers.
1064 const SCEV *PtrSCEVA = SE.getSCEV(PtrA);
1065 const SCEV *PtrSCEVB = SE.getSCEV(PtrB);
1066 const SCEV *X = SE.getAddExpr(PtrSCEVA, BaseDelta);
1067 return X == PtrSCEVB;
1068}
1069
Adam Nemet9c926572015-03-10 17:40:37 +00001070bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
1071 switch (Type) {
1072 case NoDep:
1073 case Forward:
1074 case BackwardVectorizable:
1075 return true;
1076
1077 case Unknown:
1078 case ForwardButPreventsForwarding:
1079 case Backward:
1080 case BackwardVectorizableButPreventsForwarding:
1081 return false;
1082 }
David Majnemerd388e932015-03-10 20:23:29 +00001083 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +00001084}
1085
Adam Nemet397f5822015-11-03 23:50:03 +00001086bool MemoryDepChecker::Dependence::isBackward() const {
Adam Nemet9c926572015-03-10 17:40:37 +00001087 switch (Type) {
1088 case NoDep:
1089 case Forward:
1090 case ForwardButPreventsForwarding:
Adam Nemet397f5822015-11-03 23:50:03 +00001091 case Unknown:
Adam Nemet9c926572015-03-10 17:40:37 +00001092 return false;
1093
Adam Nemet9c926572015-03-10 17:40:37 +00001094 case BackwardVectorizable:
1095 case Backward:
1096 case BackwardVectorizableButPreventsForwarding:
1097 return true;
1098 }
David Majnemerd388e932015-03-10 20:23:29 +00001099 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +00001100}
1101
Adam Nemet397f5822015-11-03 23:50:03 +00001102bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
1103 return isBackward() || Type == Unknown;
1104}
1105
1106bool MemoryDepChecker::Dependence::isForward() const {
1107 switch (Type) {
1108 case Forward:
1109 case ForwardButPreventsForwarding:
1110 return true;
1111
1112 case NoDep:
1113 case Unknown:
1114 case BackwardVectorizable:
1115 case Backward:
1116 case BackwardVectorizableButPreventsForwarding:
1117 return false;
1118 }
1119 llvm_unreachable("unexpected DepType!");
1120}
1121
David Majnemer7afb46d2016-07-07 06:24:36 +00001122bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
1123 uint64_t TypeByteSize) {
Adam Nemet04563272015-02-01 16:56:15 +00001124 // If loads occur at a distance that is not a multiple of a feasible vector
1125 // factor store-load forwarding does not take place.
1126 // Positive dependences might cause troubles because vectorizing them might
1127 // prevent store-load forwarding making vectorized code run a lot slower.
1128 // a[i] = a[i-3] ^ a[i-8];
1129 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
1130 // hence on your typical architecture store-load forwarding does not take
1131 // place. Vectorizing in such cases does not make sense.
1132 // Store-load forwarding distance.
Adam Nemet884d3132016-05-16 16:57:47 +00001133
1134 // After this many iterations store-to-load forwarding conflicts should not
1135 // cause any slowdowns.
David Majnemer7afb46d2016-07-07 06:24:36 +00001136 const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
Adam Nemet04563272015-02-01 16:56:15 +00001137 // Maximum vector factor.
David Majnemer7afb46d2016-07-07 06:24:36 +00001138 uint64_t MaxVFWithoutSLForwardIssues = std::min(
Adam Nemet2c34ab52016-05-12 21:41:53 +00001139 VectorizerParams::MaxVectorWidth * TypeByteSize, MaxSafeDepDistBytes);
Adam Nemet04563272015-02-01 16:56:15 +00001140
Adam Nemet884d3132016-05-16 16:57:47 +00001141 // Compute the smallest VF at which the store and load would be misaligned.
David Majnemer7afb46d2016-07-07 06:24:36 +00001142 for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
Adam Nemet9b5852a2016-05-16 16:57:42 +00001143 VF *= 2) {
Adam Nemet884d3132016-05-16 16:57:47 +00001144 // If the number of vector iteration between the store and the load are
1145 // small we could incur conflicts.
1146 if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
Adam Nemet9b5852a2016-05-16 16:57:42 +00001147 MaxVFWithoutSLForwardIssues = (VF >>= 1);
Adam Nemet04563272015-02-01 16:56:15 +00001148 break;
1149 }
1150 }
1151
Adam Nemet9b5852a2016-05-16 16:57:42 +00001152 if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
1153 DEBUG(dbgs() << "LAA: Distance " << Distance
1154 << " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +00001155 return true;
1156 }
1157
1158 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +00001159 MaxVFWithoutSLForwardIssues !=
Adam Nemet9b5852a2016-05-16 16:57:42 +00001160 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +00001161 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
1162 return false;
1163}
1164
Hao Liu751004a2015-06-08 04:48:37 +00001165/// \brief Check the dependence for two accesses with the same stride \p Stride.
1166/// \p Distance is the positive distance and \p TypeByteSize is type size in
1167/// bytes.
1168///
1169/// \returns true if they are independent.
David Majnemer7afb46d2016-07-07 06:24:36 +00001170static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride,
1171 uint64_t TypeByteSize) {
Hao Liu751004a2015-06-08 04:48:37 +00001172 assert(Stride > 1 && "The stride must be greater than 1");
1173 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
1174 assert(Distance > 0 && "The distance must be non-zero");
1175
1176 // Skip if the distance is not multiple of type byte size.
1177 if (Distance % TypeByteSize)
1178 return false;
1179
David Majnemer7afb46d2016-07-07 06:24:36 +00001180 uint64_t ScaledDist = Distance / TypeByteSize;
Hao Liu751004a2015-06-08 04:48:37 +00001181
1182 // No dependence if the scaled distance is not multiple of the stride.
1183 // E.g.
1184 // for (i = 0; i < 1024 ; i += 4)
1185 // A[i+2] = A[i] + 1;
1186 //
1187 // Two accesses in memory (scaled distance is 2, stride is 4):
1188 // | A[0] | | | | A[4] | | | |
1189 // | | | A[2] | | | | A[6] | |
1190 //
1191 // E.g.
1192 // for (i = 0; i < 1024 ; i += 3)
1193 // A[i+4] = A[i] + 1;
1194 //
1195 // Two accesses in memory (scaled distance is 4, stride is 3):
1196 // | A[0] | | | A[3] | | | A[6] | | |
1197 // | | | | | A[4] | | | A[7] | |
1198 return ScaledDist % Stride;
1199}
1200
Adam Nemet9c926572015-03-10 17:40:37 +00001201MemoryDepChecker::Dependence::DepType
1202MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1203 const MemAccessInfo &B, unsigned BIdx,
1204 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001205 assert (AIdx < BIdx && "Must pass arguments in program order");
1206
1207 Value *APtr = A.getPointer();
1208 Value *BPtr = B.getPointer();
1209 bool AIsWrite = A.getInt();
1210 bool BIsWrite = B.getInt();
1211
1212 // Two reads are independent.
1213 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +00001214 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +00001215
1216 // We cannot check pointers in different address spaces.
1217 if (APtr->getType()->getPointerAddressSpace() !=
1218 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +00001219 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001220
David Majnemer7afb46d2016-07-07 06:24:36 +00001221 int64_t StrideAPtr = getPtrStride(PSE, APtr, InnermostLoop, Strides, true);
1222 int64_t StrideBPtr = getPtrStride(PSE, BPtr, InnermostLoop, Strides, true);
Adam Nemet04563272015-02-01 16:56:15 +00001223
Silviu Barangaadf4b732016-05-10 12:28:49 +00001224 const SCEV *Src = PSE.getSCEV(APtr);
1225 const SCEV *Sink = PSE.getSCEV(BPtr);
Adam Nemet04563272015-02-01 16:56:15 +00001226
1227 // If the induction step is negative we have to invert source and sink of the
1228 // dependence.
1229 if (StrideAPtr < 0) {
Adam Nemet04563272015-02-01 16:56:15 +00001230 std::swap(APtr, BPtr);
1231 std::swap(Src, Sink);
1232 std::swap(AIsWrite, BIsWrite);
1233 std::swap(AIdx, BIdx);
1234 std::swap(StrideAPtr, StrideBPtr);
1235 }
1236
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001237 const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
Adam Nemet04563272015-02-01 16:56:15 +00001238
Adam Nemet339f42b2015-02-19 19:15:07 +00001239 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001240 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +00001241 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +00001242 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +00001243
Adam Nemet943befe2015-07-09 00:03:22 +00001244 // Need accesses with constant stride. We don't want to vectorize
Adam Nemet04563272015-02-01 16:56:15 +00001245 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1246 // the address space.
1247 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
Adam Nemet943befe2015-07-09 00:03:22 +00001248 DEBUG(dbgs() << "Pointer access with non-constant stride\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001249 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001250 }
1251
1252 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1253 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001254 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +00001255 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +00001256 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001257 }
1258
1259 Type *ATy = APtr->getType()->getPointerElementType();
1260 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001261 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
David Majnemer7afb46d2016-07-07 06:24:36 +00001262 uint64_t TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +00001263
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001264 const APInt &Val = C->getAPInt();
Matthew Simpson6feebe92016-05-19 15:37:19 +00001265 int64_t Distance = Val.getSExtValue();
David Majnemer7afb46d2016-07-07 06:24:36 +00001266 uint64_t Stride = std::abs(StrideAPtr);
Matthew Simpson6feebe92016-05-19 15:37:19 +00001267
1268 // Attempt to prove strided accesses independent.
1269 if (std::abs(Distance) > 0 && Stride > 1 && ATy == BTy &&
1270 areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) {
1271 DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
1272 return Dependence::NoDep;
1273 }
1274
1275 // Negative distances are not plausible dependencies.
Adam Nemet04563272015-02-01 16:56:15 +00001276 if (Val.isNegative()) {
1277 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
Matthew Simpson37ec5f92016-05-16 17:00:56 +00001278 if (IsTrueDataDependence && EnableForwardingConflictDetection &&
Adam Nemet04563272015-02-01 16:56:15 +00001279 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
Adam Nemetb8486e52016-03-01 00:50:08 +00001280 ATy != BTy)) {
1281 DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001282 return Dependence::ForwardButPreventsForwarding;
Adam Nemetb8486e52016-03-01 00:50:08 +00001283 }
Adam Nemet04563272015-02-01 16:56:15 +00001284
Adam Nemet724ab222016-05-05 23:41:28 +00001285 DEBUG(dbgs() << "LAA: Dependence is negative\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001286 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +00001287 }
1288
1289 // Write to the same location with the same size.
1290 // Could be improved to assert type sizes are the same (i32 == float, etc).
1291 if (Val == 0) {
1292 if (ATy == BTy)
Adam Nemetd7037c52015-11-03 20:13:43 +00001293 return Dependence::Forward;
Adam Nemet339f42b2015-02-19 19:15:07 +00001294 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001295 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001296 }
1297
1298 assert(Val.isStrictlyPositive() && "Expect a positive value");
1299
Adam Nemet04563272015-02-01 16:56:15 +00001300 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +00001301 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +00001302 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001303 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001304 }
1305
Adam Nemet04563272015-02-01 16:56:15 +00001306 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +00001307 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1308 VectorizerParams::VectorizationFactor : 1);
1309 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1310 VectorizerParams::VectorizationInterleave : 1);
Hao Liu751004a2015-06-08 04:48:37 +00001311 // The minimum number of iterations for a vectorized/unrolled version.
1312 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
Adam Nemet04563272015-02-01 16:56:15 +00001313
Hao Liu751004a2015-06-08 04:48:37 +00001314 // It's not vectorizable if the distance is smaller than the minimum distance
1315 // needed for a vectroized/unrolled version. Vectorizing one iteration in
1316 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1317 // TypeByteSize (No need to plus the last gap distance).
1318 //
1319 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1320 // foo(int *A) {
1321 // int *B = (int *)((char *)A + 14);
1322 // for (i = 0 ; i < 1024 ; i += 2)
1323 // B[i] = A[i] + 1;
1324 // }
1325 //
1326 // Two accesses in memory (stride is 2):
1327 // | A[0] | | A[2] | | A[4] | | A[6] | |
1328 // | B[0] | | B[2] | | B[4] |
1329 //
1330 // Distance needs for vectorizing iterations except the last iteration:
1331 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1332 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1333 //
1334 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1335 // 12, which is less than distance.
1336 //
1337 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1338 // the minimum distance needed is 28, which is greater than distance. It is
1339 // not safe to do vectorization.
David Majnemer7afb46d2016-07-07 06:24:36 +00001340 uint64_t MinDistanceNeeded =
Hao Liu751004a2015-06-08 04:48:37 +00001341 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
David Majnemer7afb46d2016-07-07 06:24:36 +00001342 if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
Hao Liu751004a2015-06-08 04:48:37 +00001343 DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1344 << '\n');
1345 return Dependence::Backward;
1346 }
1347
1348 // Unsafe if the minimum distance needed is greater than max safe distance.
1349 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1350 DEBUG(dbgs() << "LAA: Failure because it needs at least "
1351 << MinDistanceNeeded << " size in bytes");
Adam Nemet9c926572015-03-10 17:40:37 +00001352 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +00001353 }
1354
Adam Nemet9cc0c392015-02-26 17:58:48 +00001355 // Positive distance bigger than max vectorization factor.
Hao Liu751004a2015-06-08 04:48:37 +00001356 // FIXME: Should use max factor instead of max distance in bytes, which could
1357 // not handle different types.
1358 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1359 // void foo (int *A, char *B) {
1360 // for (unsigned i = 0; i < 1024; i++) {
1361 // A[i+2] = A[i] + 1;
1362 // B[i+2] = B[i] + 1;
1363 // }
1364 // }
1365 //
1366 // This case is currently unsafe according to the max safe distance. If we
1367 // analyze the two accesses on array B, the max safe dependence distance
1368 // is 2. Then we analyze the accesses on array A, the minimum distance needed
1369 // is 8, which is less than 2 and forbidden vectorization, But actually
1370 // both A and B could be vectorized by 2 iterations.
1371 MaxSafeDepDistBytes =
David Majnemer7afb46d2016-07-07 06:24:36 +00001372 std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes);
Adam Nemet04563272015-02-01 16:56:15 +00001373
1374 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
Matthew Simpson37ec5f92016-05-16 17:00:56 +00001375 if (IsTrueDataDependence && EnableForwardingConflictDetection &&
Adam Nemet04563272015-02-01 16:56:15 +00001376 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +00001377 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001378
Hao Liu751004a2015-06-08 04:48:37 +00001379 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1380 << " with max VF = "
1381 << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
Adam Nemet04563272015-02-01 16:56:15 +00001382
Adam Nemet9c926572015-03-10 17:40:37 +00001383 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +00001384}
1385
Adam Nemetdee666b2015-03-10 17:40:34 +00001386bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +00001387 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001388 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001389
David Majnemer7afb46d2016-07-07 06:24:36 +00001390 MaxSafeDepDistBytes = -1;
Adam Nemet04563272015-02-01 16:56:15 +00001391 while (!CheckDeps.empty()) {
1392 MemAccessInfo CurAccess = *CheckDeps.begin();
1393
1394 // Get the relevant memory access set.
1395 EquivalenceClasses<MemAccessInfo>::iterator I =
1396 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1397
1398 // Check accesses within this set.
Richard Trieu7a083812016-02-18 22:09:30 +00001399 EquivalenceClasses<MemAccessInfo>::member_iterator AI =
1400 AccessSets.member_begin(I);
1401 EquivalenceClasses<MemAccessInfo>::member_iterator AE =
1402 AccessSets.member_end();
Adam Nemet04563272015-02-01 16:56:15 +00001403
1404 // Check every access pair.
1405 while (AI != AE) {
1406 CheckDeps.erase(*AI);
1407 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1408 while (OI != AE) {
1409 // Check every accessing instruction pair in program order.
1410 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1411 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1412 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1413 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +00001414 auto A = std::make_pair(&*AI, *I1);
1415 auto B = std::make_pair(&*OI, *I2);
1416
1417 assert(*I1 != *I2);
1418 if (*I1 > *I2)
1419 std::swap(A, B);
1420
1421 Dependence::DepType Type =
1422 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1423 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1424
Adam Nemeta2df7502015-11-03 21:39:52 +00001425 // Gather dependences unless we accumulated MaxDependences
Adam Nemet9c926572015-03-10 17:40:37 +00001426 // dependences. In that case return as soon as we find the first
1427 // unsafe dependence. This puts a limit on this quadratic
1428 // algorithm.
Adam Nemeta2df7502015-11-03 21:39:52 +00001429 if (RecordDependences) {
1430 if (Type != Dependence::NoDep)
1431 Dependences.push_back(Dependence(A.second, B.second, Type));
Adam Nemet9c926572015-03-10 17:40:37 +00001432
Adam Nemeta2df7502015-11-03 21:39:52 +00001433 if (Dependences.size() >= MaxDependences) {
1434 RecordDependences = false;
1435 Dependences.clear();
Adam Nemet9c926572015-03-10 17:40:37 +00001436 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1437 }
1438 }
Adam Nemeta2df7502015-11-03 21:39:52 +00001439 if (!RecordDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +00001440 return false;
1441 }
1442 ++OI;
1443 }
1444 AI++;
1445 }
1446 }
Adam Nemet9c926572015-03-10 17:40:37 +00001447
Adam Nemeta2df7502015-11-03 21:39:52 +00001448 DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001449 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +00001450}
1451
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001452SmallVector<Instruction *, 4>
1453MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1454 MemAccessInfo Access(Ptr, isWrite);
1455 auto &IndexVector = Accesses.find(Access)->second;
1456
1457 SmallVector<Instruction *, 4> Insts;
David Majnemer2d006e72016-08-12 04:32:42 +00001458 transform(IndexVector,
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001459 std::back_inserter(Insts),
1460 [&](unsigned Idx) { return this->InstMap[Idx]; });
1461 return Insts;
1462}
1463
Adam Nemet58913d62015-03-10 17:40:43 +00001464const char *MemoryDepChecker::Dependence::DepName[] = {
1465 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1466 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1467
1468void MemoryDepChecker::Dependence::print(
1469 raw_ostream &OS, unsigned Depth,
1470 const SmallVectorImpl<Instruction *> &Instrs) const {
1471 OS.indent(Depth) << DepName[Type] << ":\n";
1472 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1473 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1474}
1475
Adam Nemet929c38e2015-02-19 19:15:10 +00001476bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001477 // We need to have a loop header.
Adam Nemetd8968f02016-01-18 21:16:33 +00001478 DEBUG(dbgs() << "LAA: Found a loop in "
1479 << TheLoop->getHeader()->getParent()->getName() << ": "
1480 << TheLoop->getHeader()->getName() << '\n');
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001481
Adam Nemetd8968f02016-01-18 21:16:33 +00001482 // We can only analyze innermost loops.
Adam Nemet929c38e2015-02-19 19:15:10 +00001483 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001484 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet877ccee2016-09-30 00:01:30 +00001485 recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop";
Adam Nemet929c38e2015-02-19 19:15:10 +00001486 return false;
1487 }
1488
1489 // We must have a single backedge.
1490 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001491 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet877ccee2016-09-30 00:01:30 +00001492 recordAnalysis("CFGNotUnderstood")
1493 << "loop control flow is not understood by analyzer";
Adam Nemet929c38e2015-02-19 19:15:10 +00001494 return false;
1495 }
1496
1497 // We must have a single exiting block.
1498 if (!TheLoop->getExitingBlock()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001499 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet877ccee2016-09-30 00:01:30 +00001500 recordAnalysis("CFGNotUnderstood")
1501 << "loop control flow is not understood by analyzer";
Adam Nemet929c38e2015-02-19 19:15:10 +00001502 return false;
1503 }
1504
1505 // We only handle bottom-tested loops, i.e. loop in which the condition is
1506 // checked at the end of each iteration. With that we can assume that all
1507 // instructions in the loop are executed the same number of times.
1508 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001509 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet877ccee2016-09-30 00:01:30 +00001510 recordAnalysis("CFGNotUnderstood")
1511 << "loop control flow is not understood by analyzer";
Adam Nemet929c38e2015-02-19 19:15:10 +00001512 return false;
1513 }
1514
Adam Nemet929c38e2015-02-19 19:15:10 +00001515 // ScalarEvolution needs to be able to find the exit count.
Xinliang David Li94734ee2016-07-01 05:59:55 +00001516 const SCEV *ExitCount = PSE->getBackedgeTakenCount();
1517 if (ExitCount == PSE->getSE()->getCouldNotCompute()) {
Adam Nemet877ccee2016-09-30 00:01:30 +00001518 recordAnalysis("CantComputeNumberOfIterations")
1519 << "could not determine number of loop iterations";
Adam Nemet929c38e2015-02-19 19:15:10 +00001520 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1521 return false;
1522 }
1523
1524 return true;
1525}
1526
Adam Nemetb49d9a52016-07-13 22:36:27 +00001527void LoopAccessInfo::analyzeLoop(AliasAnalysis *AA, LoopInfo *LI,
Adam Nemet7da74ab2016-07-13 22:36:35 +00001528 const TargetLibraryInfo *TLI,
1529 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001530 typedef SmallPtrSet<Value*, 16> ValueSet;
1531
Matthew Simpsone3e3b992016-06-06 14:15:41 +00001532 // Holds the Load and Store instructions.
1533 SmallVector<LoadInst *, 16> Loads;
1534 SmallVector<StoreInst *, 16> Stores;
Adam Nemet04563272015-02-01 16:56:15 +00001535
1536 // Holds all the different accesses in the loop.
1537 unsigned NumReads = 0;
1538 unsigned NumReadWrites = 0;
1539
Xinliang David Lice030ac2016-06-22 23:20:59 +00001540 PtrRtChecking->Pointers.clear();
1541 PtrRtChecking->Need = false;
Adam Nemet04563272015-02-01 16:56:15 +00001542
1543 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +00001544
1545 // For each block.
David Majnemer8b401012016-07-12 20:31:46 +00001546 for (BasicBlock *BB : TheLoop->blocks()) {
Adam Nemet04563272015-02-01 16:56:15 +00001547 // Scan the BB and collect legal loads and stores.
David Majnemer8b401012016-07-12 20:31:46 +00001548 for (Instruction &I : *BB) {
Adam Nemet04563272015-02-01 16:56:15 +00001549 // If this is a load, save it. If this instruction can read from memory
1550 // but is not a load, then we quit. Notice that we don't handle function
1551 // calls that read or write.
David Majnemer8b401012016-07-12 20:31:46 +00001552 if (I.mayReadFromMemory()) {
Adam Nemet04563272015-02-01 16:56:15 +00001553 // Many math library functions read the rounding mode. We will only
1554 // vectorize a loop if it contains known function calls that don't set
1555 // the flag. Therefore, it is safe to ignore this read from memory.
David Majnemer8b401012016-07-12 20:31:46 +00001556 auto *Call = dyn_cast<CallInst>(&I);
David Majnemerb4b27232016-04-19 19:10:21 +00001557 if (Call && getVectorIntrinsicIDForCall(Call, TLI))
Adam Nemet04563272015-02-01 16:56:15 +00001558 continue;
1559
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +00001560 // If the function has an explicit vectorized counterpart, we can safely
1561 // assume that it can be vectorized.
1562 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1563 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1564 continue;
1565
David Majnemer8b401012016-07-12 20:31:46 +00001566 auto *Ld = dyn_cast<LoadInst>(&I);
Adam Nemet04563272015-02-01 16:56:15 +00001567 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet877ccee2016-09-30 00:01:30 +00001568 recordAnalysis("NonSimpleLoad", Ld)
1569 << "read with atomic ordering or volatile read";
Adam Nemet339f42b2015-02-19 19:15:07 +00001570 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001571 CanVecMem = false;
1572 return;
Adam Nemet04563272015-02-01 16:56:15 +00001573 }
1574 NumLoads++;
1575 Loads.push_back(Ld);
Xinliang David Lice030ac2016-06-22 23:20:59 +00001576 DepChecker->addAccess(Ld);
Adam Nemeta9f09c62016-06-17 22:35:41 +00001577 if (EnableMemAccessVersioning)
Adam Nemetc953bb92016-06-16 22:57:55 +00001578 collectStridedAccess(Ld);
Adam Nemet04563272015-02-01 16:56:15 +00001579 continue;
1580 }
1581
1582 // Save 'store' instructions. Abort if other instructions write to memory.
David Majnemer8b401012016-07-12 20:31:46 +00001583 if (I.mayWriteToMemory()) {
1584 auto *St = dyn_cast<StoreInst>(&I);
Adam Nemet04563272015-02-01 16:56:15 +00001585 if (!St) {
Adam Nemet877ccee2016-09-30 00:01:30 +00001586 recordAnalysis("CantVectorizeInstruction", St)
1587 << "instruction cannot be vectorized";
Adam Nemet436018c2015-02-19 19:15:00 +00001588 CanVecMem = false;
1589 return;
Adam Nemet04563272015-02-01 16:56:15 +00001590 }
1591 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet877ccee2016-09-30 00:01:30 +00001592 recordAnalysis("NonSimpleStore", St)
1593 << "write with atomic ordering or volatile write";
Adam Nemet339f42b2015-02-19 19:15:07 +00001594 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001595 CanVecMem = false;
1596 return;
Adam Nemet04563272015-02-01 16:56:15 +00001597 }
1598 NumStores++;
1599 Stores.push_back(St);
Xinliang David Lice030ac2016-06-22 23:20:59 +00001600 DepChecker->addAccess(St);
Adam Nemeta9f09c62016-06-17 22:35:41 +00001601 if (EnableMemAccessVersioning)
Adam Nemetc953bb92016-06-16 22:57:55 +00001602 collectStridedAccess(St);
Adam Nemet04563272015-02-01 16:56:15 +00001603 }
1604 } // Next instr.
1605 } // Next block.
1606
1607 // Now we have two lists that hold the loads and the stores.
1608 // Next, we find the pointers that they use.
1609
1610 // Check if we see any stores. If there are no stores, then we don't
1611 // care if the pointers are *restrict*.
1612 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001613 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001614 CanVecMem = true;
1615 return;
Adam Nemet04563272015-02-01 16:56:15 +00001616 }
1617
Adam Nemetdee666b2015-03-10 17:40:34 +00001618 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001619 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Xinliang David Li94734ee2016-07-01 05:59:55 +00001620 AA, LI, DependentAccesses, *PSE);
Adam Nemet04563272015-02-01 16:56:15 +00001621
1622 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1623 // multiple times on the same object. If the ptr is accessed twice, once
1624 // for read and once for write, it will only appear once (on the write
1625 // list). This is okay, since we are going to check for conflicts between
1626 // writes and between reads and writes, but not between reads and reads.
1627 ValueSet Seen;
1628
Matthew Simpsone3e3b992016-06-06 14:15:41 +00001629 for (StoreInst *ST : Stores) {
1630 Value *Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001631 // Check for store to loop invariant address.
1632 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001633 // If we did *not* see this pointer before, insert it to the read-write
1634 // list. At this phase it is only a 'write' list.
1635 if (Seen.insert(Ptr).second) {
1636 ++NumReadWrites;
1637
Chandler Carruthac80dc72015-06-17 07:18:54 +00001638 MemoryLocation Loc = MemoryLocation::get(ST);
Adam Nemet04563272015-02-01 16:56:15 +00001639 // The TBAA metadata could have a control dependency on the predication
1640 // condition, so we cannot rely on it when determining whether or not we
1641 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001642 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001643 Loc.AATags.TBAA = nullptr;
1644
1645 Accesses.addStore(Loc);
1646 }
1647 }
1648
1649 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001650 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001651 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001652 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001653 CanVecMem = true;
1654 return;
Adam Nemet04563272015-02-01 16:56:15 +00001655 }
1656
Matthew Simpsone3e3b992016-06-06 14:15:41 +00001657 for (LoadInst *LD : Loads) {
1658 Value *Ptr = LD->getPointerOperand();
Adam Nemet04563272015-02-01 16:56:15 +00001659 // If we did *not* see this pointer before, insert it to the
1660 // read list. If we *did* see it before, then it is already in
1661 // the read-write list. This allows us to vectorize expressions
1662 // such as A[i] += x; Because the address of A[i] is a read-write
1663 // pointer. This only works if the index of A[i] is consecutive.
1664 // If the address of i is unknown (for example A[B[i]]) then we may
1665 // read a few words, modify, and write a few words, and some of the
1666 // words may be written to the same address.
1667 bool IsReadOnlyPtr = false;
Adam Nemet139ffba2016-06-16 08:27:03 +00001668 if (Seen.insert(Ptr).second ||
Xinliang David Li94734ee2016-07-01 05:59:55 +00001669 !getPtrStride(*PSE, Ptr, TheLoop, SymbolicStrides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001670 ++NumReads;
1671 IsReadOnlyPtr = true;
1672 }
1673
Chandler Carruthac80dc72015-06-17 07:18:54 +00001674 MemoryLocation Loc = MemoryLocation::get(LD);
Adam Nemet04563272015-02-01 16:56:15 +00001675 // The TBAA metadata could have a control dependency on the predication
1676 // condition, so we cannot rely on it when determining whether or not we
1677 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001678 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001679 Loc.AATags.TBAA = nullptr;
1680
1681 Accesses.addLoad(Loc, IsReadOnlyPtr);
1682 }
1683
1684 // If we write (or read-write) to a single destination and there are no
1685 // other reads in this loop then is it safe to vectorize.
1686 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001687 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001688 CanVecMem = true;
1689 return;
Adam Nemet04563272015-02-01 16:56:15 +00001690 }
1691
1692 // Build dependence sets and check whether we need a runtime pointer bounds
1693 // check.
1694 Accesses.buildDependenceSets();
Adam Nemet04563272015-02-01 16:56:15 +00001695
1696 // Find pointers with computable bounds. We are going to use this information
1697 // to place a runtime bound check.
Xinliang David Li94734ee2016-07-01 05:59:55 +00001698 bool CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(),
Adam Nemet139ffba2016-06-16 08:27:03 +00001699 TheLoop, SymbolicStrides);
Adam Nemetee614742015-07-09 22:17:38 +00001700 if (!CanDoRTIfNeeded) {
Adam Nemet877ccee2016-09-30 00:01:30 +00001701 recordAnalysis("CantIdentifyArrayBounds") << "cannot identify array bounds";
Adam Nemetee614742015-07-09 22:17:38 +00001702 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1703 << "the array bounds.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001704 CanVecMem = false;
1705 return;
Adam Nemet04563272015-02-01 16:56:15 +00001706 }
1707
Adam Nemetee614742015-07-09 22:17:38 +00001708 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001709
Adam Nemet436018c2015-02-19 19:15:00 +00001710 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001711 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001712 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Xinliang David Lice030ac2016-06-22 23:20:59 +00001713 CanVecMem = DepChecker->areDepsSafe(
Adam Nemet139ffba2016-06-16 08:27:03 +00001714 DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides);
Xinliang David Lice030ac2016-06-22 23:20:59 +00001715 MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes();
Adam Nemet04563272015-02-01 16:56:15 +00001716
Xinliang David Lice030ac2016-06-22 23:20:59 +00001717 if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001718 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001719
1720 // Clear the dependency checks. We assume they are not needed.
Xinliang David Lice030ac2016-06-22 23:20:59 +00001721 Accesses.resetDepChecks(*DepChecker);
Adam Nemet04563272015-02-01 16:56:15 +00001722
Xinliang David Lice030ac2016-06-22 23:20:59 +00001723 PtrRtChecking->reset();
1724 PtrRtChecking->Need = true;
Adam Nemet04563272015-02-01 16:56:15 +00001725
Xinliang David Li94734ee2016-07-01 05:59:55 +00001726 auto *SE = PSE->getSE();
Xinliang David Lice030ac2016-06-22 23:20:59 +00001727 CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, SE, TheLoop,
Adam Nemet139ffba2016-06-16 08:27:03 +00001728 SymbolicStrides, true);
Silviu Baranga98a13712015-06-08 10:27:06 +00001729
Adam Nemet949e91a2015-03-10 19:12:41 +00001730 // Check that we found the bounds for the pointer.
Adam Nemetee614742015-07-09 22:17:38 +00001731 if (!CanDoRTIfNeeded) {
Adam Nemet877ccee2016-09-30 00:01:30 +00001732 recordAnalysis("CantCheckMemDepsAtRunTime")
1733 << "cannot check memory dependencies at runtime";
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001734 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001735 CanVecMem = false;
1736 return;
1737 }
1738
Adam Nemet04563272015-02-01 16:56:15 +00001739 CanVecMem = true;
1740 }
1741 }
1742
Adam Nemet4bb90a72015-03-10 21:47:39 +00001743 if (CanVecMem)
1744 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
Xinliang David Lice030ac2016-06-22 23:20:59 +00001745 << (PtrRtChecking->Need ? "" : " don't")
Adam Nemet0f67c6c2015-07-09 22:17:41 +00001746 << " need runtime memory checks.\n");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001747 else {
Adam Nemet877ccee2016-09-30 00:01:30 +00001748 recordAnalysis("UnsafeMemDep")
Adam Nemet0a77dfa2016-05-09 23:03:44 +00001749 << "unsafe dependent memory operations in loop. Use "
1750 "#pragma loop distribute(enable) to allow loop distribution "
1751 "to attempt to isolate the offending operations into a separate "
Adam Nemet877ccee2016-09-30 00:01:30 +00001752 "loop";
Adam Nemet4bb90a72015-03-10 21:47:39 +00001753 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1754 }
Adam Nemet04563272015-02-01 16:56:15 +00001755}
1756
Adam Nemet01abb2c2015-02-18 03:43:19 +00001757bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1758 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001759 assert(TheLoop->contains(BB) && "Unknown block used");
1760
1761 // Blocks that do not dominate the latch need predication.
1762 BasicBlock* Latch = TheLoop->getLoopLatch();
1763 return !DT->dominates(BB, Latch);
1764}
1765
Adam Nemet877ccee2016-09-30 00:01:30 +00001766OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName,
1767 Instruction *I) {
Adam Nemetc9228532015-02-19 19:14:56 +00001768 assert(!Report && "Multiple reports generated");
Adam Nemet877ccee2016-09-30 00:01:30 +00001769
1770 Value *CodeRegion = TheLoop->getHeader();
1771 DebugLoc DL = TheLoop->getStartLoc();
1772
1773 if (I) {
1774 CodeRegion = I->getParent();
1775 // If there is no debug location attached to the instruction, revert back to
1776 // using the loop's.
1777 if (I->getDebugLoc())
1778 DL = I->getDebugLoc();
1779 }
1780
1781 Report = make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL,
1782 CodeRegion);
1783 return *Report;
Adam Nemet04563272015-02-01 16:56:15 +00001784}
1785
Adam Nemet57ac7662015-02-19 19:15:21 +00001786bool LoopAccessInfo::isUniform(Value *V) const {
Michael Kuperstein3ceac2b2016-08-04 22:48:03 +00001787 auto *SE = PSE->getSE();
1788 // Since we rely on SCEV for uniformity, if the type is not SCEVable, it is
1789 // never considered uniform.
1790 // TODO: Is this really what we want? Even without FP SCEV, we may want some
1791 // trivially loop-invariant FP values to be considered uniform.
1792 if (!SE->isSCEVable(V->getType()))
1793 return false;
1794 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
Adam Nemet04563272015-02-01 16:56:15 +00001795}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001796
1797// FIXME: this function is currently a duplicate of the one in
1798// LoopVectorize.cpp.
1799static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1800 Instruction *Loc) {
1801 if (FirstInst)
1802 return FirstInst;
1803 if (Instruction *I = dyn_cast<Instruction>(V))
1804 return I->getParent() == Loc->getParent() ? I : nullptr;
1805 return nullptr;
1806}
1807
Benjamin Kramer039b1042015-10-28 13:54:36 +00001808namespace {
Adam Nemet4e533ef2015-08-21 23:19:57 +00001809/// \brief IR Values for the lower and upper bounds of a pointer evolution. We
1810/// need to use value-handles because SCEV expansion can invalidate previously
1811/// expanded values. Thus expansion of a pointer can invalidate the bounds for
1812/// a previous one.
Adam Nemet1da7df32015-07-26 05:32:14 +00001813struct PointerBounds {
Adam Nemet4e533ef2015-08-21 23:19:57 +00001814 TrackingVH<Value> Start;
1815 TrackingVH<Value> End;
Adam Nemet1da7df32015-07-26 05:32:14 +00001816};
Benjamin Kramer039b1042015-10-28 13:54:36 +00001817} // end anonymous namespace
Adam Nemet7206d7a2015-02-06 18:31:04 +00001818
Adam Nemet1da7df32015-07-26 05:32:14 +00001819/// \brief Expand code for the lower and upper bound of the pointer group \p CG
1820/// in \p TheLoop. \return the values for the bounds.
1821static PointerBounds
1822expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
1823 Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
1824 const RuntimePointerChecking &PtrRtChecking) {
1825 Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
1826 const SCEV *Sc = SE->getSCEV(Ptr);
1827
1828 if (SE->isLoopInvariant(Sc, TheLoop)) {
1829 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1830 << "\n");
1831 return {Ptr, Ptr};
1832 } else {
1833 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1834 LLVMContext &Ctx = Loc->getContext();
1835
1836 // Use this type for pointer arithmetic.
1837 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1838 Value *Start = nullptr, *End = nullptr;
1839
1840 DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1841 Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
1842 End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1843 DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
1844 return {Start, End};
1845 }
1846}
1847
1848/// \brief Turns a collection of checks into a collection of expanded upper and
1849/// lower bounds for both pointers in the check.
1850static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
1851 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
1852 Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
1853 const RuntimePointerChecking &PtrRtChecking) {
1854 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1855
1856 // Here we're relying on the SCEV Expander's cache to only emit code for the
1857 // same bounds once.
David Majnemer2d006e72016-08-12 04:32:42 +00001858 transform(
1859 PointerChecks, std::back_inserter(ChecksWithBounds),
Adam Nemet1da7df32015-07-26 05:32:14 +00001860 [&](const RuntimePointerChecking::PointerCheck &Check) {
NAKAMURA Takumi94abbbd2015-07-27 01:35:30 +00001861 PointerBounds
1862 First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
1863 Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
1864 return std::make_pair(First, Second);
Adam Nemet1da7df32015-07-26 05:32:14 +00001865 });
1866
1867 return ChecksWithBounds;
1868}
1869
Adam Nemet5b0a4792015-08-11 00:09:37 +00001870std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
Adam Nemet1da7df32015-07-26 05:32:14 +00001871 Instruction *Loc,
1872 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
1873 const {
Adam Nemet1824e412016-07-13 22:18:51 +00001874 const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout();
Xinliang David Li94734ee2016-07-01 05:59:55 +00001875 auto *SE = PSE->getSE();
Adam Nemet1824e412016-07-13 22:18:51 +00001876 SCEVExpander Exp(*SE, DL, "induction");
Adam Nemet1da7df32015-07-26 05:32:14 +00001877 auto ExpandedChecks =
Xinliang David Lice030ac2016-06-22 23:20:59 +00001878 expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, *PtrRtChecking);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001879
1880 LLVMContext &Ctx = Loc->getContext();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001881 Instruction *FirstInst = nullptr;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001882 IRBuilder<> ChkBuilder(Loc);
1883 // Our instructions might fold to a constant.
1884 Value *MemoryRuntimeCheck = nullptr;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001885
Adam Nemet1da7df32015-07-26 05:32:14 +00001886 for (const auto &Check : ExpandedChecks) {
1887 const PointerBounds &A = Check.first, &B = Check.second;
Adam Nemetcdb791c2015-08-19 17:24:36 +00001888 // Check if two pointers (A and B) conflict where conflict is computed as:
1889 // start(A) <= end(B) && start(B) <= end(A)
Adam Nemet1da7df32015-07-26 05:32:14 +00001890 unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1891 unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001892
Adam Nemet1da7df32015-07-26 05:32:14 +00001893 assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
1894 (AS1 == A.End->getType()->getPointerAddressSpace()) &&
1895 "Trying to bounds check pointers with different address spaces");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001896
Adam Nemet1da7df32015-07-26 05:32:14 +00001897 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1898 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001899
Adam Nemet1da7df32015-07-26 05:32:14 +00001900 Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
1901 Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
1902 Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
1903 Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001904
Elena Demikhovsky3622fbf2016-08-28 08:53:53 +00001905 // [A|B].Start points to the first accessed byte under base [A|B].
1906 // [A|B].End points to the last accessed byte, plus one.
1907 // There is no conflict when the intervals are disjoint:
1908 // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
1909 //
1910 // bound0 = (B.Start < A.End)
1911 // bound1 = (A.Start < B.End)
1912 // IsConflict = bound0 & bound1
1913 Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
Adam Nemet1da7df32015-07-26 05:32:14 +00001914 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
Elena Demikhovsky3622fbf2016-08-28 08:53:53 +00001915 Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
Adam Nemet1da7df32015-07-26 05:32:14 +00001916 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1917 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1918 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1919 if (MemoryRuntimeCheck) {
1920 IsConflict =
1921 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001922 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001923 }
Adam Nemet1da7df32015-07-26 05:32:14 +00001924 MemoryRuntimeCheck = IsConflict;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001925 }
1926
Adam Nemet90fec842015-04-02 17:51:57 +00001927 if (!MemoryRuntimeCheck)
1928 return std::make_pair(nullptr, nullptr);
1929
Adam Nemet7206d7a2015-02-06 18:31:04 +00001930 // We have to do this trickery because the IRBuilder might fold the check to a
1931 // constant expression in which case there is no Instruction anchored in a
1932 // the block.
1933 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1934 ConstantInt::getTrue(Ctx));
1935 ChkBuilder.Insert(Check, "memcheck.conflict");
1936 FirstInst = getFirstInst(FirstInst, Check, Loc);
1937 return std::make_pair(FirstInst, Check);
1938}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001939
Adam Nemet5b0a4792015-08-11 00:09:37 +00001940std::pair<Instruction *, Instruction *>
1941LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
Xinliang David Lice030ac2016-06-22 23:20:59 +00001942 if (!PtrRtChecking->Need)
Adam Nemet1da7df32015-07-26 05:32:14 +00001943 return std::make_pair(nullptr, nullptr);
1944
Xinliang David Lice030ac2016-06-22 23:20:59 +00001945 return addRuntimeChecks(Loc, PtrRtChecking->getChecks());
Adam Nemet1da7df32015-07-26 05:32:14 +00001946}
1947
Adam Nemetc953bb92016-06-16 22:57:55 +00001948void LoopAccessInfo::collectStridedAccess(Value *MemAccess) {
1949 Value *Ptr = nullptr;
1950 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
1951 Ptr = LI->getPointerOperand();
1952 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
1953 Ptr = SI->getPointerOperand();
1954 else
1955 return;
1956
Xinliang David Li94734ee2016-07-01 05:59:55 +00001957 Value *Stride = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop);
Adam Nemetc953bb92016-06-16 22:57:55 +00001958 if (!Stride)
1959 return;
1960
1961 DEBUG(dbgs() << "LAA: Found a strided access that we can version");
1962 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
1963 SymbolicStrides[Ptr] = Stride;
1964 StrideSet.insert(Stride);
1965}
1966
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001967LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001968 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemeta9f09c62016-06-17 22:35:41 +00001969 DominatorTree *DT, LoopInfo *LI)
Xinliang David Li94734ee2016-07-01 05:59:55 +00001970 : PSE(llvm::make_unique<PredicatedScalarEvolution>(*SE, *L)),
Xinliang David Lice030ac2016-06-22 23:20:59 +00001971 PtrRtChecking(llvm::make_unique<RuntimePointerChecking>(SE)),
Xinliang David Li94734ee2016-07-01 05:59:55 +00001972 DepChecker(llvm::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L),
Adam Nemet7da74ab2016-07-13 22:36:35 +00001973 NumLoads(0), NumStores(0), MaxSafeDepDistBytes(-1), CanVecMem(false),
1974 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001975 if (canAnalyzeLoop())
Adam Nemet7da74ab2016-07-13 22:36:35 +00001976 analyzeLoop(AA, LI, TLI, DT);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001977}
1978
Adam Nemete91cc6e2015-02-19 19:15:19 +00001979void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1980 if (CanVecMem) {
Adam Nemet4ad38b62016-05-13 22:49:09 +00001981 OS.indent(Depth) << "Memory dependences are safe";
David Majnemer7afb46d2016-07-07 06:24:36 +00001982 if (MaxSafeDepDistBytes != -1ULL)
Adam Nemetc62e5542016-05-13 22:49:13 +00001983 OS << " with a maximum dependence distance of " << MaxSafeDepDistBytes
1984 << " bytes";
Xinliang David Lice030ac2016-06-22 23:20:59 +00001985 if (PtrRtChecking->Need)
Adam Nemet4ad38b62016-05-13 22:49:09 +00001986 OS << " with run-time checks";
1987 OS << "\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001988 }
1989
1990 if (Report)
Adam Nemet877ccee2016-09-30 00:01:30 +00001991 OS.indent(Depth) << "Report: " << Report->getMsg() << "\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001992
Xinliang David Lice030ac2016-06-22 23:20:59 +00001993 if (auto *Dependences = DepChecker->getDependences()) {
Adam Nemeta2df7502015-11-03 21:39:52 +00001994 OS.indent(Depth) << "Dependences:\n";
1995 for (auto &Dep : *Dependences) {
Xinliang David Lice030ac2016-06-22 23:20:59 +00001996 Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
Adam Nemet58913d62015-03-10 17:40:43 +00001997 OS << "\n";
1998 }
1999 } else
Adam Nemeta2df7502015-11-03 21:39:52 +00002000 OS.indent(Depth) << "Too many dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00002001
2002 // List the pair of accesses need run-time checks to prove independence.
Xinliang David Lice030ac2016-06-22 23:20:59 +00002003 PtrRtChecking->print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00002004 OS << "\n";
Adam Nemetc3384322015-05-18 15:36:57 +00002005
2006 OS.indent(Depth) << "Store to invariant address was "
2007 << (StoreToLoopInvariantAddress ? "" : "not ")
2008 << "found in loop.\n";
Silviu Barangae3c05342015-11-02 14:41:02 +00002009
2010 OS.indent(Depth) << "SCEV assumptions:\n";
Xinliang David Li94734ee2016-07-01 05:59:55 +00002011 PSE->getUnionPredicate().print(OS, Depth);
Silviu Barangab77365b2016-04-14 16:08:45 +00002012
2013 OS << "\n";
2014
2015 OS.indent(Depth) << "Expressions re-written:\n";
Xinliang David Li94734ee2016-07-01 05:59:55 +00002016 PSE->print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00002017}
2018
Xinliang David Li7853c1d2016-07-08 20:55:26 +00002019const LoopAccessInfo &LoopAccessLegacyAnalysis::getInfo(Loop *L) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00002020 auto &LAI = LoopAccessInfoMap[L];
2021
Adam Nemet1824e412016-07-13 22:18:51 +00002022 if (!LAI)
2023 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, TLI, AA, DT, LI);
2024
Adam Nemet3bfd93d2015-02-19 19:15:04 +00002025 return *LAI.get();
2026}
2027
Xinliang David Li7853c1d2016-07-08 20:55:26 +00002028void LoopAccessLegacyAnalysis::print(raw_ostream &OS, const Module *M) const {
2029 LoopAccessLegacyAnalysis &LAA = *const_cast<LoopAccessLegacyAnalysis *>(this);
Xinliang David Liecde1c72016-06-09 03:22:39 +00002030
Adam Nemete91cc6e2015-02-19 19:15:19 +00002031 for (Loop *TopLevelLoop : *LI)
2032 for (Loop *L : depth_first(TopLevelLoop)) {
2033 OS.indent(2) << L->getHeader()->getName() << ":\n";
Adam Nemetbdbc5222016-06-16 08:26:56 +00002034 auto &LAI = LAA.getInfo(L);
Adam Nemete91cc6e2015-02-19 19:15:19 +00002035 LAI.print(OS, 4);
2036 }
2037}
2038
Xinliang David Li7853c1d2016-07-08 20:55:26 +00002039bool LoopAccessLegacyAnalysis::runOnFunction(Function &F) {
Xinliang David Liecde1c72016-06-09 03:22:39 +00002040 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00002041 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
Xinliang David Liecde1c72016-06-09 03:22:39 +00002042 TLI = TLIP ? &TLIP->getTLI() : nullptr;
2043 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2044 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2045 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00002046
2047 return false;
2048}
2049
Xinliang David Li7853c1d2016-07-08 20:55:26 +00002050void LoopAccessLegacyAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002051 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00002052 AU.addRequired<AAResultsWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00002053 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00002054 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00002055
2056 AU.setPreservesAll();
2057}
2058
Xinliang David Li7853c1d2016-07-08 20:55:26 +00002059char LoopAccessLegacyAnalysis::ID = 0;
Adam Nemet3bfd93d2015-02-19 19:15:04 +00002060static const char laa_name[] = "Loop Access Analysis";
2061#define LAA_NAME "loop-accesses"
2062
Xinliang David Li7853c1d2016-07-08 20:55:26 +00002063INITIALIZE_PASS_BEGIN(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
Chandler Carruth7b560d42015-09-09 17:55:00 +00002064INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002065INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00002066INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00002067INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Xinliang David Li7853c1d2016-07-08 20:55:26 +00002068INITIALIZE_PASS_END(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00002069
Chandler Carruthdab4eae2016-11-23 17:53:26 +00002070AnalysisKey LoopAccessAnalysis::Key;
Xinliang David Li8a021312016-07-02 21:18:40 +00002071
Sean Silva0746f3b2016-08-09 00:28:52 +00002072LoopAccessInfo LoopAccessAnalysis::run(Loop &L, LoopAnalysisManager &AM) {
Sean Silva36e0d012016-08-09 00:28:15 +00002073 const FunctionAnalysisManager &FAM =
Sean Silva284b0322016-07-07 01:01:53 +00002074 AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
Xinliang David Li8a021312016-07-02 21:18:40 +00002075 Function &F = *L.getHeader()->getParent();
Sean Silva284b0322016-07-07 01:01:53 +00002076 auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(F);
Xinliang David Li8a021312016-07-02 21:18:40 +00002077 auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(F);
Sean Silva284b0322016-07-07 01:01:53 +00002078 auto *AA = FAM.getCachedResult<AAManager>(F);
2079 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
2080 auto *LI = FAM.getCachedResult<LoopAnalysis>(F);
2081 if (!SE)
2082 report_fatal_error(
2083 "ScalarEvolution must have been cached at a higher level");
2084 if (!AA)
2085 report_fatal_error("AliasAnalysis must have been cached at a higher level");
2086 if (!DT)
2087 report_fatal_error("DominatorTree must have been cached at a higher level");
2088 if (!LI)
2089 report_fatal_error("LoopInfo must have been cached at a higher level");
Adam Nemet1824e412016-07-13 22:18:51 +00002090 return LoopAccessInfo(&L, SE, TLI, AA, DT, LI);
Xinliang David Li8a021312016-07-02 21:18:40 +00002091}
2092
2093PreservedAnalyses LoopAccessInfoPrinterPass::run(Loop &L,
Sean Silva0746f3b2016-08-09 00:28:52 +00002094 LoopAnalysisManager &AM) {
Xinliang David Li8a021312016-07-02 21:18:40 +00002095 Function &F = *L.getHeader()->getParent();
Xinliang David Li07e08fa2016-07-08 21:21:44 +00002096 auto &LAI = AM.getResult<LoopAccessAnalysis>(L);
Xinliang David Li8a021312016-07-02 21:18:40 +00002097 OS << "Loop access info in function '" << F.getName() << "':\n";
2098 OS.indent(2) << L.getHeader()->getName() << ":\n";
2099 LAI.print(OS, 4);
2100 return PreservedAnalyses::all();
2101}
2102
Adam Nemet3bfd93d2015-02-19 19:15:04 +00002103namespace llvm {
2104 Pass *createLAAPass() {
Xinliang David Li7853c1d2016-07-08 20:55:26 +00002105 return new LoopAccessLegacyAnalysis();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00002106 }
2107}