blob: f42b93d6dfa880dd6f90ed958beb2b9408906be0 [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"
Adam Nemet7206d7a2015-02-06 18:31:04 +000017#include "llvm/Analysis/ScalarEvolutionExpander.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Adam Nemet04563272015-02-01 16:56:15 +000019#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/DiagnosticInfo.h"
21#include "llvm/IR/Dominators.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000022#include "llvm/IR/IRBuilder.h"
Adam Nemet04563272015-02-01 16:56:15 +000023#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000024#include "llvm/Support/raw_ostream.h"
David Blaikieb447ac62015-06-26 18:02:52 +000025#include "llvm/Analysis/VectorUtils.h"
Adam Nemet04563272015-02-01 16:56:15 +000026using namespace llvm;
27
Adam Nemet339f42b2015-02-19 19:15:07 +000028#define DEBUG_TYPE "loop-accesses"
Adam Nemet04563272015-02-01 16:56:15 +000029
Adam Nemetf219c642015-02-19 19:14:52 +000030static cl::opt<unsigned, true>
31VectorizationFactor("force-vector-width", cl::Hidden,
32 cl::desc("Sets the SIMD width. Zero is autoselect."),
33 cl::location(VectorizerParams::VectorizationFactor));
Adam Nemet1d862af2015-02-26 04:39:09 +000034unsigned VectorizerParams::VectorizationFactor;
Adam Nemetf219c642015-02-19 19:14:52 +000035
36static cl::opt<unsigned, true>
37VectorizationInterleave("force-vector-interleave", cl::Hidden,
38 cl::desc("Sets the vectorization interleave count. "
39 "Zero is autoselect."),
40 cl::location(
41 VectorizerParams::VectorizationInterleave));
Adam Nemet1d862af2015-02-26 04:39:09 +000042unsigned VectorizerParams::VectorizationInterleave;
Adam Nemetf219c642015-02-19 19:14:52 +000043
Adam Nemet1d862af2015-02-26 04:39:09 +000044static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
45 "runtime-memory-check-threshold", cl::Hidden,
46 cl::desc("When performing memory disambiguation checks at runtime do not "
47 "generate more than this number of comparisons (default = 8)."),
48 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
49unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
Adam Nemetf219c642015-02-19 19:14:52 +000050
Silviu Baranga1b6b50a2015-07-08 09:16:33 +000051/// \brief The maximum iterations used to merge memory checks
52static cl::opt<unsigned> MemoryCheckMergeThreshold(
53 "memory-check-merge-threshold", cl::Hidden,
54 cl::desc("Maximum number of comparisons done when trying to merge "
55 "runtime memory checks. (default = 100)"),
56 cl::init(100));
57
Adam Nemetf219c642015-02-19 19:14:52 +000058/// Maximum SIMD width.
59const unsigned VectorizerParams::MaxVectorWidth = 64;
60
Adam Nemet9c926572015-03-10 17:40:37 +000061/// \brief We collect interesting dependences up to this threshold.
62static cl::opt<unsigned> MaxInterestingDependence(
63 "max-interesting-dependences", cl::Hidden,
64 cl::desc("Maximum number of interesting dependences collected by "
65 "loop-access analysis (default = 100)"),
66 cl::init(100));
67
Adam Nemetf219c642015-02-19 19:14:52 +000068bool VectorizerParams::isInterleaveForced() {
69 return ::VectorizationInterleave.getNumOccurrences() > 0;
70}
71
Adam Nemet2bd6e982015-02-19 19:15:15 +000072void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
73 const Function *TheFunction,
74 const Loop *TheLoop,
75 const char *PassName) {
Adam Nemet04563272015-02-01 16:56:15 +000076 DebugLoc DL = TheLoop->getStartLoc();
Adam Nemet3e876342015-02-19 19:15:13 +000077 if (const Instruction *I = Message.getInstr())
Adam Nemet04563272015-02-01 16:56:15 +000078 DL = I->getDebugLoc();
Adam Nemet339f42b2015-02-19 19:15:07 +000079 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
Adam Nemet04563272015-02-01 16:56:15 +000080 *TheFunction, DL, Message.str());
81}
82
83Value *llvm::stripIntegerCast(Value *V) {
84 if (CastInst *CI = dyn_cast<CastInst>(V))
85 if (CI->getOperand(0)->getType()->isIntegerTy())
86 return CI->getOperand(0);
87 return V;
88}
89
90const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
Adam Nemet8bc61df2015-02-24 00:41:59 +000091 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +000092 Value *Ptr, Value *OrigPtr) {
93
94 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
95
96 // If there is an entry in the map return the SCEV of the pointer with the
97 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +000098 ValueToValueMap::const_iterator SI =
99 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000100 if (SI != PtrToStride.end()) {
101 Value *StrideVal = SI->second;
102
103 // Strip casts.
104 StrideVal = stripIntegerCast(StrideVal);
105
106 // Replace symbolic stride by one.
107 Value *One = ConstantInt::get(StrideVal->getType(), 1);
108 ValueToValueMap RewriteMap;
109 RewriteMap[StrideVal] = One;
110
111 const SCEV *ByOne =
112 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
Adam Nemet339f42b2015-02-19 19:15:07 +0000113 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
Adam Nemet04563272015-02-01 16:56:15 +0000114 << "\n");
115 return ByOne;
116 }
117
118 // Otherwise, just return the SCEV of the original pointer.
119 return SE->getSCEV(Ptr);
120}
121
Adam Nemet7cdebac2015-07-14 22:32:44 +0000122void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
123 unsigned DepSetId, unsigned ASId,
124 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000125 // Get the stride replaced scev.
126 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
127 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
128 assert(AR && "Invalid addrec expression");
129 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000130
131 const SCEV *ScStart = AR->getStart();
Adam Nemet04563272015-02-01 16:56:15 +0000132 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000133 const SCEV *Step = AR->getStepRecurrence(*SE);
134
135 // For expressions with negative step, the upper bound is ScStart and the
136 // lower bound is ScEnd.
137 if (const SCEVConstant *CStep = dyn_cast<const SCEVConstant>(Step)) {
138 if (CStep->getValue()->isNegative())
139 std::swap(ScStart, ScEnd);
140 } else {
141 // Fallback case: the step is not constant, but the we can still
142 // get the upper and lower bounds of the interval by using min/max
143 // expressions.
144 ScStart = SE->getUMinExpr(ScStart, ScEnd);
145 ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
146 }
147
148 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000149}
150
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000151SmallVector<RuntimePointerChecking::PointerCheck, 4>
152RuntimePointerChecking::generateChecks(
153 const SmallVectorImpl<int> *PtrPartition) const {
154 SmallVector<PointerCheck, 4> Checks;
155
Adam Nemet7c52e052015-07-27 19:38:50 +0000156 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
157 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
158 const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
159 const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000160
161 if (needsChecking(CGI, CGJ, PtrPartition))
162 Checks.push_back(std::make_pair(&CGI, &CGJ));
163 }
164 }
165 return Checks;
166}
167
Adam Nemet15840392015-08-07 22:44:15 +0000168void RuntimePointerChecking::generateChecks(
169 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
170 assert(Checks.empty() && "Checks is not empty");
171 groupChecks(DepCands, UseDependencies);
172 Checks = generateChecks();
173}
174
Adam Nemet7cdebac2015-07-14 22:32:44 +0000175bool RuntimePointerChecking::needsChecking(
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000176 const CheckingPtrGroup &M, const CheckingPtrGroup &N,
177 const SmallVectorImpl<int> *PtrPartition) const {
178 for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
179 for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
180 if (needsChecking(M.Members[I], N.Members[J], PtrPartition))
181 return true;
182 return false;
183}
184
185/// Compare \p I and \p J and return the minimum.
186/// Return nullptr in case we couldn't find an answer.
187static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
188 ScalarEvolution *SE) {
189 const SCEV *Diff = SE->getMinusSCEV(J, I);
190 const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
191
192 if (!C)
193 return nullptr;
194 if (C->getValue()->isNegative())
195 return J;
196 return I;
197}
198
Adam Nemet7cdebac2015-07-14 22:32:44 +0000199bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000200 const SCEV *Start = RtCheck.Pointers[Index].Start;
201 const SCEV *End = RtCheck.Pointers[Index].End;
202
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000203 // Compare the starts and ends with the known minimum and maximum
204 // of this set. We need to know how we compare against the min/max
205 // of the set in order to be able to emit memchecks.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000206 const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000207 if (!Min0)
208 return false;
209
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000210 const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000211 if (!Min1)
212 return false;
213
214 // Update the low bound expression if we've found a new min value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000215 if (Min0 == Start)
216 Low = Start;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000217
218 // Update the high bound expression if we've found a new max value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000219 if (Min1 != End)
220 High = End;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000221
222 Members.push_back(Index);
223 return true;
224}
225
Adam Nemet7cdebac2015-07-14 22:32:44 +0000226void RuntimePointerChecking::groupChecks(
227 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000228 // We build the groups from dependency candidates equivalence classes
229 // because:
230 // - We know that pointers in the same equivalence class share
231 // the same underlying object and therefore there is a chance
232 // that we can compare pointers
233 // - We wouldn't be able to merge two pointers for which we need
234 // to emit a memcheck. The classes in DepCands are already
235 // conveniently built such that no two pointers in the same
236 // class need checking against each other.
237
238 // We use the following (greedy) algorithm to construct the groups
239 // For every pointer in the equivalence class:
240 // For each existing group:
241 // - if the difference between this pointer and the min/max bounds
242 // of the group is a constant, then make the pointer part of the
243 // group and update the min/max bounds of that group as required.
244
245 CheckingGroups.clear();
246
Silviu Baranga48250602015-07-28 13:44:08 +0000247 // If we need to check two pointers to the same underlying object
248 // with a non-constant difference, we shouldn't perform any pointer
249 // grouping with those pointers. This is because we can easily get
250 // into cases where the resulting check would return false, even when
251 // the accesses are safe.
252 //
253 // The following example shows this:
254 // for (i = 0; i < 1000; ++i)
255 // a[5000 + i * m] = a[i] + a[i + 9000]
256 //
257 // Here grouping gives a check of (5000, 5000 + 1000 * m) against
258 // (0, 10000) which is always false. However, if m is 1, there is no
259 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
260 // us to perform an accurate check in this case.
261 //
262 // The above case requires that we have an UnknownDependence between
263 // accesses to the same underlying object. This cannot happen unless
264 // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
265 // is also false. In this case we will use the fallback path and create
266 // separate checking groups for all pointers.
267
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000268 // If we don't have the dependency partitions, construct a new
Silviu Baranga48250602015-07-28 13:44:08 +0000269 // checking pointer group for each pointer. This is also required
270 // for correctness, because in this case we can have checking between
271 // pointers to the same underlying object.
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000272 if (!UseDependencies) {
273 for (unsigned I = 0; I < Pointers.size(); ++I)
274 CheckingGroups.push_back(CheckingPtrGroup(I, *this));
275 return;
276 }
277
278 unsigned TotalComparisons = 0;
279
280 DenseMap<Value *, unsigned> PositionMap;
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000281 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
282 PositionMap[Pointers[Index].PointerValue] = Index;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000283
Silviu Barangace3877f2015-07-09 15:18:25 +0000284 // We need to keep track of what pointers we've already seen so we
285 // don't process them twice.
286 SmallSet<unsigned, 2> Seen;
287
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000288 // Go through all equivalence classes, get the the "pointer check groups"
Silviu Barangace3877f2015-07-09 15:18:25 +0000289 // and add them to the overall solution. We use the order in which accesses
290 // appear in 'Pointers' to enforce determinism.
291 for (unsigned I = 0; I < Pointers.size(); ++I) {
292 // We've seen this pointer before, and therefore already processed
293 // its equivalence class.
294 if (Seen.count(I))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000295 continue;
296
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000297 MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
298 Pointers[I].IsWritePtr);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000299
Silviu Barangace3877f2015-07-09 15:18:25 +0000300 SmallVector<CheckingPtrGroup, 2> Groups;
301 auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
302
Silviu Barangaa647c302015-07-13 14:48:24 +0000303 // Because DepCands is constructed by visiting accesses in the order in
304 // which they appear in alias sets (which is deterministic) and the
305 // iteration order within an equivalence class member is only dependent on
306 // the order in which unions and insertions are performed on the
307 // equivalence class, the iteration order is deterministic.
Silviu Barangace3877f2015-07-09 15:18:25 +0000308 for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000309 MI != ME; ++MI) {
310 unsigned Pointer = PositionMap[MI->getPointer()];
311 bool Merged = false;
Silviu Barangace3877f2015-07-09 15:18:25 +0000312 // Mark this pointer as seen.
313 Seen.insert(Pointer);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000314
315 // Go through all the existing sets and see if we can find one
316 // which can include this pointer.
317 for (CheckingPtrGroup &Group : Groups) {
318 // Don't perform more than a certain amount of comparisons.
319 // This should limit the cost of grouping the pointers to something
320 // reasonable. If we do end up hitting this threshold, the algorithm
321 // will create separate groups for all remaining pointers.
322 if (TotalComparisons > MemoryCheckMergeThreshold)
323 break;
324
325 TotalComparisons++;
326
327 if (Group.addPointer(Pointer)) {
328 Merged = true;
329 break;
330 }
331 }
332
333 if (!Merged)
334 // We couldn't add this pointer to any existing set or the threshold
335 // for the number of comparisons has been reached. Create a new group
336 // to hold the current pointer.
337 Groups.push_back(CheckingPtrGroup(Pointer, *this));
338 }
339
340 // We've computed the grouped checks for this partition.
341 // Save the results and continue with the next one.
342 std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
343 }
Adam Nemet04563272015-02-01 16:56:15 +0000344}
345
Adam Nemet041e6de2015-07-16 02:48:05 +0000346bool RuntimePointerChecking::arePointersInSamePartition(
347 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
348 unsigned PtrIdx2) {
349 return (PtrToPartition[PtrIdx1] != -1 &&
350 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
351}
352
Adam Nemet7cdebac2015-07-14 22:32:44 +0000353bool RuntimePointerChecking::needsChecking(
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000354 unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000355 const PointerInfo &PointerI = Pointers[I];
356 const PointerInfo &PointerJ = Pointers[J];
357
Adam Nemeta8945b72015-02-18 03:43:58 +0000358 // No need to check if two readonly pointers intersect.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000359 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
Adam Nemeta8945b72015-02-18 03:43:58 +0000360 return false;
361
362 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000363 if (PointerI.DependencySetId == PointerJ.DependencySetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000364 return false;
365
366 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000367 if (PointerI.AliasSetId != PointerJ.AliasSetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000368 return false;
369
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000370 // If PtrPartition is set omit checks between pointers of the same partition.
Adam Nemet041e6de2015-07-16 02:48:05 +0000371 if (PtrPartition && arePointersInSamePartition(*PtrPartition, I, J))
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000372 return false;
373
Adam Nemeta8945b72015-02-18 03:43:58 +0000374 return true;
375}
376
Adam Nemet54f0b832015-07-27 23:54:41 +0000377void RuntimePointerChecking::printChecks(
378 raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
379 unsigned Depth) const {
380 unsigned N = 0;
381 for (const auto &Check : Checks) {
382 const auto &First = Check.first->Members, &Second = Check.second->Members;
383
384 OS.indent(Depth) << "Check " << N++ << ":\n";
385
386 OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
387 for (unsigned K = 0; K < First.size(); ++K)
388 OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
389
390 OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
391 for (unsigned K = 0; K < Second.size(); ++K)
392 OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
393 }
394}
395
Adam Nemet3a91e942015-08-07 19:44:48 +0000396void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000397
398 OS.indent(Depth) << "Run-time memory checks:\n";
Adam Nemet15840392015-08-07 22:44:15 +0000399 printChecks(OS, Checks, Depth);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000400
401 OS.indent(Depth) << "Grouped accesses:\n";
402 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
Adam Nemet54f0b832015-07-27 23:54:41 +0000403 const auto &CG = CheckingGroups[I];
404
405 OS.indent(Depth + 2) << "Group " << &CG << ":\n";
406 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
407 << ")\n";
408 for (unsigned J = 0; J < CG.Members.size(); ++J) {
409 OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000410 << "\n";
411 }
412 }
Adam Nemete91cc6e2015-02-19 19:15:19 +0000413}
414
Adam Nemet04563272015-02-01 16:56:15 +0000415namespace {
416/// \brief Analyses memory accesses in a loop.
417///
418/// Checks whether run time pointer checks are needed and builds sets for data
419/// dependence checking.
420class AccessAnalysis {
421public:
422 /// \brief Read or write access location.
423 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
424 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
425
Adam Nemete2b885c2015-04-23 20:09:20 +0000426 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Adam Nemetdee666b2015-03-10 17:40:34 +0000427 MemoryDepChecker::DepCandidates &DA)
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000428 : DL(Dl), AST(*AA), LI(LI), DepCands(DA),
429 IsRTCheckAnalysisNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000430
431 /// \brief Register a load and whether it is only read from.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000432 void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
Adam Nemet04563272015-02-01 16:56:15 +0000433 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000434 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000435 Accesses.insert(MemAccessInfo(Ptr, false));
436 if (IsReadOnly)
437 ReadOnlyPtr.insert(Ptr);
438 }
439
440 /// \brief Register a store.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000441 void addStore(MemoryLocation &Loc) {
Adam Nemet04563272015-02-01 16:56:15 +0000442 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000443 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000444 Accesses.insert(MemAccessInfo(Ptr, true));
445 }
446
447 /// \brief Check whether we can check the pointers at runtime for
Adam Nemetee614742015-07-09 22:17:38 +0000448 /// non-intersection.
449 ///
450 /// Returns true if we need no check or if we do and we can generate them
451 /// (i.e. the pointers have computable bounds).
Adam Nemet7cdebac2015-07-14 22:32:44 +0000452 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
453 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000454 bool ShouldCheckStride = false);
455
456 /// \brief Goes over all memory accesses, checks whether a RT check is needed
457 /// and builds sets of dependent accesses.
458 void buildDependenceSets() {
459 processMemAccesses();
460 }
461
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000462 /// \brief Initial processing of memory accesses determined that we need to
463 /// perform dependency checking.
464 ///
465 /// Note that this can later be cleared if we retry memcheck analysis without
466 /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
Adam Nemet04563272015-02-01 16:56:15 +0000467 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000468
469 /// We decided that no dependence analysis would be used. Reset the state.
470 void resetDepChecks(MemoryDepChecker &DepChecker) {
471 CheckDeps.clear();
472 DepChecker.clearInterestingDependences();
473 }
Adam Nemet04563272015-02-01 16:56:15 +0000474
475 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
476
477private:
478 typedef SetVector<MemAccessInfo> PtrAccessSet;
479
480 /// \brief Go over all memory access and check whether runtime pointer checks
Adam Nemetb41d2d32015-07-09 06:47:21 +0000481 /// are needed and build sets of dependency check candidates.
Adam Nemet04563272015-02-01 16:56:15 +0000482 void processMemAccesses();
483
484 /// Set of all accesses.
485 PtrAccessSet Accesses;
486
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000487 const DataLayout &DL;
488
Adam Nemet04563272015-02-01 16:56:15 +0000489 /// Set of accesses that need a further dependence check.
490 MemAccessInfoSet CheckDeps;
491
492 /// Set of pointers that are read only.
493 SmallPtrSet<Value*, 16> ReadOnlyPtr;
494
Adam Nemet04563272015-02-01 16:56:15 +0000495 /// An alias set tracker to partition the access set by underlying object and
496 //intrinsic property (such as TBAA metadata).
497 AliasSetTracker AST;
498
Adam Nemete2b885c2015-04-23 20:09:20 +0000499 LoopInfo *LI;
500
Adam Nemet04563272015-02-01 16:56:15 +0000501 /// Sets of potentially dependent accesses - members of one set share an
502 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
503 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000504 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000505
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000506 /// \brief Initial processing of memory accesses determined that we may need
507 /// to add memchecks. Perform the analysis to determine the necessary checks.
508 ///
509 /// Note that, this is different from isDependencyCheckNeeded. When we retry
510 /// memcheck analysis without dependency checking
511 /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
512 /// while this remains set if we have potentially dependent accesses.
513 bool IsRTCheckAnalysisNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000514};
515
516} // end anonymous namespace
517
518/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000519static bool hasComputableBounds(ScalarEvolution *SE,
520 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000521 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
522 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
523 if (!AR)
524 return false;
525
526 return AR->isAffine();
527}
528
Adam Nemet7cdebac2015-07-14 22:32:44 +0000529bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
530 ScalarEvolution *SE, Loop *TheLoop,
531 const ValueToValueMap &StridesMap,
532 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000533 // Find pointers with computable bounds. We are going to use this information
534 // to place a runtime bound check.
535 bool CanDoRT = true;
536
Adam Nemetee614742015-07-09 22:17:38 +0000537 bool NeedRTCheck = false;
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000538 if (!IsRTCheckAnalysisNeeded) return true;
Silviu Baranga98a13712015-06-08 10:27:06 +0000539
Adam Nemet04563272015-02-01 16:56:15 +0000540 bool IsDepCheckNeeded = isDependencyCheckNeeded();
Adam Nemet04563272015-02-01 16:56:15 +0000541
542 // We assign a consecutive id to access from different alias sets.
543 // Accesses between different groups doesn't need to be checked.
544 unsigned ASId = 1;
545 for (auto &AS : AST) {
Adam Nemet424edc62015-07-08 22:58:48 +0000546 int NumReadPtrChecks = 0;
547 int NumWritePtrChecks = 0;
548
Adam Nemet04563272015-02-01 16:56:15 +0000549 // We assign consecutive id to access from different dependence sets.
550 // Accesses within the same set don't need a runtime check.
551 unsigned RunningDepId = 1;
552 DenseMap<Value *, unsigned> DepSetId;
553
554 for (auto A : AS) {
555 Value *Ptr = A.getValue();
556 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
557 MemAccessInfo Access(Ptr, IsWrite);
558
Adam Nemet424edc62015-07-08 22:58:48 +0000559 if (IsWrite)
560 ++NumWritePtrChecks;
561 else
562 ++NumReadPtrChecks;
563
Adam Nemet04563272015-02-01 16:56:15 +0000564 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000565 // When we run after a failing dependency check we have to make sure
566 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000567 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000568 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000569 // The id of the dependence set.
570 unsigned DepId;
571
572 if (IsDepCheckNeeded) {
573 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
574 unsigned &LeaderId = DepSetId[Leader];
575 if (!LeaderId)
576 LeaderId = RunningDepId++;
577 DepId = LeaderId;
578 } else
579 // Each access has its own dependence set.
580 DepId = RunningDepId++;
581
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000582 RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000583
Adam Nemet339f42b2015-02-19 19:15:07 +0000584 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000585 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000586 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000587 CanDoRT = false;
588 }
589 }
590
Adam Nemet424edc62015-07-08 22:58:48 +0000591 // If we have at least two writes or one write and a read then we need to
592 // check them. But there is no need to checks if there is only one
593 // dependence set for this alias set.
594 //
595 // Note that this function computes CanDoRT and NeedRTCheck independently.
596 // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
597 // for which we couldn't find the bounds but we don't actually need to emit
598 // any checks so it does not matter.
599 if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
600 NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
601 NumWritePtrChecks >= 1));
602
Adam Nemet04563272015-02-01 16:56:15 +0000603 ++ASId;
604 }
605
606 // If the pointers that we would use for the bounds comparison have different
607 // address spaces, assume the values aren't directly comparable, so we can't
608 // use them for the runtime check. We also have to assume they could
609 // overlap. In the future there should be metadata for whether address spaces
610 // are disjoint.
611 unsigned NumPointers = RtCheck.Pointers.size();
612 for (unsigned i = 0; i < NumPointers; ++i) {
613 for (unsigned j = i + 1; j < NumPointers; ++j) {
614 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000615 if (RtCheck.Pointers[i].DependencySetId ==
616 RtCheck.Pointers[j].DependencySetId)
Adam Nemet04563272015-02-01 16:56:15 +0000617 continue;
618 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000619 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
Adam Nemet04563272015-02-01 16:56:15 +0000620 continue;
621
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000622 Value *PtrI = RtCheck.Pointers[i].PointerValue;
623 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
Adam Nemet04563272015-02-01 16:56:15 +0000624
625 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
626 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
627 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000628 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000629 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000630 return false;
631 }
632 }
633 }
634
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000635 if (NeedRTCheck && CanDoRT)
Adam Nemet15840392015-08-07 22:44:15 +0000636 RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000637
Adam Nemet155e8742015-08-07 22:44:21 +0000638 DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
Adam Nemetee614742015-07-09 22:17:38 +0000639 << " pointer comparisons.\n");
640
641 RtCheck.Need = NeedRTCheck;
642
643 bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
644 if (!CanDoRTIfNeeded)
645 RtCheck.reset();
646 return CanDoRTIfNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000647}
648
649void AccessAnalysis::processMemAccesses() {
650 // We process the set twice: first we process read-write pointers, last we
651 // process read-only pointers. This allows us to skip dependence tests for
652 // read-only pointers.
653
Adam Nemet339f42b2015-02-19 19:15:07 +0000654 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000655 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000656 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000657 DEBUG({
658 for (auto A : Accesses)
659 dbgs() << "\t" << *A.getPointer() << " (" <<
660 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
661 "read-only" : "read")) << ")\n";
662 });
663
664 // The AliasSetTracker has nicely partitioned our pointers by metadata
665 // compatibility and potential for underlying-object overlap. As a result, we
666 // only need to check for potential pointer dependencies within each alias
667 // set.
668 for (auto &AS : AST) {
669 // Note that both the alias-set tracker and the alias sets themselves used
670 // linked lists internally and so the iteration order here is deterministic
671 // (matching the original instruction order within each set).
672
673 bool SetHasWrite = false;
674
675 // Map of pointers to last access encountered.
676 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
677 UnderlyingObjToAccessMap ObjToLastAccess;
678
679 // Set of access to check after all writes have been processed.
680 PtrAccessSet DeferredAccesses;
681
682 // Iterate over each alias set twice, once to process read/write pointers,
683 // and then to process read-only pointers.
684 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
685 bool UseDeferred = SetIteration > 0;
686 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
687
688 for (auto AV : AS) {
689 Value *Ptr = AV.getValue();
690
691 // For a single memory access in AliasSetTracker, Accesses may contain
692 // both read and write, and they both need to be handled for CheckDeps.
693 for (auto AC : S) {
694 if (AC.getPointer() != Ptr)
695 continue;
696
697 bool IsWrite = AC.getInt();
698
699 // If we're using the deferred access set, then it contains only
700 // reads.
701 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
702 if (UseDeferred && !IsReadOnlyPtr)
703 continue;
704 // Otherwise, the pointer must be in the PtrAccessSet, either as a
705 // read or a write.
706 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
707 S.count(MemAccessInfo(Ptr, false))) &&
708 "Alias-set pointer not in the access set?");
709
710 MemAccessInfo Access(Ptr, IsWrite);
711 DepCands.insert(Access);
712
713 // Memorize read-only pointers for later processing and skip them in
714 // the first round (they need to be checked after we have seen all
715 // write pointers). Note: we also mark pointer that are not
716 // consecutive as "read-only" pointers (so that we check
717 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
718 if (!UseDeferred && IsReadOnlyPtr) {
719 DeferredAccesses.insert(Access);
720 continue;
721 }
722
723 // If this is a write - check other reads and writes for conflicts. If
724 // this is a read only check other writes for conflicts (but only if
725 // there is no other write to the ptr - this is an optimization to
726 // catch "a[i] = a[i] + " without having to do a dependence check).
727 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
728 CheckDeps.insert(Access);
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000729 IsRTCheckAnalysisNeeded = true;
Adam Nemet04563272015-02-01 16:56:15 +0000730 }
731
732 if (IsWrite)
733 SetHasWrite = true;
734
735 // Create sets of pointers connected by a shared alias set and
736 // underlying object.
737 typedef SmallVector<Value *, 16> ValueVector;
738 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000739
740 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
741 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000742 for (Value *UnderlyingObj : TempObjects) {
743 UnderlyingObjToAccessMap::iterator Prev =
744 ObjToLastAccess.find(UnderlyingObj);
745 if (Prev != ObjToLastAccess.end())
746 DepCands.unionSets(Access, Prev->second);
747
748 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000749 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000750 }
751 }
752 }
753 }
754 }
755}
756
Adam Nemet04563272015-02-01 16:56:15 +0000757static bool isInBoundsGep(Value *Ptr) {
758 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
759 return GEP->isInBounds();
760 return false;
761}
762
Adam Nemetc4866d22015-06-26 17:25:43 +0000763/// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
764/// i.e. monotonically increasing/decreasing.
765static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
766 ScalarEvolution *SE, const Loop *L) {
767 // FIXME: This should probably only return true for NUW.
768 if (AR->getNoWrapFlags(SCEV::NoWrapMask))
769 return true;
770
771 // Scalar evolution does not propagate the non-wrapping flags to values that
772 // are derived from a non-wrapping induction variable because non-wrapping
773 // could be flow-sensitive.
774 //
775 // Look through the potentially overflowing instruction to try to prove
776 // non-wrapping for the *specific* value of Ptr.
777
778 // The arithmetic implied by an inbounds GEP can't overflow.
779 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
780 if (!GEP || !GEP->isInBounds())
781 return false;
782
783 // Make sure there is only one non-const index and analyze that.
784 Value *NonConstIndex = nullptr;
785 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
786 if (!isa<ConstantInt>(*Index)) {
787 if (NonConstIndex)
788 return false;
789 NonConstIndex = *Index;
790 }
791 if (!NonConstIndex)
792 // The recurrence is on the pointer, ignore for now.
793 return false;
794
795 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
796 // AddRec using a NSW operation.
797 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
798 if (OBO->hasNoSignedWrap() &&
799 // Assume constant for other the operand so that the AddRec can be
800 // easily found.
801 isa<ConstantInt>(OBO->getOperand(1))) {
802 auto *OpScev = SE->getSCEV(OBO->getOperand(0));
803
804 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
805 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
806 }
807
808 return false;
809}
810
Adam Nemet04563272015-02-01 16:56:15 +0000811/// \brief Check whether the access through \p Ptr has a constant stride.
Hao Liu32c05392015-06-08 06:39:56 +0000812int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
813 const ValueToValueMap &StridesMap) {
Craig Toppere3dcce92015-08-01 22:20:21 +0000814 Type *Ty = Ptr->getType();
Adam Nemet04563272015-02-01 16:56:15 +0000815 assert(Ty->isPointerTy() && "Unexpected non-ptr");
816
817 // Make sure that the pointer does not point to aggregate types.
Craig Toppere3dcce92015-08-01 22:20:21 +0000818 auto *PtrTy = cast<PointerType>(Ty);
Adam Nemet04563272015-02-01 16:56:15 +0000819 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000820 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
821 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000822 return 0;
823 }
824
825 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
826
827 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
828 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000829 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000830 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000831 return 0;
832 }
833
834 // The accesss function must stride over the innermost loop.
835 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000836 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000837 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000838 }
839
840 // The address calculation must not wrap. Otherwise, a dependence could be
841 // inverted.
842 // An inbounds getelementptr that is a AddRec with a unit stride
843 // cannot wrap per definition. The unit stride requirement is checked later.
844 // An getelementptr without an inbounds attribute and unit stride would have
845 // to access the pointer value "0" which is undefined behavior in address
846 // space 0, therefore we can also vectorize this case.
847 bool IsInBoundsGEP = isInBoundsGep(Ptr);
Adam Nemetc4866d22015-06-26 17:25:43 +0000848 bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp);
Adam Nemet04563272015-02-01 16:56:15 +0000849 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
850 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000851 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000852 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000853 return 0;
854 }
855
856 // Check the step is constant.
857 const SCEV *Step = AR->getStepRecurrence(*SE);
858
Adam Nemet943befe2015-07-09 00:03:22 +0000859 // Calculate the pointer stride and check if it is constant.
Adam Nemet04563272015-02-01 16:56:15 +0000860 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
861 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000862 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000863 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000864 return 0;
865 }
866
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000867 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
868 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000869 const APInt &APStepVal = C->getValue()->getValue();
870
871 // Huge step value - give up.
872 if (APStepVal.getBitWidth() > 64)
873 return 0;
874
875 int64_t StepVal = APStepVal.getSExtValue();
876
877 // Strided access.
878 int64_t Stride = StepVal / Size;
879 int64_t Rem = StepVal % Size;
880 if (Rem)
881 return 0;
882
883 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
884 // know we can't "wrap around the address space". In case of address space
885 // zero we know that this won't happen without triggering undefined behavior.
886 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
887 Stride != 1 && Stride != -1)
888 return 0;
889
890 return Stride;
891}
892
Adam Nemet9c926572015-03-10 17:40:37 +0000893bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
894 switch (Type) {
895 case NoDep:
896 case Forward:
897 case BackwardVectorizable:
898 return true;
899
900 case Unknown:
901 case ForwardButPreventsForwarding:
902 case Backward:
903 case BackwardVectorizableButPreventsForwarding:
904 return false;
905 }
David Majnemerd388e932015-03-10 20:23:29 +0000906 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000907}
908
909bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
910 switch (Type) {
911 case NoDep:
912 case Forward:
913 return false;
914
915 case BackwardVectorizable:
916 case Unknown:
917 case ForwardButPreventsForwarding:
918 case Backward:
919 case BackwardVectorizableButPreventsForwarding:
920 return true;
921 }
David Majnemerd388e932015-03-10 20:23:29 +0000922 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000923}
924
925bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
926 switch (Type) {
927 case NoDep:
928 case Forward:
929 case ForwardButPreventsForwarding:
930 return false;
931
932 case Unknown:
933 case BackwardVectorizable:
934 case Backward:
935 case BackwardVectorizableButPreventsForwarding:
936 return true;
937 }
David Majnemerd388e932015-03-10 20:23:29 +0000938 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000939}
940
Adam Nemet04563272015-02-01 16:56:15 +0000941bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
942 unsigned TypeByteSize) {
943 // If loads occur at a distance that is not a multiple of a feasible vector
944 // factor store-load forwarding does not take place.
945 // Positive dependences might cause troubles because vectorizing them might
946 // prevent store-load forwarding making vectorized code run a lot slower.
947 // a[i] = a[i-3] ^ a[i-8];
948 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
949 // hence on your typical architecture store-load forwarding does not take
950 // place. Vectorizing in such cases does not make sense.
951 // Store-load forwarding distance.
952 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
953 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000954 unsigned MaxVFWithoutSLForwardIssues =
955 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000956 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000957 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
958
959 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
960 vf *= 2) {
961 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
962 MaxVFWithoutSLForwardIssues = (vf >>=1);
963 break;
964 }
965 }
966
Adam Nemet04d41632015-02-19 19:14:34 +0000967 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000968 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000969 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000970 return true;
971 }
972
973 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000974 MaxVFWithoutSLForwardIssues !=
975 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000976 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
977 return false;
978}
979
Hao Liu751004a2015-06-08 04:48:37 +0000980/// \brief Check the dependence for two accesses with the same stride \p Stride.
981/// \p Distance is the positive distance and \p TypeByteSize is type size in
982/// bytes.
983///
984/// \returns true if they are independent.
985static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
986 unsigned TypeByteSize) {
987 assert(Stride > 1 && "The stride must be greater than 1");
988 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
989 assert(Distance > 0 && "The distance must be non-zero");
990
991 // Skip if the distance is not multiple of type byte size.
992 if (Distance % TypeByteSize)
993 return false;
994
995 unsigned ScaledDist = Distance / TypeByteSize;
996
997 // No dependence if the scaled distance is not multiple of the stride.
998 // E.g.
999 // for (i = 0; i < 1024 ; i += 4)
1000 // A[i+2] = A[i] + 1;
1001 //
1002 // Two accesses in memory (scaled distance is 2, stride is 4):
1003 // | A[0] | | | | A[4] | | | |
1004 // | | | A[2] | | | | A[6] | |
1005 //
1006 // E.g.
1007 // for (i = 0; i < 1024 ; i += 3)
1008 // A[i+4] = A[i] + 1;
1009 //
1010 // Two accesses in memory (scaled distance is 4, stride is 3):
1011 // | A[0] | | | A[3] | | | A[6] | | |
1012 // | | | | | A[4] | | | A[7] | |
1013 return ScaledDist % Stride;
1014}
1015
Adam Nemet9c926572015-03-10 17:40:37 +00001016MemoryDepChecker::Dependence::DepType
1017MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1018 const MemAccessInfo &B, unsigned BIdx,
1019 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001020 assert (AIdx < BIdx && "Must pass arguments in program order");
1021
1022 Value *APtr = A.getPointer();
1023 Value *BPtr = B.getPointer();
1024 bool AIsWrite = A.getInt();
1025 bool BIsWrite = B.getInt();
1026
1027 // Two reads are independent.
1028 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +00001029 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +00001030
1031 // We cannot check pointers in different address spaces.
1032 if (APtr->getType()->getPointerAddressSpace() !=
1033 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +00001034 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001035
1036 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
1037 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
1038
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001039 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
1040 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +00001041
1042 const SCEV *Src = AScev;
1043 const SCEV *Sink = BScev;
1044
1045 // If the induction step is negative we have to invert source and sink of the
1046 // dependence.
1047 if (StrideAPtr < 0) {
1048 //Src = BScev;
1049 //Sink = AScev;
1050 std::swap(APtr, BPtr);
1051 std::swap(Src, Sink);
1052 std::swap(AIsWrite, BIsWrite);
1053 std::swap(AIdx, BIdx);
1054 std::swap(StrideAPtr, StrideBPtr);
1055 }
1056
1057 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
1058
Adam Nemet339f42b2015-02-19 19:15:07 +00001059 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +00001060 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +00001061 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +00001062 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +00001063
Adam Nemet943befe2015-07-09 00:03:22 +00001064 // Need accesses with constant stride. We don't want to vectorize
Adam Nemet04563272015-02-01 16:56:15 +00001065 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1066 // the address space.
1067 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
Adam Nemet943befe2015-07-09 00:03:22 +00001068 DEBUG(dbgs() << "Pointer access with non-constant stride\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001069 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001070 }
1071
1072 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1073 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001074 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +00001075 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +00001076 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001077 }
1078
1079 Type *ATy = APtr->getType()->getPointerElementType();
1080 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001081 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1082 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +00001083
1084 // Negative distances are not plausible dependencies.
1085 const APInt &Val = C->getValue()->getValue();
1086 if (Val.isNegative()) {
1087 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1088 if (IsTrueDataDependence &&
1089 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1090 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +00001091 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001092
Adam Nemet339f42b2015-02-19 19:15:07 +00001093 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001094 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +00001095 }
1096
1097 // Write to the same location with the same size.
1098 // Could be improved to assert type sizes are the same (i32 == float, etc).
1099 if (Val == 0) {
1100 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +00001101 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +00001102 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001103 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001104 }
1105
1106 assert(Val.isStrictlyPositive() && "Expect a positive value");
1107
Adam Nemet04563272015-02-01 16:56:15 +00001108 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +00001109 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +00001110 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001111 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001112 }
1113
1114 unsigned Distance = (unsigned) Val.getZExtValue();
1115
Hao Liu751004a2015-06-08 04:48:37 +00001116 unsigned Stride = std::abs(StrideAPtr);
1117 if (Stride > 1 &&
Adam Nemet0131a562015-07-08 18:47:38 +00001118 areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
1119 DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
Hao Liu751004a2015-06-08 04:48:37 +00001120 return Dependence::NoDep;
Adam Nemet0131a562015-07-08 18:47:38 +00001121 }
Hao Liu751004a2015-06-08 04:48:37 +00001122
Adam Nemet04563272015-02-01 16:56:15 +00001123 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +00001124 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1125 VectorizerParams::VectorizationFactor : 1);
1126 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1127 VectorizerParams::VectorizationInterleave : 1);
Hao Liu751004a2015-06-08 04:48:37 +00001128 // The minimum number of iterations for a vectorized/unrolled version.
1129 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
Adam Nemet04563272015-02-01 16:56:15 +00001130
Hao Liu751004a2015-06-08 04:48:37 +00001131 // It's not vectorizable if the distance is smaller than the minimum distance
1132 // needed for a vectroized/unrolled version. Vectorizing one iteration in
1133 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1134 // TypeByteSize (No need to plus the last gap distance).
1135 //
1136 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1137 // foo(int *A) {
1138 // int *B = (int *)((char *)A + 14);
1139 // for (i = 0 ; i < 1024 ; i += 2)
1140 // B[i] = A[i] + 1;
1141 // }
1142 //
1143 // Two accesses in memory (stride is 2):
1144 // | A[0] | | A[2] | | A[4] | | A[6] | |
1145 // | B[0] | | B[2] | | B[4] |
1146 //
1147 // Distance needs for vectorizing iterations except the last iteration:
1148 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1149 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1150 //
1151 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1152 // 12, which is less than distance.
1153 //
1154 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1155 // the minimum distance needed is 28, which is greater than distance. It is
1156 // not safe to do vectorization.
1157 unsigned MinDistanceNeeded =
1158 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1159 if (MinDistanceNeeded > Distance) {
1160 DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1161 << '\n');
1162 return Dependence::Backward;
1163 }
1164
1165 // Unsafe if the minimum distance needed is greater than max safe distance.
1166 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1167 DEBUG(dbgs() << "LAA: Failure because it needs at least "
1168 << MinDistanceNeeded << " size in bytes");
Adam Nemet9c926572015-03-10 17:40:37 +00001169 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +00001170 }
1171
Adam Nemet9cc0c392015-02-26 17:58:48 +00001172 // Positive distance bigger than max vectorization factor.
Hao Liu751004a2015-06-08 04:48:37 +00001173 // FIXME: Should use max factor instead of max distance in bytes, which could
1174 // not handle different types.
1175 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1176 // void foo (int *A, char *B) {
1177 // for (unsigned i = 0; i < 1024; i++) {
1178 // A[i+2] = A[i] + 1;
1179 // B[i+2] = B[i] + 1;
1180 // }
1181 // }
1182 //
1183 // This case is currently unsafe according to the max safe distance. If we
1184 // analyze the two accesses on array B, the max safe dependence distance
1185 // is 2. Then we analyze the accesses on array A, the minimum distance needed
1186 // is 8, which is less than 2 and forbidden vectorization, But actually
1187 // both A and B could be vectorized by 2 iterations.
1188 MaxSafeDepDistBytes =
1189 Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
Adam Nemet04563272015-02-01 16:56:15 +00001190
1191 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1192 if (IsTrueDataDependence &&
1193 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +00001194 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001195
Hao Liu751004a2015-06-08 04:48:37 +00001196 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1197 << " with max VF = "
1198 << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
Adam Nemet04563272015-02-01 16:56:15 +00001199
Adam Nemet9c926572015-03-10 17:40:37 +00001200 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +00001201}
1202
Adam Nemetdee666b2015-03-10 17:40:34 +00001203bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +00001204 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001205 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001206
1207 MaxSafeDepDistBytes = -1U;
1208 while (!CheckDeps.empty()) {
1209 MemAccessInfo CurAccess = *CheckDeps.begin();
1210
1211 // Get the relevant memory access set.
1212 EquivalenceClasses<MemAccessInfo>::iterator I =
1213 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1214
1215 // Check accesses within this set.
1216 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
1217 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
1218
1219 // Check every access pair.
1220 while (AI != AE) {
1221 CheckDeps.erase(*AI);
1222 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1223 while (OI != AE) {
1224 // Check every accessing instruction pair in program order.
1225 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1226 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1227 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1228 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +00001229 auto A = std::make_pair(&*AI, *I1);
1230 auto B = std::make_pair(&*OI, *I2);
1231
1232 assert(*I1 != *I2);
1233 if (*I1 > *I2)
1234 std::swap(A, B);
1235
1236 Dependence::DepType Type =
1237 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1238 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1239
1240 // Gather dependences unless we accumulated MaxInterestingDependence
1241 // dependences. In that case return as soon as we find the first
1242 // unsafe dependence. This puts a limit on this quadratic
1243 // algorithm.
1244 if (RecordInterestingDependences) {
1245 if (Dependence::isInterestingDependence(Type))
1246 InterestingDependences.push_back(
1247 Dependence(A.second, B.second, Type));
1248
1249 if (InterestingDependences.size() >= MaxInterestingDependence) {
1250 RecordInterestingDependences = false;
1251 InterestingDependences.clear();
1252 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1253 }
1254 }
1255 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +00001256 return false;
1257 }
1258 ++OI;
1259 }
1260 AI++;
1261 }
1262 }
Adam Nemet9c926572015-03-10 17:40:37 +00001263
1264 DEBUG(dbgs() << "Total Interesting Dependences: "
1265 << InterestingDependences.size() << "\n");
1266 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +00001267}
1268
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001269SmallVector<Instruction *, 4>
1270MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1271 MemAccessInfo Access(Ptr, isWrite);
1272 auto &IndexVector = Accesses.find(Access)->second;
1273
1274 SmallVector<Instruction *, 4> Insts;
1275 std::transform(IndexVector.begin(), IndexVector.end(),
1276 std::back_inserter(Insts),
1277 [&](unsigned Idx) { return this->InstMap[Idx]; });
1278 return Insts;
1279}
1280
Adam Nemet58913d62015-03-10 17:40:43 +00001281const char *MemoryDepChecker::Dependence::DepName[] = {
1282 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1283 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1284
1285void MemoryDepChecker::Dependence::print(
1286 raw_ostream &OS, unsigned Depth,
1287 const SmallVectorImpl<Instruction *> &Instrs) const {
1288 OS.indent(Depth) << DepName[Type] << ":\n";
1289 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1290 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1291}
1292
Adam Nemet929c38e2015-02-19 19:15:10 +00001293bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001294 // We need to have a loop header.
1295 DEBUG(dbgs() << "LAA: Found a loop: " <<
1296 TheLoop->getHeader()->getName() << '\n');
1297
Adam Nemet929c38e2015-02-19 19:15:10 +00001298 // We can only analyze innermost loops.
1299 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001300 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +00001301 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +00001302 return false;
1303 }
1304
1305 // We must have a single backedge.
1306 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001307 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001308 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001309 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001310 "loop control flow is not understood by analyzer");
1311 return false;
1312 }
1313
1314 // We must have a single exiting block.
1315 if (!TheLoop->getExitingBlock()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001316 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001317 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001318 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001319 "loop control flow is not understood by analyzer");
1320 return false;
1321 }
1322
1323 // We only handle bottom-tested loops, i.e. loop in which the condition is
1324 // checked at the end of each iteration. With that we can assume that all
1325 // instructions in the loop are executed the same number of times.
1326 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001327 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001328 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001329 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001330 "loop control flow is not understood by analyzer");
1331 return false;
1332 }
1333
Adam Nemet929c38e2015-02-19 19:15:10 +00001334 // ScalarEvolution needs to be able to find the exit count.
1335 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
1336 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001337 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001338 "could not determine number of loop iterations");
1339 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1340 return false;
1341 }
1342
1343 return true;
1344}
1345
Adam Nemet8bc61df2015-02-24 00:41:59 +00001346void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001347
1348 typedef SmallVector<Value*, 16> ValueVector;
1349 typedef SmallPtrSet<Value*, 16> ValueSet;
1350
1351 // Holds the Load and Store *instructions*.
1352 ValueVector Loads;
1353 ValueVector Stores;
1354
1355 // Holds all the different accesses in the loop.
1356 unsigned NumReads = 0;
1357 unsigned NumReadWrites = 0;
1358
Adam Nemet7cdebac2015-07-14 22:32:44 +00001359 PtrRtChecking.Pointers.clear();
1360 PtrRtChecking.Need = false;
Adam Nemet04563272015-02-01 16:56:15 +00001361
1362 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +00001363
1364 // For each block.
1365 for (Loop::block_iterator bb = TheLoop->block_begin(),
1366 be = TheLoop->block_end(); bb != be; ++bb) {
1367
1368 // Scan the BB and collect legal loads and stores.
1369 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1370 ++it) {
1371
1372 // If this is a load, save it. If this instruction can read from memory
1373 // but is not a load, then we quit. Notice that we don't handle function
1374 // calls that read or write.
1375 if (it->mayReadFromMemory()) {
1376 // Many math library functions read the rounding mode. We will only
1377 // vectorize a loop if it contains known function calls that don't set
1378 // the flag. Therefore, it is safe to ignore this read from memory.
1379 CallInst *Call = dyn_cast<CallInst>(it);
1380 if (Call && getIntrinsicIDForCall(Call, TLI))
1381 continue;
1382
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +00001383 // If the function has an explicit vectorized counterpart, we can safely
1384 // assume that it can be vectorized.
1385 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1386 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1387 continue;
1388
Adam Nemet04563272015-02-01 16:56:15 +00001389 LoadInst *Ld = dyn_cast<LoadInst>(it);
1390 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001391 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +00001392 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +00001393 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001394 CanVecMem = false;
1395 return;
Adam Nemet04563272015-02-01 16:56:15 +00001396 }
1397 NumLoads++;
1398 Loads.push_back(Ld);
1399 DepChecker.addAccess(Ld);
1400 continue;
1401 }
1402
1403 // Save 'store' instructions. Abort if other instructions write to memory.
1404 if (it->mayWriteToMemory()) {
1405 StoreInst *St = dyn_cast<StoreInst>(it);
1406 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001407 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001408 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001409 CanVecMem = false;
1410 return;
Adam Nemet04563272015-02-01 16:56:15 +00001411 }
1412 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001413 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001414 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001415 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001416 CanVecMem = false;
1417 return;
Adam Nemet04563272015-02-01 16:56:15 +00001418 }
1419 NumStores++;
1420 Stores.push_back(St);
1421 DepChecker.addAccess(St);
1422 }
1423 } // Next instr.
1424 } // Next block.
1425
1426 // Now we have two lists that hold the loads and the stores.
1427 // Next, we find the pointers that they use.
1428
1429 // Check if we see any stores. If there are no stores, then we don't
1430 // care if the pointers are *restrict*.
1431 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001432 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001433 CanVecMem = true;
1434 return;
Adam Nemet04563272015-02-01 16:56:15 +00001435 }
1436
Adam Nemetdee666b2015-03-10 17:40:34 +00001437 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001438 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Adam Nemete2b885c2015-04-23 20:09:20 +00001439 AA, LI, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001440
1441 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1442 // multiple times on the same object. If the ptr is accessed twice, once
1443 // for read and once for write, it will only appear once (on the write
1444 // list). This is okay, since we are going to check for conflicts between
1445 // writes and between reads and writes, but not between reads and reads.
1446 ValueSet Seen;
1447
1448 ValueVector::iterator I, IE;
1449 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1450 StoreInst *ST = cast<StoreInst>(*I);
1451 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001452 // Check for store to loop invariant address.
1453 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001454 // If we did *not* see this pointer before, insert it to the read-write
1455 // list. At this phase it is only a 'write' list.
1456 if (Seen.insert(Ptr).second) {
1457 ++NumReadWrites;
1458
Chandler Carruthac80dc72015-06-17 07:18:54 +00001459 MemoryLocation Loc = MemoryLocation::get(ST);
Adam Nemet04563272015-02-01 16:56:15 +00001460 // The TBAA metadata could have a control dependency on the predication
1461 // condition, so we cannot rely on it when determining whether or not we
1462 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001463 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001464 Loc.AATags.TBAA = nullptr;
1465
1466 Accesses.addStore(Loc);
1467 }
1468 }
1469
1470 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001471 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001472 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001473 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001474 CanVecMem = true;
1475 return;
Adam Nemet04563272015-02-01 16:56:15 +00001476 }
1477
1478 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1479 LoadInst *LD = cast<LoadInst>(*I);
1480 Value* Ptr = LD->getPointerOperand();
1481 // If we did *not* see this pointer before, insert it to the
1482 // read list. If we *did* see it before, then it is already in
1483 // the read-write list. This allows us to vectorize expressions
1484 // such as A[i] += x; Because the address of A[i] is a read-write
1485 // pointer. This only works if the index of A[i] is consecutive.
1486 // If the address of i is unknown (for example A[B[i]]) then we may
1487 // read a few words, modify, and write a few words, and some of the
1488 // words may be written to the same address.
1489 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001490 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001491 ++NumReads;
1492 IsReadOnlyPtr = true;
1493 }
1494
Chandler Carruthac80dc72015-06-17 07:18:54 +00001495 MemoryLocation Loc = MemoryLocation::get(LD);
Adam Nemet04563272015-02-01 16:56:15 +00001496 // The TBAA metadata could have a control dependency on the predication
1497 // condition, so we cannot rely on it when determining whether or not we
1498 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001499 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001500 Loc.AATags.TBAA = nullptr;
1501
1502 Accesses.addLoad(Loc, IsReadOnlyPtr);
1503 }
1504
1505 // If we write (or read-write) to a single destination and there are no
1506 // other reads in this loop then is it safe to vectorize.
1507 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001508 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001509 CanVecMem = true;
1510 return;
Adam Nemet04563272015-02-01 16:56:15 +00001511 }
1512
1513 // Build dependence sets and check whether we need a runtime pointer bounds
1514 // check.
1515 Accesses.buildDependenceSets();
Adam Nemet04563272015-02-01 16:56:15 +00001516
1517 // Find pointers with computable bounds. We are going to use this information
1518 // to place a runtime bound check.
Adam Nemetee614742015-07-09 22:17:38 +00001519 bool CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001520 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides);
Adam Nemetee614742015-07-09 22:17:38 +00001521 if (!CanDoRTIfNeeded) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001522 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemetee614742015-07-09 22:17:38 +00001523 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1524 << "the array bounds.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001525 CanVecMem = false;
1526 return;
Adam Nemet04563272015-02-01 16:56:15 +00001527 }
1528
Adam Nemetee614742015-07-09 22:17:38 +00001529 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001530
Adam Nemet436018c2015-02-19 19:15:00 +00001531 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001532 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001533 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001534 CanVecMem = DepChecker.areDepsSafe(
1535 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1536 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1537
1538 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001539 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001540
1541 // Clear the dependency checks. We assume they are not needed.
Adam Nemetdf3dc5b2015-05-18 15:37:03 +00001542 Accesses.resetDepChecks(DepChecker);
Adam Nemet04563272015-02-01 16:56:15 +00001543
Adam Nemet7cdebac2015-07-14 22:32:44 +00001544 PtrRtChecking.reset();
1545 PtrRtChecking.Need = true;
Adam Nemet04563272015-02-01 16:56:15 +00001546
Adam Nemetee614742015-07-09 22:17:38 +00001547 CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001548 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
Silviu Baranga98a13712015-06-08 10:27:06 +00001549
Adam Nemet949e91a2015-03-10 19:12:41 +00001550 // Check that we found the bounds for the pointer.
Adam Nemetee614742015-07-09 22:17:38 +00001551 if (!CanDoRTIfNeeded) {
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001552 emitAnalysis(LoopAccessReport()
1553 << "cannot check memory dependencies at runtime");
1554 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001555 CanVecMem = false;
1556 return;
1557 }
1558
Adam Nemet04563272015-02-01 16:56:15 +00001559 CanVecMem = true;
1560 }
1561 }
1562
Adam Nemet4bb90a72015-03-10 21:47:39 +00001563 if (CanVecMem)
1564 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
Adam Nemet7cdebac2015-07-14 22:32:44 +00001565 << (PtrRtChecking.Need ? "" : " don't")
Adam Nemet0f67c6c2015-07-09 22:17:41 +00001566 << " need runtime memory checks.\n");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001567 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001568 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001569 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001570 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1571 }
Adam Nemet04563272015-02-01 16:56:15 +00001572}
1573
Adam Nemet01abb2c2015-02-18 03:43:19 +00001574bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1575 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001576 assert(TheLoop->contains(BB) && "Unknown block used");
1577
1578 // Blocks that do not dominate the latch need predication.
1579 BasicBlock* Latch = TheLoop->getLoopLatch();
1580 return !DT->dominates(BB, Latch);
1581}
1582
Adam Nemet2bd6e982015-02-19 19:15:15 +00001583void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001584 assert(!Report && "Multiple reports generated");
1585 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001586}
1587
Adam Nemet57ac7662015-02-19 19:15:21 +00001588bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001589 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1590}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001591
1592// FIXME: this function is currently a duplicate of the one in
1593// LoopVectorize.cpp.
1594static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1595 Instruction *Loc) {
1596 if (FirstInst)
1597 return FirstInst;
1598 if (Instruction *I = dyn_cast<Instruction>(V))
1599 return I->getParent() == Loc->getParent() ? I : nullptr;
1600 return nullptr;
1601}
1602
Adam Nemet1da7df32015-07-26 05:32:14 +00001603/// \brief IR Values for the lower and upper bounds of a pointer evolution.
1604struct PointerBounds {
1605 Value *Start;
1606 Value *End;
1607};
Adam Nemet7206d7a2015-02-06 18:31:04 +00001608
Adam Nemet1da7df32015-07-26 05:32:14 +00001609/// \brief Expand code for the lower and upper bound of the pointer group \p CG
1610/// in \p TheLoop. \return the values for the bounds.
1611static PointerBounds
1612expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
1613 Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
1614 const RuntimePointerChecking &PtrRtChecking) {
1615 Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
1616 const SCEV *Sc = SE->getSCEV(Ptr);
1617
1618 if (SE->isLoopInvariant(Sc, TheLoop)) {
1619 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1620 << "\n");
1621 return {Ptr, Ptr};
1622 } else {
1623 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1624 LLVMContext &Ctx = Loc->getContext();
1625
1626 // Use this type for pointer arithmetic.
1627 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1628 Value *Start = nullptr, *End = nullptr;
1629
1630 DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1631 Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
1632 End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1633 DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
1634 return {Start, End};
1635 }
1636}
1637
1638/// \brief Turns a collection of checks into a collection of expanded upper and
1639/// lower bounds for both pointers in the check.
1640static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
1641 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
1642 Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
1643 const RuntimePointerChecking &PtrRtChecking) {
1644 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1645
1646 // Here we're relying on the SCEV Expander's cache to only emit code for the
1647 // same bounds once.
1648 std::transform(
1649 PointerChecks.begin(), PointerChecks.end(),
1650 std::back_inserter(ChecksWithBounds),
1651 [&](const RuntimePointerChecking::PointerCheck &Check) {
NAKAMURA Takumi94abbbd2015-07-27 01:35:30 +00001652 PointerBounds
1653 First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
1654 Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
1655 return std::make_pair(First, Second);
Adam Nemet1da7df32015-07-26 05:32:14 +00001656 });
1657
1658 return ChecksWithBounds;
1659}
1660
1661std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1662 Instruction *Loc,
1663 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
1664 const {
1665
1666 SCEVExpander Exp(*SE, DL, "induction");
1667 auto ExpandedChecks =
1668 expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, PtrRtChecking);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001669
1670 LLVMContext &Ctx = Loc->getContext();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001671 Instruction *FirstInst = nullptr;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001672 IRBuilder<> ChkBuilder(Loc);
1673 // Our instructions might fold to a constant.
1674 Value *MemoryRuntimeCheck = nullptr;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001675
Adam Nemet1da7df32015-07-26 05:32:14 +00001676 for (const auto &Check : ExpandedChecks) {
1677 const PointerBounds &A = Check.first, &B = Check.second;
1678 unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1679 unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001680
Adam Nemet1da7df32015-07-26 05:32:14 +00001681 assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
1682 (AS1 == A.End->getType()->getPointerAddressSpace()) &&
1683 "Trying to bounds check pointers with different address spaces");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001684
Adam Nemet1da7df32015-07-26 05:32:14 +00001685 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1686 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001687
Adam Nemet1da7df32015-07-26 05:32:14 +00001688 Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
1689 Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
1690 Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
1691 Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001692
Adam Nemet1da7df32015-07-26 05:32:14 +00001693 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1694 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1695 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1696 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1697 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1698 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1699 if (MemoryRuntimeCheck) {
1700 IsConflict =
1701 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001702 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001703 }
Adam Nemet1da7df32015-07-26 05:32:14 +00001704 MemoryRuntimeCheck = IsConflict;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001705 }
1706
Adam Nemet90fec842015-04-02 17:51:57 +00001707 if (!MemoryRuntimeCheck)
1708 return std::make_pair(nullptr, nullptr);
1709
Adam Nemet7206d7a2015-02-06 18:31:04 +00001710 // We have to do this trickery because the IRBuilder might fold the check to a
1711 // constant expression in which case there is no Instruction anchored in a
1712 // the block.
1713 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1714 ConstantInt::getTrue(Ctx));
1715 ChkBuilder.Insert(Check, "memcheck.conflict");
1716 FirstInst = getFirstInst(FirstInst, Check, Loc);
1717 return std::make_pair(FirstInst, Check);
1718}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001719
Adam Nemet1da7df32015-07-26 05:32:14 +00001720std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
Adam Nemet87011182015-08-04 05:16:20 +00001721 Instruction *Loc) const {
Adam Nemet1da7df32015-07-26 05:32:14 +00001722 if (!PtrRtChecking.Need)
1723 return std::make_pair(nullptr, nullptr);
1724
Adam Nemet15840392015-08-07 22:44:15 +00001725 return addRuntimeCheck(Loc, PtrRtChecking.getChecks());
Adam Nemet1da7df32015-07-26 05:32:14 +00001726}
1727
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001728LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001729 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001730 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemete2b885c2015-04-23 20:09:20 +00001731 DominatorTree *DT, LoopInfo *LI,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001732 const ValueToValueMap &Strides)
Adam Nemet7cdebac2015-07-14 22:32:44 +00001733 : PtrRtChecking(SE), DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL),
1734 TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001735 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1736 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001737 if (canAnalyzeLoop())
1738 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001739}
1740
Adam Nemete91cc6e2015-02-19 19:15:19 +00001741void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1742 if (CanVecMem) {
Adam Nemet7cdebac2015-07-14 22:32:44 +00001743 if (PtrRtChecking.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001744 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001745 else
1746 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001747 }
1748
1749 if (Report)
1750 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1751
Adam Nemet58913d62015-03-10 17:40:43 +00001752 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1753 OS.indent(Depth) << "Interesting Dependences:\n";
1754 for (auto &Dep : *InterestingDependences) {
1755 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1756 OS << "\n";
1757 }
1758 } else
1759 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001760
1761 // List the pair of accesses need run-time checks to prove independence.
Adam Nemet7cdebac2015-07-14 22:32:44 +00001762 PtrRtChecking.print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00001763 OS << "\n";
Adam Nemetc3384322015-05-18 15:36:57 +00001764
1765 OS.indent(Depth) << "Store to invariant address was "
1766 << (StoreToLoopInvariantAddress ? "" : "not ")
1767 << "found in loop.\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001768}
1769
Adam Nemet8bc61df2015-02-24 00:41:59 +00001770const LoopAccessInfo &
1771LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001772 auto &LAI = LoopAccessInfoMap[L];
1773
1774#ifndef NDEBUG
1775 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1776 "Symbolic strides changed for loop");
1777#endif
1778
1779 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001780 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemete2b885c2015-04-23 20:09:20 +00001781 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
1782 Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001783#ifndef NDEBUG
1784 LAI->NumSymbolicStrides = Strides.size();
1785#endif
1786 }
1787 return *LAI.get();
1788}
1789
Adam Nemete91cc6e2015-02-19 19:15:19 +00001790void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1791 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1792
Adam Nemete91cc6e2015-02-19 19:15:19 +00001793 ValueToValueMap NoSymbolicStrides;
1794
1795 for (Loop *TopLevelLoop : *LI)
1796 for (Loop *L : depth_first(TopLevelLoop)) {
1797 OS.indent(2) << L->getHeader()->getName() << ":\n";
1798 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1799 LAI.print(OS, 4);
1800 }
1801}
1802
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001803bool LoopAccessAnalysis::runOnFunction(Function &F) {
1804 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001805 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1806 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1807 AA = &getAnalysis<AliasAnalysis>();
1808 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete2b885c2015-04-23 20:09:20 +00001809 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001810
1811 return false;
1812}
1813
1814void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1815 AU.addRequired<ScalarEvolution>();
1816 AU.addRequired<AliasAnalysis>();
1817 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001818 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001819
1820 AU.setPreservesAll();
1821}
1822
1823char LoopAccessAnalysis::ID = 0;
1824static const char laa_name[] = "Loop Access Analysis";
1825#define LAA_NAME "loop-accesses"
1826
1827INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1828INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1829INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1830INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001831INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001832INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1833
1834namespace llvm {
1835 Pass *createLAAPass() {
1836 return new LoopAccessAnalysis();
1837 }
1838}