blob: 86f7c2e9757d4b877643e1d93ccb21b76ecfcc16 [file] [log] [blame]
Adam Nemet04563272015-02-01 16:56:15 +00001//===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The implementation for the loop memory dependence that was originally
11// developed for the loop vectorizer.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LoopAccessAnalysis.h"
16#include "llvm/Analysis/LoopInfo.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000017#include "llvm/Analysis/ScalarEvolutionExpander.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Adam Nemet04563272015-02-01 16:56:15 +000019#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/DiagnosticInfo.h"
21#include "llvm/IR/Dominators.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000022#include "llvm/IR/IRBuilder.h"
Adam Nemet04563272015-02-01 16:56:15 +000023#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000024#include "llvm/Support/raw_ostream.h"
Adam Nemet04563272015-02-01 16:56:15 +000025#include "llvm/Transforms/Utils/VectorUtils.h"
26using namespace llvm;
27
Adam Nemet339f42b2015-02-19 19:15:07 +000028#define DEBUG_TYPE "loop-accesses"
Adam Nemet04563272015-02-01 16:56:15 +000029
Adam Nemetf219c642015-02-19 19:14:52 +000030static cl::opt<unsigned, true>
31VectorizationFactor("force-vector-width", cl::Hidden,
32 cl::desc("Sets the SIMD width. Zero is autoselect."),
33 cl::location(VectorizerParams::VectorizationFactor));
Adam Nemet1d862af2015-02-26 04:39:09 +000034unsigned VectorizerParams::VectorizationFactor;
Adam Nemetf219c642015-02-19 19:14:52 +000035
36static cl::opt<unsigned, true>
37VectorizationInterleave("force-vector-interleave", cl::Hidden,
38 cl::desc("Sets the vectorization interleave count. "
39 "Zero is autoselect."),
40 cl::location(
41 VectorizerParams::VectorizationInterleave));
Adam Nemet1d862af2015-02-26 04:39:09 +000042unsigned VectorizerParams::VectorizationInterleave;
Adam Nemetf219c642015-02-19 19:14:52 +000043
Adam Nemet1d862af2015-02-26 04:39:09 +000044static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
45 "runtime-memory-check-threshold", cl::Hidden,
46 cl::desc("When performing memory disambiguation checks at runtime do not "
47 "generate more than this number of comparisons (default = 8)."),
48 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
49unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
Adam Nemetf219c642015-02-19 19:14:52 +000050
51/// Maximum SIMD width.
52const unsigned VectorizerParams::MaxVectorWidth = 64;
53
Adam Nemet9c926572015-03-10 17:40:37 +000054/// \brief We collect interesting dependences up to this threshold.
55static cl::opt<unsigned> MaxInterestingDependence(
56 "max-interesting-dependences", cl::Hidden,
57 cl::desc("Maximum number of interesting dependences collected by "
58 "loop-access analysis (default = 100)"),
59 cl::init(100));
60
Adam Nemetf219c642015-02-19 19:14:52 +000061bool VectorizerParams::isInterleaveForced() {
62 return ::VectorizationInterleave.getNumOccurrences() > 0;
63}
64
Adam Nemet2bd6e982015-02-19 19:15:15 +000065void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
66 const Function *TheFunction,
67 const Loop *TheLoop,
68 const char *PassName) {
Adam Nemet04563272015-02-01 16:56:15 +000069 DebugLoc DL = TheLoop->getStartLoc();
Adam Nemet3e876342015-02-19 19:15:13 +000070 if (const Instruction *I = Message.getInstr())
Adam Nemet04563272015-02-01 16:56:15 +000071 DL = I->getDebugLoc();
Adam Nemet339f42b2015-02-19 19:15:07 +000072 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
Adam Nemet04563272015-02-01 16:56:15 +000073 *TheFunction, DL, Message.str());
74}
75
76Value *llvm::stripIntegerCast(Value *V) {
77 if (CastInst *CI = dyn_cast<CastInst>(V))
78 if (CI->getOperand(0)->getType()->isIntegerTy())
79 return CI->getOperand(0);
80 return V;
81}
82
83const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
Adam Nemet8bc61df2015-02-24 00:41:59 +000084 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +000085 Value *Ptr, Value *OrigPtr) {
86
87 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
88
89 // If there is an entry in the map return the SCEV of the pointer with the
90 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +000091 ValueToValueMap::const_iterator SI =
92 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +000093 if (SI != PtrToStride.end()) {
94 Value *StrideVal = SI->second;
95
96 // Strip casts.
97 StrideVal = stripIntegerCast(StrideVal);
98
99 // Replace symbolic stride by one.
100 Value *One = ConstantInt::get(StrideVal->getType(), 1);
101 ValueToValueMap RewriteMap;
102 RewriteMap[StrideVal] = One;
103
104 const SCEV *ByOne =
105 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
Adam Nemet339f42b2015-02-19 19:15:07 +0000106 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
Adam Nemet04563272015-02-01 16:56:15 +0000107 << "\n");
108 return ByOne;
109 }
110
111 // Otherwise, just return the SCEV of the original pointer.
112 return SE->getSCEV(Ptr);
113}
114
Adam Nemet8bc61df2015-02-24 00:41:59 +0000115void LoopAccessInfo::RuntimePointerCheck::insert(
116 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
117 unsigned ASId, const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000118 // Get the stride replaced scev.
119 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
120 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
121 assert(AR && "Invalid addrec expression");
122 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
123 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
124 Pointers.push_back(Ptr);
125 Starts.push_back(AR->getStart());
126 Ends.push_back(ScEnd);
127 IsWritePtr.push_back(WritePtr);
128 DependencySetId.push_back(DepSetId);
129 AliasSetId.push_back(ASId);
130}
131
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000132bool LoopAccessInfo::RuntimePointerCheck::needsChecking(
133 unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemeta8945b72015-02-18 03:43:58 +0000134 // No need to check if two readonly pointers intersect.
135 if (!IsWritePtr[I] && !IsWritePtr[J])
136 return false;
137
138 // Only need to check pointers between two different dependency sets.
139 if (DependencySetId[I] == DependencySetId[J])
140 return false;
141
142 // Only need to check pointers in the same alias set.
143 if (AliasSetId[I] != AliasSetId[J])
144 return false;
145
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000146 // If PtrPartition is set omit checks between pointers of the same partition.
147 // Partition number -1 means that the pointer is used in multiple partitions.
148 // In this case we can't omit the check.
149 if (PtrPartition && (*PtrPartition)[I] != -1 &&
150 (*PtrPartition)[I] == (*PtrPartition)[J])
151 return false;
152
Adam Nemeta8945b72015-02-18 03:43:58 +0000153 return true;
154}
155
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000156void LoopAccessInfo::RuntimePointerCheck::print(
157 raw_ostream &OS, unsigned Depth,
158 const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000159 unsigned NumPointers = Pointers.size();
160 if (NumPointers == 0)
161 return;
162
163 OS.indent(Depth) << "Run-time memory checks:\n";
164 unsigned N = 0;
165 for (unsigned I = 0; I < NumPointers; ++I)
166 for (unsigned J = I + 1; J < NumPointers; ++J)
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000167 if (needsChecking(I, J, PtrPartition)) {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000168 OS.indent(Depth) << N++ << ":\n";
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000169 OS.indent(Depth + 2) << *Pointers[I];
170 if (PtrPartition)
171 OS << " (Partition: " << (*PtrPartition)[I] << ")";
172 OS << "\n";
173 OS.indent(Depth + 2) << *Pointers[J];
174 if (PtrPartition)
175 OS << " (Partition: " << (*PtrPartition)[J] << ")";
176 OS << "\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +0000177 }
178}
179
Adam Nemet51870d12015-04-07 03:35:26 +0000180bool LoopAccessInfo::RuntimePointerCheck::needsAnyChecking(
181 const SmallVectorImpl<int> *PtrPartition) const {
182 unsigned NumPointers = Pointers.size();
183
184 for (unsigned I = 0; I < NumPointers; ++I)
185 for (unsigned J = I + 1; J < NumPointers; ++J)
186 if (needsChecking(I, J, PtrPartition))
187 return true;
188 return false;
189}
190
Adam Nemet04563272015-02-01 16:56:15 +0000191namespace {
192/// \brief Analyses memory accesses in a loop.
193///
194/// Checks whether run time pointer checks are needed and builds sets for data
195/// dependence checking.
196class AccessAnalysis {
197public:
198 /// \brief Read or write access location.
199 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
200 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
201
Adam Nemete2b885c2015-04-23 20:09:20 +0000202 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Adam Nemetdee666b2015-03-10 17:40:34 +0000203 MemoryDepChecker::DepCandidates &DA)
Adam Nemete2b885c2015-04-23 20:09:20 +0000204 : DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000205
206 /// \brief Register a load and whether it is only read from.
207 void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) {
208 Value *Ptr = const_cast<Value*>(Loc.Ptr);
209 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
210 Accesses.insert(MemAccessInfo(Ptr, false));
211 if (IsReadOnly)
212 ReadOnlyPtr.insert(Ptr);
213 }
214
215 /// \brief Register a store.
216 void addStore(AliasAnalysis::Location &Loc) {
217 Value *Ptr = const_cast<Value*>(Loc.Ptr);
218 AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags);
219 Accesses.insert(MemAccessInfo(Ptr, true));
220 }
221
222 /// \brief Check whether we can check the pointers at runtime for
223 /// non-intersection.
Adam Nemet30f16e12015-02-18 03:42:35 +0000224 bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000225 unsigned &NumComparisons, ScalarEvolution *SE,
226 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000227 bool ShouldCheckStride = false);
228
229 /// \brief Goes over all memory accesses, checks whether a RT check is needed
230 /// and builds sets of dependent accesses.
231 void buildDependenceSets() {
232 processMemAccesses();
233 }
234
235 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
236
237 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
238 void resetDepChecks() { CheckDeps.clear(); }
239
240 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
241
242private:
243 typedef SetVector<MemAccessInfo> PtrAccessSet;
244
245 /// \brief Go over all memory access and check whether runtime pointer checks
246 /// are needed /// and build sets of dependency check candidates.
247 void processMemAccesses();
248
249 /// Set of all accesses.
250 PtrAccessSet Accesses;
251
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000252 const DataLayout &DL;
253
Adam Nemet04563272015-02-01 16:56:15 +0000254 /// Set of accesses that need a further dependence check.
255 MemAccessInfoSet CheckDeps;
256
257 /// Set of pointers that are read only.
258 SmallPtrSet<Value*, 16> ReadOnlyPtr;
259
Adam Nemet04563272015-02-01 16:56:15 +0000260 /// An alias set tracker to partition the access set by underlying object and
261 //intrinsic property (such as TBAA metadata).
262 AliasSetTracker AST;
263
Adam Nemete2b885c2015-04-23 20:09:20 +0000264 LoopInfo *LI;
265
Adam Nemet04563272015-02-01 16:56:15 +0000266 /// Sets of potentially dependent accesses - members of one set share an
267 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
268 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000269 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000270
271 bool IsRTCheckNeeded;
272};
273
274} // end anonymous namespace
275
276/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000277static bool hasComputableBounds(ScalarEvolution *SE,
278 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000279 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
280 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
281 if (!AR)
282 return false;
283
284 return AR->isAffine();
285}
286
287/// \brief Check the stride of the pointer and ensure that it does not wrap in
288/// the address space.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000289static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
290 const ValueToValueMap &StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000291
292bool AccessAnalysis::canCheckPtrAtRT(
Adam Nemet8bc61df2015-02-24 00:41:59 +0000293 LoopAccessInfo::RuntimePointerCheck &RtCheck, unsigned &NumComparisons,
294 ScalarEvolution *SE, Loop *TheLoop, const ValueToValueMap &StridesMap,
295 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000296 // Find pointers with computable bounds. We are going to use this information
297 // to place a runtime bound check.
298 bool CanDoRT = true;
299
300 bool IsDepCheckNeeded = isDependencyCheckNeeded();
301 NumComparisons = 0;
302
303 // We assign a consecutive id to access from different alias sets.
304 // Accesses between different groups doesn't need to be checked.
305 unsigned ASId = 1;
306 for (auto &AS : AST) {
307 unsigned NumReadPtrChecks = 0;
308 unsigned NumWritePtrChecks = 0;
309
310 // We assign consecutive id to access from different dependence sets.
311 // Accesses within the same set don't need a runtime check.
312 unsigned RunningDepId = 1;
313 DenseMap<Value *, unsigned> DepSetId;
314
315 for (auto A : AS) {
316 Value *Ptr = A.getValue();
317 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
318 MemAccessInfo Access(Ptr, IsWrite);
319
320 if (IsWrite)
321 ++NumWritePtrChecks;
322 else
323 ++NumReadPtrChecks;
324
325 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000326 // When we run after a failing dependency check we have to make sure
327 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000328 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000329 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000330 // The id of the dependence set.
331 unsigned DepId;
332
333 if (IsDepCheckNeeded) {
334 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
335 unsigned &LeaderId = DepSetId[Leader];
336 if (!LeaderId)
337 LeaderId = RunningDepId++;
338 DepId = LeaderId;
339 } else
340 // Each access has its own dependence set.
341 DepId = RunningDepId++;
342
343 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
344
Adam Nemet339f42b2015-02-19 19:15:07 +0000345 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000346 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000347 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000348 CanDoRT = false;
349 }
350 }
351
352 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
353 NumComparisons += 0; // Only one dependence set.
354 else {
355 NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks +
356 NumWritePtrChecks - 1));
357 }
358
359 ++ASId;
360 }
361
362 // If the pointers that we would use for the bounds comparison have different
363 // address spaces, assume the values aren't directly comparable, so we can't
364 // use them for the runtime check. We also have to assume they could
365 // overlap. In the future there should be metadata for whether address spaces
366 // are disjoint.
367 unsigned NumPointers = RtCheck.Pointers.size();
368 for (unsigned i = 0; i < NumPointers; ++i) {
369 for (unsigned j = i + 1; j < NumPointers; ++j) {
370 // Only need to check pointers between two different dependency sets.
371 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
372 continue;
373 // Only need to check pointers in the same alias set.
374 if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j])
375 continue;
376
377 Value *PtrI = RtCheck.Pointers[i];
378 Value *PtrJ = RtCheck.Pointers[j];
379
380 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
381 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
382 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000383 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000384 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000385 return false;
386 }
387 }
388 }
389
390 return CanDoRT;
391}
392
393void AccessAnalysis::processMemAccesses() {
394 // We process the set twice: first we process read-write pointers, last we
395 // process read-only pointers. This allows us to skip dependence tests for
396 // read-only pointers.
397
Adam Nemet339f42b2015-02-19 19:15:07 +0000398 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000399 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000400 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000401 DEBUG({
402 for (auto A : Accesses)
403 dbgs() << "\t" << *A.getPointer() << " (" <<
404 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
405 "read-only" : "read")) << ")\n";
406 });
407
408 // The AliasSetTracker has nicely partitioned our pointers by metadata
409 // compatibility and potential for underlying-object overlap. As a result, we
410 // only need to check for potential pointer dependencies within each alias
411 // set.
412 for (auto &AS : AST) {
413 // Note that both the alias-set tracker and the alias sets themselves used
414 // linked lists internally and so the iteration order here is deterministic
415 // (matching the original instruction order within each set).
416
417 bool SetHasWrite = false;
418
419 // Map of pointers to last access encountered.
420 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
421 UnderlyingObjToAccessMap ObjToLastAccess;
422
423 // Set of access to check after all writes have been processed.
424 PtrAccessSet DeferredAccesses;
425
426 // Iterate over each alias set twice, once to process read/write pointers,
427 // and then to process read-only pointers.
428 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
429 bool UseDeferred = SetIteration > 0;
430 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
431
432 for (auto AV : AS) {
433 Value *Ptr = AV.getValue();
434
435 // For a single memory access in AliasSetTracker, Accesses may contain
436 // both read and write, and they both need to be handled for CheckDeps.
437 for (auto AC : S) {
438 if (AC.getPointer() != Ptr)
439 continue;
440
441 bool IsWrite = AC.getInt();
442
443 // If we're using the deferred access set, then it contains only
444 // reads.
445 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
446 if (UseDeferred && !IsReadOnlyPtr)
447 continue;
448 // Otherwise, the pointer must be in the PtrAccessSet, either as a
449 // read or a write.
450 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
451 S.count(MemAccessInfo(Ptr, false))) &&
452 "Alias-set pointer not in the access set?");
453
454 MemAccessInfo Access(Ptr, IsWrite);
455 DepCands.insert(Access);
456
457 // Memorize read-only pointers for later processing and skip them in
458 // the first round (they need to be checked after we have seen all
459 // write pointers). Note: we also mark pointer that are not
460 // consecutive as "read-only" pointers (so that we check
461 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
462 if (!UseDeferred && IsReadOnlyPtr) {
463 DeferredAccesses.insert(Access);
464 continue;
465 }
466
467 // If this is a write - check other reads and writes for conflicts. If
468 // this is a read only check other writes for conflicts (but only if
469 // there is no other write to the ptr - this is an optimization to
470 // catch "a[i] = a[i] + " without having to do a dependence check).
471 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
472 CheckDeps.insert(Access);
473 IsRTCheckNeeded = true;
474 }
475
476 if (IsWrite)
477 SetHasWrite = true;
478
479 // Create sets of pointers connected by a shared alias set and
480 // underlying object.
481 typedef SmallVector<Value *, 16> ValueVector;
482 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000483
484 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
485 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000486 for (Value *UnderlyingObj : TempObjects) {
487 UnderlyingObjToAccessMap::iterator Prev =
488 ObjToLastAccess.find(UnderlyingObj);
489 if (Prev != ObjToLastAccess.end())
490 DepCands.unionSets(Access, Prev->second);
491
492 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000493 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000494 }
495 }
496 }
497 }
498 }
499}
500
Adam Nemet04563272015-02-01 16:56:15 +0000501static bool isInBoundsGep(Value *Ptr) {
502 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
503 return GEP->isInBounds();
504 return false;
505}
506
507/// \brief Check whether the access through \p Ptr has a constant stride.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000508static int isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
509 const ValueToValueMap &StridesMap) {
Adam Nemet04563272015-02-01 16:56:15 +0000510 const Type *Ty = Ptr->getType();
511 assert(Ty->isPointerTy() && "Unexpected non-ptr");
512
513 // Make sure that the pointer does not point to aggregate types.
514 const PointerType *PtrTy = cast<PointerType>(Ty);
515 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000516 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
517 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000518 return 0;
519 }
520
521 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
522
523 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
524 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000525 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000526 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000527 return 0;
528 }
529
530 // The accesss function must stride over the innermost loop.
531 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000532 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000533 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000534 }
535
536 // The address calculation must not wrap. Otherwise, a dependence could be
537 // inverted.
538 // An inbounds getelementptr that is a AddRec with a unit stride
539 // cannot wrap per definition. The unit stride requirement is checked later.
540 // An getelementptr without an inbounds attribute and unit stride would have
541 // to access the pointer value "0" which is undefined behavior in address
542 // space 0, therefore we can also vectorize this case.
543 bool IsInBoundsGEP = isInBoundsGep(Ptr);
544 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
545 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
546 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000547 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000548 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000549 return 0;
550 }
551
552 // Check the step is constant.
553 const SCEV *Step = AR->getStepRecurrence(*SE);
554
555 // Calculate the pointer stride and check if it is consecutive.
556 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
557 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000558 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000559 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000560 return 0;
561 }
562
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000563 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
564 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000565 const APInt &APStepVal = C->getValue()->getValue();
566
567 // Huge step value - give up.
568 if (APStepVal.getBitWidth() > 64)
569 return 0;
570
571 int64_t StepVal = APStepVal.getSExtValue();
572
573 // Strided access.
574 int64_t Stride = StepVal / Size;
575 int64_t Rem = StepVal % Size;
576 if (Rem)
577 return 0;
578
579 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
580 // know we can't "wrap around the address space". In case of address space
581 // zero we know that this won't happen without triggering undefined behavior.
582 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
583 Stride != 1 && Stride != -1)
584 return 0;
585
586 return Stride;
587}
588
Adam Nemet9c926572015-03-10 17:40:37 +0000589bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
590 switch (Type) {
591 case NoDep:
592 case Forward:
593 case BackwardVectorizable:
594 return true;
595
596 case Unknown:
597 case ForwardButPreventsForwarding:
598 case Backward:
599 case BackwardVectorizableButPreventsForwarding:
600 return false;
601 }
David Majnemerd388e932015-03-10 20:23:29 +0000602 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000603}
604
605bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
606 switch (Type) {
607 case NoDep:
608 case Forward:
609 return false;
610
611 case BackwardVectorizable:
612 case Unknown:
613 case ForwardButPreventsForwarding:
614 case Backward:
615 case BackwardVectorizableButPreventsForwarding:
616 return true;
617 }
David Majnemerd388e932015-03-10 20:23:29 +0000618 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000619}
620
621bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
622 switch (Type) {
623 case NoDep:
624 case Forward:
625 case ForwardButPreventsForwarding:
626 return false;
627
628 case Unknown:
629 case BackwardVectorizable:
630 case Backward:
631 case BackwardVectorizableButPreventsForwarding:
632 return true;
633 }
David Majnemerd388e932015-03-10 20:23:29 +0000634 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000635}
636
Adam Nemet04563272015-02-01 16:56:15 +0000637bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
638 unsigned TypeByteSize) {
639 // If loads occur at a distance that is not a multiple of a feasible vector
640 // factor store-load forwarding does not take place.
641 // Positive dependences might cause troubles because vectorizing them might
642 // prevent store-load forwarding making vectorized code run a lot slower.
643 // a[i] = a[i-3] ^ a[i-8];
644 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
645 // hence on your typical architecture store-load forwarding does not take
646 // place. Vectorizing in such cases does not make sense.
647 // Store-load forwarding distance.
648 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
649 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000650 unsigned MaxVFWithoutSLForwardIssues =
651 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000652 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000653 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
654
655 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
656 vf *= 2) {
657 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
658 MaxVFWithoutSLForwardIssues = (vf >>=1);
659 break;
660 }
661 }
662
Adam Nemet04d41632015-02-19 19:14:34 +0000663 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000664 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000665 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000666 return true;
667 }
668
669 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000670 MaxVFWithoutSLForwardIssues !=
671 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000672 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
673 return false;
674}
675
Adam Nemet9c926572015-03-10 17:40:37 +0000676MemoryDepChecker::Dependence::DepType
677MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
678 const MemAccessInfo &B, unsigned BIdx,
679 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000680 assert (AIdx < BIdx && "Must pass arguments in program order");
681
682 Value *APtr = A.getPointer();
683 Value *BPtr = B.getPointer();
684 bool AIsWrite = A.getInt();
685 bool BIsWrite = B.getInt();
686
687 // Two reads are independent.
688 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +0000689 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +0000690
691 // We cannot check pointers in different address spaces.
692 if (APtr->getType()->getPointerAddressSpace() !=
693 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +0000694 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000695
696 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
697 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
698
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000699 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
700 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +0000701
702 const SCEV *Src = AScev;
703 const SCEV *Sink = BScev;
704
705 // If the induction step is negative we have to invert source and sink of the
706 // dependence.
707 if (StrideAPtr < 0) {
708 //Src = BScev;
709 //Sink = AScev;
710 std::swap(APtr, BPtr);
711 std::swap(Src, Sink);
712 std::swap(AIsWrite, BIsWrite);
713 std::swap(AIdx, BIdx);
714 std::swap(StrideAPtr, StrideBPtr);
715 }
716
717 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
718
Adam Nemet339f42b2015-02-19 19:15:07 +0000719 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +0000720 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +0000721 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +0000722 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000723
724 // Need consecutive accesses. We don't want to vectorize
725 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
726 // the address space.
727 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
728 DEBUG(dbgs() << "Non-consecutive pointer access\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000729 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000730 }
731
732 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
733 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000734 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +0000735 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +0000736 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000737 }
738
739 Type *ATy = APtr->getType()->getPointerElementType();
740 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000741 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
742 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +0000743
744 // Negative distances are not plausible dependencies.
745 const APInt &Val = C->getValue()->getValue();
746 if (Val.isNegative()) {
747 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
748 if (IsTrueDataDependence &&
749 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
750 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +0000751 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000752
Adam Nemet339f42b2015-02-19 19:15:07 +0000753 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000754 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +0000755 }
756
757 // Write to the same location with the same size.
758 // Could be improved to assert type sizes are the same (i32 == float, etc).
759 if (Val == 0) {
760 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +0000761 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +0000762 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000763 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000764 }
765
766 assert(Val.isStrictlyPositive() && "Expect a positive value");
767
Adam Nemet04563272015-02-01 16:56:15 +0000768 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +0000769 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +0000770 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +0000771 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +0000772 }
773
774 unsigned Distance = (unsigned) Val.getZExtValue();
775
776 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +0000777 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
778 VectorizerParams::VectorizationFactor : 1);
779 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
780 VectorizerParams::VectorizationInterleave : 1);
Adam Nemet04563272015-02-01 16:56:15 +0000781
782 // The distance must be bigger than the size needed for a vectorized version
783 // of the operation and the size of the vectorized operation must not be
784 // bigger than the currrent maximum size.
785 if (Distance < 2*TypeByteSize ||
786 2*TypeByteSize > MaxSafeDepDistBytes ||
787 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000788 DEBUG(dbgs() << "LAA: Failure because of Positive distance "
Adam Nemet04d41632015-02-19 19:14:34 +0000789 << Val.getSExtValue() << '\n');
Adam Nemet9c926572015-03-10 17:40:37 +0000790 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +0000791 }
792
Adam Nemet9cc0c392015-02-26 17:58:48 +0000793 // Positive distance bigger than max vectorization factor.
Adam Nemet04563272015-02-01 16:56:15 +0000794 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
795 Distance : MaxSafeDepDistBytes;
796
797 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
798 if (IsTrueDataDependence &&
799 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +0000800 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +0000801
Adam Nemet339f42b2015-02-19 19:15:07 +0000802 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() <<
Adam Nemet04d41632015-02-19 19:14:34 +0000803 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000804
Adam Nemet9c926572015-03-10 17:40:37 +0000805 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +0000806}
807
Adam Nemetdee666b2015-03-10 17:40:34 +0000808bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +0000809 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +0000810 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000811
812 MaxSafeDepDistBytes = -1U;
813 while (!CheckDeps.empty()) {
814 MemAccessInfo CurAccess = *CheckDeps.begin();
815
816 // Get the relevant memory access set.
817 EquivalenceClasses<MemAccessInfo>::iterator I =
818 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
819
820 // Check accesses within this set.
821 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
822 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
823
824 // Check every access pair.
825 while (AI != AE) {
826 CheckDeps.erase(*AI);
827 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
828 while (OI != AE) {
829 // Check every accessing instruction pair in program order.
830 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
831 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
832 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
833 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +0000834 auto A = std::make_pair(&*AI, *I1);
835 auto B = std::make_pair(&*OI, *I2);
836
837 assert(*I1 != *I2);
838 if (*I1 > *I2)
839 std::swap(A, B);
840
841 Dependence::DepType Type =
842 isDependent(*A.first, A.second, *B.first, B.second, Strides);
843 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
844
845 // Gather dependences unless we accumulated MaxInterestingDependence
846 // dependences. In that case return as soon as we find the first
847 // unsafe dependence. This puts a limit on this quadratic
848 // algorithm.
849 if (RecordInterestingDependences) {
850 if (Dependence::isInterestingDependence(Type))
851 InterestingDependences.push_back(
852 Dependence(A.second, B.second, Type));
853
854 if (InterestingDependences.size() >= MaxInterestingDependence) {
855 RecordInterestingDependences = false;
856 InterestingDependences.clear();
857 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
858 }
859 }
860 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +0000861 return false;
862 }
863 ++OI;
864 }
865 AI++;
866 }
867 }
Adam Nemet9c926572015-03-10 17:40:37 +0000868
869 DEBUG(dbgs() << "Total Interesting Dependences: "
870 << InterestingDependences.size() << "\n");
871 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +0000872}
873
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000874SmallVector<Instruction *, 4>
875MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
876 MemAccessInfo Access(Ptr, isWrite);
877 auto &IndexVector = Accesses.find(Access)->second;
878
879 SmallVector<Instruction *, 4> Insts;
880 std::transform(IndexVector.begin(), IndexVector.end(),
881 std::back_inserter(Insts),
882 [&](unsigned Idx) { return this->InstMap[Idx]; });
883 return Insts;
884}
885
Adam Nemet58913d62015-03-10 17:40:43 +0000886const char *MemoryDepChecker::Dependence::DepName[] = {
887 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
888 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
889
890void MemoryDepChecker::Dependence::print(
891 raw_ostream &OS, unsigned Depth,
892 const SmallVectorImpl<Instruction *> &Instrs) const {
893 OS.indent(Depth) << DepName[Type] << ":\n";
894 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
895 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
896}
897
Adam Nemet929c38e2015-02-19 19:15:10 +0000898bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000899 // We need to have a loop header.
900 DEBUG(dbgs() << "LAA: Found a loop: " <<
901 TheLoop->getHeader()->getName() << '\n');
902
Adam Nemet929c38e2015-02-19 19:15:10 +0000903 // We can only analyze innermost loops.
904 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000905 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +0000906 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +0000907 return false;
908 }
909
910 // We must have a single backedge.
911 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000912 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +0000913 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000914 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000915 "loop control flow is not understood by analyzer");
916 return false;
917 }
918
919 // We must have a single exiting block.
920 if (!TheLoop->getExitingBlock()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000921 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +0000922 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000923 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000924 "loop control flow is not understood by analyzer");
925 return false;
926 }
927
928 // We only handle bottom-tested loops, i.e. loop in which the condition is
929 // checked at the end of each iteration. With that we can assume that all
930 // instructions in the loop are executed the same number of times.
931 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +0000932 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +0000933 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +0000934 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000935 "loop control flow is not understood by analyzer");
936 return false;
937 }
938
Adam Nemet929c38e2015-02-19 19:15:10 +0000939 // ScalarEvolution needs to be able to find the exit count.
940 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
941 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000942 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +0000943 "could not determine number of loop iterations");
944 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
945 return false;
946 }
947
948 return true;
949}
950
Adam Nemet8bc61df2015-02-24 00:41:59 +0000951void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000952
953 typedef SmallVector<Value*, 16> ValueVector;
954 typedef SmallPtrSet<Value*, 16> ValueSet;
955
956 // Holds the Load and Store *instructions*.
957 ValueVector Loads;
958 ValueVector Stores;
959
960 // Holds all the different accesses in the loop.
961 unsigned NumReads = 0;
962 unsigned NumReadWrites = 0;
963
964 PtrRtCheck.Pointers.clear();
965 PtrRtCheck.Need = false;
966
967 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +0000968
969 // For each block.
970 for (Loop::block_iterator bb = TheLoop->block_begin(),
971 be = TheLoop->block_end(); bb != be; ++bb) {
972
973 // Scan the BB and collect legal loads and stores.
974 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
975 ++it) {
976
977 // If this is a load, save it. If this instruction can read from memory
978 // but is not a load, then we quit. Notice that we don't handle function
979 // calls that read or write.
980 if (it->mayReadFromMemory()) {
981 // Many math library functions read the rounding mode. We will only
982 // vectorize a loop if it contains known function calls that don't set
983 // the flag. Therefore, it is safe to ignore this read from memory.
984 CallInst *Call = dyn_cast<CallInst>(it);
985 if (Call && getIntrinsicIDForCall(Call, TLI))
986 continue;
987
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +0000988 // If the function has an explicit vectorized counterpart, we can safely
989 // assume that it can be vectorized.
990 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
991 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
992 continue;
993
Adam Nemet04563272015-02-01 16:56:15 +0000994 LoadInst *Ld = dyn_cast<LoadInst>(it);
995 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +0000996 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +0000997 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +0000998 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +0000999 CanVecMem = false;
1000 return;
Adam Nemet04563272015-02-01 16:56:15 +00001001 }
1002 NumLoads++;
1003 Loads.push_back(Ld);
1004 DepChecker.addAccess(Ld);
1005 continue;
1006 }
1007
1008 // Save 'store' instructions. Abort if other instructions write to memory.
1009 if (it->mayWriteToMemory()) {
1010 StoreInst *St = dyn_cast<StoreInst>(it);
1011 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001012 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001013 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001014 CanVecMem = false;
1015 return;
Adam Nemet04563272015-02-01 16:56:15 +00001016 }
1017 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001018 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001019 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001020 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001021 CanVecMem = false;
1022 return;
Adam Nemet04563272015-02-01 16:56:15 +00001023 }
1024 NumStores++;
1025 Stores.push_back(St);
1026 DepChecker.addAccess(St);
1027 }
1028 } // Next instr.
1029 } // Next block.
1030
1031 // Now we have two lists that hold the loads and the stores.
1032 // Next, we find the pointers that they use.
1033
1034 // Check if we see any stores. If there are no stores, then we don't
1035 // care if the pointers are *restrict*.
1036 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001037 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001038 CanVecMem = true;
1039 return;
Adam Nemet04563272015-02-01 16:56:15 +00001040 }
1041
Adam Nemetdee666b2015-03-10 17:40:34 +00001042 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001043 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Adam Nemete2b885c2015-04-23 20:09:20 +00001044 AA, LI, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001045
1046 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1047 // multiple times on the same object. If the ptr is accessed twice, once
1048 // for read and once for write, it will only appear once (on the write
1049 // list). This is okay, since we are going to check for conflicts between
1050 // writes and between reads and writes, but not between reads and reads.
1051 ValueSet Seen;
1052
1053 ValueVector::iterator I, IE;
1054 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1055 StoreInst *ST = cast<StoreInst>(*I);
1056 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001057 // Check for store to loop invariant address.
1058 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001059 // If we did *not* see this pointer before, insert it to the read-write
1060 // list. At this phase it is only a 'write' list.
1061 if (Seen.insert(Ptr).second) {
1062 ++NumReadWrites;
1063
1064 AliasAnalysis::Location Loc = AA->getLocation(ST);
1065 // The TBAA metadata could have a control dependency on the predication
1066 // condition, so we cannot rely on it when determining whether or not we
1067 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001068 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001069 Loc.AATags.TBAA = nullptr;
1070
1071 Accesses.addStore(Loc);
1072 }
1073 }
1074
1075 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001076 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001077 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001078 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001079 CanVecMem = true;
1080 return;
Adam Nemet04563272015-02-01 16:56:15 +00001081 }
1082
1083 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1084 LoadInst *LD = cast<LoadInst>(*I);
1085 Value* Ptr = LD->getPointerOperand();
1086 // If we did *not* see this pointer before, insert it to the
1087 // read list. If we *did* see it before, then it is already in
1088 // the read-write list. This allows us to vectorize expressions
1089 // such as A[i] += x; Because the address of A[i] is a read-write
1090 // pointer. This only works if the index of A[i] is consecutive.
1091 // If the address of i is unknown (for example A[B[i]]) then we may
1092 // read a few words, modify, and write a few words, and some of the
1093 // words may be written to the same address.
1094 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001095 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001096 ++NumReads;
1097 IsReadOnlyPtr = true;
1098 }
1099
1100 AliasAnalysis::Location Loc = AA->getLocation(LD);
1101 // The TBAA metadata could have a control dependency on the predication
1102 // condition, so we cannot rely on it when determining whether or not we
1103 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001104 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001105 Loc.AATags.TBAA = nullptr;
1106
1107 Accesses.addLoad(Loc, IsReadOnlyPtr);
1108 }
1109
1110 // If we write (or read-write) to a single destination and there are no
1111 // other reads in this loop then is it safe to vectorize.
1112 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001113 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001114 CanVecMem = true;
1115 return;
Adam Nemet04563272015-02-01 16:56:15 +00001116 }
1117
1118 // Build dependence sets and check whether we need a runtime pointer bounds
1119 // check.
1120 Accesses.buildDependenceSets();
1121 bool NeedRTCheck = Accesses.isRTCheckNeeded();
1122
1123 // Find pointers with computable bounds. We are going to use this information
1124 // to place a runtime bound check.
Adam Nemet04563272015-02-01 16:56:15 +00001125 bool CanDoRT = false;
1126 if (NeedRTCheck)
1127 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
1128 Strides);
1129
Adam Nemet339f42b2015-02-19 19:15:07 +00001130 DEBUG(dbgs() << "LAA: We need to do " << NumComparisons <<
Adam Nemet04d41632015-02-19 19:14:34 +00001131 " pointer comparisons.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001132
1133 // If we only have one set of dependences to check pointers among we don't
1134 // need a runtime check.
1135 if (NumComparisons == 0 && NeedRTCheck)
1136 NeedRTCheck = false;
1137
Adam Nemet949e91a2015-03-10 19:12:41 +00001138 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001139 if (CanDoRT)
Adam Nemet339f42b2015-02-19 19:15:07 +00001140 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001141 else if (NeedRTCheck) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001142 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemet339f42b2015-02-19 19:15:07 +00001143 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " <<
Adam Nemet04d41632015-02-19 19:14:34 +00001144 "the array bounds.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001145 PtrRtCheck.reset();
Adam Nemet436018c2015-02-19 19:15:00 +00001146 CanVecMem = false;
1147 return;
Adam Nemet04563272015-02-01 16:56:15 +00001148 }
1149
1150 PtrRtCheck.Need = NeedRTCheck;
1151
Adam Nemet436018c2015-02-19 19:15:00 +00001152 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001153 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001154 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001155 CanVecMem = DepChecker.areDepsSafe(
1156 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1157 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1158
1159 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001160 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001161 NeedRTCheck = true;
1162
1163 // Clear the dependency checks. We assume they are not needed.
1164 Accesses.resetDepChecks();
1165
1166 PtrRtCheck.reset();
1167 PtrRtCheck.Need = true;
1168
1169 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
1170 TheLoop, Strides, true);
Adam Nemet949e91a2015-03-10 19:12:41 +00001171 // Check that we found the bounds for the pointer.
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001172 if (!CanDoRT && NumComparisons > 0) {
1173 emitAnalysis(LoopAccessReport()
1174 << "cannot check memory dependencies at runtime");
1175 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
1176 PtrRtCheck.reset();
1177 CanVecMem = false;
1178 return;
1179 }
1180
Adam Nemet04563272015-02-01 16:56:15 +00001181 CanVecMem = true;
1182 }
1183 }
1184
Adam Nemet4bb90a72015-03-10 21:47:39 +00001185 if (CanVecMem)
1186 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
1187 << (NeedRTCheck ? "" : " don't")
1188 << " need a runtime memory check.\n");
1189 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001190 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001191 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001192 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1193 }
Adam Nemet04563272015-02-01 16:56:15 +00001194}
1195
Adam Nemet01abb2c2015-02-18 03:43:19 +00001196bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1197 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001198 assert(TheLoop->contains(BB) && "Unknown block used");
1199
1200 // Blocks that do not dominate the latch need predication.
1201 BasicBlock* Latch = TheLoop->getLoopLatch();
1202 return !DT->dominates(BB, Latch);
1203}
1204
Adam Nemet2bd6e982015-02-19 19:15:15 +00001205void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001206 assert(!Report && "Multiple reports generated");
1207 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001208}
1209
Adam Nemet57ac7662015-02-19 19:15:21 +00001210bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001211 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1212}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001213
1214// FIXME: this function is currently a duplicate of the one in
1215// LoopVectorize.cpp.
1216static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1217 Instruction *Loc) {
1218 if (FirstInst)
1219 return FirstInst;
1220 if (Instruction *I = dyn_cast<Instruction>(V))
1221 return I->getParent() == Loc->getParent() ? I : nullptr;
1222 return nullptr;
1223}
1224
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001225std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1226 Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemet7206d7a2015-02-06 18:31:04 +00001227 if (!PtrRtCheck.Need)
Adam Nemet90fec842015-04-02 17:51:57 +00001228 return std::make_pair(nullptr, nullptr);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001229
1230 unsigned NumPointers = PtrRtCheck.Pointers.size();
1231 SmallVector<TrackingVH<Value> , 2> Starts;
1232 SmallVector<TrackingVH<Value> , 2> Ends;
1233
1234 LLVMContext &Ctx = Loc->getContext();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001235 SCEVExpander Exp(*SE, DL, "induction");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001236 Instruction *FirstInst = nullptr;
1237
1238 for (unsigned i = 0; i < NumPointers; ++i) {
1239 Value *Ptr = PtrRtCheck.Pointers[i];
1240 const SCEV *Sc = SE->getSCEV(Ptr);
1241
1242 if (SE->isLoopInvariant(Sc, TheLoop)) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001243 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" <<
Adam Nemet04d41632015-02-19 19:14:34 +00001244 *Ptr <<"\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001245 Starts.push_back(Ptr);
1246 Ends.push_back(Ptr);
1247 } else {
Adam Nemet339f42b2015-02-19 19:15:07 +00001248 DEBUG(dbgs() << "LAA: Adding RT check for range:" << *Ptr << '\n');
Adam Nemet7206d7a2015-02-06 18:31:04 +00001249 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1250
1251 // Use this type for pointer arithmetic.
1252 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1253
1254 Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc);
1255 Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc);
1256 Starts.push_back(Start);
1257 Ends.push_back(End);
1258 }
1259 }
1260
1261 IRBuilder<> ChkBuilder(Loc);
1262 // Our instructions might fold to a constant.
1263 Value *MemoryRuntimeCheck = nullptr;
1264 for (unsigned i = 0; i < NumPointers; ++i) {
1265 for (unsigned j = i+1; j < NumPointers; ++j) {
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001266 if (!PtrRtCheck.needsChecking(i, j, PtrPartition))
Adam Nemet7206d7a2015-02-06 18:31:04 +00001267 continue;
1268
1269 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1270 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1271
1272 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1273 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1274 "Trying to bounds check pointers with different address spaces");
1275
1276 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1277 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1278
1279 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1280 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1281 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1282 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1283
1284 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1285 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1286 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1287 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1288 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1289 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1290 if (MemoryRuntimeCheck) {
1291 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1292 "conflict.rdx");
1293 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1294 }
1295 MemoryRuntimeCheck = IsConflict;
1296 }
1297 }
1298
Adam Nemet90fec842015-04-02 17:51:57 +00001299 if (!MemoryRuntimeCheck)
1300 return std::make_pair(nullptr, nullptr);
1301
Adam Nemet7206d7a2015-02-06 18:31:04 +00001302 // We have to do this trickery because the IRBuilder might fold the check to a
1303 // constant expression in which case there is no Instruction anchored in a
1304 // the block.
1305 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1306 ConstantInt::getTrue(Ctx));
1307 ChkBuilder.Insert(Check, "memcheck.conflict");
1308 FirstInst = getFirstInst(FirstInst, Check, Loc);
1309 return std::make_pair(FirstInst, Check);
1310}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001311
1312LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001313 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001314 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemete2b885c2015-04-23 20:09:20 +00001315 DominatorTree *DT, LoopInfo *LI,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001316 const ValueToValueMap &Strides)
Adam Nemet98c4c5d2015-03-10 18:54:23 +00001317 : DepChecker(SE, L), NumComparisons(0), TheLoop(L), SE(SE), DL(DL),
Adam Nemete2b885c2015-04-23 20:09:20 +00001318 TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001319 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1320 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001321 if (canAnalyzeLoop())
1322 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001323}
1324
Adam Nemete91cc6e2015-02-19 19:15:19 +00001325void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1326 if (CanVecMem) {
Adam Nemet26da8e92015-04-14 01:12:55 +00001327 if (PtrRtCheck.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001328 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001329 else
1330 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001331 }
1332
Adam Nemetce482502015-04-08 17:48:40 +00001333 OS.indent(Depth) << "Store to invariant address was "
1334 << (StoreToLoopInvariantAddress ? "" : "not ")
1335 << "found in loop.\n";
1336
Adam Nemete91cc6e2015-02-19 19:15:19 +00001337 if (Report)
1338 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1339
Adam Nemet58913d62015-03-10 17:40:43 +00001340 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1341 OS.indent(Depth) << "Interesting Dependences:\n";
1342 for (auto &Dep : *InterestingDependences) {
1343 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1344 OS << "\n";
1345 }
1346 } else
1347 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001348
1349 // List the pair of accesses need run-time checks to prove independence.
1350 PtrRtCheck.print(OS, Depth);
1351 OS << "\n";
1352}
1353
Adam Nemet8bc61df2015-02-24 00:41:59 +00001354const LoopAccessInfo &
1355LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001356 auto &LAI = LoopAccessInfoMap[L];
1357
1358#ifndef NDEBUG
1359 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1360 "Symbolic strides changed for loop");
1361#endif
1362
1363 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001364 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemete2b885c2015-04-23 20:09:20 +00001365 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
1366 Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001367#ifndef NDEBUG
1368 LAI->NumSymbolicStrides = Strides.size();
1369#endif
1370 }
1371 return *LAI.get();
1372}
1373
Adam Nemete91cc6e2015-02-19 19:15:19 +00001374void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1375 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1376
Adam Nemete91cc6e2015-02-19 19:15:19 +00001377 ValueToValueMap NoSymbolicStrides;
1378
1379 for (Loop *TopLevelLoop : *LI)
1380 for (Loop *L : depth_first(TopLevelLoop)) {
1381 OS.indent(2) << L->getHeader()->getName() << ":\n";
1382 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1383 LAI.print(OS, 4);
1384 }
1385}
1386
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001387bool LoopAccessAnalysis::runOnFunction(Function &F) {
1388 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001389 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1390 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1391 AA = &getAnalysis<AliasAnalysis>();
1392 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete2b885c2015-04-23 20:09:20 +00001393 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001394
1395 return false;
1396}
1397
1398void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1399 AU.addRequired<ScalarEvolution>();
1400 AU.addRequired<AliasAnalysis>();
1401 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001402 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001403
1404 AU.setPreservesAll();
1405}
1406
1407char LoopAccessAnalysis::ID = 0;
1408static const char laa_name[] = "Loop Access Analysis";
1409#define LAA_NAME "loop-accesses"
1410
1411INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1412INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1413INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1414INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001415INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001416INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1417
1418namespace llvm {
1419 Pass *createLAAPass() {
1420 return new LoopAccessAnalysis();
1421 }
1422}