blob: 25025db0527ad0dc1deca5261a9588c2c3723007 [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,
Silviu Barangae3c05342015-11-02 14:41:02 +000092 SCEVUnionPredicate &Preds,
Adam Nemet04563272015-02-01 16:56:15 +000093 Value *Ptr, Value *OrigPtr) {
Adam Nemet04563272015-02-01 16:56:15 +000094 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
Silviu Barangae3c05342015-11-02 14:41:02 +0000111 const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal));
112 const auto *CT =
113 static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType()));
114
115 Preds.add(SE->getEqualPredicate(U, CT));
116
117 const SCEV *ByOne = SE->rewriteUsingPredicate(OrigSCEV, Preds);
Adam Nemet339f42b2015-02-19 19:15:07 +0000118 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
Adam Nemet04563272015-02-01 16:56:15 +0000119 << "\n");
120 return ByOne;
121 }
122
123 // Otherwise, just return the SCEV of the original pointer.
Silviu Barangae3c05342015-11-02 14:41:02 +0000124 return OrigSCEV;
Adam Nemet04563272015-02-01 16:56:15 +0000125}
126
Adam Nemet7cdebac2015-07-14 22:32:44 +0000127void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
128 unsigned DepSetId, unsigned ASId,
Silviu Barangae3c05342015-11-02 14:41:02 +0000129 const ValueToValueMap &Strides,
130 SCEVUnionPredicate &Preds) {
Adam Nemet04563272015-02-01 16:56:15 +0000131 // Get the stride replaced scev.
Silviu Barangae3c05342015-11-02 14:41:02 +0000132 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Preds, Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000133 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
134 assert(AR && "Invalid addrec expression");
135 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000136
137 const SCEV *ScStart = AR->getStart();
Adam Nemet04563272015-02-01 16:56:15 +0000138 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
Silviu Baranga0e5804a2015-07-16 14:02:58 +0000139 const SCEV *Step = AR->getStepRecurrence(*SE);
140
141 // For expressions with negative step, the upper bound is ScStart and the
142 // lower bound is ScEnd.
143 if (const SCEVConstant *CStep = dyn_cast<const SCEVConstant>(Step)) {
144 if (CStep->getValue()->isNegative())
145 std::swap(ScStart, ScEnd);
146 } else {
147 // Fallback case: the step is not constant, but the we can still
148 // get the upper and lower bounds of the interval by using min/max
149 // expressions.
150 ScStart = SE->getUMinExpr(ScStart, ScEnd);
151 ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd);
152 }
153
154 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000155}
156
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000157SmallVector<RuntimePointerChecking::PointerCheck, 4>
Adam Nemet38530882015-08-09 20:06:06 +0000158RuntimePointerChecking::generateChecks() const {
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000159 SmallVector<PointerCheck, 4> Checks;
160
Adam Nemet7c52e052015-07-27 19:38:50 +0000161 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
162 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) {
163 const RuntimePointerChecking::CheckingPtrGroup &CGI = CheckingGroups[I];
164 const RuntimePointerChecking::CheckingPtrGroup &CGJ = CheckingGroups[J];
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000165
Adam Nemet38530882015-08-09 20:06:06 +0000166 if (needsChecking(CGI, CGJ))
Adam Nemetbbe1f1d2015-07-27 19:38:48 +0000167 Checks.push_back(std::make_pair(&CGI, &CGJ));
168 }
169 }
170 return Checks;
171}
172
Adam Nemet15840392015-08-07 22:44:15 +0000173void RuntimePointerChecking::generateChecks(
174 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
175 assert(Checks.empty() && "Checks is not empty");
176 groupChecks(DepCands, UseDependencies);
177 Checks = generateChecks();
178}
179
Adam Nemet651a5a22015-08-09 20:06:08 +0000180bool RuntimePointerChecking::needsChecking(const CheckingPtrGroup &M,
181 const CheckingPtrGroup &N) const {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000182 for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
183 for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
Adam Nemet651a5a22015-08-09 20:06:08 +0000184 if (needsChecking(M.Members[I], N.Members[J]))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000185 return true;
186 return false;
187}
188
189/// Compare \p I and \p J and return the minimum.
190/// Return nullptr in case we couldn't find an answer.
191static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
192 ScalarEvolution *SE) {
193 const SCEV *Diff = SE->getMinusSCEV(J, I);
194 const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
195
196 if (!C)
197 return nullptr;
198 if (C->getValue()->isNegative())
199 return J;
200 return I;
201}
202
Adam Nemet7cdebac2015-07-14 22:32:44 +0000203bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000204 const SCEV *Start = RtCheck.Pointers[Index].Start;
205 const SCEV *End = RtCheck.Pointers[Index].End;
206
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000207 // Compare the starts and ends with the known minimum and maximum
208 // of this set. We need to know how we compare against the min/max
209 // of the set in order to be able to emit memchecks.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000210 const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000211 if (!Min0)
212 return false;
213
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000214 const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000215 if (!Min1)
216 return false;
217
218 // Update the low bound expression if we've found a new min value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000219 if (Min0 == Start)
220 Low = Start;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000221
222 // Update the high bound expression if we've found a new max value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000223 if (Min1 != End)
224 High = End;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000225
226 Members.push_back(Index);
227 return true;
228}
229
Adam Nemet7cdebac2015-07-14 22:32:44 +0000230void RuntimePointerChecking::groupChecks(
231 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000232 // We build the groups from dependency candidates equivalence classes
233 // because:
234 // - We know that pointers in the same equivalence class share
235 // the same underlying object and therefore there is a chance
236 // that we can compare pointers
237 // - We wouldn't be able to merge two pointers for which we need
238 // to emit a memcheck. The classes in DepCands are already
239 // conveniently built such that no two pointers in the same
240 // class need checking against each other.
241
242 // We use the following (greedy) algorithm to construct the groups
243 // For every pointer in the equivalence class:
244 // For each existing group:
245 // - if the difference between this pointer and the min/max bounds
246 // of the group is a constant, then make the pointer part of the
247 // group and update the min/max bounds of that group as required.
248
249 CheckingGroups.clear();
250
Silviu Baranga48250602015-07-28 13:44:08 +0000251 // If we need to check two pointers to the same underlying object
252 // with a non-constant difference, we shouldn't perform any pointer
253 // grouping with those pointers. This is because we can easily get
254 // into cases where the resulting check would return false, even when
255 // the accesses are safe.
256 //
257 // The following example shows this:
258 // for (i = 0; i < 1000; ++i)
259 // a[5000 + i * m] = a[i] + a[i + 9000]
260 //
261 // Here grouping gives a check of (5000, 5000 + 1000 * m) against
262 // (0, 10000) which is always false. However, if m is 1, there is no
263 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows
264 // us to perform an accurate check in this case.
265 //
266 // The above case requires that we have an UnknownDependence between
267 // accesses to the same underlying object. This cannot happen unless
268 // ShouldRetryWithRuntimeCheck is set, and therefore UseDependencies
269 // is also false. In this case we will use the fallback path and create
270 // separate checking groups for all pointers.
271
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000272 // If we don't have the dependency partitions, construct a new
Silviu Baranga48250602015-07-28 13:44:08 +0000273 // checking pointer group for each pointer. This is also required
274 // for correctness, because in this case we can have checking between
275 // pointers to the same underlying object.
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000276 if (!UseDependencies) {
277 for (unsigned I = 0; I < Pointers.size(); ++I)
278 CheckingGroups.push_back(CheckingPtrGroup(I, *this));
279 return;
280 }
281
282 unsigned TotalComparisons = 0;
283
284 DenseMap<Value *, unsigned> PositionMap;
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000285 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
286 PositionMap[Pointers[Index].PointerValue] = Index;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000287
Silviu Barangace3877f2015-07-09 15:18:25 +0000288 // We need to keep track of what pointers we've already seen so we
289 // don't process them twice.
290 SmallSet<unsigned, 2> Seen;
291
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000292 // Go through all equivalence classes, get the the "pointer check groups"
Silviu Barangace3877f2015-07-09 15:18:25 +0000293 // and add them to the overall solution. We use the order in which accesses
294 // appear in 'Pointers' to enforce determinism.
295 for (unsigned I = 0; I < Pointers.size(); ++I) {
296 // We've seen this pointer before, and therefore already processed
297 // its equivalence class.
298 if (Seen.count(I))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000299 continue;
300
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000301 MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
302 Pointers[I].IsWritePtr);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000303
Silviu Barangace3877f2015-07-09 15:18:25 +0000304 SmallVector<CheckingPtrGroup, 2> Groups;
305 auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
306
Silviu Barangaa647c302015-07-13 14:48:24 +0000307 // Because DepCands is constructed by visiting accesses in the order in
308 // which they appear in alias sets (which is deterministic) and the
309 // iteration order within an equivalence class member is only dependent on
310 // the order in which unions and insertions are performed on the
311 // equivalence class, the iteration order is deterministic.
Silviu Barangace3877f2015-07-09 15:18:25 +0000312 for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000313 MI != ME; ++MI) {
314 unsigned Pointer = PositionMap[MI->getPointer()];
315 bool Merged = false;
Silviu Barangace3877f2015-07-09 15:18:25 +0000316 // Mark this pointer as seen.
317 Seen.insert(Pointer);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000318
319 // Go through all the existing sets and see if we can find one
320 // which can include this pointer.
321 for (CheckingPtrGroup &Group : Groups) {
322 // Don't perform more than a certain amount of comparisons.
323 // This should limit the cost of grouping the pointers to something
324 // reasonable. If we do end up hitting this threshold, the algorithm
325 // will create separate groups for all remaining pointers.
326 if (TotalComparisons > MemoryCheckMergeThreshold)
327 break;
328
329 TotalComparisons++;
330
331 if (Group.addPointer(Pointer)) {
332 Merged = true;
333 break;
334 }
335 }
336
337 if (!Merged)
338 // We couldn't add this pointer to any existing set or the threshold
339 // for the number of comparisons has been reached. Create a new group
340 // to hold the current pointer.
341 Groups.push_back(CheckingPtrGroup(Pointer, *this));
342 }
343
344 // We've computed the grouped checks for this partition.
345 // Save the results and continue with the next one.
346 std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
347 }
Adam Nemet04563272015-02-01 16:56:15 +0000348}
349
Adam Nemet041e6de2015-07-16 02:48:05 +0000350bool RuntimePointerChecking::arePointersInSamePartition(
351 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
352 unsigned PtrIdx2) {
353 return (PtrToPartition[PtrIdx1] != -1 &&
354 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
355}
356
Adam Nemet651a5a22015-08-09 20:06:08 +0000357bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000358 const PointerInfo &PointerI = Pointers[I];
359 const PointerInfo &PointerJ = Pointers[J];
360
Adam Nemeta8945b72015-02-18 03:43:58 +0000361 // No need to check if two readonly pointers intersect.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000362 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
Adam Nemeta8945b72015-02-18 03:43:58 +0000363 return false;
364
365 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000366 if (PointerI.DependencySetId == PointerJ.DependencySetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000367 return false;
368
369 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000370 if (PointerI.AliasSetId != PointerJ.AliasSetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000371 return false;
372
373 return true;
374}
375
Adam Nemet54f0b832015-07-27 23:54:41 +0000376void RuntimePointerChecking::printChecks(
377 raw_ostream &OS, const SmallVectorImpl<PointerCheck> &Checks,
378 unsigned Depth) const {
379 unsigned N = 0;
380 for (const auto &Check : Checks) {
381 const auto &First = Check.first->Members, &Second = Check.second->Members;
382
383 OS.indent(Depth) << "Check " << N++ << ":\n";
384
385 OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n";
386 for (unsigned K = 0; K < First.size(); ++K)
387 OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n";
388
389 OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n";
390 for (unsigned K = 0; K < Second.size(); ++K)
391 OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n";
392 }
393}
394
Adam Nemet3a91e942015-08-07 19:44:48 +0000395void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000396
397 OS.indent(Depth) << "Run-time memory checks:\n";
Adam Nemet15840392015-08-07 22:44:15 +0000398 printChecks(OS, Checks, Depth);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000399
400 OS.indent(Depth) << "Grouped accesses:\n";
401 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
Adam Nemet54f0b832015-07-27 23:54:41 +0000402 const auto &CG = CheckingGroups[I];
403
404 OS.indent(Depth + 2) << "Group " << &CG << ":\n";
405 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High
406 << ")\n";
407 for (unsigned J = 0; J < CG.Members.size(); ++J) {
408 OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000409 << "\n";
410 }
411 }
Adam Nemete91cc6e2015-02-19 19:15:19 +0000412}
413
Adam Nemet04563272015-02-01 16:56:15 +0000414namespace {
415/// \brief Analyses memory accesses in a loop.
416///
417/// Checks whether run time pointer checks are needed and builds sets for data
418/// dependence checking.
419class AccessAnalysis {
420public:
421 /// \brief Read or write access location.
422 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
423 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
424
Adam Nemete2b885c2015-04-23 20:09:20 +0000425 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Silviu Barangae3c05342015-11-02 14:41:02 +0000426 MemoryDepChecker::DepCandidates &DA, SCEVUnionPredicate &Preds)
427 : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckAnalysisNeeded(false),
428 Preds(Preds) {}
Adam Nemet04563272015-02-01 16:56:15 +0000429
430 /// \brief Register a load and whether it is only read from.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000431 void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
Adam Nemet04563272015-02-01 16:56:15 +0000432 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000433 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000434 Accesses.insert(MemAccessInfo(Ptr, false));
435 if (IsReadOnly)
436 ReadOnlyPtr.insert(Ptr);
437 }
438
439 /// \brief Register a store.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000440 void addStore(MemoryLocation &Loc) {
Adam Nemet04563272015-02-01 16:56:15 +0000441 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000442 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000443 Accesses.insert(MemAccessInfo(Ptr, true));
444 }
445
446 /// \brief Check whether we can check the pointers at runtime for
Adam Nemetee614742015-07-09 22:17:38 +0000447 /// non-intersection.
448 ///
449 /// Returns true if we need no check or if we do and we can generate them
450 /// (i.e. the pointers have computable bounds).
Adam Nemet7cdebac2015-07-14 22:32:44 +0000451 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
452 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000453 bool ShouldCheckStride = false);
454
455 /// \brief Goes over all memory accesses, checks whether a RT check is needed
456 /// and builds sets of dependent accesses.
457 void buildDependenceSets() {
458 processMemAccesses();
459 }
460
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000461 /// \brief Initial processing of memory accesses determined that we need to
462 /// perform dependency checking.
463 ///
464 /// Note that this can later be cleared if we retry memcheck analysis without
465 /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
Adam Nemet04563272015-02-01 16:56:15 +0000466 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000467
468 /// We decided that no dependence analysis would be used. Reset the state.
469 void resetDepChecks(MemoryDepChecker &DepChecker) {
470 CheckDeps.clear();
471 DepChecker.clearInterestingDependences();
472 }
Adam Nemet04563272015-02-01 16:56:15 +0000473
474 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
475
476private:
477 typedef SetVector<MemAccessInfo> PtrAccessSet;
478
479 /// \brief Go over all memory access and check whether runtime pointer checks
Adam Nemetb41d2d32015-07-09 06:47:21 +0000480 /// are needed and build sets of dependency check candidates.
Adam Nemet04563272015-02-01 16:56:15 +0000481 void processMemAccesses();
482
483 /// Set of all accesses.
484 PtrAccessSet Accesses;
485
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000486 const DataLayout &DL;
487
Adam Nemet04563272015-02-01 16:56:15 +0000488 /// Set of accesses that need a further dependence check.
489 MemAccessInfoSet CheckDeps;
490
491 /// Set of pointers that are read only.
492 SmallPtrSet<Value*, 16> ReadOnlyPtr;
493
Adam Nemet04563272015-02-01 16:56:15 +0000494 /// An alias set tracker to partition the access set by underlying object and
495 //intrinsic property (such as TBAA metadata).
496 AliasSetTracker AST;
497
Adam Nemete2b885c2015-04-23 20:09:20 +0000498 LoopInfo *LI;
499
Adam Nemet04563272015-02-01 16:56:15 +0000500 /// Sets of potentially dependent accesses - members of one set share an
501 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
502 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000503 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000504
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000505 /// \brief Initial processing of memory accesses determined that we may need
506 /// to add memchecks. Perform the analysis to determine the necessary checks.
507 ///
508 /// Note that, this is different from isDependencyCheckNeeded. When we retry
509 /// memcheck analysis without dependency checking
510 /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
511 /// while this remains set if we have potentially dependent accesses.
512 bool IsRTCheckAnalysisNeeded;
Silviu Barangae3c05342015-11-02 14:41:02 +0000513
514 /// The SCEV predicate containing all the SCEV-related assumptions.
515 SCEVUnionPredicate &Preds;
Adam Nemet04563272015-02-01 16:56:15 +0000516};
517
518} // end anonymous namespace
519
520/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000521static bool hasComputableBounds(ScalarEvolution *SE,
Silviu Barangae3c05342015-11-02 14:41:02 +0000522 const ValueToValueMap &Strides, Value *Ptr,
523 Loop *L, SCEVUnionPredicate &Preds) {
524 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Preds, Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000525 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
526 if (!AR)
527 return false;
528
529 return AR->isAffine();
530}
531
Adam Nemet7cdebac2015-07-14 22:32:44 +0000532bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
533 ScalarEvolution *SE, Loop *TheLoop,
534 const ValueToValueMap &StridesMap,
535 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000536 // Find pointers with computable bounds. We are going to use this information
537 // to place a runtime bound check.
538 bool CanDoRT = true;
539
Adam Nemetee614742015-07-09 22:17:38 +0000540 bool NeedRTCheck = false;
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000541 if (!IsRTCheckAnalysisNeeded) return true;
Silviu Baranga98a13712015-06-08 10:27:06 +0000542
Adam Nemet04563272015-02-01 16:56:15 +0000543 bool IsDepCheckNeeded = isDependencyCheckNeeded();
Adam Nemet04563272015-02-01 16:56:15 +0000544
545 // We assign a consecutive id to access from different alias sets.
546 // Accesses between different groups doesn't need to be checked.
547 unsigned ASId = 1;
548 for (auto &AS : AST) {
Adam Nemet424edc62015-07-08 22:58:48 +0000549 int NumReadPtrChecks = 0;
550 int NumWritePtrChecks = 0;
551
Adam Nemet04563272015-02-01 16:56:15 +0000552 // We assign consecutive id to access from different dependence sets.
553 // Accesses within the same set don't need a runtime check.
554 unsigned RunningDepId = 1;
555 DenseMap<Value *, unsigned> DepSetId;
556
557 for (auto A : AS) {
558 Value *Ptr = A.getValue();
559 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
560 MemAccessInfo Access(Ptr, IsWrite);
561
Adam Nemet424edc62015-07-08 22:58:48 +0000562 if (IsWrite)
563 ++NumWritePtrChecks;
564 else
565 ++NumReadPtrChecks;
566
Silviu Barangae3c05342015-11-02 14:41:02 +0000567 if (hasComputableBounds(SE, StridesMap, Ptr, TheLoop, Preds) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000568 // When we run after a failing dependency check we have to make sure
569 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000570 (!ShouldCheckStride ||
Silviu Barangae3c05342015-11-02 14:41:02 +0000571 isStridedPtr(SE, Ptr, TheLoop, StridesMap, Preds) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000572 // The id of the dependence set.
573 unsigned DepId;
574
575 if (IsDepCheckNeeded) {
576 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
577 unsigned &LeaderId = DepSetId[Leader];
578 if (!LeaderId)
579 LeaderId = RunningDepId++;
580 DepId = LeaderId;
581 } else
582 // Each access has its own dependence set.
583 DepId = RunningDepId++;
584
Silviu Barangae3c05342015-11-02 14:41:02 +0000585 RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, Preds);
Adam Nemet04563272015-02-01 16:56:15 +0000586
Adam Nemet339f42b2015-02-19 19:15:07 +0000587 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000588 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000589 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000590 CanDoRT = false;
591 }
592 }
593
Adam Nemet424edc62015-07-08 22:58:48 +0000594 // If we have at least two writes or one write and a read then we need to
595 // check them. But there is no need to checks if there is only one
596 // dependence set for this alias set.
597 //
598 // Note that this function computes CanDoRT and NeedRTCheck independently.
599 // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
600 // for which we couldn't find the bounds but we don't actually need to emit
601 // any checks so it does not matter.
602 if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
603 NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
604 NumWritePtrChecks >= 1));
605
Adam Nemet04563272015-02-01 16:56:15 +0000606 ++ASId;
607 }
608
609 // If the pointers that we would use for the bounds comparison have different
610 // address spaces, assume the values aren't directly comparable, so we can't
611 // use them for the runtime check. We also have to assume they could
612 // overlap. In the future there should be metadata for whether address spaces
613 // are disjoint.
614 unsigned NumPointers = RtCheck.Pointers.size();
615 for (unsigned i = 0; i < NumPointers; ++i) {
616 for (unsigned j = i + 1; j < NumPointers; ++j) {
617 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000618 if (RtCheck.Pointers[i].DependencySetId ==
619 RtCheck.Pointers[j].DependencySetId)
Adam Nemet04563272015-02-01 16:56:15 +0000620 continue;
621 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000622 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
Adam Nemet04563272015-02-01 16:56:15 +0000623 continue;
624
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000625 Value *PtrI = RtCheck.Pointers[i].PointerValue;
626 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
Adam Nemet04563272015-02-01 16:56:15 +0000627
628 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
629 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
630 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000631 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000632 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000633 return false;
634 }
635 }
636 }
637
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000638 if (NeedRTCheck && CanDoRT)
Adam Nemet15840392015-08-07 22:44:15 +0000639 RtCheck.generateChecks(DepCands, IsDepCheckNeeded);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000640
Adam Nemet155e8742015-08-07 22:44:21 +0000641 DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks()
Adam Nemetee614742015-07-09 22:17:38 +0000642 << " pointer comparisons.\n");
643
644 RtCheck.Need = NeedRTCheck;
645
646 bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
647 if (!CanDoRTIfNeeded)
648 RtCheck.reset();
649 return CanDoRTIfNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000650}
651
652void AccessAnalysis::processMemAccesses() {
653 // We process the set twice: first we process read-write pointers, last we
654 // process read-only pointers. This allows us to skip dependence tests for
655 // read-only pointers.
656
Adam Nemet339f42b2015-02-19 19:15:07 +0000657 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000658 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000659 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000660 DEBUG({
661 for (auto A : Accesses)
662 dbgs() << "\t" << *A.getPointer() << " (" <<
663 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
664 "read-only" : "read")) << ")\n";
665 });
666
667 // The AliasSetTracker has nicely partitioned our pointers by metadata
668 // compatibility and potential for underlying-object overlap. As a result, we
669 // only need to check for potential pointer dependencies within each alias
670 // set.
671 for (auto &AS : AST) {
672 // Note that both the alias-set tracker and the alias sets themselves used
673 // linked lists internally and so the iteration order here is deterministic
674 // (matching the original instruction order within each set).
675
676 bool SetHasWrite = false;
677
678 // Map of pointers to last access encountered.
679 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
680 UnderlyingObjToAccessMap ObjToLastAccess;
681
682 // Set of access to check after all writes have been processed.
683 PtrAccessSet DeferredAccesses;
684
685 // Iterate over each alias set twice, once to process read/write pointers,
686 // and then to process read-only pointers.
687 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
688 bool UseDeferred = SetIteration > 0;
689 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
690
691 for (auto AV : AS) {
692 Value *Ptr = AV.getValue();
693
694 // For a single memory access in AliasSetTracker, Accesses may contain
695 // both read and write, and they both need to be handled for CheckDeps.
696 for (auto AC : S) {
697 if (AC.getPointer() != Ptr)
698 continue;
699
700 bool IsWrite = AC.getInt();
701
702 // If we're using the deferred access set, then it contains only
703 // reads.
704 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
705 if (UseDeferred && !IsReadOnlyPtr)
706 continue;
707 // Otherwise, the pointer must be in the PtrAccessSet, either as a
708 // read or a write.
709 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
710 S.count(MemAccessInfo(Ptr, false))) &&
711 "Alias-set pointer not in the access set?");
712
713 MemAccessInfo Access(Ptr, IsWrite);
714 DepCands.insert(Access);
715
716 // Memorize read-only pointers for later processing and skip them in
717 // the first round (they need to be checked after we have seen all
718 // write pointers). Note: we also mark pointer that are not
719 // consecutive as "read-only" pointers (so that we check
720 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
721 if (!UseDeferred && IsReadOnlyPtr) {
722 DeferredAccesses.insert(Access);
723 continue;
724 }
725
726 // If this is a write - check other reads and writes for conflicts. If
727 // this is a read only check other writes for conflicts (but only if
728 // there is no other write to the ptr - this is an optimization to
729 // catch "a[i] = a[i] + " without having to do a dependence check).
730 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
731 CheckDeps.insert(Access);
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000732 IsRTCheckAnalysisNeeded = true;
Adam Nemet04563272015-02-01 16:56:15 +0000733 }
734
735 if (IsWrite)
736 SetHasWrite = true;
737
738 // Create sets of pointers connected by a shared alias set and
739 // underlying object.
740 typedef SmallVector<Value *, 16> ValueVector;
741 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000742
743 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
744 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000745 for (Value *UnderlyingObj : TempObjects) {
746 UnderlyingObjToAccessMap::iterator Prev =
747 ObjToLastAccess.find(UnderlyingObj);
748 if (Prev != ObjToLastAccess.end())
749 DepCands.unionSets(Access, Prev->second);
750
751 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000752 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000753 }
754 }
755 }
756 }
757 }
758}
759
Adam Nemet04563272015-02-01 16:56:15 +0000760static bool isInBoundsGep(Value *Ptr) {
761 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
762 return GEP->isInBounds();
763 return false;
764}
765
Adam Nemetc4866d22015-06-26 17:25:43 +0000766/// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
767/// i.e. monotonically increasing/decreasing.
768static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
769 ScalarEvolution *SE, const Loop *L) {
770 // FIXME: This should probably only return true for NUW.
771 if (AR->getNoWrapFlags(SCEV::NoWrapMask))
772 return true;
773
774 // Scalar evolution does not propagate the non-wrapping flags to values that
775 // are derived from a non-wrapping induction variable because non-wrapping
776 // could be flow-sensitive.
777 //
778 // Look through the potentially overflowing instruction to try to prove
779 // non-wrapping for the *specific* value of Ptr.
780
781 // The arithmetic implied by an inbounds GEP can't overflow.
782 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
783 if (!GEP || !GEP->isInBounds())
784 return false;
785
786 // Make sure there is only one non-const index and analyze that.
787 Value *NonConstIndex = nullptr;
788 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
789 if (!isa<ConstantInt>(*Index)) {
790 if (NonConstIndex)
791 return false;
792 NonConstIndex = *Index;
793 }
794 if (!NonConstIndex)
795 // The recurrence is on the pointer, ignore for now.
796 return false;
797
798 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
799 // AddRec using a NSW operation.
800 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
801 if (OBO->hasNoSignedWrap() &&
802 // Assume constant for other the operand so that the AddRec can be
803 // easily found.
804 isa<ConstantInt>(OBO->getOperand(1))) {
805 auto *OpScev = SE->getSCEV(OBO->getOperand(0));
806
807 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
808 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
809 }
810
811 return false;
812}
813
Adam Nemet04563272015-02-01 16:56:15 +0000814/// \brief Check whether the access through \p Ptr has a constant stride.
Hao Liu32c05392015-06-08 06:39:56 +0000815int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
Silviu Barangae3c05342015-11-02 14:41:02 +0000816 const ValueToValueMap &StridesMap,
817 SCEVUnionPredicate &Preds) {
Craig Toppere3dcce92015-08-01 22:20:21 +0000818 Type *Ty = Ptr->getType();
Adam Nemet04563272015-02-01 16:56:15 +0000819 assert(Ty->isPointerTy() && "Unexpected non-ptr");
820
821 // Make sure that the pointer does not point to aggregate types.
Craig Toppere3dcce92015-08-01 22:20:21 +0000822 auto *PtrTy = cast<PointerType>(Ty);
Adam Nemet04563272015-02-01 16:56:15 +0000823 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000824 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
825 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000826 return 0;
827 }
828
Silviu Barangae3c05342015-11-02 14:41:02 +0000829 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Preds, Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000830
831 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
832 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000833 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000834 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000835 return 0;
836 }
837
838 // The accesss function must stride over the innermost loop.
839 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000840 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000841 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000842 }
843
844 // The address calculation must not wrap. Otherwise, a dependence could be
845 // inverted.
846 // An inbounds getelementptr that is a AddRec with a unit stride
847 // cannot wrap per definition. The unit stride requirement is checked later.
848 // An getelementptr without an inbounds attribute and unit stride would have
849 // to access the pointer value "0" which is undefined behavior in address
850 // space 0, therefore we can also vectorize this case.
851 bool IsInBoundsGEP = isInBoundsGep(Ptr);
Adam Nemetc4866d22015-06-26 17:25:43 +0000852 bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp);
Adam Nemet04563272015-02-01 16:56:15 +0000853 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
854 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000855 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000856 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000857 return 0;
858 }
859
860 // Check the step is constant.
861 const SCEV *Step = AR->getStepRecurrence(*SE);
862
Adam Nemet943befe2015-07-09 00:03:22 +0000863 // Calculate the pointer stride and check if it is constant.
Adam Nemet04563272015-02-01 16:56:15 +0000864 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
865 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000866 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000867 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000868 return 0;
869 }
870
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000871 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
872 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000873 const APInt &APStepVal = C->getValue()->getValue();
874
875 // Huge step value - give up.
876 if (APStepVal.getBitWidth() > 64)
877 return 0;
878
879 int64_t StepVal = APStepVal.getSExtValue();
880
881 // Strided access.
882 int64_t Stride = StepVal / Size;
883 int64_t Rem = StepVal % Size;
884 if (Rem)
885 return 0;
886
887 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
888 // know we can't "wrap around the address space". In case of address space
889 // zero we know that this won't happen without triggering undefined behavior.
890 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
891 Stride != 1 && Stride != -1)
892 return 0;
893
894 return Stride;
895}
896
Adam Nemet9c926572015-03-10 17:40:37 +0000897bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
898 switch (Type) {
899 case NoDep:
900 case Forward:
901 case BackwardVectorizable:
902 return true;
903
904 case Unknown:
905 case ForwardButPreventsForwarding:
906 case Backward:
907 case BackwardVectorizableButPreventsForwarding:
908 return false;
909 }
David Majnemerd388e932015-03-10 20:23:29 +0000910 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000911}
912
913bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
914 switch (Type) {
915 case NoDep:
916 case Forward:
917 return false;
918
919 case BackwardVectorizable:
920 case Unknown:
921 case ForwardButPreventsForwarding:
922 case Backward:
923 case BackwardVectorizableButPreventsForwarding:
924 return true;
925 }
David Majnemerd388e932015-03-10 20:23:29 +0000926 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000927}
928
929bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
930 switch (Type) {
931 case NoDep:
932 case Forward:
933 case ForwardButPreventsForwarding:
934 return false;
935
936 case Unknown:
937 case BackwardVectorizable:
938 case Backward:
939 case BackwardVectorizableButPreventsForwarding:
940 return true;
941 }
David Majnemerd388e932015-03-10 20:23:29 +0000942 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000943}
944
Adam Nemet04563272015-02-01 16:56:15 +0000945bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
946 unsigned TypeByteSize) {
947 // If loads occur at a distance that is not a multiple of a feasible vector
948 // factor store-load forwarding does not take place.
949 // Positive dependences might cause troubles because vectorizing them might
950 // prevent store-load forwarding making vectorized code run a lot slower.
951 // a[i] = a[i-3] ^ a[i-8];
952 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
953 // hence on your typical architecture store-load forwarding does not take
954 // place. Vectorizing in such cases does not make sense.
955 // Store-load forwarding distance.
956 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
957 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000958 unsigned MaxVFWithoutSLForwardIssues =
959 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000960 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000961 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
962
963 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
964 vf *= 2) {
965 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
966 MaxVFWithoutSLForwardIssues = (vf >>=1);
967 break;
968 }
969 }
970
Adam Nemet04d41632015-02-19 19:14:34 +0000971 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000972 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000973 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000974 return true;
975 }
976
977 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000978 MaxVFWithoutSLForwardIssues !=
979 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000980 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
981 return false;
982}
983
Hao Liu751004a2015-06-08 04:48:37 +0000984/// \brief Check the dependence for two accesses with the same stride \p Stride.
985/// \p Distance is the positive distance and \p TypeByteSize is type size in
986/// bytes.
987///
988/// \returns true if they are independent.
989static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
990 unsigned TypeByteSize) {
991 assert(Stride > 1 && "The stride must be greater than 1");
992 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
993 assert(Distance > 0 && "The distance must be non-zero");
994
995 // Skip if the distance is not multiple of type byte size.
996 if (Distance % TypeByteSize)
997 return false;
998
999 unsigned ScaledDist = Distance / TypeByteSize;
1000
1001 // No dependence if the scaled distance is not multiple of the stride.
1002 // E.g.
1003 // for (i = 0; i < 1024 ; i += 4)
1004 // A[i+2] = A[i] + 1;
1005 //
1006 // Two accesses in memory (scaled distance is 2, stride is 4):
1007 // | A[0] | | | | A[4] | | | |
1008 // | | | A[2] | | | | A[6] | |
1009 //
1010 // E.g.
1011 // for (i = 0; i < 1024 ; i += 3)
1012 // A[i+4] = A[i] + 1;
1013 //
1014 // Two accesses in memory (scaled distance is 4, stride is 3):
1015 // | A[0] | | | A[3] | | | A[6] | | |
1016 // | | | | | A[4] | | | A[7] | |
1017 return ScaledDist % Stride;
1018}
1019
Adam Nemet9c926572015-03-10 17:40:37 +00001020MemoryDepChecker::Dependence::DepType
1021MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
1022 const MemAccessInfo &B, unsigned BIdx,
1023 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001024 assert (AIdx < BIdx && "Must pass arguments in program order");
1025
1026 Value *APtr = A.getPointer();
1027 Value *BPtr = B.getPointer();
1028 bool AIsWrite = A.getInt();
1029 bool BIsWrite = B.getInt();
1030
1031 // Two reads are independent.
1032 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +00001033 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +00001034
1035 // We cannot check pointers in different address spaces.
1036 if (APtr->getType()->getPointerAddressSpace() !=
1037 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +00001038 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001039
Silviu Barangae3c05342015-11-02 14:41:02 +00001040 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, Preds, APtr);
1041 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, Preds, BPtr);
Adam Nemet04563272015-02-01 16:56:15 +00001042
Silviu Barangae3c05342015-11-02 14:41:02 +00001043 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides, Preds);
1044 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides, Preds);
Adam Nemet04563272015-02-01 16:56:15 +00001045
1046 const SCEV *Src = AScev;
1047 const SCEV *Sink = BScev;
1048
1049 // If the induction step is negative we have to invert source and sink of the
1050 // dependence.
1051 if (StrideAPtr < 0) {
1052 //Src = BScev;
1053 //Sink = AScev;
1054 std::swap(APtr, BPtr);
1055 std::swap(Src, Sink);
1056 std::swap(AIsWrite, BIsWrite);
1057 std::swap(AIdx, BIdx);
1058 std::swap(StrideAPtr, StrideBPtr);
1059 }
1060
1061 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
1062
Adam Nemet339f42b2015-02-19 19:15:07 +00001063 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +00001064 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +00001065 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +00001066 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +00001067
Adam Nemet943befe2015-07-09 00:03:22 +00001068 // Need accesses with constant stride. We don't want to vectorize
Adam Nemet04563272015-02-01 16:56:15 +00001069 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1070 // the address space.
1071 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
Adam Nemet943befe2015-07-09 00:03:22 +00001072 DEBUG(dbgs() << "Pointer access with non-constant stride\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001073 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001074 }
1075
1076 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1077 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001078 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +00001079 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +00001080 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001081 }
1082
1083 Type *ATy = APtr->getType()->getPointerElementType();
1084 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001085 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1086 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +00001087
1088 // Negative distances are not plausible dependencies.
1089 const APInt &Val = C->getValue()->getValue();
1090 if (Val.isNegative()) {
1091 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1092 if (IsTrueDataDependence &&
1093 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1094 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +00001095 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001096
Adam Nemet339f42b2015-02-19 19:15:07 +00001097 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001098 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +00001099 }
1100
1101 // Write to the same location with the same size.
1102 // Could be improved to assert type sizes are the same (i32 == float, etc).
1103 if (Val == 0) {
1104 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +00001105 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +00001106 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001107 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001108 }
1109
1110 assert(Val.isStrictlyPositive() && "Expect a positive value");
1111
Adam Nemet04563272015-02-01 16:56:15 +00001112 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +00001113 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +00001114 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001115 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001116 }
1117
1118 unsigned Distance = (unsigned) Val.getZExtValue();
1119
Hao Liu751004a2015-06-08 04:48:37 +00001120 unsigned Stride = std::abs(StrideAPtr);
1121 if (Stride > 1 &&
Adam Nemet0131a562015-07-08 18:47:38 +00001122 areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
1123 DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
Hao Liu751004a2015-06-08 04:48:37 +00001124 return Dependence::NoDep;
Adam Nemet0131a562015-07-08 18:47:38 +00001125 }
Hao Liu751004a2015-06-08 04:48:37 +00001126
Adam Nemet04563272015-02-01 16:56:15 +00001127 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +00001128 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1129 VectorizerParams::VectorizationFactor : 1);
1130 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1131 VectorizerParams::VectorizationInterleave : 1);
Hao Liu751004a2015-06-08 04:48:37 +00001132 // The minimum number of iterations for a vectorized/unrolled version.
1133 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
Adam Nemet04563272015-02-01 16:56:15 +00001134
Hao Liu751004a2015-06-08 04:48:37 +00001135 // It's not vectorizable if the distance is smaller than the minimum distance
1136 // needed for a vectroized/unrolled version. Vectorizing one iteration in
1137 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1138 // TypeByteSize (No need to plus the last gap distance).
1139 //
1140 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1141 // foo(int *A) {
1142 // int *B = (int *)((char *)A + 14);
1143 // for (i = 0 ; i < 1024 ; i += 2)
1144 // B[i] = A[i] + 1;
1145 // }
1146 //
1147 // Two accesses in memory (stride is 2):
1148 // | A[0] | | A[2] | | A[4] | | A[6] | |
1149 // | B[0] | | B[2] | | B[4] |
1150 //
1151 // Distance needs for vectorizing iterations except the last iteration:
1152 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1153 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1154 //
1155 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1156 // 12, which is less than distance.
1157 //
1158 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1159 // the minimum distance needed is 28, which is greater than distance. It is
1160 // not safe to do vectorization.
1161 unsigned MinDistanceNeeded =
1162 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1163 if (MinDistanceNeeded > Distance) {
1164 DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1165 << '\n');
1166 return Dependence::Backward;
1167 }
1168
1169 // Unsafe if the minimum distance needed is greater than max safe distance.
1170 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1171 DEBUG(dbgs() << "LAA: Failure because it needs at least "
1172 << MinDistanceNeeded << " size in bytes");
Adam Nemet9c926572015-03-10 17:40:37 +00001173 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +00001174 }
1175
Adam Nemet9cc0c392015-02-26 17:58:48 +00001176 // Positive distance bigger than max vectorization factor.
Hao Liu751004a2015-06-08 04:48:37 +00001177 // FIXME: Should use max factor instead of max distance in bytes, which could
1178 // not handle different types.
1179 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1180 // void foo (int *A, char *B) {
1181 // for (unsigned i = 0; i < 1024; i++) {
1182 // A[i+2] = A[i] + 1;
1183 // B[i+2] = B[i] + 1;
1184 // }
1185 // }
1186 //
1187 // This case is currently unsafe according to the max safe distance. If we
1188 // analyze the two accesses on array B, the max safe dependence distance
1189 // is 2. Then we analyze the accesses on array A, the minimum distance needed
1190 // is 8, which is less than 2 and forbidden vectorization, But actually
1191 // both A and B could be vectorized by 2 iterations.
1192 MaxSafeDepDistBytes =
1193 Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
Adam Nemet04563272015-02-01 16:56:15 +00001194
1195 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1196 if (IsTrueDataDependence &&
1197 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +00001198 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001199
Hao Liu751004a2015-06-08 04:48:37 +00001200 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1201 << " with max VF = "
1202 << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
Adam Nemet04563272015-02-01 16:56:15 +00001203
Adam Nemet9c926572015-03-10 17:40:37 +00001204 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +00001205}
1206
Adam Nemetdee666b2015-03-10 17:40:34 +00001207bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +00001208 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001209 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001210
1211 MaxSafeDepDistBytes = -1U;
1212 while (!CheckDeps.empty()) {
1213 MemAccessInfo CurAccess = *CheckDeps.begin();
1214
1215 // Get the relevant memory access set.
1216 EquivalenceClasses<MemAccessInfo>::iterator I =
1217 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1218
1219 // Check accesses within this set.
1220 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
1221 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
1222
1223 // Check every access pair.
1224 while (AI != AE) {
1225 CheckDeps.erase(*AI);
1226 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1227 while (OI != AE) {
1228 // Check every accessing instruction pair in program order.
1229 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1230 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1231 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1232 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +00001233 auto A = std::make_pair(&*AI, *I1);
1234 auto B = std::make_pair(&*OI, *I2);
1235
1236 assert(*I1 != *I2);
1237 if (*I1 > *I2)
1238 std::swap(A, B);
1239
1240 Dependence::DepType Type =
1241 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1242 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1243
1244 // Gather dependences unless we accumulated MaxInterestingDependence
1245 // dependences. In that case return as soon as we find the first
1246 // unsafe dependence. This puts a limit on this quadratic
1247 // algorithm.
1248 if (RecordInterestingDependences) {
1249 if (Dependence::isInterestingDependence(Type))
1250 InterestingDependences.push_back(
1251 Dependence(A.second, B.second, Type));
1252
1253 if (InterestingDependences.size() >= MaxInterestingDependence) {
1254 RecordInterestingDependences = false;
1255 InterestingDependences.clear();
1256 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1257 }
1258 }
1259 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +00001260 return false;
1261 }
1262 ++OI;
1263 }
1264 AI++;
1265 }
1266 }
Adam Nemet9c926572015-03-10 17:40:37 +00001267
1268 DEBUG(dbgs() << "Total Interesting Dependences: "
1269 << InterestingDependences.size() << "\n");
1270 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +00001271}
1272
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001273SmallVector<Instruction *, 4>
1274MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1275 MemAccessInfo Access(Ptr, isWrite);
1276 auto &IndexVector = Accesses.find(Access)->second;
1277
1278 SmallVector<Instruction *, 4> Insts;
1279 std::transform(IndexVector.begin(), IndexVector.end(),
1280 std::back_inserter(Insts),
1281 [&](unsigned Idx) { return this->InstMap[Idx]; });
1282 return Insts;
1283}
1284
Adam Nemet58913d62015-03-10 17:40:43 +00001285const char *MemoryDepChecker::Dependence::DepName[] = {
1286 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1287 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1288
1289void MemoryDepChecker::Dependence::print(
1290 raw_ostream &OS, unsigned Depth,
1291 const SmallVectorImpl<Instruction *> &Instrs) const {
1292 OS.indent(Depth) << DepName[Type] << ":\n";
1293 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1294 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1295}
1296
Adam Nemet929c38e2015-02-19 19:15:10 +00001297bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001298 // We need to have a loop header.
1299 DEBUG(dbgs() << "LAA: Found a loop: " <<
1300 TheLoop->getHeader()->getName() << '\n');
1301
Adam Nemet929c38e2015-02-19 19:15:10 +00001302 // We can only analyze innermost loops.
1303 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001304 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +00001305 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +00001306 return false;
1307 }
1308
1309 // We must have a single backedge.
1310 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001311 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001312 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001313 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001314 "loop control flow is not understood by analyzer");
1315 return false;
1316 }
1317
1318 // We must have a single exiting block.
1319 if (!TheLoop->getExitingBlock()) {
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
1327 // We only handle bottom-tested loops, i.e. loop in which the condition is
1328 // checked at the end of each iteration. With that we can assume that all
1329 // instructions in the loop are executed the same number of times.
1330 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001331 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001332 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001333 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001334 "loop control flow is not understood by analyzer");
1335 return false;
1336 }
1337
Adam Nemet929c38e2015-02-19 19:15:10 +00001338 // ScalarEvolution needs to be able to find the exit count.
1339 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
1340 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001341 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001342 "could not determine number of loop iterations");
1343 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1344 return false;
1345 }
1346
1347 return true;
1348}
1349
Adam Nemet8bc61df2015-02-24 00:41:59 +00001350void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001351
1352 typedef SmallVector<Value*, 16> ValueVector;
1353 typedef SmallPtrSet<Value*, 16> ValueSet;
1354
1355 // Holds the Load and Store *instructions*.
1356 ValueVector Loads;
1357 ValueVector Stores;
1358
1359 // Holds all the different accesses in the loop.
1360 unsigned NumReads = 0;
1361 unsigned NumReadWrites = 0;
1362
Adam Nemet7cdebac2015-07-14 22:32:44 +00001363 PtrRtChecking.Pointers.clear();
1364 PtrRtChecking.Need = false;
Adam Nemet04563272015-02-01 16:56:15 +00001365
1366 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +00001367
1368 // For each block.
1369 for (Loop::block_iterator bb = TheLoop->block_begin(),
1370 be = TheLoop->block_end(); bb != be; ++bb) {
1371
1372 // Scan the BB and collect legal loads and stores.
1373 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1374 ++it) {
1375
1376 // If this is a load, save it. If this instruction can read from memory
1377 // but is not a load, then we quit. Notice that we don't handle function
1378 // calls that read or write.
1379 if (it->mayReadFromMemory()) {
1380 // Many math library functions read the rounding mode. We will only
1381 // vectorize a loop if it contains known function calls that don't set
1382 // the flag. Therefore, it is safe to ignore this read from memory.
1383 CallInst *Call = dyn_cast<CallInst>(it);
1384 if (Call && getIntrinsicIDForCall(Call, TLI))
1385 continue;
1386
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +00001387 // If the function has an explicit vectorized counterpart, we can safely
1388 // assume that it can be vectorized.
1389 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1390 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1391 continue;
1392
Adam Nemet04563272015-02-01 16:56:15 +00001393 LoadInst *Ld = dyn_cast<LoadInst>(it);
1394 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001395 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +00001396 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +00001397 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001398 CanVecMem = false;
1399 return;
Adam Nemet04563272015-02-01 16:56:15 +00001400 }
1401 NumLoads++;
1402 Loads.push_back(Ld);
1403 DepChecker.addAccess(Ld);
1404 continue;
1405 }
1406
1407 // Save 'store' instructions. Abort if other instructions write to memory.
1408 if (it->mayWriteToMemory()) {
1409 StoreInst *St = dyn_cast<StoreInst>(it);
1410 if (!St) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001411 emitAnalysis(LoopAccessReport(&*it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001412 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001413 CanVecMem = false;
1414 return;
Adam Nemet04563272015-02-01 16:56:15 +00001415 }
1416 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001417 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001418 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001419 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001420 CanVecMem = false;
1421 return;
Adam Nemet04563272015-02-01 16:56:15 +00001422 }
1423 NumStores++;
1424 Stores.push_back(St);
1425 DepChecker.addAccess(St);
1426 }
1427 } // Next instr.
1428 } // Next block.
1429
1430 // Now we have two lists that hold the loads and the stores.
1431 // Next, we find the pointers that they use.
1432
1433 // Check if we see any stores. If there are no stores, then we don't
1434 // care if the pointers are *restrict*.
1435 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001436 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001437 CanVecMem = true;
1438 return;
Adam Nemet04563272015-02-01 16:56:15 +00001439 }
1440
Adam Nemetdee666b2015-03-10 17:40:34 +00001441 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001442 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Silviu Barangae3c05342015-11-02 14:41:02 +00001443 AA, LI, DependentAccesses, Preds);
Adam Nemet04563272015-02-01 16:56:15 +00001444
1445 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1446 // multiple times on the same object. If the ptr is accessed twice, once
1447 // for read and once for write, it will only appear once (on the write
1448 // list). This is okay, since we are going to check for conflicts between
1449 // writes and between reads and writes, but not between reads and reads.
1450 ValueSet Seen;
1451
1452 ValueVector::iterator I, IE;
1453 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1454 StoreInst *ST = cast<StoreInst>(*I);
1455 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001456 // Check for store to loop invariant address.
1457 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001458 // If we did *not* see this pointer before, insert it to the read-write
1459 // list. At this phase it is only a 'write' list.
1460 if (Seen.insert(Ptr).second) {
1461 ++NumReadWrites;
1462
Chandler Carruthac80dc72015-06-17 07:18:54 +00001463 MemoryLocation Loc = MemoryLocation::get(ST);
Adam Nemet04563272015-02-01 16:56:15 +00001464 // The TBAA metadata could have a control dependency on the predication
1465 // condition, so we cannot rely on it when determining whether or not we
1466 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001467 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001468 Loc.AATags.TBAA = nullptr;
1469
1470 Accesses.addStore(Loc);
1471 }
1472 }
1473
1474 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001475 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001476 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001477 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001478 CanVecMem = true;
1479 return;
Adam Nemet04563272015-02-01 16:56:15 +00001480 }
1481
1482 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1483 LoadInst *LD = cast<LoadInst>(*I);
1484 Value* Ptr = LD->getPointerOperand();
1485 // If we did *not* see this pointer before, insert it to the
1486 // read list. If we *did* see it before, then it is already in
1487 // the read-write list. This allows us to vectorize expressions
1488 // such as A[i] += x; Because the address of A[i] is a read-write
1489 // pointer. This only works if the index of A[i] is consecutive.
1490 // If the address of i is unknown (for example A[B[i]]) then we may
1491 // read a few words, modify, and write a few words, and some of the
1492 // words may be written to the same address.
1493 bool IsReadOnlyPtr = false;
Silviu Barangae3c05342015-11-02 14:41:02 +00001494 if (Seen.insert(Ptr).second ||
1495 !isStridedPtr(SE, Ptr, TheLoop, Strides, Preds)) {
Adam Nemet04563272015-02-01 16:56:15 +00001496 ++NumReads;
1497 IsReadOnlyPtr = true;
1498 }
1499
Chandler Carruthac80dc72015-06-17 07:18:54 +00001500 MemoryLocation Loc = MemoryLocation::get(LD);
Adam Nemet04563272015-02-01 16:56:15 +00001501 // The TBAA metadata could have a control dependency on the predication
1502 // condition, so we cannot rely on it when determining whether or not we
1503 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001504 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001505 Loc.AATags.TBAA = nullptr;
1506
1507 Accesses.addLoad(Loc, IsReadOnlyPtr);
1508 }
1509
1510 // If we write (or read-write) to a single destination and there are no
1511 // other reads in this loop then is it safe to vectorize.
1512 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001513 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001514 CanVecMem = true;
1515 return;
Adam Nemet04563272015-02-01 16:56:15 +00001516 }
1517
1518 // Build dependence sets and check whether we need a runtime pointer bounds
1519 // check.
1520 Accesses.buildDependenceSets();
Adam Nemet04563272015-02-01 16:56:15 +00001521
1522 // Find pointers with computable bounds. We are going to use this information
1523 // to place a runtime bound check.
Adam Nemetee614742015-07-09 22:17:38 +00001524 bool CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001525 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides);
Adam Nemetee614742015-07-09 22:17:38 +00001526 if (!CanDoRTIfNeeded) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001527 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemetee614742015-07-09 22:17:38 +00001528 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1529 << "the array bounds.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001530 CanVecMem = false;
1531 return;
Adam Nemet04563272015-02-01 16:56:15 +00001532 }
1533
Adam Nemetee614742015-07-09 22:17:38 +00001534 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001535
Adam Nemet436018c2015-02-19 19:15:00 +00001536 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001537 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001538 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001539 CanVecMem = DepChecker.areDepsSafe(
1540 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1541 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1542
1543 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001544 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001545
1546 // Clear the dependency checks. We assume they are not needed.
Adam Nemetdf3dc5b2015-05-18 15:37:03 +00001547 Accesses.resetDepChecks(DepChecker);
Adam Nemet04563272015-02-01 16:56:15 +00001548
Adam Nemet7cdebac2015-07-14 22:32:44 +00001549 PtrRtChecking.reset();
1550 PtrRtChecking.Need = true;
Adam Nemet04563272015-02-01 16:56:15 +00001551
Adam Nemetee614742015-07-09 22:17:38 +00001552 CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001553 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
Silviu Baranga98a13712015-06-08 10:27:06 +00001554
Adam Nemet949e91a2015-03-10 19:12:41 +00001555 // Check that we found the bounds for the pointer.
Adam Nemetee614742015-07-09 22:17:38 +00001556 if (!CanDoRTIfNeeded) {
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001557 emitAnalysis(LoopAccessReport()
1558 << "cannot check memory dependencies at runtime");
1559 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001560 CanVecMem = false;
1561 return;
1562 }
1563
Adam Nemet04563272015-02-01 16:56:15 +00001564 CanVecMem = true;
1565 }
1566 }
1567
Adam Nemet4bb90a72015-03-10 21:47:39 +00001568 if (CanVecMem)
1569 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
Adam Nemet7cdebac2015-07-14 22:32:44 +00001570 << (PtrRtChecking.Need ? "" : " don't")
Adam Nemet0f67c6c2015-07-09 22:17:41 +00001571 << " need runtime memory checks.\n");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001572 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001573 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001574 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001575 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1576 }
Adam Nemet04563272015-02-01 16:56:15 +00001577}
1578
Adam Nemet01abb2c2015-02-18 03:43:19 +00001579bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1580 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001581 assert(TheLoop->contains(BB) && "Unknown block used");
1582
1583 // Blocks that do not dominate the latch need predication.
1584 BasicBlock* Latch = TheLoop->getLoopLatch();
1585 return !DT->dominates(BB, Latch);
1586}
1587
Adam Nemet2bd6e982015-02-19 19:15:15 +00001588void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001589 assert(!Report && "Multiple reports generated");
1590 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001591}
1592
Adam Nemet57ac7662015-02-19 19:15:21 +00001593bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001594 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1595}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001596
1597// FIXME: this function is currently a duplicate of the one in
1598// LoopVectorize.cpp.
1599static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1600 Instruction *Loc) {
1601 if (FirstInst)
1602 return FirstInst;
1603 if (Instruction *I = dyn_cast<Instruction>(V))
1604 return I->getParent() == Loc->getParent() ? I : nullptr;
1605 return nullptr;
1606}
1607
Benjamin Kramer039b1042015-10-28 13:54:36 +00001608namespace {
Adam Nemet4e533ef2015-08-21 23:19:57 +00001609/// \brief IR Values for the lower and upper bounds of a pointer evolution. We
1610/// need to use value-handles because SCEV expansion can invalidate previously
1611/// expanded values. Thus expansion of a pointer can invalidate the bounds for
1612/// a previous one.
Adam Nemet1da7df32015-07-26 05:32:14 +00001613struct PointerBounds {
Adam Nemet4e533ef2015-08-21 23:19:57 +00001614 TrackingVH<Value> Start;
1615 TrackingVH<Value> End;
Adam Nemet1da7df32015-07-26 05:32:14 +00001616};
Benjamin Kramer039b1042015-10-28 13:54:36 +00001617} // end anonymous namespace
Adam Nemet7206d7a2015-02-06 18:31:04 +00001618
Adam Nemet1da7df32015-07-26 05:32:14 +00001619/// \brief Expand code for the lower and upper bound of the pointer group \p CG
1620/// in \p TheLoop. \return the values for the bounds.
1621static PointerBounds
1622expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop,
1623 Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE,
1624 const RuntimePointerChecking &PtrRtChecking) {
1625 Value *Ptr = PtrRtChecking.Pointers[CG->Members[0]].PointerValue;
1626 const SCEV *Sc = SE->getSCEV(Ptr);
1627
1628 if (SE->isLoopInvariant(Sc, TheLoop)) {
1629 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1630 << "\n");
1631 return {Ptr, Ptr};
1632 } else {
1633 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1634 LLVMContext &Ctx = Loc->getContext();
1635
1636 // Use this type for pointer arithmetic.
1637 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1638 Value *Start = nullptr, *End = nullptr;
1639
1640 DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1641 Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
1642 End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
1643 DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
1644 return {Start, End};
1645 }
1646}
1647
1648/// \brief Turns a collection of checks into a collection of expanded upper and
1649/// lower bounds for both pointers in the check.
1650static SmallVector<std::pair<PointerBounds, PointerBounds>, 4> expandBounds(
1651 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks,
1652 Loop *L, Instruction *Loc, ScalarEvolution *SE, SCEVExpander &Exp,
1653 const RuntimePointerChecking &PtrRtChecking) {
1654 SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
1655
1656 // Here we're relying on the SCEV Expander's cache to only emit code for the
1657 // same bounds once.
1658 std::transform(
1659 PointerChecks.begin(), PointerChecks.end(),
1660 std::back_inserter(ChecksWithBounds),
1661 [&](const RuntimePointerChecking::PointerCheck &Check) {
NAKAMURA Takumi94abbbd2015-07-27 01:35:30 +00001662 PointerBounds
1663 First = expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
1664 Second = expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
1665 return std::make_pair(First, Second);
Adam Nemet1da7df32015-07-26 05:32:14 +00001666 });
1667
1668 return ChecksWithBounds;
1669}
1670
Adam Nemet5b0a4792015-08-11 00:09:37 +00001671std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeChecks(
Adam Nemet1da7df32015-07-26 05:32:14 +00001672 Instruction *Loc,
1673 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &PointerChecks)
1674 const {
1675
1676 SCEVExpander Exp(*SE, DL, "induction");
1677 auto ExpandedChecks =
1678 expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, PtrRtChecking);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001679
1680 LLVMContext &Ctx = Loc->getContext();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001681 Instruction *FirstInst = nullptr;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001682 IRBuilder<> ChkBuilder(Loc);
1683 // Our instructions might fold to a constant.
1684 Value *MemoryRuntimeCheck = nullptr;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001685
Adam Nemet1da7df32015-07-26 05:32:14 +00001686 for (const auto &Check : ExpandedChecks) {
1687 const PointerBounds &A = Check.first, &B = Check.second;
Adam Nemetcdb791c2015-08-19 17:24:36 +00001688 // Check if two pointers (A and B) conflict where conflict is computed as:
1689 // start(A) <= end(B) && start(B) <= end(A)
Adam Nemet1da7df32015-07-26 05:32:14 +00001690 unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1691 unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
Adam Nemet7206d7a2015-02-06 18:31:04 +00001692
Adam Nemet1da7df32015-07-26 05:32:14 +00001693 assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
1694 (AS1 == A.End->getType()->getPointerAddressSpace()) &&
1695 "Trying to bounds check pointers with different address spaces");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001696
Adam Nemet1da7df32015-07-26 05:32:14 +00001697 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1698 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001699
Adam Nemet1da7df32015-07-26 05:32:14 +00001700 Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
1701 Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
1702 Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
1703 Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001704
Adam Nemet1da7df32015-07-26 05:32:14 +00001705 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1706 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1707 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1708 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1709 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1710 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1711 if (MemoryRuntimeCheck) {
1712 IsConflict =
1713 ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001714 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001715 }
Adam Nemet1da7df32015-07-26 05:32:14 +00001716 MemoryRuntimeCheck = IsConflict;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001717 }
1718
Adam Nemet90fec842015-04-02 17:51:57 +00001719 if (!MemoryRuntimeCheck)
1720 return std::make_pair(nullptr, nullptr);
1721
Adam Nemet7206d7a2015-02-06 18:31:04 +00001722 // We have to do this trickery because the IRBuilder might fold the check to a
1723 // constant expression in which case there is no Instruction anchored in a
1724 // the block.
1725 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1726 ConstantInt::getTrue(Ctx));
1727 ChkBuilder.Insert(Check, "memcheck.conflict");
1728 FirstInst = getFirstInst(FirstInst, Check, Loc);
1729 return std::make_pair(FirstInst, Check);
1730}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001731
Adam Nemet5b0a4792015-08-11 00:09:37 +00001732std::pair<Instruction *, Instruction *>
1733LoopAccessInfo::addRuntimeChecks(Instruction *Loc) const {
Adam Nemet1da7df32015-07-26 05:32:14 +00001734 if (!PtrRtChecking.Need)
1735 return std::make_pair(nullptr, nullptr);
1736
Adam Nemet5b0a4792015-08-11 00:09:37 +00001737 return addRuntimeChecks(Loc, PtrRtChecking.getChecks());
Adam Nemet1da7df32015-07-26 05:32:14 +00001738}
1739
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001740LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001741 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001742 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemete2b885c2015-04-23 20:09:20 +00001743 DominatorTree *DT, LoopInfo *LI,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001744 const ValueToValueMap &Strides)
Silviu Barangae3c05342015-11-02 14:41:02 +00001745 : PtrRtChecking(SE), DepChecker(SE, L, Preds), TheLoop(L), SE(SE), DL(DL),
Adam Nemet7cdebac2015-07-14 22:32:44 +00001746 TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001747 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1748 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001749 if (canAnalyzeLoop())
1750 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001751}
1752
Adam Nemete91cc6e2015-02-19 19:15:19 +00001753void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1754 if (CanVecMem) {
Adam Nemet7cdebac2015-07-14 22:32:44 +00001755 if (PtrRtChecking.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001756 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001757 else
1758 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001759 }
1760
1761 if (Report)
1762 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1763
Adam Nemet58913d62015-03-10 17:40:43 +00001764 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1765 OS.indent(Depth) << "Interesting Dependences:\n";
1766 for (auto &Dep : *InterestingDependences) {
1767 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1768 OS << "\n";
1769 }
1770 } else
1771 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001772
1773 // List the pair of accesses need run-time checks to prove independence.
Adam Nemet7cdebac2015-07-14 22:32:44 +00001774 PtrRtChecking.print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00001775 OS << "\n";
Adam Nemetc3384322015-05-18 15:36:57 +00001776
1777 OS.indent(Depth) << "Store to invariant address was "
1778 << (StoreToLoopInvariantAddress ? "" : "not ")
1779 << "found in loop.\n";
Silviu Barangae3c05342015-11-02 14:41:02 +00001780
1781 OS.indent(Depth) << "SCEV assumptions:\n";
1782 Preds.print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00001783}
1784
Adam Nemet8bc61df2015-02-24 00:41:59 +00001785const LoopAccessInfo &
1786LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001787 auto &LAI = LoopAccessInfoMap[L];
1788
1789#ifndef NDEBUG
1790 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1791 "Symbolic strides changed for loop");
1792#endif
1793
1794 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001795 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Silviu Barangae3c05342015-11-02 14:41:02 +00001796 LAI =
1797 llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI, Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001798#ifndef NDEBUG
1799 LAI->NumSymbolicStrides = Strides.size();
1800#endif
1801 }
1802 return *LAI.get();
1803}
1804
Adam Nemete91cc6e2015-02-19 19:15:19 +00001805void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1806 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1807
Adam Nemete91cc6e2015-02-19 19:15:19 +00001808 ValueToValueMap NoSymbolicStrides;
1809
1810 for (Loop *TopLevelLoop : *LI)
1811 for (Loop *L : depth_first(TopLevelLoop)) {
1812 OS.indent(2) << L->getHeader()->getName() << ":\n";
1813 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1814 LAI.print(OS, 4);
1815 }
1816}
1817
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001818bool LoopAccessAnalysis::runOnFunction(Function &F) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001819 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001820 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1821 TLI = TLIP ? &TLIP->getTLI() : nullptr;
Chandler Carruth7b560d42015-09-09 17:55:00 +00001822 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001823 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete2b885c2015-04-23 20:09:20 +00001824 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001825
1826 return false;
1827}
1828
1829void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001830 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00001831 AU.addRequired<AAResultsWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001832 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001833 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001834
1835 AU.setPreservesAll();
1836}
1837
1838char LoopAccessAnalysis::ID = 0;
1839static const char laa_name[] = "Loop Access Analysis";
1840#define LAA_NAME "loop-accesses"
1841
1842INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
Chandler Carruth7b560d42015-09-09 17:55:00 +00001843INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001844INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001845INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001846INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001847INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1848
1849namespace llvm {
1850 Pass *createLAAPass() {
1851 return new LoopAccessAnalysis();
1852 }
1853}