blob: 14c3c57e4c96d1b670af120f21f8528efa442ccb [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>
Adam Nemet38530882015-08-09 20:06:06 +0000152RuntimePointerChecking::generateChecks() const {
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000153 SmallVector<PointerCheck, 4> Checks;
154
Adam Nemet7c52e052015-07-27 19:38:50 +0000155 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
156 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
157 const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
158 const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000159
Adam Nemet38530882015-08-09 20:06:06 +0000160 if (needsChecking(CGI, CGJ))
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000161 Checks.push_back(std::make_pair(&CGI, &CGJ));
162 }
163 }
164 return Checks;
165}
166
Adam Nemet15840392015-08-07 22:44:15 +0000167void RuntimePointerChecking::generateChecks(
168 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
169 assert(Checks.empty() && "Checks is not empty");
170 groupChecks(DepCands, UseDependencies);
171 Checks = generateChecks();
172}
173
Adam Nemet651a5a22015-08-09 20:06:08 +0000174bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
175 const CheckingPtrGroup &N) const {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000176 for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
177 for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
Adam Nemet651a5a22015-08-09 20:06:08 +0000178 if (needsChecking(M.Members[I], N.Members[J]))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000179 return true;
180 return false;
181}
182
183/// Compare \p I and \p J and return the minimum.
184/// Return nullptr in case we couldn't find an answer.
185static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
186 ScalarEvolution *SE) {
187 const SCEV *Diff = SE->getMinusSCEV(J, I);
188 const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
189
190 if (!C)
191 return nullptr;
192 if (C->getValue()->isNegative())
193 return J;
194 return I;
195}
196
Adam Nemet7cdebac2015-07-14 22:32:44 +0000197bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000198 const SCEV *Start = RtCheck.Pointers[Index].Start;
199 const SCEV *End = RtCheck.Pointers[Index].End;
200
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000201 // Compare the starts and ends with the known minimum and maximum
202 // of this set. We need to know how we compare against the min/max
203 // of the set in order to be able to emit memchecks.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000204 const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000205 if (!Min0)
206 return false;
207
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000208 const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000209 if (!Min1)
210 return false;
211
212 // Update the low bound expression if we've found a new min value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000213 if (Min0 == Start)
214 Low = Start;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000215
216 // Update the high bound expression if we've found a new max value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000217 if (Min1 != End)
218 High = End;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000219
220 Members.push_back(Index);
221 return true;
222}
223
Adam Nemet7cdebac2015-07-14 22:32:44 +0000224void RuntimePointerChecking::groupChecks(
225 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000226 // We build the groups from dependency candidates equivalence classes
227 // because:
228 // - We know that pointers in the same equivalence class share
229 // the same underlying object and therefore there is a chance
230 // that we can compare pointers
231 // - We wouldn't be able to merge two pointers for which we need
232 // to emit a memcheck. The classes in DepCands are already
233 // conveniently built such that no two pointers in the same
234 // class need checking against each other.
235
236 // We use the following (greedy) algorithm to construct the groups
237 // For every pointer in the equivalence class:
238 // For each existing group:
239 // - if the difference between this pointer and the min/max bounds
240 // of the group is a constant, then make the pointer part of the
241 // group and update the min/max bounds of that group as required.
242
243 CheckingGroups.clear();
244
Silviu Baranga48250602015-07-28 13:44:08 +0000245 // If we need to check two pointers to the same underlying object
246 // with a non-constant difference, we shouldn't perform any pointer
247 // grouping with those pointers. This is because we can easily get
248 // into cases where the resulting check would return false, even when
249 // the accesses are safe.
250 //
251 // The following example shows this:
252 // for (i = 0; i < 1000; ++i)
253 // a[5000 + i * m] = a[i] + a[i + 9000]
254 //
255 // Here grouping gives a check of (5000, 5000 + 1000 * m) against
256 // (0, 10000) which is always false. However, if m is 1, there is no
257 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
258 // us to perform an accurate check in this case.
259 //
260 // The above case requires that we have an UnknownDependence between
261 // accesses to the same underlying object. This cannot happen unless
262 // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
263 // is also false. In this case we will use the fallback path and create
264 // separate checking groups for all pointers.
265
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000266 // If we don't have the dependency partitions, construct a new
Silviu Baranga48250602015-07-28 13:44:08 +0000267 // checking pointer group for each pointer. This is also required
268 // for correctness, because in this case we can have checking between
269 // pointers to the same underlying object.
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000270 if (!UseDependencies) {
271 for (unsigned I = 0; I < Pointers.size(); ++I)
272 CheckingGroups.push_back(CheckingPtrGroup(I, *this));
273 return;
274 }
275
276 unsigned TotalComparisons = 0;
277
278 DenseMap<Value *, unsigned> PositionMap;
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000279 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
280 PositionMap[Pointers[Index].PointerValue] = Index;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000281
Silviu Barangace3877f2015-07-09 15:18:25 +0000282 // We need to keep track of what pointers we've already seen so we
283 // don't process them twice.
284 SmallSet<unsigned, 2> Seen;
285
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000286 // Go through all equivalence classes, get the the "pointer check groups"
Silviu Barangace3877f2015-07-09 15:18:25 +0000287 // and add them to the overall solution. We use the order in which accesses
288 // appear in 'Pointers' to enforce determinism.
289 for (unsigned I = 0; I < Pointers.size(); ++I) {
290 // We've seen this pointer before, and therefore already processed
291 // its equivalence class.
292 if (Seen.count(I))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000293 continue;
294
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000295 MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
296 Pointers[I].IsWritePtr);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000297
Silviu Barangace3877f2015-07-09 15:18:25 +0000298 SmallVector<CheckingPtrGroup, 2> Groups;
299 auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
300
Silviu Barangaa647c302015-07-13 14:48:24 +0000301 // Because DepCands is constructed by visiting accesses in the order in
302 // which they appear in alias sets (which is deterministic) and the
303 // iteration order within an equivalence class member is only dependent on
304 // the order in which unions and insertions are performed on the
305 // equivalence class, the iteration order is deterministic.
Silviu Barangace3877f2015-07-09 15:18:25 +0000306 for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000307 MI != ME; ++MI) {
308 unsigned Pointer = PositionMap[MI->getPointer()];
309 bool Merged = false;
Silviu Barangace3877f2015-07-09 15:18:25 +0000310 // Mark this pointer as seen.
311 Seen.insert(Pointer);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000312
313 // Go through all the existing sets and see if we can find one
314 // which can include this pointer.
315 for (CheckingPtrGroup &Group : Groups) {
316 // Don't perform more than a certain amount of comparisons.
317 // This should limit the cost of grouping the pointers to something
318 // reasonable. If we do end up hitting this threshold, the algorithm
319 // will create separate groups for all remaining pointers.
320 if (TotalComparisons > MemoryCheckMergeThreshold)
321 break;
322
323 TotalComparisons++;
324
325 if (Group.addPointer(Pointer)) {
326 Merged = true;
327 break;
328 }
329 }
330
331 if (!Merged)
332 // We couldn't add this pointer to any existing set or the threshold
333 // for the number of comparisons has been reached. Create a new group
334 // to hold the current pointer.
335 Groups.push_back(CheckingPtrGroup(Pointer, *this));
336 }
337
338 // We've computed the grouped checks for this partition.
339 // Save the results and continue with the next one.
340 std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
341 }
Adam Nemet04563272015-02-01 16:56:15 +0000342}
343
Adam Nemet041e6de2015-07-16 02:48:05 +0000344bool RuntimePointerChecking::arePointersInSamePartition(
345 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
346 unsigned PtrIdx2) {
347 return (PtrToPartition[PtrIdx1] != -1 &&
348 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
349}
350
Adam Nemet651a5a22015-08-09 20:06:08 +0000351bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000352 const PointerInfo &PointerI = Pointers[I];
353 const PointerInfo &PointerJ = Pointers[J];
354
Adam Nemeta8945b72015-02-18 03:43:58 +0000355 // No need to check if two readonly pointers intersect.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000356 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
Adam Nemeta8945b72015-02-18 03:43:58 +0000357 return false;
358
359 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000360 if (PointerI.DependencySetId == PointerJ.DependencySetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000361 return false;
362
363 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000364 if (PointerI.AliasSetId != PointerJ.AliasSetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000365 return false;
366
367 return true;
368}
369
Adam Nemet54f0b832015-07-27 23:54:41 +0000370void RuntimePointerChecking::printChecks(
371 raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
372 unsigned Depth) const {
373 unsigned N = 0;
374 for (const auto &Check : Checks) {
375 const auto &First = Check.first->Members, &Second = Check.second->Members;
376
377 OS.indent(Depth) << "Check " << N++ << ":\n";
378
379 OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
380 for (unsigned K = 0; K < First.size(); ++K)
381 OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
382
383 OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
384 for (unsigned K = 0; K < Second.size(); ++K)
385 OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
386 }
387}
388
Adam Nemet3a91e942015-08-07 19:44:48 +0000389void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000390
391 OS.indent(Depth) << "Run-time memory checks:\n";
Adam Nemet15840392015-08-07 22:44:15 +0000392 printChecks(OS, Checks, Depth);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000393
394 OS.indent(Depth) << "Grouped accesses:\n";
395 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
Adam Nemet54f0b832015-07-27 23:54:41 +0000396 const auto &CG = CheckingGroups[I];
397
398 OS.indent(Depth + 2) << "Group " << &CG << ":\n";
399 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
400 << ")\n";
401 for (unsigned J = 0; J < CG.Members.size(); ++J) {
402 OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000403 << "\n";
404 }
405 }
Adam Nemete91cc6e2015-02-19 19:15:19 +0000406}
407
Adam Nemet04563272015-02-01 16:56:15 +0000408namespace {
409/// \brief Analyses memory accesses in a loop.
410///
411/// Checks whether run time pointer checks are needed and builds sets for data
412/// dependence checking.
413class AccessAnalysis {
414public:
415 /// \brief Read or write access location.
416 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
417 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
418
Adam Nemete2b885c2015-04-23 20:09:20 +0000419 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Adam Nemetdee666b2015-03-10 17:40:34 +0000420 MemoryDepChecker::DepCandidates &DA)
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000421 : DL(Dl), AST(*AA), LI(LI), DepCands(DA),
422 IsRTCheckAnalysisNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000423
424 /// \brief Register a load and whether it is only read from.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000425 void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
Adam Nemet04563272015-02-01 16:56:15 +0000426 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000427 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000428 Accesses.insert(MemAccessInfo(Ptr, false));
429 if (IsReadOnly)
430 ReadOnlyPtr.insert(Ptr);
431 }
432
433 /// \brief Register a store.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000434 void addStore(MemoryLocation &Loc) {
Adam Nemet04563272015-02-01 16:56:15 +0000435 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000436 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000437 Accesses.insert(MemAccessInfo(Ptr, true));
438 }
439
440 /// \brief Check whether we can check the pointers at runtime for
Adam Nemetee614742015-07-09 22:17:38 +0000441 /// non-intersection.
442 ///
443 /// Returns true if we need no check or if we do and we can generate them
444 /// (i.e. the pointers have computable bounds).
Adam Nemet7cdebac2015-07-14 22:32:44 +0000445 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
446 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000447 bool ShouldCheckStride = false);
448
449 /// \brief Goes over all memory accesses, checks whether a RT check is needed
450 /// and builds sets of dependent accesses.
451 void buildDependenceSets() {
452 processMemAccesses();
453 }
454
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000455 /// \brief Initial processing of memory accesses determined that we need to
456 /// perform dependency checking.
457 ///
458 /// Note that this can later be cleared if we retry memcheck analysis without
459 /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
Adam Nemet04563272015-02-01 16:56:15 +0000460 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000461
462 /// We decided that no dependence analysis would be used. Reset the state.
463 void resetDepChecks(MemoryDepChecker &DepChecker) {
464 CheckDeps.clear();
465 DepChecker.clearInterestingDependences();
466 }
Adam Nemet04563272015-02-01 16:56:15 +0000467
468 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
469
470private:
471 typedef SetVector<MemAccessInfo> PtrAccessSet;
472
473 /// \brief Go over all memory access and check whether runtime pointer checks
Adam Nemetb41d2d32015-07-09 06:47:21 +0000474 /// are needed and build sets of dependency check candidates.
Adam Nemet04563272015-02-01 16:56:15 +0000475 void processMemAccesses();
476
477 /// Set of all accesses.
478 PtrAccessSet Accesses;
479
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000480 const DataLayout &DL;
481
Adam Nemet04563272015-02-01 16:56:15 +0000482 /// Set of accesses that need a further dependence check.
483 MemAccessInfoSet CheckDeps;
484
485 /// Set of pointers that are read only.
486 SmallPtrSet<Value*, 16> ReadOnlyPtr;
487
Adam Nemet04563272015-02-01 16:56:15 +0000488 /// An alias set tracker to partition the access set by underlying object and
489 //intrinsic property (such as TBAA metadata).
490 AliasSetTracker AST;
491
Adam Nemete2b885c2015-04-23 20:09:20 +0000492 LoopInfo *LI;
493
Adam Nemet04563272015-02-01 16:56:15 +0000494 /// Sets of potentially dependent accesses - members of one set share an
495 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
496 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000497 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000498
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000499 /// \brief Initial processing of memory accesses determined that we may need
500 /// to add memchecks. Perform the analysis to determine the necessary checks.
501 ///
502 /// Note that, this is different from isDependencyCheckNeeded. When we retry
503 /// memcheck analysis without dependency checking
504 /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
505 /// while this remains set if we have potentially dependent accesses.
506 bool IsRTCheckAnalysisNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000507};
508
509} // end anonymous namespace
510
511/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000512static bool hasComputableBounds(ScalarEvolution *SE,
513 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000514 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
515 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
516 if (!AR)
517 return false;
518
519 return AR->isAffine();
520}
521
Adam Nemet7cdebac2015-07-14 22:32:44 +0000522bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
523 ScalarEvolution *SE, Loop *TheLoop,
524 const ValueToValueMap &StridesMap,
525 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000526 // Find pointers with computable bounds. We are going to use this information
527 // to place a runtime bound check.
528 bool CanDoRT = true;
529
Adam Nemetee614742015-07-09 22:17:38 +0000530 bool NeedRTCheck = false;
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000531 if (!IsRTCheckAnalysisNeeded) return true;
Silviu Baranga98a13712015-06-08 10:27:06 +0000532
Adam Nemet04563272015-02-01 16:56:15 +0000533 bool IsDepCheckNeeded = isDependencyCheckNeeded();
Adam Nemet04563272015-02-01 16:56:15 +0000534
535 // We assign a consecutive id to access from different alias sets.
536 // Accesses between different groups doesn't need to be checked.
537 unsigned ASId = 1;
538 for (auto &AS : AST) {
Adam Nemet424edc62015-07-08 22:58:48 +0000539 int NumReadPtrChecks = 0;
540 int NumWritePtrChecks = 0;
541
Adam Nemet04563272015-02-01 16:56:15 +0000542 // We assign consecutive id to access from different dependence sets.
543 // Accesses within the same set don't need a runtime check.
544 unsigned RunningDepId = 1;
545 DenseMap<Value *, unsigned> DepSetId;
546
547 for (auto A : AS) {
548 Value *Ptr = A.getValue();
549 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
550 MemAccessInfo Access(Ptr, IsWrite);
551
Adam Nemet424edc62015-07-08 22:58:48 +0000552 if (IsWrite)
553 ++NumWritePtrChecks;
554 else
555 ++NumReadPtrChecks;
556
Adam Nemet04563272015-02-01 16:56:15 +0000557 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000558 // When we run after a failing dependency check we have to make sure
559 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000560 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000561 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000562 // The id of the dependence set.
563 unsigned DepId;
564
565 if (IsDepCheckNeeded) {
566 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
567 unsigned &LeaderId = DepSetId[Leader];
568 if (!LeaderId)
569 LeaderId = RunningDepId++;
570 DepId = LeaderId;
571 } else
572 // Each access has its own dependence set.
573 DepId = RunningDepId++;
574
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000575 RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000576
Adam Nemet339f42b2015-02-19 19:15:07 +0000577 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000578 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000579 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000580 CanDoRT = false;
581 }
582 }
583
Adam Nemet424edc62015-07-08 22:58:48 +0000584 // If we have at least two writes or one write and a read then we need to
585 // check them. But there is no need to checks if there is only one
586 // dependence set for this alias set.
587 //
588 // Note that this function computes CanDoRT and NeedRTCheck independently.
589 // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
590 // for which we couldn't find the bounds but we don't actually need to emit
591 // any checks so it does not matter.
592 if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
593 NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
594 NumWritePtrChecks >= 1));
595
Adam Nemet04563272015-02-01 16:56:15 +0000596 ++ASId;
597 }
598
599 // If the pointers that we would use for the bounds comparison have different
600 // address spaces, assume the values aren't directly comparable, so we can't
601 // use them for the runtime check. We also have to assume they could
602 // overlap. In the future there should be metadata for whether address spaces
603 // are disjoint.
604 unsigned NumPointers = RtCheck.Pointers.size();
605 for (unsigned i = 0; i < NumPointers; ++i) {
606 for (unsigned j = i + 1; j < NumPointers; ++j) {
607 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000608 if (RtCheck.Pointers[i].DependencySetId ==
609 RtCheck.Pointers[j].DependencySetId)
Adam Nemet04563272015-02-01 16:56:15 +0000610 continue;
611 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000612 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
Adam Nemet04563272015-02-01 16:56:15 +0000613 continue;
614
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000615 Value *PtrI = RtCheck.Pointers[i].PointerValue;
616 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
Adam Nemet04563272015-02-01 16:56:15 +0000617
618 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
619 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
620 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000621 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000622 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000623 return false;
624 }
625 }
626 }
627
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000628 if (NeedRTCheck && CanDoRT)
Adam Nemet15840392015-08-07 22:44:15 +0000629 RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000630
Adam Nemet155e8742015-08-07 22:44:21 +0000631 DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
Adam Nemetee614742015-07-09 22:17:38 +0000632 << " pointer comparisons.\n");
633
634 RtCheck.Need = NeedRTCheck;
635
636 bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
637 if (!CanDoRTIfNeeded)
638 RtCheck.reset();
639 return CanDoRTIfNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000640}
641
642void AccessAnalysis::processMemAccesses() {
643 // We process the set twice: first we process read-write pointers, last we
644 // process read-only pointers. This allows us to skip dependence tests for
645 // read-only pointers.
646
Adam Nemet339f42b2015-02-19 19:15:07 +0000647 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000648 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000649 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000650 DEBUG({
651 for (auto A : Accesses)
652 dbgs() << "\t" << *A.getPointer() << " (" <<
653 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
654 "read-only" : "read")) << ")\n";
655 });
656
657 // The AliasSetTracker has nicely partitioned our pointers by metadata
658 // compatibility and potential for underlying-object overlap. As a result, we
659 // only need to check for potential pointer dependencies within each alias
660 // set.
661 for (auto &AS : AST) {
662 // Note that both the alias-set tracker and the alias sets themselves used
663 // linked lists internally and so the iteration order here is deterministic
664 // (matching the original instruction order within each set).
665
666 bool SetHasWrite = false;
667
668 // Map of pointers to last access encountered.
669 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
670 UnderlyingObjToAccessMap ObjToLastAccess;
671
672 // Set of access to check after all writes have been processed.
673 PtrAccessSet DeferredAccesses;
674
675 // Iterate over each alias set twice, once to process read/write pointers,
676 // and then to process read-only pointers.
677 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
678 bool UseDeferred = SetIteration > 0;
679 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
680
681 for (auto AV : AS) {
682 Value *Ptr = AV.getValue();
683
684 // For a single memory access in AliasSetTracker, Accesses may contain
685 // both read and write, and they both need to be handled for CheckDeps.
686 for (auto AC : S) {
687 if (AC.getPointer() != Ptr)
688 continue;
689
690 bool IsWrite = AC.getInt();
691
692 // If we're using the deferred access set, then it contains only
693 // reads.
694 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
695 if (UseDeferred && !IsReadOnlyPtr)
696 continue;
697 // Otherwise, the pointer must be in the PtrAccessSet, either as a
698 // read or a write.
699 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
700 S.count(MemAccessInfo(Ptr, false))) &&
701 "Alias-set pointer not in the access set?");
702
703 MemAccessInfo Access(Ptr, IsWrite);
704 DepCands.insert(Access);
705
706 // Memorize read-only pointers for later processing and skip them in
707 // the first round (they need to be checked after we have seen all
708 // write pointers). Note: we also mark pointer that are not
709 // consecutive as "read-only" pointers (so that we check
710 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
711 if (!UseDeferred && IsReadOnlyPtr) {
712 DeferredAccesses.insert(Access);
713 continue;
714 }
715
716 // If this is a write - check other reads and writes for conflicts. If
717 // this is a read only check other writes for conflicts (but only if
718 // there is no other write to the ptr - this is an optimization to
719 // catch "a[i] = a[i] + " without having to do a dependence check).
720 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
721 CheckDeps.insert(Access);
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000722 IsRTCheckAnalysisNeeded = true;
Adam Nemet04563272015-02-01 16:56:15 +0000723 }
724
725 if (IsWrite)
726 SetHasWrite = true;
727
728 // Create sets of pointers connected by a shared alias set and
729 // underlying object.
730 typedef SmallVector<Value *, 16> ValueVector;
731 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000732
733 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
734 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000735 for (Value *UnderlyingObj : TempObjects) {
736 UnderlyingObjToAccessMap::iterator Prev =
737 ObjToLastAccess.find(UnderlyingObj);
738 if (Prev != ObjToLastAccess.end())
739 DepCands.unionSets(Access, Prev->second);
740
741 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000742 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000743 }
744 }
745 }
746 }
747 }
748}
749
Adam Nemet04563272015-02-01 16:56:15 +0000750static bool isInBoundsGep(Value *Ptr) {
751 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
752 return GEP->isInBounds();
753 return false;
754}
755
Adam Nemetc4866d22015-06-26 17:25:43 +0000756/// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
757/// i.e. monotonically increasing/decreasing.
758static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
759 ScalarEvolution *SE, const Loop *L) {
760 // FIXME: This should probably only return true for NUW.
761 if (AR->getNoWrapFlags(SCEV::NoWrapMask))
762 return true;
763
764 // Scalar evolution does not propagate the non-wrapping flags to values that
765 // are derived from a non-wrapping induction variable because non-wrapping
766 // could be flow-sensitive.
767 //
768 // Look through the potentially overflowing instruction to try to prove
769 // non-wrapping for the *specific* value of Ptr.
770
771 // The arithmetic implied by an inbounds GEP can't overflow.
772 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
773 if (!GEP || !GEP->isInBounds())
774 return false;
775
776 // Make sure there is only one non-const index and analyze that.
777 Value *NonConstIndex = nullptr;
778 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
779 if (!isa<ConstantInt>(*Index)) {
780 if (NonConstIndex)
781 return false;
782 NonConstIndex = *Index;
783 }
784 if (!NonConstIndex)
785 // The recurrence is on the pointer, ignore for now.
786 return false;
787
788 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
789 // AddRec using a NSW operation.
790 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
791 if (OBO->hasNoSignedWrap() &&
792 // Assume constant for other the operand so that the AddRec can be
793 // easily found.
794 isa<ConstantInt>(OBO->getOperand(1))) {
795 auto *OpScev = SE->getSCEV(OBO->getOperand(0));
796
797 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
798 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
799 }
800
801 return false;
802}
803
Adam Nemet04563272015-02-01 16:56:15 +0000804/// \brief Check whether the access through \p Ptr has a constant stride.
Hao Liu32c05392015-06-08 06:39:56 +0000805int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
806 const ValueToValueMap &StridesMap) {
Craig Toppere3dcce92015-08-01 22:20:21 +0000807 Type *Ty = Ptr->getType();
Adam Nemet04563272015-02-01 16:56:15 +0000808 assert(Ty->isPointerTy() && "Unexpected non-ptr");
809
810 // Make sure that the pointer does not point to aggregate types.
Craig Toppere3dcce92015-08-01 22:20:21 +0000811 auto *PtrTy = cast<PointerType>(Ty);
Adam Nemet04563272015-02-01 16:56:15 +0000812 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000813 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
814 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000815 return 0;
816 }
817
818 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
819
820 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
821 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000822 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000823 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000824 return 0;
825 }
826
827 // The accesss function must stride over the innermost loop.
828 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000829 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000830 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000831 }
832
833 // The address calculation must not wrap. Otherwise, a dependence could be
834 // inverted.
835 // An inbounds getelementptr that is a AddRec with a unit stride
836 // cannot wrap per definition. The unit stride requirement is checked later.
837 // An getelementptr without an inbounds attribute and unit stride would have
838 // to access the pointer value "0" which is undefined behavior in address
839 // space 0, therefore we can also vectorize this case.
840 bool IsInBoundsGEP = isInBoundsGep(Ptr);
Adam Nemetc4866d22015-06-26 17:25:43 +0000841 bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp);
Adam Nemet04563272015-02-01 16:56:15 +0000842 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
843 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000844 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000845 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000846 return 0;
847 }
848
849 // Check the step is constant.
850 const SCEV *Step = AR->getStepRecurrence(*SE);
851
Adam Nemet943befe2015-07-09 00:03:22 +0000852 // Calculate the pointer stride and check if it is constant.
Adam Nemet04563272015-02-01 16:56:15 +0000853 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
854 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000855 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000856 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000857 return 0;
858 }
859
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000860 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
861 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000862 const APInt &APStepVal = C->getValue()->getValue();
863
864 // Huge step value - give up.
865 if (APStepVal.getBitWidth() > 64)
866 return 0;
867
868 int64_t StepVal = APStepVal.getSExtValue();
869
870 // Strided access.
871 int64_t Stride = StepVal / Size;
872 int64_t Rem = StepVal % Size;
873 if (Rem)
874 return 0;
875
876 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
877 // know we can't "wrap around the address space". In case of address space
878 // zero we know that this won't happen without triggering undefined behavior.
879 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
880 Stride != 1 && Stride != -1)
881 return 0;
882
883 return Stride;
884}
885
Adam Nemet9c926572015-03-10 17:40:37 +0000886bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
887 switch (Type) {
888 case NoDep:
889 case Forward:
890 case BackwardVectorizable:
891 return true;
892
893 case Unknown:
894 case ForwardButPreventsForwarding:
895 case Backward:
896 case BackwardVectorizableButPreventsForwarding:
897 return false;
898 }
David Majnemerd388e932015-03-10 20:23:29 +0000899 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000900}
901
902bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
903 switch (Type) {
904 case NoDep:
905 case Forward:
906 return false;
907
908 case BackwardVectorizable:
909 case Unknown:
910 case ForwardButPreventsForwarding:
911 case Backward:
912 case BackwardVectorizableButPreventsForwarding:
913 return true;
914 }
David Majnemerd388e932015-03-10 20:23:29 +0000915 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000916}
917
918bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
919 switch (Type) {
920 case NoDep:
921 case Forward:
922 case ForwardButPreventsForwarding:
923 return false;
924
925 case Unknown:
926 case BackwardVectorizable:
927 case Backward:
928 case BackwardVectorizableButPreventsForwarding:
929 return true;
930 }
David Majnemerd388e932015-03-10 20:23:29 +0000931 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000932}
933
Adam Nemet04563272015-02-01 16:56:15 +0000934bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
935 unsigned TypeByteSize) {
936 // If loads occur at a distance that is not a multiple of a feasible vector
937 // factor store-load forwarding does not take place.
938 // Positive dependences might cause troubles because vectorizing them might
939 // prevent store-load forwarding making vectorized code run a lot slower.
940 // a[i] = a[i-3] ^ a[i-8];
941 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
942 // hence on your typical architecture store-load forwarding does not take
943 // place. Vectorizing in such cases does not make sense.
944 // Store-load forwarding distance.
945 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
946 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000947 unsigned MaxVFWithoutSLForwardIssues =
948 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000949 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000950 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
951
952 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
953 vf *= 2) {
954 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
955 MaxVFWithoutSLForwardIssues = (vf >>=1);
956 break;
957 }
958 }
959
Adam Nemet04d41632015-02-19 19:14:34 +0000960 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000961 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000962 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000963 return true;
964 }
965
966 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000967 MaxVFWithoutSLForwardIssues !=
968 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000969 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
970 return false;
971}
972
Hao Liu751004a2015-06-08 04:48:37 +0000973/// \brief Check the dependence for two accesses with the same stride \p Stride.
974/// \p Distance is the positive distance and \p TypeByteSize is type size in
975/// bytes.
976///
977/// \returns true if they are independent.
978static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
979 unsigned TypeByteSize) {
980 assert(Stride > 1 && "The stride must be greater than 1");
981 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
982 assert(Distance > 0 && "The distance must be non-zero");
983
984 // Skip if the distance is not multiple of type byte size.
985 if (Distance % TypeByteSize)
986 return false;
987
988 unsigned ScaledDist = Distance / TypeByteSize;
989
990 // No dependence if the scaled distance is not multiple of the stride.
991 // E.g.
992 // for (i = 0; i < 1024 ; i += 4)
993 // A[i+2] = A[i] + 1;
994 //
995 // Two accesses in memory (scaled distance is 2, stride is 4):
996 // | A[0] | | | | A[4] | | | |
997 // | | | A[2] | | | | A[6] | |
998 //
999 // E.g.
1000 // for (i = 0; i < 1024 ; i += 3)
1001 // A[i+4] = A[i] + 1;
1002 //
1003 // Two accesses in memory (scaled distance is 4, stride is 3):
1004 // | A[0] | | | A[3] | | | A[6] | | |
1005 // | | | | | A[4] | | | A[7] | |
1006 return ScaledDist % Stride;
1007}
1008
Adam Nemet9c926572015-03-10 17:40:37 +00001009MemoryDepChecker::Dependence::DepType
1010MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1011 const MemAccessInfo &B, unsigned BIdx,
1012 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001013 assert (AIdx < BIdx && "Must pass arguments in program order");
1014
1015 Value *APtr = A.getPointer();
1016 Value *BPtr = B.getPointer();
1017 bool AIsWrite = A.getInt();
1018 bool BIsWrite = B.getInt();
1019
1020 // Two reads are independent.
1021 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +00001022 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +00001023
1024 // We cannot check pointers in different address spaces.
1025 if (APtr->getType()->getPointerAddressSpace() !=
1026 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +00001027 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001028
1029 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
1030 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
1031
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001032 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
1033 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +00001034
1035 const SCEV *Src = AScev;
1036 const SCEV *Sink = BScev;
1037
1038 // If the induction step is negative we have to invert source and sink of the
1039 // dependence.
1040 if (StrideAPtr < 0) {
1041 //Src = BScev;
1042 //Sink = AScev;
1043 std::swap(APtr, BPtr);
1044 std::swap(Src, Sink);
1045 std::swap(AIsWrite, BIsWrite);
1046 std::swap(AIdx, BIdx);
1047 std::swap(StrideAPtr, StrideBPtr);
1048 }
1049
1050 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
1051
Adam Nemet339f42b2015-02-19 19:15:07 +00001052 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +00001053 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +00001054 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +00001055 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +00001056
Adam Nemet943befe2015-07-09 00:03:22 +00001057 // Need accesses with constant stride. We don't want to vectorize
Adam Nemet04563272015-02-01 16:56:15 +00001058 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1059 // the address space.
1060 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
Adam Nemet943befe2015-07-09 00:03:22 +00001061 DEBUG(dbgs() << "Pointer access with non-constant stride\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001062 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001063 }
1064
1065 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1066 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001067 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +00001068 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +00001069 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001070 }
1071
1072 Type *ATy = APtr->getType()->getPointerElementType();
1073 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001074 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1075 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +00001076
1077 // Negative distances are not plausible dependencies.
1078 const APInt &Val = C->getValue()->getValue();
1079 if (Val.isNegative()) {
1080 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1081 if (IsTrueDataDependence &&
1082 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1083 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +00001084 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001085
Adam Nemet339f42b2015-02-19 19:15:07 +00001086 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001087 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +00001088 }
1089
1090 // Write to the same location with the same size.
1091 // Could be improved to assert type sizes are the same (i32 == float, etc).
1092 if (Val == 0) {
1093 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +00001094 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +00001095 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001096 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001097 }
1098
1099 assert(Val.isStrictlyPositive() && "Expect a positive value");
1100
Adam Nemet04563272015-02-01 16:56:15 +00001101 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +00001102 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +00001103 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001104 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001105 }
1106
1107 unsigned Distance = (unsigned) Val.getZExtValue();
1108
Hao Liu751004a2015-06-08 04:48:37 +00001109 unsigned Stride = std::abs(StrideAPtr);
1110 if (Stride > 1 &&
Adam Nemet0131a562015-07-08 18:47:38 +00001111 areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
1112 DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
Hao Liu751004a2015-06-08 04:48:37 +00001113 return Dependence::NoDep;
Adam Nemet0131a562015-07-08 18:47:38 +00001114 }
Hao Liu751004a2015-06-08 04:48:37 +00001115
Adam Nemet04563272015-02-01 16:56:15 +00001116 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +00001117 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1118 VectorizerParams::VectorizationFactor : 1);
1119 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1120 VectorizerParams::VectorizationInterleave : 1);
Hao Liu751004a2015-06-08 04:48:37 +00001121 // The minimum number of iterations for a vectorized/unrolled version.
1122 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
Adam Nemet04563272015-02-01 16:56:15 +00001123
Hao Liu751004a2015-06-08 04:48:37 +00001124 // It's not vectorizable if the distance is smaller than the minimum distance
1125 // needed for a vectroized/unrolled version. Vectorizing one iteration in
1126 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1127 // TypeByteSize (No need to plus the last gap distance).
1128 //
1129 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1130 // foo(int *A) {
1131 // int *B = (int *)((char *)A + 14);
1132 // for (i = 0 ; i < 1024 ; i += 2)
1133 // B[i] = A[i] + 1;
1134 // }
1135 //
1136 // Two accesses in memory (stride is 2):
1137 // | A[0] | | A[2] | | A[4] | | A[6] | |
1138 // | B[0] | | B[2] | | B[4] |
1139 //
1140 // Distance needs for vectorizing iterations except the last iteration:
1141 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1142 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1143 //
1144 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1145 // 12, which is less than distance.
1146 //
1147 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1148 // the minimum distance needed is 28, which is greater than distance. It is
1149 // not safe to do vectorization.
1150 unsigned MinDistanceNeeded =
1151 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1152 if (MinDistanceNeeded > Distance) {
1153 DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1154 << '\n');
1155 return Dependence::Backward;
1156 }
1157
1158 // Unsafe if the minimum distance needed is greater than max safe distance.
1159 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1160 DEBUG(dbgs() << "LAA: Failure because it needs at least "
1161 << MinDistanceNeeded << " size in bytes");
Adam Nemet9c926572015-03-10 17:40:37 +00001162 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +00001163 }
1164
Adam Nemet9cc0c392015-02-26 17:58:48 +00001165 // Positive distance bigger than max vectorization factor.
Hao Liu751004a2015-06-08 04:48:37 +00001166 // FIXME: Should use max factor instead of max distance in bytes, which could
1167 // not handle different types.
1168 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1169 // void foo (int *A, char *B) {
1170 // for (unsigned i = 0; i < 1024; i++) {
1171 // A[i+2] = A[i] + 1;
1172 // B[i+2] = B[i] + 1;
1173 // }
1174 // }
1175 //
1176 // This case is currently unsafe according to the max safe distance. If we
1177 // analyze the two accesses on array B, the max safe dependence distance
1178 // is 2. Then we analyze the accesses on array A, the minimum distance needed
1179 // is 8, which is less than 2 and forbidden vectorization, But actually
1180 // both A and B could be vectorized by 2 iterations.
1181 MaxSafeDepDistBytes =
1182 Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
Adam Nemet04563272015-02-01 16:56:15 +00001183
1184 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1185 if (IsTrueDataDependence &&
1186 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +00001187 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001188
Hao Liu751004a2015-06-08 04:48:37 +00001189 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1190 << " with max VF = "
1191 << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
Adam Nemet04563272015-02-01 16:56:15 +00001192
Adam Nemet9c926572015-03-10 17:40:37 +00001193 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +00001194}
1195
Adam Nemetdee666b2015-03-10 17:40:34 +00001196bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +00001197 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001198 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001199
1200 MaxSafeDepDistBytes = -1U;
1201 while (!CheckDeps.empty()) {
1202 MemAccessInfo CurAccess = *CheckDeps.begin();
1203
1204 // Get the relevant memory access set.
1205 EquivalenceClasses<MemAccessInfo>::iterator I =
1206 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1207
1208 // Check accesses within this set.
1209 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
1210 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
1211
1212 // Check every access pair.
1213 while (AI != AE) {
1214 CheckDeps.erase(*AI);
1215 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1216 while (OI != AE) {
1217 // Check every accessing instruction pair in program order.
1218 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1219 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1220 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1221 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +00001222 auto A = std::make_pair(&*AI, *I1);
1223 auto B = std::make_pair(&*OI, *I2);
1224
1225 assert(*I1 != *I2);
1226 if (*I1 > *I2)
1227 std::swap(A, B);
1228
1229 Dependence::DepType Type =
1230 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1231 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1232
1233 // Gather dependences unless we accumulated MaxInterestingDependence
1234 // dependences. In that case return as soon as we find the first
1235 // unsafe dependence. This puts a limit on this quadratic
1236 // algorithm.
1237 if (RecordInterestingDependences) {
1238 if (Dependence::isInterestingDependence(Type))
1239 InterestingDependences.push_back(
1240 Dependence(A.second, B.second, Type));
1241
1242 if (InterestingDependences.size() >= MaxInterestingDependence) {
1243 RecordInterestingDependences = false;
1244 InterestingDependences.clear();
1245 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1246 }
1247 }
1248 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +00001249 return false;
1250 }
1251 ++OI;
1252 }
1253 AI++;
1254 }
1255 }
Adam Nemet9c926572015-03-10 17:40:37 +00001256
1257 DEBUG(dbgs() << "Total Interesting Dependences: "
1258 << InterestingDependences.size() << "\n");
1259 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +00001260}
1261
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001262SmallVector<Instruction *, 4>
1263MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1264 MemAccessInfo Access(Ptr, isWrite);
1265 auto &IndexVector = Accesses.find(Access)->second;
1266
1267 SmallVector<Instruction *, 4> Insts;
1268 std::transform(IndexVector.begin(), IndexVector.end(),
1269 std::back_inserter(Insts),
1270 [&](unsigned Idx) { return this->InstMap[Idx]; });
1271 return Insts;
1272}
1273
Adam Nemet58913d62015-03-10 17:40:43 +00001274const char *MemoryDepChecker::Dependence::DepName[] = {
1275 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1276 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1277
1278void MemoryDepChecker::Dependence::print(
1279 raw_ostream &OS, unsigned Depth,
1280 const SmallVectorImpl<Instruction *> &Instrs) const {
1281 OS.indent(Depth) << DepName[Type] << ":\n";
1282 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1283 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1284}
1285
Adam Nemet929c38e2015-02-19 19:15:10 +00001286bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001287 // We need to have a loop header.
1288 DEBUG(dbgs() << "LAA: Found a loop: " <<
1289 TheLoop->getHeader()->getName() << '\n');
1290
Adam Nemet929c38e2015-02-19 19:15:10 +00001291 // We can only analyze innermost loops.
1292 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001293 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +00001294 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +00001295 return false;
1296 }
1297
1298 // We must have a single backedge.
1299 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001300 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001301 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001302 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001303 "loop control flow is not understood by analyzer");
1304 return false;
1305 }
1306
1307 // We must have a single exiting block.
1308 if (!TheLoop->getExitingBlock()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001309 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001310 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001311 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001312 "loop control flow is not understood by analyzer");
1313 return false;
1314 }
1315
1316 // We only handle bottom-tested loops, i.e. loop in which the condition is
1317 // checked at the end of each iteration. With that we can assume that all
1318 // instructions in the loop are executed the same number of times.
1319 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001320 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001321 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001322 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001323 "loop control flow is not understood by analyzer");
1324 return false;
1325 }
1326
Adam Nemet929c38e2015-02-19 19:15:10 +00001327 // ScalarEvolution needs to be able to find the exit count.
1328 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
1329 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001330 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001331 "could not determine number of loop iterations");
1332 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1333 return false;
1334 }
1335
1336 return true;
1337}
1338
Adam Nemet8bc61df2015-02-24 00:41:59 +00001339void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001340
1341 typedef SmallVector<Value*, 16> ValueVector;
1342 typedef SmallPtrSet<Value*, 16> ValueSet;
1343
1344 // Holds the Load and Store *instructions*.
1345 ValueVector Loads;
1346 ValueVector Stores;
1347
1348 // Holds all the different accesses in the loop.
1349 unsigned NumReads = 0;
1350 unsigned NumReadWrites = 0;
1351
Adam Nemet7cdebac2015-07-14 22:32:44 +00001352 PtrRtChecking.Pointers.clear();
1353 PtrRtChecking.Need = false;
Adam Nemet04563272015-02-01 16:56:15 +00001354
1355 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +00001356
1357 // For each block.
1358 for (Loop::block_iterator bb = TheLoop->block_begin(),
1359 be = TheLoop->block_end(); bb != be; ++bb) {
1360
1361 // Scan the BB and collect legal loads and stores.
1362 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1363 ++it) {
1364
1365 // If this is a load, save it. If this instruction can read from memory
1366 // but is not a load, then we quit. Notice that we don't handle function
1367 // calls that read or write.
1368 if (it->mayReadFromMemory()) {
1369 // Many math library functions read the rounding mode. We will only
1370 // vectorize a loop if it contains known function calls that don't set
1371 // the flag. Therefore, it is safe to ignore this read from memory.
1372 CallInst *Call = dyn_cast<CallInst>(it);
1373 if (Call && getIntrinsicIDForCall(Call, TLI))
1374 continue;
1375
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +00001376 // If the function has an explicit vectorized counterpart, we can safely
1377 // assume that it can be vectorized.
1378 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1379 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1380 continue;
1381
Adam Nemet04563272015-02-01 16:56:15 +00001382 LoadInst *Ld = dyn_cast<LoadInst>(it);
1383 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001384 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +00001385 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +00001386 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001387 CanVecMem = false;
1388 return;
Adam Nemet04563272015-02-01 16:56:15 +00001389 }
1390 NumLoads++;
1391 Loads.push_back(Ld);
1392 DepChecker.addAccess(Ld);
1393 continue;
1394 }
1395
1396 // Save 'store' instructions. Abort if other instructions write to memory.
1397 if (it->mayWriteToMemory()) {
1398 StoreInst *St = dyn_cast<StoreInst>(it);
1399 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001400 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001401 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001402 CanVecMem = false;
1403 return;
Adam Nemet04563272015-02-01 16:56:15 +00001404 }
1405 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001406 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001407 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001408 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001409 CanVecMem = false;
1410 return;
Adam Nemet04563272015-02-01 16:56:15 +00001411 }
1412 NumStores++;
1413 Stores.push_back(St);
1414 DepChecker.addAccess(St);
1415 }
1416 } // Next instr.
1417 } // Next block.
1418
1419 // Now we have two lists that hold the loads and the stores.
1420 // Next, we find the pointers that they use.
1421
1422 // Check if we see any stores. If there are no stores, then we don't
1423 // care if the pointers are *restrict*.
1424 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001425 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001426 CanVecMem = true;
1427 return;
Adam Nemet04563272015-02-01 16:56:15 +00001428 }
1429
Adam Nemetdee666b2015-03-10 17:40:34 +00001430 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001431 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Adam Nemete2b885c2015-04-23 20:09:20 +00001432 AA, LI, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001433
1434 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1435 // multiple times on the same object. If the ptr is accessed twice, once
1436 // for read and once for write, it will only appear once (on the write
1437 // list). This is okay, since we are going to check for conflicts between
1438 // writes and between reads and writes, but not between reads and reads.
1439 ValueSet Seen;
1440
1441 ValueVector::iterator I, IE;
1442 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1443 StoreInst *ST = cast<StoreInst>(*I);
1444 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001445 // Check for store to loop invariant address.
1446 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001447 // If we did *not* see this pointer before, insert it to the read-write
1448 // list. At this phase it is only a 'write' list.
1449 if (Seen.insert(Ptr).second) {
1450 ++NumReadWrites;
1451
Chandler Carruthac80dc72015-06-17 07:18:54 +00001452 MemoryLocation Loc = MemoryLocation::get(ST);
Adam Nemet04563272015-02-01 16:56:15 +00001453 // The TBAA metadata could have a control dependency on the predication
1454 // condition, so we cannot rely on it when determining whether or not we
1455 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001456 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001457 Loc.AATags.TBAA = nullptr;
1458
1459 Accesses.addStore(Loc);
1460 }
1461 }
1462
1463 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001464 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001465 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001466 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001467 CanVecMem = true;
1468 return;
Adam Nemet04563272015-02-01 16:56:15 +00001469 }
1470
1471 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1472 LoadInst *LD = cast<LoadInst>(*I);
1473 Value* Ptr = LD->getPointerOperand();
1474 // If we did *not* see this pointer before, insert it to the
1475 // read list. If we *did* see it before, then it is already in
1476 // the read-write list. This allows us to vectorize expressions
1477 // such as A[i] += x; Because the address of A[i] is a read-write
1478 // pointer. This only works if the index of A[i] is consecutive.
1479 // If the address of i is unknown (for example A[B[i]]) then we may
1480 // read a few words, modify, and write a few words, and some of the
1481 // words may be written to the same address.
1482 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001483 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001484 ++NumReads;
1485 IsReadOnlyPtr = true;
1486 }
1487
Chandler Carruthac80dc72015-06-17 07:18:54 +00001488 MemoryLocation Loc = MemoryLocation::get(LD);
Adam Nemet04563272015-02-01 16:56:15 +00001489 // The TBAA metadata could have a control dependency on the predication
1490 // condition, so we cannot rely on it when determining whether or not we
1491 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001492 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001493 Loc.AATags.TBAA = nullptr;
1494
1495 Accesses.addLoad(Loc, IsReadOnlyPtr);
1496 }
1497
1498 // If we write (or read-write) to a single destination and there are no
1499 // other reads in this loop then is it safe to vectorize.
1500 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001501 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001502 CanVecMem = true;
1503 return;
Adam Nemet04563272015-02-01 16:56:15 +00001504 }
1505
1506 // Build dependence sets and check whether we need a runtime pointer bounds
1507 // check.
1508 Accesses.buildDependenceSets();
Adam Nemet04563272015-02-01 16:56:15 +00001509
1510 // Find pointers with computable bounds. We are going to use this information
1511 // to place a runtime bound check.
Adam Nemetee614742015-07-09 22:17:38 +00001512 bool CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001513 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides);
Adam Nemetee614742015-07-09 22:17:38 +00001514 if (!CanDoRTIfNeeded) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001515 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemetee614742015-07-09 22:17:38 +00001516 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1517 << "the array bounds.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001518 CanVecMem = false;
1519 return;
Adam Nemet04563272015-02-01 16:56:15 +00001520 }
1521
Adam Nemetee614742015-07-09 22:17:38 +00001522 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001523
Adam Nemet436018c2015-02-19 19:15:00 +00001524 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001525 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001526 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001527 CanVecMem = DepChecker.areDepsSafe(
1528 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1529 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1530
1531 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001532 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001533
1534 // Clear the dependency checks. We assume they are not needed.
Adam Nemetdf3dc5b2015-05-18 15:37:03 +00001535 Accesses.resetDepChecks(DepChecker);
Adam Nemet04563272015-02-01 16:56:15 +00001536
Adam Nemet7cdebac2015-07-14 22:32:44 +00001537 PtrRtChecking.reset();
1538 PtrRtChecking.Need = true;
Adam Nemet04563272015-02-01 16:56:15 +00001539
Adam Nemetee614742015-07-09 22:17:38 +00001540 CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001541 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
Silviu Baranga98a13712015-06-08 10:27:06 +00001542
Adam Nemet949e91a2015-03-10 19:12:41 +00001543 // Check that we found the bounds for the pointer.
Adam Nemetee614742015-07-09 22:17:38 +00001544 if (!CanDoRTIfNeeded) {
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001545 emitAnalysis(LoopAccessReport()
1546 << "cannot check memory dependencies at runtime");
1547 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001548 CanVecMem = false;
1549 return;
1550 }
1551
Adam Nemet04563272015-02-01 16:56:15 +00001552 CanVecMem = true;
1553 }
1554 }
1555
Adam Nemet4bb90a72015-03-10 21:47:39 +00001556 if (CanVecMem)
1557 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
Adam Nemet7cdebac2015-07-14 22:32:44 +00001558 << (PtrRtChecking.Need ? "" : " don't")
Adam Nemet0f67c6c2015-07-09 22:17:41 +00001559 << " need runtime memory checks.\n");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001560 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001561 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001562 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001563 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1564 }
Adam Nemet04563272015-02-01 16:56:15 +00001565}
1566
Adam Nemet01abb2c2015-02-18 03:43:19 +00001567bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1568 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001569 assert(TheLoop->contains(BB) && "Unknown block used");
1570
1571 // Blocks that do not dominate the latch need predication.
1572 BasicBlock* Latch = TheLoop->getLoopLatch();
1573 return !DT->dominates(BB, Latch);
1574}
1575
Adam Nemet2bd6e982015-02-19 19:15:15 +00001576void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001577 assert(!Report && "Multiple reports generated");
1578 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001579}
1580
Adam Nemet57ac7662015-02-19 19:15:21 +00001581bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001582 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1583}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001584
1585// FIXME: this function is currently a duplicate of the one in
1586// LoopVectorize.cpp.
1587static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1588 Instruction *Loc) {
1589 if (FirstInst)
1590 return FirstInst;
1591 if (Instruction *I = dyn_cast<Instruction>(V))
1592 return I->getParent() == Loc->getParent() ? I : nullptr;
1593 return nullptr;
1594}
1595
Adam Nemet4e533ef2015-08-21 23:19:57 +00001596/// \brief IR Values for the lower and upper bounds of a pointer evolution. We
1597/// need to use value-handles because SCEV expansion can invalidate previously
1598/// expanded values. Thus expansion of a pointer can invalidate the bounds for
1599/// a previous one.
Adam Nemet1da7df32015-07-26 05:32:14 +00001600struct PointerBounds {
Adam Nemet4e533ef2015-08-21 23:19:57 +00001601 TrackingVH<Value> Start;
1602 TrackingVH<Value> End;
Adam Nemet1da7df32015-07-26 05:32:14 +00001603};
Adam Nemet7206d7a2015-02-06 18:31:04 +00001604
Adam Nemet1da7df32015-07-26 05:32:14 +00001605/// \brief Expand code for the lower and upper bound of the pointer group \p CG
1606/// in \p TheLoop. \return the values for the bounds.
1607static PointerBounds
1608expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
1609 Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
1610 const RuntimePointerChecking &PtrRtChecking) {
1611 Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
1612 const SCEV *Sc = SE->getSCEV(Ptr);
1613
1614 if (SE->isLoopInvariant(Sc, TheLoop)) {
1615 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1616 << "\n");
1617 return {Ptr, Ptr};
1618 } else {
1619 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1620 LLVMContext &Ctx = Loc->getContext();
1621
1622 // Use this type for pointer arithmetic.
1623 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1624 Value *Start = nullptr, *End = nullptr;
1625
1626 DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1627 Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
1628 End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1629 DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
1630 return {Start, End};
1631 }
1632}
1633
1634/// \brief Turns a collection of checks into a collection of expanded upper and
1635/// lower bounds for both pointers in the check.
1636static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
1637 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
1638 Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
1639 const RuntimePointerChecking &PtrRtChecking) {
1640 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1641
1642 // Here we're relying on the SCEV Expander's cache to only emit code for the
1643 // same bounds once.
1644 std::transform(
1645 PointerChecks.begin(), PointerChecks.end(),
1646 std::back_inserter(ChecksWithBounds),
1647 [&](const RuntimePointerChecking::PointerCheck &Check) {
NAKAMURA Takumi94abbbd2015-07-27 01:35:30 +00001648 PointerBounds
1649 First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
1650 Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
1651 return std::make_pair(First, Second);
Adam Nemet1da7df32015-07-26 05:32:14 +00001652 });
1653
1654 return ChecksWithBounds;
1655}
1656
Adam Nemet5b0a4792015-08-11 00:09:37 +00001657std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
Adam Nemet1da7df32015-07-26 05:32:14 +00001658 Instruction *Loc,
1659 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
1660 const {
1661
1662 SCEVExpander Exp(*SE, DL, "induction");
1663 auto ExpandedChecks =
1664 expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, PtrRtChecking);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001665
1666 LLVMContext &Ctx = Loc->getContext();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001667 Instruction *FirstInst = nullptr;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001668 IRBuilder<> ChkBuilder(Loc);
1669 // Our instructions might fold to a constant.
1670 Value *MemoryRuntimeCheck = nullptr;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001671
Adam Nemet1da7df32015-07-26 05:32:14 +00001672 for (const auto &Check : ExpandedChecks) {
1673 const PointerBounds &A = Check.first, &B = Check.second;
Adam Nemetcdb791c2015-08-19 17:24:36 +00001674 // Check if two pointers (A and B) conflict where conflict is computed as:
1675 // start(A) <= end(B) && start(B) <= end(A)
Adam Nemet1da7df32015-07-26 05:32:14 +00001676 unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1677 unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001678
Adam Nemet1da7df32015-07-26 05:32:14 +00001679 assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
1680 (AS1 == A.End->getType()->getPointerAddressSpace()) &&
1681 "Trying to bounds check pointers with different address spaces");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001682
Adam Nemet1da7df32015-07-26 05:32:14 +00001683 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1684 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001685
Adam Nemet1da7df32015-07-26 05:32:14 +00001686 Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
1687 Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
1688 Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
1689 Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001690
Adam Nemet1da7df32015-07-26 05:32:14 +00001691 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1692 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1693 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1694 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1695 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1696 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1697 if (MemoryRuntimeCheck) {
1698 IsConflict =
1699 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001700 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001701 }
Adam Nemet1da7df32015-07-26 05:32:14 +00001702 MemoryRuntimeCheck = IsConflict;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001703 }
1704
Adam Nemet90fec842015-04-02 17:51:57 +00001705 if (!MemoryRuntimeCheck)
1706 return std::make_pair(nullptr, nullptr);
1707
Adam Nemet7206d7a2015-02-06 18:31:04 +00001708 // We have to do this trickery because the IRBuilder might fold the check to a
1709 // constant expression in which case there is no Instruction anchored in a
1710 // the block.
1711 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1712 ConstantInt::getTrue(Ctx));
1713 ChkBuilder.Insert(Check, "memcheck.conflict");
1714 FirstInst = getFirstInst(FirstInst, Check, Loc);
1715 return std::make_pair(FirstInst, Check);
1716}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001717
Adam Nemet5b0a4792015-08-11 00:09:37 +00001718std::pair<Instruction *, Instruction *>
1719LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
Adam Nemet1da7df32015-07-26 05:32:14 +00001720 if (!PtrRtChecking.Need)
1721 return std::make_pair(nullptr, nullptr);
1722
Adam Nemet5b0a4792015-08-11 00:09:37 +00001723 return addRuntimeChecks(Loc, PtrRtChecking.getChecks());
Adam Nemet1da7df32015-07-26 05:32:14 +00001724}
1725
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001726LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001727 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001728 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemete2b885c2015-04-23 20:09:20 +00001729 DominatorTree *DT, LoopInfo *LI,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001730 const ValueToValueMap &Strides)
Adam Nemet7cdebac2015-07-14 22:32:44 +00001731 : PtrRtChecking(SE), DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL),
1732 TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001733 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1734 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001735 if (canAnalyzeLoop())
1736 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001737}
1738
Adam Nemete91cc6e2015-02-19 19:15:19 +00001739void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1740 if (CanVecMem) {
Adam Nemet7cdebac2015-07-14 22:32:44 +00001741 if (PtrRtChecking.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001742 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001743 else
1744 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001745 }
1746
1747 if (Report)
1748 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1749
Adam Nemet58913d62015-03-10 17:40:43 +00001750 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1751 OS.indent(Depth) << "Interesting Dependences:\n";
1752 for (auto &Dep : *InterestingDependences) {
1753 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1754 OS << "\n";
1755 }
1756 } else
1757 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001758
1759 // List the pair of accesses need run-time checks to prove independence.
Adam Nemet7cdebac2015-07-14 22:32:44 +00001760 PtrRtChecking.print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00001761 OS << "\n";
Adam Nemetc3384322015-05-18 15:36:57 +00001762
1763 OS.indent(Depth) << "Store to invariant address was "
1764 << (StoreToLoopInvariantAddress ? "" : "not ")
1765 << "found in loop.\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001766}
1767
Adam Nemet8bc61df2015-02-24 00:41:59 +00001768const LoopAccessInfo &
1769LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001770 auto &LAI = LoopAccessInfoMap[L];
1771
1772#ifndef NDEBUG
1773 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1774 "Symbolic strides changed for loop");
1775#endif
1776
1777 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001778 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemete2b885c2015-04-23 20:09:20 +00001779 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
1780 Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001781#ifndef NDEBUG
1782 LAI->NumSymbolicStrides = Strides.size();
1783#endif
1784 }
1785 return *LAI.get();
1786}
1787
Adam Nemete91cc6e2015-02-19 19:15:19 +00001788void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1789 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1790
Adam Nemete91cc6e2015-02-19 19:15:19 +00001791 ValueToValueMap NoSymbolicStrides;
1792
1793 for (Loop *TopLevelLoop : *LI)
1794 for (Loop *L : depth_first(TopLevelLoop)) {
1795 OS.indent(2) << L->getHeader()->getName() << ":\n";
1796 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1797 LAI.print(OS, 4);
1798 }
1799}
1800
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001801bool LoopAccessAnalysis::runOnFunction(Function &F) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001802 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001803 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1804 TLI = TLIP ? &TLIP->getTLI() : nullptr;
Chandler Carruth7b560d42015-09-09 17:55:00 +00001805 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001806 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete2b885c2015-04-23 20:09:20 +00001807 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001808
1809 return false;
1810}
1811
1812void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001813 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00001814 AU.addRequired<AAResultsWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001815 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001816 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001817
1818 AU.setPreservesAll();
1819}
1820
1821char LoopAccessAnalysis::ID = 0;
1822static const char laa_name[] = "Loop Access Analysis";
1823#define LAA_NAME "loop-accesses"
1824
1825INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001826INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001827INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001828INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001829INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001830INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1831
1832namespace llvm {
1833 Pass *createLAAPass() {
1834 return new LoopAccessAnalysis();
1835 }
1836}