blob: 7201a93f12a4bd7d9f05fb99fbc23177a4f60019 [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"
Adam Nemet04563272015-02-01 16:56:15 +000018#include "llvm/Analysis/ValueTracking.h"
19#include "llvm/IR/DiagnosticInfo.h"
20#include "llvm/IR/Dominators.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000021#include "llvm/IR/IRBuilder.h"
Adam Nemet04563272015-02-01 16:56:15 +000022#include "llvm/Support/Debug.h"
23#include "llvm/Transforms/Utils/VectorUtils.h"
24using namespace llvm;
25
Adam Nemet339f42b2015-02-19 19:15:07 +000026#define DEBUG_TYPE "loop-accesses"
Adam Nemet04563272015-02-01 16:56:15 +000027
Adam Nemetf219c642015-02-19 19:14:52 +000028static cl::opt<unsigned, true>
29VectorizationFactor("force-vector-width", cl::Hidden,
30 cl::desc("Sets the SIMD width. Zero is autoselect."),
31 cl::location(VectorizerParams::VectorizationFactor));
Adam Nemet1d862af2015-02-26 04:39:09 +000032unsigned VectorizerParams::VectorizationFactor;
Adam Nemetf219c642015-02-19 19:14:52 +000033
34static cl::opt<unsigned, true>
35VectorizationInterleave("force-vector-interleave", cl::Hidden,
36 cl::desc("Sets the vectorization interleave count. "
37 "Zero is autoselect."),
38 cl::location(
39 VectorizerParams::VectorizationInterleave));
Adam Nemet1d862af2015-02-26 04:39:09 +000040unsigned VectorizerParams::VectorizationInterleave;
Adam Nemetf219c642015-02-19 19:14:52 +000041
Adam Nemet1d862af2015-02-26 04:39:09 +000042static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
43 "runtime-memory-check-threshold", cl::Hidden,
44 cl::desc("When performing memory disambiguation checks at runtime do not "
45 "generate more than this number of comparisons (default = 8)."),
46 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
47unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
Adam Nemetf219c642015-02-19 19:14:52 +000048
49/// Maximum SIMD width.
50const unsigned VectorizerParams::MaxVectorWidth = 64;
51
Adam Nemet9c926572015-03-10 17:40:37 +000052/// \brief We collect interesting dependences up to this threshold.
53static cl::opt<unsigned> MaxInterestingDependence(
54 "max-interesting-dependences", cl::Hidden,
55 cl::desc("Maximum number of interesting dependences collected by "
56 "loop-access analysis (default = 100)"),
57 cl::init(100));
58
Adam Nemetf219c642015-02-19 19:14:52 +000059bool VectorizerParams::isInterleaveForced() {
60 return ::VectorizationInterleave.getNumOccurrences() > 0;
61}
62
Adam Nemet2bd6e982015-02-19 19:15:15 +000063void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
64 const Function *TheFunction,
65 const Loop *TheLoop,
66 const char *PassName) {
Adam Nemet04563272015-02-01 16:56:15 +000067 DebugLoc DL = TheLoop->getStartLoc();
Adam Nemet3e876342015-02-19 19:15:13 +000068 if (const Instruction *I = Message.getInstr())
Adam Nemet04563272015-02-01 16:56:15 +000069 DL = I->getDebugLoc();
Adam Nemet339f42b2015-02-19 19:15:07 +000070 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
Adam Nemet04563272015-02-01 16:56:15 +000071 *TheFunction, DL, Message.str());
72}
73
74Value *llvm::stripIntegerCast(Value *V) {
75 if (CastInst *CI = dyn_cast<CastInst>(V))
76 if (CI->getOperand(0)->getType()->isIntegerTy())
77 return CI->getOperand(0);
78 return V;
79}
80
81const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
Adam Nemet8bc61df2015-02-24 00:41:59 +000082 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +000083 Value *Ptr, Value *OrigPtr) {
84
85 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
86
87 // If there is an entry in the map return the SCEV of the pointer with the
88 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +000089 ValueToValueMap::const_iterator SI =
90 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +000091 if (SI != PtrToStride.end()) {
92 Value *StrideVal = SI->second;
93
94 // Strip casts.
95 StrideVal = stripIntegerCast(StrideVal);
96
97 // Replace symbolic stride by one.
98 Value *One = ConstantInt::get(StrideVal->getType(), 1);
99 ValueToValueMap RewriteMap;
100 RewriteMap[StrideVal] = One;
101
102 const SCEV *ByOne =
103 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
Adam Nemet339f42b2015-02-19 19:15:07 +0000104 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
Adam Nemet04563272015-02-01 16:56:15 +0000105 << "\n");
106 return ByOne;
107 }
108
109 // Otherwise, just return the SCEV of the original pointer.
110 return SE->getSCEV(Ptr);
111}
112
Adam Nemet8bc61df2015-02-24 00:41:59 +0000113void LoopAccessInfo::RuntimePointerCheck::insert(
114 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
115 unsigned ASId, const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000116 // Get the stride replaced scev.
117 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
118 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
119 assert(AR && "Invalid addrec expression");
120 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
121 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
122 Pointers.push_back(Ptr);
123 Starts.push_back(AR->getStart());
124 Ends.push_back(ScEnd);
125 IsWritePtr.push_back(WritePtr);
126 DependencySetId.push_back(DepSetId);
127 AliasSetId.push_back(ASId);
128}
129
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000130bool LoopAccessInfo::RuntimePointerCheck::needsChecking(
131 unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemeta8945b72015-02-18 03:43:58 +0000132 // No need to check if two readonly pointers intersect.
133 if (!IsWritePtr[I] && !IsWritePtr[J])
134 return false;
135
136 // Only need to check pointers between two different dependency sets.
137 if (DependencySetId[I] == DependencySetId[J])
138 return false;
139
140 // Only need to check pointers in the same alias set.
141 if (AliasSetId[I] != AliasSetId[J])
142 return false;
143
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000144 // If PtrPartition is set omit checks between pointers of the same partition.
145 // Partition number -1 means that the pointer is used in multiple partitions.
146 // In this case we can't omit the check.
147 if (PtrPartition && (*PtrPartition)[I] != -1 &&
148 (*PtrPartition)[I] == (*PtrPartition)[J])
149 return false;
150
Adam Nemeta8945b72015-02-18 03:43:58 +0000151 return true;
152}
153
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000154void LoopAccessInfo::RuntimePointerCheck::print(
155 raw_ostream &OS, unsigned Depth,
156 const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000157 unsigned NumPointers = Pointers.size();
158 if (NumPointers == 0)
159 return;
160
161 OS.indent(Depth) << "Run-time memory checks:\n";
162 unsigned N = 0;
163 for (unsigned I = 0; I < NumPointers; ++I)
164 for (unsigned J = I + 1; J < NumPointers; ++J)
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000165 if (needsChecking(I, J, PtrPartition)) {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000166 OS.indent(Depth) << N++ << ":\n";
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000167 OS.indent(Depth + 2) << *Pointers[I];
168 if (PtrPartition)
169 OS << " (Partition: " << (*PtrPartition)[I] << ")";
170 OS << "\n";
171 OS.indent(Depth + 2) << *Pointers[J];
172 if (PtrPartition)
173 OS << " (Partition: " << (*PtrPartition)[J] << ")";
174 OS << "\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +0000175 }
176}
177
Adam Nemet04563272015-02-01 16:56:15 +0000178namespace {
179/// \brief Analyses memory accesses in a loop.
180///
181/// Checks whether run time pointer checks are needed and builds sets for data
182/// dependence checking.
183class AccessAnalysis {
184public:
185 /// \brief Read or write access location.
186 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
187 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
188
Adam Nemetdee666b2015-03-10 17:40:34 +0000189 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA,
190 MemoryDepChecker::DepCandidates &DA)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000191 : DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000192
193 /// \brief Register a load and whether it is only read from.
194 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
195 Value *Ptr = const_cast<Value*>(Loc.Ptr);
196 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
197 Accesses.insert(MemAccessInfo(Ptr, false));
198 if (IsReadOnly)
199 ReadOnlyPtr.insert(Ptr);
200 }
201
202 /// \brief Register a store.
203 void addStore(AliasAnalysis::Location &Loc) {
204 Value *Ptr = const_cast<Value*>(Loc.Ptr);
205 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
206 Accesses.insert(MemAccessInfo(Ptr, true));
207 }
208
209 /// \brief Check whether we can check the pointers at runtime for
210 /// non-intersection.
Adam Nemet30f16e12015-02-18 03:42:35 +0000211 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000212 unsigned &NumComparisons, ScalarEvolution *SE,
213 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000214 bool ShouldCheckStride = false);
215
216 /// \brief Goes over all memory accesses, checks whether a RT check is needed
217 /// and builds sets of dependent accesses.
218 void buildDependenceSets() {
219 processMemAccesses();
220 }
221
222 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
223
224 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
225 void resetDepChecks() { CheckDeps.clear(); }
226
227 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
228
229private:
230 typedef SetVector<MemAccessInfo> PtrAccessSet;
231
232 /// \brief Go over all memory access and check whether runtime pointer checks
233 /// are needed /// and build sets of dependency check candidates.
234 void processMemAccesses();
235
236 /// Set of all accesses.
237 PtrAccessSet Accesses;
238
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000239 const DataLayout &DL;
240
Adam Nemet04563272015-02-01 16:56:15 +0000241 /// Set of accesses that need a further dependence check.
242 MemAccessInfoSet CheckDeps;
243
244 /// Set of pointers that are read only.
245 SmallPtrSet<Value*, 16> ReadOnlyPtr;
246
Adam Nemet04563272015-02-01 16:56:15 +0000247 /// An alias set tracker to partition the access set by underlying object and
248 //intrinsic property (such as TBAA metadata).
249 AliasSetTracker AST;
250
251 /// Sets of potentially dependent accesses - members of one set share an
252 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
253 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000254 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000255
256 bool IsRTCheckNeeded;
257};
258
259} // end anonymous namespace
260
261/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000262static bool hasComputableBounds(ScalarEvolution *SE,
263 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000264 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
265 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
266 if (!AR)
267 return false;
268
269 return AR->isAffine();
270}
271
272/// \brief Check the stride of the pointer and ensure that it does not wrap in
273/// the address space.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000274static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
275 const ValueToValueMap &StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000276
277bool AccessAnalysis::canCheckPtrAtRT(
Adam Nemet8bc61df2015-02-24 00:41:59 +0000278 LoopAccessInfo::RuntimePointerCheck &RtCheck, unsigned &NumComparisons,
279 ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
280 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000281 // Find pointers with computable bounds. We are going to use this information
282 // to place a runtime bound check.
283 bool CanDoRT = true;
284
285 bool IsDepCheckNeeded = isDependencyCheckNeeded();
286 NumComparisons = 0;
287
288 // We assign a consecutive id to access from different alias sets.
289 // Accesses between different groups doesn't need to be checked.
290 unsigned ASId = 1;
291 for (auto &AS : AST) {
292 unsigned NumReadPtrChecks = 0;
293 unsigned NumWritePtrChecks = 0;
294
295 // We assign consecutive id to access from different dependence sets.
296 // Accesses within the same set don't need a runtime check.
297 unsigned RunningDepId = 1;
298 DenseMap<Value *, unsigned> DepSetId;
299
300 for (auto A : AS) {
301 Value *Ptr = A.getValue();
302 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
303 MemAccessInfo Access(Ptr, IsWrite);
304
305 if (IsWrite)
306 ++NumWritePtrChecks;
307 else
308 ++NumReadPtrChecks;
309
310 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000311 // When we run after a failing dependency check we have to make sure
312 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000313 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000314 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000315 // The id of the dependence set.
316 unsigned DepId;
317
318 if (IsDepCheckNeeded) {
319 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
320 unsigned &LeaderId = DepSetId[Leader];
321 if (!LeaderId)
322 LeaderId = RunningDepId++;
323 DepId = LeaderId;
324 } else
325 // Each access has its own dependence set.
326 DepId = RunningDepId++;
327
328 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
329
Adam Nemet339f42b2015-02-19 19:15:07 +0000330 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000331 } else {
332 CanDoRT = false;
333 }
334 }
335
336 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
337 NumComparisons += 0; // Only one dependence set.
338 else {
339 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
340 NumWritePtrChecks - 1));
341 }
342
343 ++ASId;
344 }
345
346 // If the pointers that we would use for the bounds comparison have different
347 // address spaces, assume the values aren't directly comparable, so we can't
348 // use them for the runtime check. We also have to assume they could
349 // overlap. In the future there should be metadata for whether address spaces
350 // are disjoint.
351 unsigned NumPointers = RtCheck.Pointers.size();
352 for (unsigned i = 0; i < NumPointers; ++i) {
353 for (unsigned j = i + 1; j < NumPointers; ++j) {
354 // Only need to check pointers between two different dependency sets.
355 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
356 continue;
357 // Only need to check pointers in the same alias set.
358 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
359 continue;
360
361 Value *PtrI = RtCheck.Pointers[i];
362 Value *PtrJ = RtCheck.Pointers[j];
363
364 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
365 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
366 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000367 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000368 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000369 return false;
370 }
371 }
372 }
373
374 return CanDoRT;
375}
376
377void AccessAnalysis::processMemAccesses() {
378 // We process the set twice: first we process read-write pointers, last we
379 // process read-only pointers. This allows us to skip dependence tests for
380 // read-only pointers.
381
Adam Nemet339f42b2015-02-19 19:15:07 +0000382 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000383 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000384 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000385 DEBUG({
386 for (auto A : Accesses)
387 dbgs() << "\t" << *A.getPointer() << " (" <<
388 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
389 "read-only" : "read")) << ")\n";
390 });
391
392 // The AliasSetTracker has nicely partitioned our pointers by metadata
393 // compatibility and potential for underlying-object overlap. As a result, we
394 // only need to check for potential pointer dependencies within each alias
395 // set.
396 for (auto &AS : AST) {
397 // Note that both the alias-set tracker and the alias sets themselves used
398 // linked lists internally and so the iteration order here is deterministic
399 // (matching the original instruction order within each set).
400
401 bool SetHasWrite = false;
402
403 // Map of pointers to last access encountered.
404 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
405 UnderlyingObjToAccessMap ObjToLastAccess;
406
407 // Set of access to check after all writes have been processed.
408 PtrAccessSet DeferredAccesses;
409
410 // Iterate over each alias set twice, once to process read/write pointers,
411 // and then to process read-only pointers.
412 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
413 bool UseDeferred = SetIteration > 0;
414 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
415
416 for (auto AV : AS) {
417 Value *Ptr = AV.getValue();
418
419 // For a single memory access in AliasSetTracker, Accesses may contain
420 // both read and write, and they both need to be handled for CheckDeps.
421 for (auto AC : S) {
422 if (AC.getPointer() != Ptr)
423 continue;
424
425 bool IsWrite = AC.getInt();
426
427 // If we're using the deferred access set, then it contains only
428 // reads.
429 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
430 if (UseDeferred && !IsReadOnlyPtr)
431 continue;
432 // Otherwise, the pointer must be in the PtrAccessSet, either as a
433 // read or a write.
434 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
435 S.count(MemAccessInfo(Ptr, false))) &&
436 "Alias-set pointer not in the access set?");
437
438 MemAccessInfo Access(Ptr, IsWrite);
439 DepCands.insert(Access);
440
441 // Memorize read-only pointers for later processing and skip them in
442 // the first round (they need to be checked after we have seen all
443 // write pointers). Note: we also mark pointer that are not
444 // consecutive as "read-only" pointers (so that we check
445 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
446 if (!UseDeferred && IsReadOnlyPtr) {
447 DeferredAccesses.insert(Access);
448 continue;
449 }
450
451 // If this is a write - check other reads and writes for conflicts. If
452 // this is a read only check other writes for conflicts (but only if
453 // there is no other write to the ptr - this is an optimization to
454 // catch "a[i] = a[i] + " without having to do a dependence check).
455 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
456 CheckDeps.insert(Access);
457 IsRTCheckNeeded = true;
458 }
459
460 if (IsWrite)
461 SetHasWrite = true;
462
463 // Create sets of pointers connected by a shared alias set and
464 // underlying object.
465 typedef SmallVector<Value *, 16> ValueVector;
466 ValueVector TempObjects;
467 GetUnderlyingObjects(Ptr, TempObjects, DL);
468 for (Value *UnderlyingObj : TempObjects) {
469 UnderlyingObjToAccessMap::iterator Prev =
470 ObjToLastAccess.find(UnderlyingObj);
471 if (Prev != ObjToLastAccess.end())
472 DepCands.unionSets(Access, Prev->second);
473
474 ObjToLastAccess[UnderlyingObj] = Access;
475 }
476 }
477 }
478 }
479 }
480}
481
Adam Nemet04563272015-02-01 16:56:15 +0000482static bool isInBoundsGep(Value *Ptr) {
483 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
484 return GEP->isInBounds();
485 return false;
486}
487
488/// \brief Check whether the access through \p Ptr has a constant stride.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000489static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
490 const ValueToValueMap &StridesMap) {
Adam Nemet04563272015-02-01 16:56:15 +0000491 const Type *Ty = Ptr->getType();
492 assert(Ty->isPointerTy() && "Unexpected non-ptr");
493
494 // Make sure that the pointer does not point to aggregate types.
495 const PointerType *PtrTy = cast<PointerType>(Ty);
496 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000497 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
498 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000499 return 0;
500 }
501
502 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
503
504 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
505 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000506 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000507 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000508 return 0;
509 }
510
511 // The accesss function must stride over the innermost loop.
512 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000513 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000514 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000515 }
516
517 // The address calculation must not wrap. Otherwise, a dependence could be
518 // inverted.
519 // An inbounds getelementptr that is a AddRec with a unit stride
520 // cannot wrap per definition. The unit stride requirement is checked later.
521 // An getelementptr without an inbounds attribute and unit stride would have
522 // to access the pointer value "0" which is undefined behavior in address
523 // space 0, therefore we can also vectorize this case.
524 bool IsInBoundsGEP = isInBoundsGep(Ptr);
525 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
526 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
527 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000528 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000529 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000530 return 0;
531 }
532
533 // Check the step is constant.
534 const SCEV *Step = AR->getStepRecurrence(*SE);
535
536 // Calculate the pointer stride and check if it is consecutive.
537 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
538 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000539 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000540 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000541 return 0;
542 }
543
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000544 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
545 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000546 const APInt &APStepVal = C->getValue()->getValue();
547
548 // Huge step value - give up.
549 if (APStepVal.getBitWidth() > 64)
550 return 0;
551
552 int64_t StepVal = APStepVal.getSExtValue();
553
554 // Strided access.
555 int64_t Stride = StepVal / Size;
556 int64_t Rem = StepVal % Size;
557 if (Rem)
558 return 0;
559
560 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
561 // know we can't "wrap around the address space". In case of address space
562 // zero we know that this won't happen without triggering undefined behavior.
563 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
564 Stride != 1 && Stride != -1)
565 return 0;
566
567 return Stride;
568}
569
Adam Nemet9c926572015-03-10 17:40:37 +0000570bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
571 switch (Type) {
572 case NoDep:
573 case Forward:
574 case BackwardVectorizable:
575 return true;
576
577 case Unknown:
578 case ForwardButPreventsForwarding:
579 case Backward:
580 case BackwardVectorizableButPreventsForwarding:
581 return false;
582 }
583}
584
585bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
586 switch (Type) {
587 case NoDep:
588 case Forward:
589 return false;
590
591 case BackwardVectorizable:
592 case Unknown:
593 case ForwardButPreventsForwarding:
594 case Backward:
595 case BackwardVectorizableButPreventsForwarding:
596 return true;
597 }
598}
599
600bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
601 switch (Type) {
602 case NoDep:
603 case Forward:
604 case ForwardButPreventsForwarding:
605 return false;
606
607 case Unknown:
608 case BackwardVectorizable:
609 case Backward:
610 case BackwardVectorizableButPreventsForwarding:
611 return true;
612 }
613}
614
Adam Nemet04563272015-02-01 16:56:15 +0000615bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
616 unsigned TypeByteSize) {
617 // If loads occur at a distance that is not a multiple of a feasible vector
618 // factor store-load forwarding does not take place.
619 // Positive dependences might cause troubles because vectorizing them might
620 // prevent store-load forwarding making vectorized code run a lot slower.
621 // a[i] = a[i-3] ^ a[i-8];
622 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
623 // hence on your typical architecture store-load forwarding does not take
624 // place. Vectorizing in such cases does not make sense.
625 // Store-load forwarding distance.
626 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
627 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000628 unsigned MaxVFWithoutSLForwardIssues =
629 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000630 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000631 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
632
633 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
634 vf *= 2) {
635 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
636 MaxVFWithoutSLForwardIssues = (vf >>=1);
637 break;
638 }
639 }
640
Adam Nemet04d41632015-02-19 19:14:34 +0000641 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000642 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000643 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000644 return true;
645 }
646
647 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000648 MaxVFWithoutSLForwardIssues !=
649 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000650 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
651 return false;
652}
653
Adam Nemet9c926572015-03-10 17:40:37 +0000654MemoryDepChecker::Dependence::DepType
655MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
656 const MemAccessInfo &B, unsigned BIdx,
657 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000658 assert (AIdx < BIdx && "Must pass arguments in program order");
659
660 Value *APtr = A.getPointer();
661 Value *BPtr = B.getPointer();
662 bool AIsWrite = A.getInt();
663 bool BIsWrite = B.getInt();
664
665 // Two reads are independent.
666 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +0000667 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +0000668
669 // We cannot check pointers in different address spaces.
670 if (APtr->getType()->getPointerAddressSpace() !=
671 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +0000672 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000673
674 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
675 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
676
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000677 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
678 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +0000679
680 const SCEV *Src = AScev;
681 const SCEV *Sink = BScev;
682
683 // If the induction step is negative we have to invert source and sink of the
684 // dependence.
685 if (StrideAPtr < 0) {
686 //Src = BScev;
687 //Sink = AScev;
688 std::swap(APtr, BPtr);
689 std::swap(Src, Sink);
690 std::swap(AIsWrite, BIsWrite);
691 std::swap(AIdx, BIdx);
692 std::swap(StrideAPtr, StrideBPtr);
693 }
694
695 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
696
Adam Nemet339f42b2015-02-19 19:15:07 +0000697 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +0000698 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +0000699 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +0000700 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000701
702 // Need consecutive accesses. We don't want to vectorize
703 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
704 // the address space.
705 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
706 DEBUG(dbgs() << "Non-consecutive pointer access\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000707 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000708 }
709
710 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
711 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000712 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +0000713 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +0000714 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000715 }
716
717 Type *ATy = APtr->getType()->getPointerElementType();
718 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000719 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
720 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +0000721
722 // Negative distances are not plausible dependencies.
723 const APInt &Val = C->getValue()->getValue();
724 if (Val.isNegative()) {
725 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
726 if (IsTrueDataDependence &&
727 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
728 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +0000729 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000730
Adam Nemet339f42b2015-02-19 19:15:07 +0000731 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000732 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +0000733 }
734
735 // Write to the same location with the same size.
736 // Could be improved to assert type sizes are the same (i32 == float, etc).
737 if (Val == 0) {
738 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +0000739 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +0000740 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000741 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000742 }
743
744 assert(Val.isStrictlyPositive() && "Expect a positive value");
745
Adam Nemet04563272015-02-01 16:56:15 +0000746 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +0000747 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +0000748 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000749 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000750 }
751
752 unsigned Distance = (unsigned) Val.getZExtValue();
753
754 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +0000755 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
756 VectorizerParams::VectorizationFactor : 1);
757 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
758 VectorizerParams::VectorizationInterleave : 1);
Adam Nemet04563272015-02-01 16:56:15 +0000759
760 // The distance must be bigger than the size needed for a vectorized version
761 // of the operation and the size of the vectorized operation must not be
762 // bigger than the currrent maximum size.
763 if (Distance < 2*TypeByteSize ||
764 2*TypeByteSize > MaxSafeDepDistBytes ||
765 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000766 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
Adam Nemet04d41632015-02-19 19:14:34 +0000767 << Val.getSExtValue() << '\n');
Adam Nemet9c926572015-03-10 17:40:37 +0000768 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +0000769 }
770
Adam Nemet9cc0c392015-02-26 17:58:48 +0000771 // Positive distance bigger than max vectorization factor.
Adam Nemet04563272015-02-01 16:56:15 +0000772 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
773 Distance : MaxSafeDepDistBytes;
774
775 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
776 if (IsTrueDataDependence &&
777 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +0000778 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000779
Adam Nemet339f42b2015-02-19 19:15:07 +0000780 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
Adam Nemet04d41632015-02-19 19:14:34 +0000781 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000782
Adam Nemet9c926572015-03-10 17:40:37 +0000783 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +0000784}
785
Adam Nemetdee666b2015-03-10 17:40:34 +0000786bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +0000787 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000788 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000789
790 MaxSafeDepDistBytes = -1U;
791 while (!CheckDeps.empty()) {
792 MemAccessInfo CurAccess = *CheckDeps.begin();
793
794 // Get the relevant memory access set.
795 EquivalenceClasses<MemAccessInfo>::iterator I =
796 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
797
798 // Check accesses within this set.
799 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
800 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
801
802 // Check every access pair.
803 while (AI != AE) {
804 CheckDeps.erase(*AI);
805 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
806 while (OI != AE) {
807 // Check every accessing instruction pair in program order.
808 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
809 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
810 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
811 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +0000812 auto A = std::make_pair(&*AI, *I1);
813 auto B = std::make_pair(&*OI, *I2);
814
815 assert(*I1 != *I2);
816 if (*I1 > *I2)
817 std::swap(A, B);
818
819 Dependence::DepType Type =
820 isDependent(*A.first, A.second, *B.first, B.second, Strides);
821 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
822
823 // Gather dependences unless we accumulated MaxInterestingDependence
824 // dependences. In that case return as soon as we find the first
825 // unsafe dependence. This puts a limit on this quadratic
826 // algorithm.
827 if (RecordInterestingDependences) {
828 if (Dependence::isInterestingDependence(Type))
829 InterestingDependences.push_back(
830 Dependence(A.second, B.second, Type));
831
832 if (InterestingDependences.size() >= MaxInterestingDependence) {
833 RecordInterestingDependences = false;
834 InterestingDependences.clear();
835 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
836 }
837 }
838 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +0000839 return false;
840 }
841 ++OI;
842 }
843 AI++;
844 }
845 }
Adam Nemet9c926572015-03-10 17:40:37 +0000846
847 DEBUG(dbgs() << "Total Interesting Dependences: "
848 << InterestingDependences.size() << "\n");
849 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +0000850}
851
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000852SmallVector<Instruction *, 4>
853MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
854 MemAccessInfo Access(Ptr, isWrite);
855 auto &IndexVector = Accesses.find(Access)->second;
856
857 SmallVector<Instruction *, 4> Insts;
858 std::transform(IndexVector.begin(), IndexVector.end(),
859 std::back_inserter(Insts),
860 [&](unsigned Idx) { return this->InstMap[Idx]; });
861 return Insts;
862}
863
Adam Nemet58913d62015-03-10 17:40:43 +0000864const char *MemoryDepChecker::Dependence::DepName[] = {
865 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
866 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
867
868void MemoryDepChecker::Dependence::print(
869 raw_ostream &OS, unsigned Depth,
870 const SmallVectorImpl<Instruction *> &Instrs) const {
871 OS.indent(Depth) << DepName[Type] << ":\n";
872 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
873 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
874}
875
Adam Nemet929c38e2015-02-19 19:15:10 +0000876bool LoopAccessInfo::canAnalyzeLoop() {
877 // We can only analyze innermost loops.
878 if (!TheLoop->empty()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000879 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +0000880 return false;
881 }
882
883 // We must have a single backedge.
884 if (TheLoop->getNumBackEdges() != 1) {
885 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000886 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000887 "loop control flow is not understood by analyzer");
888 return false;
889 }
890
891 // We must have a single exiting block.
892 if (!TheLoop->getExitingBlock()) {
893 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000894 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000895 "loop control flow is not understood by analyzer");
896 return false;
897 }
898
899 // We only handle bottom-tested loops, i.e. loop in which the condition is
900 // checked at the end of each iteration. With that we can assume that all
901 // instructions in the loop are executed the same number of times.
902 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
903 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000904 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000905 "loop control flow is not understood by analyzer");
906 return false;
907 }
908
909 // We need to have a loop header.
910 DEBUG(dbgs() << "LAA: Found a loop: " <<
911 TheLoop->getHeader()->getName() << '\n');
912
913 // ScalarEvolution needs to be able to find the exit count.
914 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
915 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000916 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000917 "could not determine number of loop iterations");
918 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
919 return false;
920 }
921
922 return true;
923}
924
Adam Nemet8bc61df2015-02-24 00:41:59 +0000925void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000926
927 typedef SmallVector<Value*, 16> ValueVector;
928 typedef SmallPtrSet<Value*, 16> ValueSet;
929
930 // Holds the Load and Store *instructions*.
931 ValueVector Loads;
932 ValueVector Stores;
933
934 // Holds all the different accesses in the loop.
935 unsigned NumReads = 0;
936 unsigned NumReadWrites = 0;
937
938 PtrRtCheck.Pointers.clear();
939 PtrRtCheck.Need = false;
940
941 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +0000942
943 // For each block.
944 for (Loop::block_iterator bb = TheLoop->block_begin(),
945 be = TheLoop->block_end(); bb != be; ++bb) {
946
947 // Scan the BB and collect legal loads and stores.
948 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
949 ++it) {
950
951 // If this is a load, save it. If this instruction can read from memory
952 // but is not a load, then we quit. Notice that we don't handle function
953 // calls that read or write.
954 if (it->mayReadFromMemory()) {
955 // Many math library functions read the rounding mode. We will only
956 // vectorize a loop if it contains known function calls that don't set
957 // the flag. Therefore, it is safe to ignore this read from memory.
958 CallInst *Call = dyn_cast<CallInst>(it);
959 if (Call && getIntrinsicIDForCall(Call, TLI))
960 continue;
961
962 LoadInst *Ld = dyn_cast<LoadInst>(it);
963 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000964 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +0000965 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +0000966 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000967 CanVecMem = false;
968 return;
Adam Nemet04563272015-02-01 16:56:15 +0000969 }
970 NumLoads++;
971 Loads.push_back(Ld);
972 DepChecker.addAccess(Ld);
973 continue;
974 }
975
976 // Save 'store' instructions. Abort if other instructions write to memory.
977 if (it->mayWriteToMemory()) {
978 StoreInst *St = dyn_cast<StoreInst>(it);
979 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000980 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +0000981 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +0000982 CanVecMem = false;
983 return;
Adam Nemet04563272015-02-01 16:56:15 +0000984 }
985 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000986 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +0000987 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +0000988 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000989 CanVecMem = false;
990 return;
Adam Nemet04563272015-02-01 16:56:15 +0000991 }
992 NumStores++;
993 Stores.push_back(St);
994 DepChecker.addAccess(St);
995 }
996 } // Next instr.
997 } // Next block.
998
999 // Now we have two lists that hold the loads and the stores.
1000 // Next, we find the pointers that they use.
1001
1002 // Check if we see any stores. If there are no stores, then we don't
1003 // care if the pointers are *restrict*.
1004 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001005 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001006 CanVecMem = true;
1007 return;
Adam Nemet04563272015-02-01 16:56:15 +00001008 }
1009
Adam Nemetdee666b2015-03-10 17:40:34 +00001010 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001011 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1012 AA, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001013
1014 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1015 // multiple times on the same object. If the ptr is accessed twice, once
1016 // for read and once for write, it will only appear once (on the write
1017 // list). This is okay, since we are going to check for conflicts between
1018 // writes and between reads and writes, but not between reads and reads.
1019 ValueSet Seen;
1020
1021 ValueVector::iterator I, IE;
1022 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1023 StoreInst *ST = cast<StoreInst>(*I);
1024 Value* Ptr = ST->getPointerOperand();
1025
1026 if (isUniform(Ptr)) {
1027 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001028 LoopAccessReport(ST)
Adam Nemet04563272015-02-01 16:56:15 +00001029 << "write to a loop invariant address could not be vectorized");
Adam Nemet339f42b2015-02-19 19:15:07 +00001030 DEBUG(dbgs() << "LAA: We don't allow storing to uniform addresses\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001031 CanVecMem = false;
1032 return;
Adam Nemet04563272015-02-01 16:56:15 +00001033 }
1034
1035 // If we did *not* see this pointer before, insert it to the read-write
1036 // list. At this phase it is only a 'write' list.
1037 if (Seen.insert(Ptr).second) {
1038 ++NumReadWrites;
1039
1040 AliasAnalysis::Location Loc = AA->getLocation(ST);
1041 // The TBAA metadata could have a control dependency on the predication
1042 // condition, so we cannot rely on it when determining whether or not we
1043 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001044 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001045 Loc.AATags.TBAA = nullptr;
1046
1047 Accesses.addStore(Loc);
1048 }
1049 }
1050
1051 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001052 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001053 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001054 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001055 CanVecMem = true;
1056 return;
Adam Nemet04563272015-02-01 16:56:15 +00001057 }
1058
1059 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1060 LoadInst *LD = cast<LoadInst>(*I);
1061 Value* Ptr = LD->getPointerOperand();
1062 // If we did *not* see this pointer before, insert it to the
1063 // read list. If we *did* see it before, then it is already in
1064 // the read-write list. This allows us to vectorize expressions
1065 // such as A[i] += x; Because the address of A[i] is a read-write
1066 // pointer. This only works if the index of A[i] is consecutive.
1067 // If the address of i is unknown (for example A[B[i]]) then we may
1068 // read a few words, modify, and write a few words, and some of the
1069 // words may be written to the same address.
1070 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001071 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001072 ++NumReads;
1073 IsReadOnlyPtr = true;
1074 }
1075
1076 AliasAnalysis::Location Loc = AA->getLocation(LD);
1077 // The TBAA metadata could have a control dependency on the predication
1078 // condition, so we cannot rely on it when determining whether or not we
1079 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001080 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001081 Loc.AATags.TBAA = nullptr;
1082
1083 Accesses.addLoad(Loc, IsReadOnlyPtr);
1084 }
1085
1086 // If we write (or read-write) to a single destination and there are no
1087 // other reads in this loop then is it safe to vectorize.
1088 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001089 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001090 CanVecMem = true;
1091 return;
Adam Nemet04563272015-02-01 16:56:15 +00001092 }
1093
1094 // Build dependence sets and check whether we need a runtime pointer bounds
1095 // check.
1096 Accesses.buildDependenceSets();
1097 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1098
1099 // Find pointers with computable bounds. We are going to use this information
1100 // to place a runtime bound check.
Adam Nemet04563272015-02-01 16:56:15 +00001101 bool CanDoRT = false;
1102 if (NeedRTCheck)
1103 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1104 Strides);
1105
Adam Nemet339f42b2015-02-19 19:15:07 +00001106 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
Adam Nemet04d41632015-02-19 19:14:34 +00001107 " pointer comparisons.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001108
1109 // If we only have one set of dependences to check pointers among we don't
1110 // need a runtime check.
1111 if (NumComparisons == 0 && NeedRTCheck)
1112 NeedRTCheck = false;
1113
Adam Nemet949e91a2015-03-10 19:12:41 +00001114 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001115 if (CanDoRT)
Adam Nemet339f42b2015-02-19 19:15:07 +00001116 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001117 else if (NeedRTCheck) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001118 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemet339f42b2015-02-19 19:15:07 +00001119 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
Adam Nemet04d41632015-02-19 19:14:34 +00001120 "the array bounds.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001121 PtrRtCheck.reset();
Adam Nemet436018c2015-02-19 19:15:00 +00001122 CanVecMem = false;
1123 return;
Adam Nemet04563272015-02-01 16:56:15 +00001124 }
1125
1126 PtrRtCheck.Need = NeedRTCheck;
1127
Adam Nemet436018c2015-02-19 19:15:00 +00001128 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001129 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001130 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001131 CanVecMem = DepChecker.areDepsSafe(
1132 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1133 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1134
1135 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001136 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001137 NeedRTCheck = true;
1138
1139 // Clear the dependency checks. We assume they are not needed.
1140 Accesses.resetDepChecks();
1141
1142 PtrRtCheck.reset();
1143 PtrRtCheck.Need = true;
1144
1145 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1146 TheLoop, Strides, true);
Adam Nemet949e91a2015-03-10 19:12:41 +00001147 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001148 if (!CanDoRT && NumComparisons > 0) {
1149 emitAnalysis(LoopAccessReport()
1150 << "cannot check memory dependencies at runtime");
1151 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1152 PtrRtCheck.reset();
1153 CanVecMem = false;
1154 return;
1155 }
1156
Adam Nemet04563272015-02-01 16:56:15 +00001157 CanVecMem = true;
1158 }
1159 }
1160
1161 if (!CanVecMem)
Adam Nemet2bd6e982015-02-19 19:15:15 +00001162 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001163 "unsafe dependent memory operations in loop");
Adam Nemet04563272015-02-01 16:56:15 +00001164
Adam Nemet339f42b2015-02-19 19:15:07 +00001165 DEBUG(dbgs() << "LAA: We" << (NeedRTCheck ? "" : " don't") <<
Adam Nemet04d41632015-02-19 19:14:34 +00001166 " need a runtime memory check.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001167}
1168
Adam Nemet01abb2c2015-02-18 03:43:19 +00001169bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1170 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001171 assert(TheLoop->contains(BB) && "Unknown block used");
1172
1173 // Blocks that do not dominate the latch need predication.
1174 BasicBlock* Latch = TheLoop->getLoopLatch();
1175 return !DT->dominates(BB, Latch);
1176}
1177
Adam Nemet2bd6e982015-02-19 19:15:15 +00001178void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001179 assert(!Report && "Multiple reports generated");
1180 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001181}
1182
Adam Nemet57ac7662015-02-19 19:15:21 +00001183bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001184 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1185}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001186
1187// FIXME: this function is currently a duplicate of the one in
1188// LoopVectorize.cpp.
1189static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1190 Instruction *Loc) {
1191 if (FirstInst)
1192 return FirstInst;
1193 if (Instruction *I = dyn_cast<Instruction>(V))
1194 return I->getParent() == Loc->getParent() ? I : nullptr;
1195 return nullptr;
1196}
1197
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001198std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1199 Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemet7206d7a2015-02-06 18:31:04 +00001200 Instruction *tnullptr = nullptr;
1201 if (!PtrRtCheck.Need)
1202 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1203
1204 unsigned NumPointers = PtrRtCheck.Pointers.size();
1205 SmallVector<TrackingVH<Value> , 2> Starts;
1206 SmallVector<TrackingVH<Value> , 2> Ends;
1207
1208 LLVMContext &Ctx = Loc->getContext();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001209 SCEVExpander Exp(*SE, DL, "induction");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001210 Instruction *FirstInst = nullptr;
1211
1212 for (unsigned i = 0; i < NumPointers; ++i) {
1213 Value *Ptr = PtrRtCheck.Pointers[i];
1214 const SCEV *Sc = SE->getSCEV(Ptr);
1215
1216 if (SE->isLoopInvariant(Sc, TheLoop)) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001217 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
Adam Nemet04d41632015-02-19 19:14:34 +00001218 *Ptr <<"\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001219 Starts.push_back(Ptr);
1220 Ends.push_back(Ptr);
1221 } else {
Adam Nemet339f42b2015-02-19 19:15:07 +00001222 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
Adam Nemet7206d7a2015-02-06 18:31:04 +00001223 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1224
1225 // Use this type for pointer arithmetic.
1226 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1227
1228 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1229 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1230 Starts.push_back(Start);
1231 Ends.push_back(End);
1232 }
1233 }
1234
1235 IRBuilder<> ChkBuilder(Loc);
1236 // Our instructions might fold to a constant.
1237 Value *MemoryRuntimeCheck = nullptr;
1238 for (unsigned i = 0; i < NumPointers; ++i) {
1239 for (unsigned j = i+1; j < NumPointers; ++j) {
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001240 if (!PtrRtCheck.needsChecking(i, j, PtrPartition))
Adam Nemet7206d7a2015-02-06 18:31:04 +00001241 continue;
1242
1243 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1244 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1245
1246 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1247 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1248 "Trying to bounds check pointers with different address spaces");
1249
1250 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1251 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1252
1253 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1254 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1255 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1256 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1257
1258 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1259 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1260 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1261 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1262 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1263 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1264 if (MemoryRuntimeCheck) {
1265 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1266 "conflict.rdx");
1267 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1268 }
1269 MemoryRuntimeCheck = IsConflict;
1270 }
1271 }
1272
1273 // We have to do this trickery because the IRBuilder might fold the check to a
1274 // constant expression in which case there is no Instruction anchored in a
1275 // the block.
1276 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1277 ConstantInt::getTrue(Ctx));
1278 ChkBuilder.Insert(Check, "memcheck.conflict");
1279 FirstInst = getFirstInst(FirstInst, Check, Loc);
1280 return std::make_pair(FirstInst, Check);
1281}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001282
1283LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001284 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001285 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001286 DominatorTree *DT,
1287 const ValueToValueMap &Strides)
Adam Nemet98c4c5d2015-03-10 18:54:23 +00001288 : DepChecker(SE, L), NumComparisons(0), TheLoop(L), SE(SE), DL(DL),
1289 TLI(TLI), AA(AA), DT(DT), NumLoads(0), NumStores(0),
1290 MaxSafeDepDistBytes(-1U), CanVecMem(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001291 if (canAnalyzeLoop())
1292 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001293}
1294
Adam Nemete91cc6e2015-02-19 19:15:19 +00001295void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1296 if (CanVecMem) {
1297 if (PtrRtCheck.empty())
1298 OS.indent(Depth) << "Memory dependences are safe\n";
1299 else
1300 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
1301 }
1302
1303 if (Report)
1304 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1305
Adam Nemet58913d62015-03-10 17:40:43 +00001306 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1307 OS.indent(Depth) << "Interesting Dependences:\n";
1308 for (auto &Dep : *InterestingDependences) {
1309 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1310 OS << "\n";
1311 }
1312 } else
1313 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001314
1315 // List the pair of accesses need run-time checks to prove independence.
1316 PtrRtCheck.print(OS, Depth);
1317 OS << "\n";
1318}
1319
Adam Nemet8bc61df2015-02-24 00:41:59 +00001320const LoopAccessInfo &
1321LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001322 auto &LAI = LoopAccessInfoMap[L];
1323
1324#ifndef NDEBUG
1325 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1326 "Symbolic strides changed for loop");
1327#endif
1328
1329 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001330 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001331 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1332#ifndef NDEBUG
1333 LAI->NumSymbolicStrides = Strides.size();
1334#endif
1335 }
1336 return *LAI.get();
1337}
1338
Adam Nemete91cc6e2015-02-19 19:15:19 +00001339void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1340 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1341
1342 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1343 ValueToValueMap NoSymbolicStrides;
1344
1345 for (Loop *TopLevelLoop : *LI)
1346 for (Loop *L : depth_first(TopLevelLoop)) {
1347 OS.indent(2) << L->getHeader()->getName() << ":\n";
1348 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1349 LAI.print(OS, 4);
1350 }
1351}
1352
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001353bool LoopAccessAnalysis::runOnFunction(Function &F) {
1354 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001355 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1356 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1357 AA = &getAnalysis<AliasAnalysis>();
1358 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1359
1360 return false;
1361}
1362
1363void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1364 AU.addRequired<ScalarEvolution>();
1365 AU.addRequired<AliasAnalysis>();
1366 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001367 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001368
1369 AU.setPreservesAll();
1370}
1371
1372char LoopAccessAnalysis::ID = 0;
1373static const char laa_name[] = "Loop Access Analysis";
1374#define LAA_NAME "loop-accesses"
1375
1376INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1377INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1378INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1379INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001380INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001381INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1382
1383namespace llvm {
1384 Pass *createLAAPass() {
1385 return new LoopAccessAnalysis();
1386 }
1387}