blob: 2e8b6f44490d7ae6a7a4c87dde44219c5f18d880 [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"
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +000024#include "llvm/Analysis/TargetLibraryInfo.h"
Adam Nemet04563272015-02-01 16:56:15 +000025using namespace llvm;
26
Adam Nemet339f42b2015-02-19 19:15:07 +000027#define DEBUG_TYPE "loop-accesses"
Adam Nemet04563272015-02-01 16:56:15 +000028
Adam Nemetf219c642015-02-19 19:14:52 +000029static cl::opt<unsigned, true>
30VectorizationFactor("force-vector-width", cl::Hidden,
31 cl::desc("Sets the SIMD width. Zero is autoselect."),
32 cl::location(VectorizerParams::VectorizationFactor));
Adam Nemet1d862af2015-02-26 04:39:09 +000033unsigned VectorizerParams::VectorizationFactor;
Adam Nemetf219c642015-02-19 19:14:52 +000034
35static cl::opt<unsigned, true>
36VectorizationInterleave("force-vector-interleave", cl::Hidden,
37 cl::desc("Sets the vectorization interleave count. "
38 "Zero is autoselect."),
39 cl::location(
40 VectorizerParams::VectorizationInterleave));
Adam Nemet1d862af2015-02-26 04:39:09 +000041unsigned VectorizerParams::VectorizationInterleave;
Adam Nemetf219c642015-02-19 19:14:52 +000042
Adam Nemet1d862af2015-02-26 04:39:09 +000043static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
44 "runtime-memory-check-threshold", cl::Hidden,
45 cl::desc("When performing memory disambiguation checks at runtime do not "
46 "generate more than this number of comparisons (default = 8)."),
47 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
48unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
Adam Nemetf219c642015-02-19 19:14:52 +000049
50/// Maximum SIMD width.
51const unsigned VectorizerParams::MaxVectorWidth = 64;
52
Adam Nemet9c926572015-03-10 17:40:37 +000053/// \brief We collect interesting dependences up to this threshold.
54static cl::opt<unsigned> MaxInterestingDependence(
55 "max-interesting-dependences", cl::Hidden,
56 cl::desc("Maximum number of interesting dependences collected by "
57 "loop-access analysis (default = 100)"),
58 cl::init(100));
59
Adam Nemetf219c642015-02-19 19:14:52 +000060bool VectorizerParams::isInterleaveForced() {
61 return ::VectorizationInterleave.getNumOccurrences() > 0;
62}
63
Adam Nemet2bd6e982015-02-19 19:15:15 +000064void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
65 const Function *TheFunction,
66 const Loop *TheLoop,
67 const char *PassName) {
Adam Nemet04563272015-02-01 16:56:15 +000068 DebugLoc DL = TheLoop->getStartLoc();
Adam Nemet3e876342015-02-19 19:15:13 +000069 if (const Instruction *I = Message.getInstr())
Adam Nemet04563272015-02-01 16:56:15 +000070 DL = I->getDebugLoc();
Adam Nemet339f42b2015-02-19 19:15:07 +000071 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
Adam Nemet04563272015-02-01 16:56:15 +000072 *TheFunction, DL, Message.str());
73}
74
75Value *llvm::stripIntegerCast(Value *V) {
76 if (CastInst *CI = dyn_cast<CastInst>(V))
77 if (CI->getOperand(0)->getType()->isIntegerTy())
78 return CI->getOperand(0);
79 return V;
80}
81
82const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
Adam Nemet8bc61df2015-02-24 00:41:59 +000083 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +000084 Value *Ptr, Value *OrigPtr) {
85
86 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
87
88 // If there is an entry in the map return the SCEV of the pointer with the
89 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +000090 ValueToValueMap::const_iterator SI =
91 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +000092 if (SI != PtrToStride.end()) {
93 Value *StrideVal = SI->second;
94
95 // Strip casts.
96 StrideVal = stripIntegerCast(StrideVal);
97
98 // Replace symbolic stride by one.
99 Value *One = ConstantInt::get(StrideVal->getType(), 1);
100 ValueToValueMap RewriteMap;
101 RewriteMap[StrideVal] = One;
102
103 const SCEV *ByOne =
104 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
Adam Nemet339f42b2015-02-19 19:15:07 +0000105 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
Adam Nemet04563272015-02-01 16:56:15 +0000106 << "\n");
107 return ByOne;
108 }
109
110 // Otherwise, just return the SCEV of the original pointer.
111 return SE->getSCEV(Ptr);
112}
113
Adam Nemet8bc61df2015-02-24 00:41:59 +0000114void LoopAccessInfo::RuntimePointerCheck::insert(
115 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
116 unsigned ASId, const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000117 // Get the stride replaced scev.
118 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
119 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
120 assert(AR && "Invalid addrec expression");
121 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
122 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
123 Pointers.push_back(Ptr);
124 Starts.push_back(AR->getStart());
125 Ends.push_back(ScEnd);
126 IsWritePtr.push_back(WritePtr);
127 DependencySetId.push_back(DepSetId);
128 AliasSetId.push_back(ASId);
129}
130
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000131bool LoopAccessInfo::RuntimePointerCheck::needsChecking(
132 unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemeta8945b72015-02-18 03:43:58 +0000133 // No need to check if two readonly pointers intersect.
134 if (!IsWritePtr[I] && !IsWritePtr[J])
135 return false;
136
137 // Only need to check pointers between two different dependency sets.
138 if (DependencySetId[I] == DependencySetId[J])
139 return false;
140
141 // Only need to check pointers in the same alias set.
142 if (AliasSetId[I] != AliasSetId[J])
143 return false;
144
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000145 // If PtrPartition is set omit checks between pointers of the same partition.
146 // Partition number -1 means that the pointer is used in multiple partitions.
147 // In this case we can't omit the check.
148 if (PtrPartition && (*PtrPartition)[I] != -1 &&
149 (*PtrPartition)[I] == (*PtrPartition)[J])
150 return false;
151
Adam Nemeta8945b72015-02-18 03:43:58 +0000152 return true;
153}
154
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000155void LoopAccessInfo::RuntimePointerCheck::print(
156 raw_ostream &OS, unsigned Depth,
157 const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000158 unsigned NumPointers = Pointers.size();
159 if (NumPointers == 0)
160 return;
161
162 OS.indent(Depth) << "Run-time memory checks:\n";
163 unsigned N = 0;
164 for (unsigned I = 0; I < NumPointers; ++I)
165 for (unsigned J = I + 1; J < NumPointers; ++J)
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000166 if (needsChecking(I, J, PtrPartition)) {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000167 OS.indent(Depth) << N++ << ":\n";
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000168 OS.indent(Depth + 2) << *Pointers[I];
169 if (PtrPartition)
170 OS << " (Partition: " << (*PtrPartition)[I] << ")";
171 OS << "\n";
172 OS.indent(Depth + 2) << *Pointers[J];
173 if (PtrPartition)
174 OS << " (Partition: " << (*PtrPartition)[J] << ")";
175 OS << "\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +0000176 }
177}
178
Adam Nemet04563272015-02-01 16:56:15 +0000179namespace {
180/// \brief Analyses memory accesses in a loop.
181///
182/// Checks whether run time pointer checks are needed and builds sets for data
183/// dependence checking.
184class AccessAnalysis {
185public:
186 /// \brief Read or write access location.
187 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
188 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
189
Adam Nemetdee666b2015-03-10 17:40:34 +0000190 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA,
191 MemoryDepChecker::DepCandidates &DA)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000192 : DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000193
194 /// \brief Register a load and whether it is only read from.
195 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
196 Value *Ptr = const_cast<Value*>(Loc.Ptr);
197 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
198 Accesses.insert(MemAccessInfo(Ptr, false));
199 if (IsReadOnly)
200 ReadOnlyPtr.insert(Ptr);
201 }
202
203 /// \brief Register a store.
204 void addStore(AliasAnalysis::Location &Loc) {
205 Value *Ptr = const_cast<Value*>(Loc.Ptr);
206 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
207 Accesses.insert(MemAccessInfo(Ptr, true));
208 }
209
210 /// \brief Check whether we can check the pointers at runtime for
211 /// non-intersection.
Adam Nemet30f16e12015-02-18 03:42:35 +0000212 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000213 unsigned &NumComparisons, ScalarEvolution *SE,
214 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000215 bool ShouldCheckStride = false);
216
217 /// \brief Goes over all memory accesses, checks whether a RT check is needed
218 /// and builds sets of dependent accesses.
219 void buildDependenceSets() {
220 processMemAccesses();
221 }
222
223 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
224
225 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
226 void resetDepChecks() { CheckDeps.clear(); }
227
228 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
229
230private:
231 typedef SetVector<MemAccessInfo> PtrAccessSet;
232
233 /// \brief Go over all memory access and check whether runtime pointer checks
234 /// are needed /// and build sets of dependency check candidates.
235 void processMemAccesses();
236
237 /// Set of all accesses.
238 PtrAccessSet Accesses;
239
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000240 const DataLayout &DL;
241
Adam Nemet04563272015-02-01 16:56:15 +0000242 /// Set of accesses that need a further dependence check.
243 MemAccessInfoSet CheckDeps;
244
245 /// Set of pointers that are read only.
246 SmallPtrSet<Value*, 16> ReadOnlyPtr;
247
Adam Nemet04563272015-02-01 16:56:15 +0000248 /// An alias set tracker to partition the access set by underlying object and
249 //intrinsic property (such as TBAA metadata).
250 AliasSetTracker AST;
251
252 /// Sets of potentially dependent accesses - members of one set share an
253 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
254 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000255 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000256
257 bool IsRTCheckNeeded;
258};
259
260} // end anonymous namespace
261
262/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000263static bool hasComputableBounds(ScalarEvolution *SE,
264 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000265 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
266 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
267 if (!AR)
268 return false;
269
270 return AR->isAffine();
271}
272
273/// \brief Check the stride of the pointer and ensure that it does not wrap in
274/// the address space.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000275static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
276 const ValueToValueMap &StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000277
278bool AccessAnalysis::canCheckPtrAtRT(
Adam Nemet8bc61df2015-02-24 00:41:59 +0000279 LoopAccessInfo::RuntimePointerCheck &RtCheck, unsigned &NumComparisons,
280 ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
281 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000282 // Find pointers with computable bounds. We are going to use this information
283 // to place a runtime bound check.
284 bool CanDoRT = true;
285
286 bool IsDepCheckNeeded = isDependencyCheckNeeded();
287 NumComparisons = 0;
288
289 // We assign a consecutive id to access from different alias sets.
290 // Accesses between different groups doesn't need to be checked.
291 unsigned ASId = 1;
292 for (auto &AS : AST) {
293 unsigned NumReadPtrChecks = 0;
294 unsigned NumWritePtrChecks = 0;
295
296 // We assign consecutive id to access from different dependence sets.
297 // Accesses within the same set don't need a runtime check.
298 unsigned RunningDepId = 1;
299 DenseMap<Value *, unsigned> DepSetId;
300
301 for (auto A : AS) {
302 Value *Ptr = A.getValue();
303 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
304 MemAccessInfo Access(Ptr, IsWrite);
305
306 if (IsWrite)
307 ++NumWritePtrChecks;
308 else
309 ++NumReadPtrChecks;
310
311 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000312 // When we run after a failing dependency check we have to make sure
313 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000314 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000315 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000316 // The id of the dependence set.
317 unsigned DepId;
318
319 if (IsDepCheckNeeded) {
320 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
321 unsigned &LeaderId = DepSetId[Leader];
322 if (!LeaderId)
323 LeaderId = RunningDepId++;
324 DepId = LeaderId;
325 } else
326 // Each access has its own dependence set.
327 DepId = RunningDepId++;
328
329 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
330
Adam Nemet339f42b2015-02-19 19:15:07 +0000331 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000332 } else {
333 CanDoRT = false;
334 }
335 }
336
337 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
338 NumComparisons += 0; // Only one dependence set.
339 else {
340 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
341 NumWritePtrChecks - 1));
342 }
343
344 ++ASId;
345 }
346
347 // If the pointers that we would use for the bounds comparison have different
348 // address spaces, assume the values aren't directly comparable, so we can't
349 // use them for the runtime check. We also have to assume they could
350 // overlap. In the future there should be metadata for whether address spaces
351 // are disjoint.
352 unsigned NumPointers = RtCheck.Pointers.size();
353 for (unsigned i = 0; i < NumPointers; ++i) {
354 for (unsigned j = i + 1; j < NumPointers; ++j) {
355 // Only need to check pointers between two different dependency sets.
356 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
357 continue;
358 // Only need to check pointers in the same alias set.
359 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
360 continue;
361
362 Value *PtrI = RtCheck.Pointers[i];
363 Value *PtrJ = RtCheck.Pointers[j];
364
365 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
366 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
367 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000368 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000369 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000370 return false;
371 }
372 }
373 }
374
375 return CanDoRT;
376}
377
378void AccessAnalysis::processMemAccesses() {
379 // We process the set twice: first we process read-write pointers, last we
380 // process read-only pointers. This allows us to skip dependence tests for
381 // read-only pointers.
382
Adam Nemet339f42b2015-02-19 19:15:07 +0000383 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000384 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000385 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000386 DEBUG({
387 for (auto A : Accesses)
388 dbgs() << "\t" << *A.getPointer() << " (" <<
389 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
390 "read-only" : "read")) << ")\n";
391 });
392
393 // The AliasSetTracker has nicely partitioned our pointers by metadata
394 // compatibility and potential for underlying-object overlap. As a result, we
395 // only need to check for potential pointer dependencies within each alias
396 // set.
397 for (auto &AS : AST) {
398 // Note that both the alias-set tracker and the alias sets themselves used
399 // linked lists internally and so the iteration order here is deterministic
400 // (matching the original instruction order within each set).
401
402 bool SetHasWrite = false;
403
404 // Map of pointers to last access encountered.
405 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
406 UnderlyingObjToAccessMap ObjToLastAccess;
407
408 // Set of access to check after all writes have been processed.
409 PtrAccessSet DeferredAccesses;
410
411 // Iterate over each alias set twice, once to process read/write pointers,
412 // and then to process read-only pointers.
413 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
414 bool UseDeferred = SetIteration > 0;
415 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
416
417 for (auto AV : AS) {
418 Value *Ptr = AV.getValue();
419
420 // For a single memory access in AliasSetTracker, Accesses may contain
421 // both read and write, and they both need to be handled for CheckDeps.
422 for (auto AC : S) {
423 if (AC.getPointer() != Ptr)
424 continue;
425
426 bool IsWrite = AC.getInt();
427
428 // If we're using the deferred access set, then it contains only
429 // reads.
430 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
431 if (UseDeferred && !IsReadOnlyPtr)
432 continue;
433 // Otherwise, the pointer must be in the PtrAccessSet, either as a
434 // read or a write.
435 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
436 S.count(MemAccessInfo(Ptr, false))) &&
437 "Alias-set pointer not in the access set?");
438
439 MemAccessInfo Access(Ptr, IsWrite);
440 DepCands.insert(Access);
441
442 // Memorize read-only pointers for later processing and skip them in
443 // the first round (they need to be checked after we have seen all
444 // write pointers). Note: we also mark pointer that are not
445 // consecutive as "read-only" pointers (so that we check
446 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
447 if (!UseDeferred && IsReadOnlyPtr) {
448 DeferredAccesses.insert(Access);
449 continue;
450 }
451
452 // If this is a write - check other reads and writes for conflicts. If
453 // this is a read only check other writes for conflicts (but only if
454 // there is no other write to the ptr - this is an optimization to
455 // catch "a[i] = a[i] + " without having to do a dependence check).
456 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
457 CheckDeps.insert(Access);
458 IsRTCheckNeeded = true;
459 }
460
461 if (IsWrite)
462 SetHasWrite = true;
463
464 // Create sets of pointers connected by a shared alias set and
465 // underlying object.
466 typedef SmallVector<Value *, 16> ValueVector;
467 ValueVector TempObjects;
468 GetUnderlyingObjects(Ptr, TempObjects, DL);
469 for (Value *UnderlyingObj : TempObjects) {
470 UnderlyingObjToAccessMap::iterator Prev =
471 ObjToLastAccess.find(UnderlyingObj);
472 if (Prev != ObjToLastAccess.end())
473 DepCands.unionSets(Access, Prev->second);
474
475 ObjToLastAccess[UnderlyingObj] = Access;
476 }
477 }
478 }
479 }
480 }
481}
482
Adam Nemet04563272015-02-01 16:56:15 +0000483static bool isInBoundsGep(Value *Ptr) {
484 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
485 return GEP->isInBounds();
486 return false;
487}
488
489/// \brief Check whether the access through \p Ptr has a constant stride.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000490static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
491 const ValueToValueMap &StridesMap) {
Adam Nemet04563272015-02-01 16:56:15 +0000492 const Type *Ty = Ptr->getType();
493 assert(Ty->isPointerTy() && "Unexpected non-ptr");
494
495 // Make sure that the pointer does not point to aggregate types.
496 const PointerType *PtrTy = cast<PointerType>(Ty);
497 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000498 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
499 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000500 return 0;
501 }
502
503 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
504
505 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
506 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000507 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000508 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000509 return 0;
510 }
511
512 // The accesss function must stride over the innermost loop.
513 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000514 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000515 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000516 }
517
518 // The address calculation must not wrap. Otherwise, a dependence could be
519 // inverted.
520 // An inbounds getelementptr that is a AddRec with a unit stride
521 // cannot wrap per definition. The unit stride requirement is checked later.
522 // An getelementptr without an inbounds attribute and unit stride would have
523 // to access the pointer value "0" which is undefined behavior in address
524 // space 0, therefore we can also vectorize this case.
525 bool IsInBoundsGEP = isInBoundsGep(Ptr);
526 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
527 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
528 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000529 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000530 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000531 return 0;
532 }
533
534 // Check the step is constant.
535 const SCEV *Step = AR->getStepRecurrence(*SE);
536
537 // Calculate the pointer stride and check if it is consecutive.
538 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
539 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000540 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000541 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000542 return 0;
543 }
544
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000545 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
546 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000547 const APInt &APStepVal = C->getValue()->getValue();
548
549 // Huge step value - give up.
550 if (APStepVal.getBitWidth() > 64)
551 return 0;
552
553 int64_t StepVal = APStepVal.getSExtValue();
554
555 // Strided access.
556 int64_t Stride = StepVal / Size;
557 int64_t Rem = StepVal % Size;
558 if (Rem)
559 return 0;
560
561 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
562 // know we can't "wrap around the address space". In case of address space
563 // zero we know that this won't happen without triggering undefined behavior.
564 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
565 Stride != 1 && Stride != -1)
566 return 0;
567
568 return Stride;
569}
570
Adam Nemet9c926572015-03-10 17:40:37 +0000571bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
572 switch (Type) {
573 case NoDep:
574 case Forward:
575 case BackwardVectorizable:
576 return true;
577
578 case Unknown:
579 case ForwardButPreventsForwarding:
580 case Backward:
581 case BackwardVectorizableButPreventsForwarding:
582 return false;
583 }
David Majnemerd388e932015-03-10 20:23:29 +0000584 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000585}
586
587bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
588 switch (Type) {
589 case NoDep:
590 case Forward:
591 return false;
592
593 case BackwardVectorizable:
594 case Unknown:
595 case ForwardButPreventsForwarding:
596 case Backward:
597 case BackwardVectorizableButPreventsForwarding:
598 return true;
599 }
David Majnemerd388e932015-03-10 20:23:29 +0000600 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000601}
602
603bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
604 switch (Type) {
605 case NoDep:
606 case Forward:
607 case ForwardButPreventsForwarding:
608 return false;
609
610 case Unknown:
611 case BackwardVectorizable:
612 case Backward:
613 case BackwardVectorizableButPreventsForwarding:
614 return true;
615 }
David Majnemerd388e932015-03-10 20:23:29 +0000616 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000617}
618
Adam Nemet04563272015-02-01 16:56:15 +0000619bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
620 unsigned TypeByteSize) {
621 // If loads occur at a distance that is not a multiple of a feasible vector
622 // factor store-load forwarding does not take place.
623 // Positive dependences might cause troubles because vectorizing them might
624 // prevent store-load forwarding making vectorized code run a lot slower.
625 // a[i] = a[i-3] ^ a[i-8];
626 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
627 // hence on your typical architecture store-load forwarding does not take
628 // place. Vectorizing in such cases does not make sense.
629 // Store-load forwarding distance.
630 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
631 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000632 unsigned MaxVFWithoutSLForwardIssues =
633 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000634 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000635 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
636
637 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
638 vf *= 2) {
639 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
640 MaxVFWithoutSLForwardIssues = (vf >>=1);
641 break;
642 }
643 }
644
Adam Nemet04d41632015-02-19 19:14:34 +0000645 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000646 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000647 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000648 return true;
649 }
650
651 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000652 MaxVFWithoutSLForwardIssues !=
653 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000654 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
655 return false;
656}
657
Adam Nemet9c926572015-03-10 17:40:37 +0000658MemoryDepChecker::Dependence::DepType
659MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
660 const MemAccessInfo &B, unsigned BIdx,
661 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000662 assert (AIdx < BIdx && "Must pass arguments in program order");
663
664 Value *APtr = A.getPointer();
665 Value *BPtr = B.getPointer();
666 bool AIsWrite = A.getInt();
667 bool BIsWrite = B.getInt();
668
669 // Two reads are independent.
670 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +0000671 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +0000672
673 // We cannot check pointers in different address spaces.
674 if (APtr->getType()->getPointerAddressSpace() !=
675 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +0000676 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000677
678 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
679 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
680
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000681 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
682 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +0000683
684 const SCEV *Src = AScev;
685 const SCEV *Sink = BScev;
686
687 // If the induction step is negative we have to invert source and sink of the
688 // dependence.
689 if (StrideAPtr < 0) {
690 //Src = BScev;
691 //Sink = AScev;
692 std::swap(APtr, BPtr);
693 std::swap(Src, Sink);
694 std::swap(AIsWrite, BIsWrite);
695 std::swap(AIdx, BIdx);
696 std::swap(StrideAPtr, StrideBPtr);
697 }
698
699 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
700
Adam Nemet339f42b2015-02-19 19:15:07 +0000701 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +0000702 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +0000703 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +0000704 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000705
706 // Need consecutive accesses. We don't want to vectorize
707 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
708 // the address space.
709 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
710 DEBUG(dbgs() << "Non-consecutive pointer access\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000711 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000712 }
713
714 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
715 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000716 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +0000717 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +0000718 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000719 }
720
721 Type *ATy = APtr->getType()->getPointerElementType();
722 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000723 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
724 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +0000725
726 // Negative distances are not plausible dependencies.
727 const APInt &Val = C->getValue()->getValue();
728 if (Val.isNegative()) {
729 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
730 if (IsTrueDataDependence &&
731 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
732 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +0000733 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000734
Adam Nemet339f42b2015-02-19 19:15:07 +0000735 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000736 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +0000737 }
738
739 // Write to the same location with the same size.
740 // Could be improved to assert type sizes are the same (i32 == float, etc).
741 if (Val == 0) {
742 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +0000743 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +0000744 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000745 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000746 }
747
748 assert(Val.isStrictlyPositive() && "Expect a positive value");
749
Adam Nemet04563272015-02-01 16:56:15 +0000750 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +0000751 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +0000752 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000753 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000754 }
755
756 unsigned Distance = (unsigned) Val.getZExtValue();
757
758 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +0000759 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
760 VectorizerParams::VectorizationFactor : 1);
761 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
762 VectorizerParams::VectorizationInterleave : 1);
Adam Nemet04563272015-02-01 16:56:15 +0000763
764 // The distance must be bigger than the size needed for a vectorized version
765 // of the operation and the size of the vectorized operation must not be
766 // bigger than the currrent maximum size.
767 if (Distance < 2*TypeByteSize ||
768 2*TypeByteSize > MaxSafeDepDistBytes ||
769 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000770 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
Adam Nemet04d41632015-02-19 19:14:34 +0000771 << Val.getSExtValue() << '\n');
Adam Nemet9c926572015-03-10 17:40:37 +0000772 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +0000773 }
774
Adam Nemet9cc0c392015-02-26 17:58:48 +0000775 // Positive distance bigger than max vectorization factor.
Adam Nemet04563272015-02-01 16:56:15 +0000776 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
777 Distance : MaxSafeDepDistBytes;
778
779 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
780 if (IsTrueDataDependence &&
781 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +0000782 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000783
Adam Nemet339f42b2015-02-19 19:15:07 +0000784 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
Adam Nemet04d41632015-02-19 19:14:34 +0000785 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000786
Adam Nemet9c926572015-03-10 17:40:37 +0000787 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +0000788}
789
Adam Nemetdee666b2015-03-10 17:40:34 +0000790bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +0000791 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000792 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000793
794 MaxSafeDepDistBytes = -1U;
795 while (!CheckDeps.empty()) {
796 MemAccessInfo CurAccess = *CheckDeps.begin();
797
798 // Get the relevant memory access set.
799 EquivalenceClasses<MemAccessInfo>::iterator I =
800 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
801
802 // Check accesses within this set.
803 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
804 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
805
806 // Check every access pair.
807 while (AI != AE) {
808 CheckDeps.erase(*AI);
809 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
810 while (OI != AE) {
811 // Check every accessing instruction pair in program order.
812 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
813 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
814 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
815 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +0000816 auto A = std::make_pair(&*AI, *I1);
817 auto B = std::make_pair(&*OI, *I2);
818
819 assert(*I1 != *I2);
820 if (*I1 > *I2)
821 std::swap(A, B);
822
823 Dependence::DepType Type =
824 isDependent(*A.first, A.second, *B.first, B.second, Strides);
825 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
826
827 // Gather dependences unless we accumulated MaxInterestingDependence
828 // dependences. In that case return as soon as we find the first
829 // unsafe dependence. This puts a limit on this quadratic
830 // algorithm.
831 if (RecordInterestingDependences) {
832 if (Dependence::isInterestingDependence(Type))
833 InterestingDependences.push_back(
834 Dependence(A.second, B.second, Type));
835
836 if (InterestingDependences.size() >= MaxInterestingDependence) {
837 RecordInterestingDependences = false;
838 InterestingDependences.clear();
839 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
840 }
841 }
842 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +0000843 return false;
844 }
845 ++OI;
846 }
847 AI++;
848 }
849 }
Adam Nemet9c926572015-03-10 17:40:37 +0000850
851 DEBUG(dbgs() << "Total Interesting Dependences: "
852 << InterestingDependences.size() << "\n");
853 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +0000854}
855
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000856SmallVector<Instruction *, 4>
857MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
858 MemAccessInfo Access(Ptr, isWrite);
859 auto &IndexVector = Accesses.find(Access)->second;
860
861 SmallVector<Instruction *, 4> Insts;
862 std::transform(IndexVector.begin(), IndexVector.end(),
863 std::back_inserter(Insts),
864 [&](unsigned Idx) { return this->InstMap[Idx]; });
865 return Insts;
866}
867
Adam Nemet58913d62015-03-10 17:40:43 +0000868const char *MemoryDepChecker::Dependence::DepName[] = {
869 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
870 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
871
872void MemoryDepChecker::Dependence::print(
873 raw_ostream &OS, unsigned Depth,
874 const SmallVectorImpl<Instruction *> &Instrs) const {
875 OS.indent(Depth) << DepName[Type] << ":\n";
876 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
877 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
878}
879
Adam Nemet929c38e2015-02-19 19:15:10 +0000880bool LoopAccessInfo::canAnalyzeLoop() {
881 // We can only analyze innermost loops.
882 if (!TheLoop->empty()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000883 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +0000884 return false;
885 }
886
887 // We must have a single backedge.
888 if (TheLoop->getNumBackEdges() != 1) {
889 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000890 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000891 "loop control flow is not understood by analyzer");
892 return false;
893 }
894
895 // We must have a single exiting block.
896 if (!TheLoop->getExitingBlock()) {
897 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000898 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000899 "loop control flow is not understood by analyzer");
900 return false;
901 }
902
903 // We only handle bottom-tested loops, i.e. loop in which the condition is
904 // checked at the end of each iteration. With that we can assume that all
905 // instructions in the loop are executed the same number of times.
906 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
907 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000908 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000909 "loop control flow is not understood by analyzer");
910 return false;
911 }
912
913 // We need to have a loop header.
914 DEBUG(dbgs() << "LAA: Found a loop: " <<
915 TheLoop->getHeader()->getName() << '\n');
916
917 // ScalarEvolution needs to be able to find the exit count.
918 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
919 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000920 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000921 "could not determine number of loop iterations");
922 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
923 return false;
924 }
925
926 return true;
927}
928
Adam Nemet8bc61df2015-02-24 00:41:59 +0000929void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000930
931 typedef SmallVector<Value*, 16> ValueVector;
932 typedef SmallPtrSet<Value*, 16> ValueSet;
933
934 // Holds the Load and Store *instructions*.
935 ValueVector Loads;
936 ValueVector Stores;
937
938 // Holds all the different accesses in the loop.
939 unsigned NumReads = 0;
940 unsigned NumReadWrites = 0;
941
942 PtrRtCheck.Pointers.clear();
943 PtrRtCheck.Need = false;
944
945 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +0000946
947 // For each block.
948 for (Loop::block_iterator bb = TheLoop->block_begin(),
949 be = TheLoop->block_end(); bb != be; ++bb) {
950
951 // Scan the BB and collect legal loads and stores.
952 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
953 ++it) {
954
955 // If this is a load, save it. If this instruction can read from memory
956 // but is not a load, then we quit. Notice that we don't handle function
957 // calls that read or write.
958 if (it->mayReadFromMemory()) {
959 // Many math library functions read the rounding mode. We will only
960 // vectorize a loop if it contains known function calls that don't set
961 // the flag. Therefore, it is safe to ignore this read from memory.
962 CallInst *Call = dyn_cast<CallInst>(it);
963 if (Call && getIntrinsicIDForCall(Call, TLI))
964 continue;
965
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +0000966 // If the function has an explicit vectorized counterpart, we can safely
967 // assume that it can be vectorized.
968 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
969 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
970 continue;
971
Adam Nemet04563272015-02-01 16:56:15 +0000972 LoadInst *Ld = dyn_cast<LoadInst>(it);
973 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000974 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +0000975 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +0000976 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000977 CanVecMem = false;
978 return;
Adam Nemet04563272015-02-01 16:56:15 +0000979 }
980 NumLoads++;
981 Loads.push_back(Ld);
982 DepChecker.addAccess(Ld);
983 continue;
984 }
985
986 // Save 'store' instructions. Abort if other instructions write to memory.
987 if (it->mayWriteToMemory()) {
988 StoreInst *St = dyn_cast<StoreInst>(it);
989 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000990 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +0000991 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +0000992 CanVecMem = false;
993 return;
Adam Nemet04563272015-02-01 16:56:15 +0000994 }
995 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000996 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +0000997 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +0000998 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000999 CanVecMem = false;
1000 return;
Adam Nemet04563272015-02-01 16:56:15 +00001001 }
1002 NumStores++;
1003 Stores.push_back(St);
1004 DepChecker.addAccess(St);
1005 }
1006 } // Next instr.
1007 } // Next block.
1008
1009 // Now we have two lists that hold the loads and the stores.
1010 // Next, we find the pointers that they use.
1011
1012 // Check if we see any stores. If there are no stores, then we don't
1013 // care if the pointers are *restrict*.
1014 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001015 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001016 CanVecMem = true;
1017 return;
Adam Nemet04563272015-02-01 16:56:15 +00001018 }
1019
Adam Nemetdee666b2015-03-10 17:40:34 +00001020 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001021 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
1022 AA, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001023
1024 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1025 // multiple times on the same object. If the ptr is accessed twice, once
1026 // for read and once for write, it will only appear once (on the write
1027 // list). This is okay, since we are going to check for conflicts between
1028 // writes and between reads and writes, but not between reads and reads.
1029 ValueSet Seen;
1030
1031 ValueVector::iterator I, IE;
1032 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1033 StoreInst *ST = cast<StoreInst>(*I);
1034 Value* Ptr = ST->getPointerOperand();
1035
1036 if (isUniform(Ptr)) {
1037 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001038 LoopAccessReport(ST)
Adam Nemet04563272015-02-01 16:56:15 +00001039 << "write to a loop invariant address could not be vectorized");
Adam Nemet339f42b2015-02-19 19:15:07 +00001040 DEBUG(dbgs() << "LAA: We don't allow storing to uniform addresses\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001041 CanVecMem = false;
1042 return;
Adam Nemet04563272015-02-01 16:56:15 +00001043 }
1044
1045 // If we did *not* see this pointer before, insert it to the read-write
1046 // list. At this phase it is only a 'write' list.
1047 if (Seen.insert(Ptr).second) {
1048 ++NumReadWrites;
1049
1050 AliasAnalysis::Location Loc = AA->getLocation(ST);
1051 // The TBAA metadata could have a control dependency on the predication
1052 // condition, so we cannot rely on it when determining whether or not we
1053 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001054 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001055 Loc.AATags.TBAA = nullptr;
1056
1057 Accesses.addStore(Loc);
1058 }
1059 }
1060
1061 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001062 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001063 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001064 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001065 CanVecMem = true;
1066 return;
Adam Nemet04563272015-02-01 16:56:15 +00001067 }
1068
1069 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1070 LoadInst *LD = cast<LoadInst>(*I);
1071 Value* Ptr = LD->getPointerOperand();
1072 // If we did *not* see this pointer before, insert it to the
1073 // read list. If we *did* see it before, then it is already in
1074 // the read-write list. This allows us to vectorize expressions
1075 // such as A[i] += x; Because the address of A[i] is a read-write
1076 // pointer. This only works if the index of A[i] is consecutive.
1077 // If the address of i is unknown (for example A[B[i]]) then we may
1078 // read a few words, modify, and write a few words, and some of the
1079 // words may be written to the same address.
1080 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001081 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001082 ++NumReads;
1083 IsReadOnlyPtr = true;
1084 }
1085
1086 AliasAnalysis::Location Loc = AA->getLocation(LD);
1087 // The TBAA metadata could have a control dependency on the predication
1088 // condition, so we cannot rely on it when determining whether or not we
1089 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001090 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001091 Loc.AATags.TBAA = nullptr;
1092
1093 Accesses.addLoad(Loc, IsReadOnlyPtr);
1094 }
1095
1096 // If we write (or read-write) to a single destination and there are no
1097 // other reads in this loop then is it safe to vectorize.
1098 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001099 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001100 CanVecMem = true;
1101 return;
Adam Nemet04563272015-02-01 16:56:15 +00001102 }
1103
1104 // Build dependence sets and check whether we need a runtime pointer bounds
1105 // check.
1106 Accesses.buildDependenceSets();
1107 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1108
1109 // Find pointers with computable bounds. We are going to use this information
1110 // to place a runtime bound check.
Adam Nemet04563272015-02-01 16:56:15 +00001111 bool CanDoRT = false;
1112 if (NeedRTCheck)
1113 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1114 Strides);
1115
Adam Nemet339f42b2015-02-19 19:15:07 +00001116 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
Adam Nemet04d41632015-02-19 19:14:34 +00001117 " pointer comparisons.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001118
1119 // If we only have one set of dependences to check pointers among we don't
1120 // need a runtime check.
1121 if (NumComparisons == 0 && NeedRTCheck)
1122 NeedRTCheck = false;
1123
Adam Nemet949e91a2015-03-10 19:12:41 +00001124 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001125 if (CanDoRT)
Adam Nemet339f42b2015-02-19 19:15:07 +00001126 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001127 else if (NeedRTCheck) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001128 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemet339f42b2015-02-19 19:15:07 +00001129 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
Adam Nemet04d41632015-02-19 19:14:34 +00001130 "the array bounds.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001131 PtrRtCheck.reset();
Adam Nemet436018c2015-02-19 19:15:00 +00001132 CanVecMem = false;
1133 return;
Adam Nemet04563272015-02-01 16:56:15 +00001134 }
1135
1136 PtrRtCheck.Need = NeedRTCheck;
1137
Adam Nemet436018c2015-02-19 19:15:00 +00001138 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001139 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001140 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001141 CanVecMem = DepChecker.areDepsSafe(
1142 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1143 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1144
1145 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001146 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001147 NeedRTCheck = true;
1148
1149 // Clear the dependency checks. We assume they are not needed.
1150 Accesses.resetDepChecks();
1151
1152 PtrRtCheck.reset();
1153 PtrRtCheck.Need = true;
1154
1155 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1156 TheLoop, Strides, true);
Adam Nemet949e91a2015-03-10 19:12:41 +00001157 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001158 if (!CanDoRT && NumComparisons > 0) {
1159 emitAnalysis(LoopAccessReport()
1160 << "cannot check memory dependencies at runtime");
1161 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1162 PtrRtCheck.reset();
1163 CanVecMem = false;
1164 return;
1165 }
1166
Adam Nemet04563272015-02-01 16:56:15 +00001167 CanVecMem = true;
1168 }
1169 }
1170
Adam Nemet4bb90a72015-03-10 21:47:39 +00001171 if (CanVecMem)
1172 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
1173 << (NeedRTCheck ? "" : " don't")
1174 << " need a runtime memory check.\n");
1175 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001176 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001177 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001178 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1179 }
Adam Nemet04563272015-02-01 16:56:15 +00001180}
1181
Adam Nemet01abb2c2015-02-18 03:43:19 +00001182bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1183 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001184 assert(TheLoop->contains(BB) && "Unknown block used");
1185
1186 // Blocks that do not dominate the latch need predication.
1187 BasicBlock* Latch = TheLoop->getLoopLatch();
1188 return !DT->dominates(BB, Latch);
1189}
1190
Adam Nemet2bd6e982015-02-19 19:15:15 +00001191void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001192 assert(!Report && "Multiple reports generated");
1193 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001194}
1195
Adam Nemet57ac7662015-02-19 19:15:21 +00001196bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001197 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1198}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001199
1200// FIXME: this function is currently a duplicate of the one in
1201// LoopVectorize.cpp.
1202static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1203 Instruction *Loc) {
1204 if (FirstInst)
1205 return FirstInst;
1206 if (Instruction *I = dyn_cast<Instruction>(V))
1207 return I->getParent() == Loc->getParent() ? I : nullptr;
1208 return nullptr;
1209}
1210
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001211std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1212 Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemet7206d7a2015-02-06 18:31:04 +00001213 Instruction *tnullptr = nullptr;
1214 if (!PtrRtCheck.Need)
1215 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1216
1217 unsigned NumPointers = PtrRtCheck.Pointers.size();
1218 SmallVector<TrackingVH<Value> , 2> Starts;
1219 SmallVector<TrackingVH<Value> , 2> Ends;
1220
1221 LLVMContext &Ctx = Loc->getContext();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001222 SCEVExpander Exp(*SE, DL, "induction");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001223 Instruction *FirstInst = nullptr;
1224
1225 for (unsigned i = 0; i < NumPointers; ++i) {
1226 Value *Ptr = PtrRtCheck.Pointers[i];
1227 const SCEV *Sc = SE->getSCEV(Ptr);
1228
1229 if (SE->isLoopInvariant(Sc, TheLoop)) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001230 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
Adam Nemet04d41632015-02-19 19:14:34 +00001231 *Ptr <<"\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001232 Starts.push_back(Ptr);
1233 Ends.push_back(Ptr);
1234 } else {
Adam Nemet339f42b2015-02-19 19:15:07 +00001235 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
Adam Nemet7206d7a2015-02-06 18:31:04 +00001236 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1237
1238 // Use this type for pointer arithmetic.
1239 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1240
1241 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1242 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1243 Starts.push_back(Start);
1244 Ends.push_back(End);
1245 }
1246 }
1247
1248 IRBuilder<> ChkBuilder(Loc);
1249 // Our instructions might fold to a constant.
1250 Value *MemoryRuntimeCheck = nullptr;
1251 for (unsigned i = 0; i < NumPointers; ++i) {
1252 for (unsigned j = i+1; j < NumPointers; ++j) {
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001253 if (!PtrRtCheck.needsChecking(i, j, PtrPartition))
Adam Nemet7206d7a2015-02-06 18:31:04 +00001254 continue;
1255
1256 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1257 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1258
1259 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1260 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1261 "Trying to bounds check pointers with different address spaces");
1262
1263 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1264 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1265
1266 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1267 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1268 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1269 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1270
1271 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1272 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1273 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1274 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1275 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1276 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1277 if (MemoryRuntimeCheck) {
1278 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1279 "conflict.rdx");
1280 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1281 }
1282 MemoryRuntimeCheck = IsConflict;
1283 }
1284 }
1285
1286 // We have to do this trickery because the IRBuilder might fold the check to a
1287 // constant expression in which case there is no Instruction anchored in a
1288 // the block.
1289 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1290 ConstantInt::getTrue(Ctx));
1291 ChkBuilder.Insert(Check, "memcheck.conflict");
1292 FirstInst = getFirstInst(FirstInst, Check, Loc);
1293 return std::make_pair(FirstInst, Check);
1294}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001295
1296LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001297 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001298 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001299 DominatorTree *DT,
1300 const ValueToValueMap &Strides)
Adam Nemet98c4c5d2015-03-10 18:54:23 +00001301 : DepChecker(SE, L), NumComparisons(0), TheLoop(L), SE(SE), DL(DL),
1302 TLI(TLI), AA(AA), DT(DT), NumLoads(0), NumStores(0),
1303 MaxSafeDepDistBytes(-1U), CanVecMem(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001304 if (canAnalyzeLoop())
1305 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001306}
1307
Adam Nemete91cc6e2015-02-19 19:15:19 +00001308void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1309 if (CanVecMem) {
1310 if (PtrRtCheck.empty())
1311 OS.indent(Depth) << "Memory dependences are safe\n";
1312 else
1313 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
1314 }
1315
1316 if (Report)
1317 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1318
Adam Nemet58913d62015-03-10 17:40:43 +00001319 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1320 OS.indent(Depth) << "Interesting Dependences:\n";
1321 for (auto &Dep : *InterestingDependences) {
1322 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1323 OS << "\n";
1324 }
1325 } else
1326 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001327
1328 // List the pair of accesses need run-time checks to prove independence.
1329 PtrRtCheck.print(OS, Depth);
1330 OS << "\n";
1331}
1332
Adam Nemet8bc61df2015-02-24 00:41:59 +00001333const LoopAccessInfo &
1334LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001335 auto &LAI = LoopAccessInfoMap[L];
1336
1337#ifndef NDEBUG
1338 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1339 "Symbolic strides changed for loop");
1340#endif
1341
1342 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001343 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001344 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, Strides);
1345#ifndef NDEBUG
1346 LAI->NumSymbolicStrides = Strides.size();
1347#endif
1348 }
1349 return *LAI.get();
1350}
1351
Adam Nemete91cc6e2015-02-19 19:15:19 +00001352void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1353 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1354
1355 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1356 ValueToValueMap NoSymbolicStrides;
1357
1358 for (Loop *TopLevelLoop : *LI)
1359 for (Loop *L : depth_first(TopLevelLoop)) {
1360 OS.indent(2) << L->getHeader()->getName() << ":\n";
1361 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1362 LAI.print(OS, 4);
1363 }
1364}
1365
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001366bool LoopAccessAnalysis::runOnFunction(Function &F) {
1367 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001368 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1369 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1370 AA = &getAnalysis<AliasAnalysis>();
1371 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1372
1373 return false;
1374}
1375
1376void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1377 AU.addRequired<ScalarEvolution>();
1378 AU.addRequired<AliasAnalysis>();
1379 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001380 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001381
1382 AU.setPreservesAll();
1383}
1384
1385char LoopAccessAnalysis::ID = 0;
1386static const char laa_name[] = "Loop Access Analysis";
1387#define LAA_NAME "loop-accesses"
1388
1389INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1390INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1391INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1392INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001393INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001394INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1395
1396namespace llvm {
1397 Pass *createLAAPass() {
1398 return new LoopAccessAnalysis();
1399 }
1400}