blob: d7880cc2dfad2214caea06539194148b8ba7253e [file] [log] [blame]
Adam Nemet04563272015-02-01 16:56:15 +00001//===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The implementation for the loop memory dependence that was originally
11// developed for the loop vectorizer.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LoopAccessAnalysis.h"
16#include "llvm/Analysis/LoopInfo.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000017#include "llvm/Analysis/ScalarEvolutionExpander.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Adam Nemet04563272015-02-01 16:56:15 +000019#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/DiagnosticInfo.h"
21#include "llvm/IR/Dominators.h"
Adam Nemet7206d7a2015-02-06 18:31:04 +000022#include "llvm/IR/IRBuilder.h"
Adam Nemet04563272015-02-01 16:56:15 +000023#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000024#include "llvm/Support/raw_ostream.h"
David Blaikieb447ac62015-06-26 18:02:52 +000025#include "llvm/Analysis/VectorUtils.h"
Adam Nemet04563272015-02-01 16:56:15 +000026using namespace llvm;
27
Adam Nemet339f42b2015-02-19 19:15:07 +000028#define DEBUG_TYPE "loop-accesses"
Adam Nemet04563272015-02-01 16:56:15 +000029
Adam Nemetf219c642015-02-19 19:14:52 +000030static cl::opt<unsigned, true>
31VectorizationFactor("force-vector-width", cl::Hidden,
32 cl::desc("Sets the SIMD width. Zero is autoselect."),
33 cl::location(VectorizerParams::VectorizationFactor));
Adam Nemet1d862af2015-02-26 04:39:09 +000034unsigned VectorizerParams::VectorizationFactor;
Adam Nemetf219c642015-02-19 19:14:52 +000035
36static cl::opt<unsigned, true>
37VectorizationInterleave("force-vector-interleave", cl::Hidden,
38 cl::desc("Sets the vectorization interleave count. "
39 "Zero is autoselect."),
40 cl::location(
41 VectorizerParams::VectorizationInterleave));
Adam Nemet1d862af2015-02-26 04:39:09 +000042unsigned VectorizerParams::VectorizationInterleave;
Adam Nemetf219c642015-02-19 19:14:52 +000043
Adam Nemet1d862af2015-02-26 04:39:09 +000044static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold(
45 "runtime-memory-check-threshold", cl::Hidden,
46 cl::desc("When performing memory disambiguation checks at runtime do not "
47 "generate more than this number of comparisons (default = 8)."),
48 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8));
49unsigned VectorizerParams::RuntimeMemoryCheckThreshold;
Adam Nemetf219c642015-02-19 19:14:52 +000050
Silviu Baranga1b6b50a2015-07-08 09:16:33 +000051/// \brief The maximum iterations used to merge memory checks
52static cl::opt<unsigned> MemoryCheckMergeThreshold(
53 "memory-check-merge-threshold", cl::Hidden,
54 cl::desc("Maximum number of comparisons done when trying to merge "
55 "runtime memory checks. (default = 100)"),
56 cl::init(100));
57
Adam Nemetf219c642015-02-19 19:14:52 +000058/// Maximum SIMD width.
59const unsigned VectorizerParams::MaxVectorWidth = 64;
60
Adam Nemet9c926572015-03-10 17:40:37 +000061/// \brief We collect interesting dependences up to this threshold.
62static cl::opt<unsigned> MaxInterestingDependence(
63 "max-interesting-dependences", cl::Hidden,
64 cl::desc("Maximum number of interesting dependences collected by "
65 "loop-access analysis (default = 100)"),
66 cl::init(100));
67
Adam Nemetf219c642015-02-19 19:14:52 +000068bool VectorizerParams::isInterleaveForced() {
69 return ::VectorizationInterleave.getNumOccurrences() > 0;
70}
71
Adam Nemet2bd6e982015-02-19 19:15:15 +000072void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message,
73 const Function *TheFunction,
74 const Loop *TheLoop,
75 const char *PassName) {
Adam Nemet04563272015-02-01 16:56:15 +000076 DebugLoc DL = TheLoop->getStartLoc();
Adam Nemet3e876342015-02-19 19:15:13 +000077 if (const Instruction *I = Message.getInstr())
Adam Nemet04563272015-02-01 16:56:15 +000078 DL = I->getDebugLoc();
Adam Nemet339f42b2015-02-19 19:15:07 +000079 emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName,
Adam Nemet04563272015-02-01 16:56:15 +000080 *TheFunction, DL, Message.str());
81}
82
83Value *llvm::stripIntegerCast(Value *V) {
84 if (CastInst *CI = dyn_cast<CastInst>(V))
85 if (CI->getOperand(0)->getType()->isIntegerTy())
86 return CI->getOperand(0);
87 return V;
88}
89
90const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE,
Adam Nemet8bc61df2015-02-24 00:41:59 +000091 const ValueToValueMap &PtrToStride,
Adam Nemet04563272015-02-01 16:56:15 +000092 Value *Ptr, Value *OrigPtr) {
93
94 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
95
96 // If there is an entry in the map return the SCEV of the pointer with the
97 // symbolic stride replaced by one.
Adam Nemet8bc61df2015-02-24 00:41:59 +000098 ValueToValueMap::const_iterator SI =
99 PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
Adam Nemet04563272015-02-01 16:56:15 +0000100 if (SI != PtrToStride.end()) {
101 Value *StrideVal = SI->second;
102
103 // Strip casts.
104 StrideVal = stripIntegerCast(StrideVal);
105
106 // Replace symbolic stride by one.
107 Value *One = ConstantInt::get(StrideVal->getType(), 1);
108 ValueToValueMap RewriteMap;
109 RewriteMap[StrideVal] = One;
110
111 const SCEV *ByOne =
112 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
Adam Nemet339f42b2015-02-19 19:15:07 +0000113 DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
Adam Nemet04563272015-02-01 16:56:15 +0000114 << "\n");
115 return ByOne;
116 }
117
118 // Otherwise, just return the SCEV of the original pointer.
119 return SE->getSCEV(Ptr);
120}
121
Adam Nemet7cdebac2015-07-14 22:32:44 +0000122void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, bool WritePtr,
123 unsigned DepSetId, unsigned ASId,
124 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000125 // Get the stride replaced scev.
126 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
127 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
128 assert(AR && "Invalid addrec expression");
129 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
130 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000131 Pointers.emplace_back(Ptr, AR->getStart(), ScEnd, WritePtr, DepSetId, ASId,
132 Sc);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000133}
134
Adam Nemet7cdebac2015-07-14 22:32:44 +0000135bool RuntimePointerChecking::needsChecking(
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000136 const CheckingPtrGroup &M, const CheckingPtrGroup &N,
137 const SmallVectorImpl<int> *PtrPartition) const {
138 for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I)
139 for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J)
140 if (needsChecking(M.Members[I], N.Members[J], PtrPartition))
141 return true;
142 return false;
143}
144
145/// Compare \p I and \p J and return the minimum.
146/// Return nullptr in case we couldn't find an answer.
147static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J,
148 ScalarEvolution *SE) {
149 const SCEV *Diff = SE->getMinusSCEV(J, I);
150 const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff);
151
152 if (!C)
153 return nullptr;
154 if (C->getValue()->isNegative())
155 return J;
156 return I;
157}
158
Adam Nemet7cdebac2015-07-14 22:32:44 +0000159bool RuntimePointerChecking::CheckingPtrGroup::addPointer(unsigned Index) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000160 const SCEV *Start = RtCheck.Pointers[Index].Start;
161 const SCEV *End = RtCheck.Pointers[Index].End;
162
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000163 // Compare the starts and ends with the known minimum and maximum
164 // of this set. We need to know how we compare against the min/max
165 // of the set in order to be able to emit memchecks.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000166 const SCEV *Min0 = getMinFromExprs(Start, Low, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000167 if (!Min0)
168 return false;
169
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000170 const SCEV *Min1 = getMinFromExprs(End, High, RtCheck.SE);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000171 if (!Min1)
172 return false;
173
174 // Update the low bound expression if we've found a new min value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000175 if (Min0 == Start)
176 Low = Start;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000177
178 // Update the high bound expression if we've found a new max value.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000179 if (Min1 != End)
180 High = End;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000181
182 Members.push_back(Index);
183 return true;
184}
185
Adam Nemet7cdebac2015-07-14 22:32:44 +0000186void RuntimePointerChecking::groupChecks(
187 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000188 // We build the groups from dependency candidates equivalence classes
189 // because:
190 // - We know that pointers in the same equivalence class share
191 // the same underlying object and therefore there is a chance
192 // that we can compare pointers
193 // - We wouldn't be able to merge two pointers for which we need
194 // to emit a memcheck. The classes in DepCands are already
195 // conveniently built such that no two pointers in the same
196 // class need checking against each other.
197
198 // We use the following (greedy) algorithm to construct the groups
199 // For every pointer in the equivalence class:
200 // For each existing group:
201 // - if the difference between this pointer and the min/max bounds
202 // of the group is a constant, then make the pointer part of the
203 // group and update the min/max bounds of that group as required.
204
205 CheckingGroups.clear();
206
207 // If we don't have the dependency partitions, construct a new
208 // checking pointer group for each pointer.
209 if (!UseDependencies) {
210 for (unsigned I = 0; I < Pointers.size(); ++I)
211 CheckingGroups.push_back(CheckingPtrGroup(I, *this));
212 return;
213 }
214
215 unsigned TotalComparisons = 0;
216
217 DenseMap<Value *, unsigned> PositionMap;
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000218 for (unsigned Index = 0; Index < Pointers.size(); ++Index)
219 PositionMap[Pointers[Index].PointerValue] = Index;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000220
Silviu Barangace3877f2015-07-09 15:18:25 +0000221 // We need to keep track of what pointers we've already seen so we
222 // don't process them twice.
223 SmallSet<unsigned, 2> Seen;
224
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000225 // Go through all equivalence classes, get the the "pointer check groups"
Silviu Barangace3877f2015-07-09 15:18:25 +0000226 // and add them to the overall solution. We use the order in which accesses
227 // appear in 'Pointers' to enforce determinism.
228 for (unsigned I = 0; I < Pointers.size(); ++I) {
229 // We've seen this pointer before, and therefore already processed
230 // its equivalence class.
231 if (Seen.count(I))
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000232 continue;
233
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000234 MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue,
235 Pointers[I].IsWritePtr);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000236
Silviu Barangace3877f2015-07-09 15:18:25 +0000237 SmallVector<CheckingPtrGroup, 2> Groups;
238 auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access));
239
Silviu Barangaa647c302015-07-13 14:48:24 +0000240 // Because DepCands is constructed by visiting accesses in the order in
241 // which they appear in alias sets (which is deterministic) and the
242 // iteration order within an equivalence class member is only dependent on
243 // the order in which unions and insertions are performed on the
244 // equivalence class, the iteration order is deterministic.
Silviu Barangace3877f2015-07-09 15:18:25 +0000245 for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end();
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000246 MI != ME; ++MI) {
247 unsigned Pointer = PositionMap[MI->getPointer()];
248 bool Merged = false;
Silviu Barangace3877f2015-07-09 15:18:25 +0000249 // Mark this pointer as seen.
250 Seen.insert(Pointer);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000251
252 // Go through all the existing sets and see if we can find one
253 // which can include this pointer.
254 for (CheckingPtrGroup &Group : Groups) {
255 // Don't perform more than a certain amount of comparisons.
256 // This should limit the cost of grouping the pointers to something
257 // reasonable. If we do end up hitting this threshold, the algorithm
258 // will create separate groups for all remaining pointers.
259 if (TotalComparisons > MemoryCheckMergeThreshold)
260 break;
261
262 TotalComparisons++;
263
264 if (Group.addPointer(Pointer)) {
265 Merged = true;
266 break;
267 }
268 }
269
270 if (!Merged)
271 // We couldn't add this pointer to any existing set or the threshold
272 // for the number of comparisons has been reached. Create a new group
273 // to hold the current pointer.
274 Groups.push_back(CheckingPtrGroup(Pointer, *this));
275 }
276
277 // We've computed the grouped checks for this partition.
278 // Save the results and continue with the next one.
279 std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups));
280 }
Adam Nemet04563272015-02-01 16:56:15 +0000281}
282
Adam Nemet041e6de2015-07-16 02:48:05 +0000283bool RuntimePointerChecking::arePointersInSamePartition(
284 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1,
285 unsigned PtrIdx2) {
286 return (PtrToPartition[PtrIdx1] != -1 &&
287 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
288}
289
Adam Nemet7cdebac2015-07-14 22:32:44 +0000290bool RuntimePointerChecking::needsChecking(
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000291 unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000292 const PointerInfo &PointerI = Pointers[I];
293 const PointerInfo &PointerJ = Pointers[J];
294
Adam Nemeta8945b72015-02-18 03:43:58 +0000295 // No need to check if two readonly pointers intersect.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000296 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr)
Adam Nemeta8945b72015-02-18 03:43:58 +0000297 return false;
298
299 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000300 if (PointerI.DependencySetId == PointerJ.DependencySetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000301 return false;
302
303 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000304 if (PointerI.AliasSetId != PointerJ.AliasSetId)
Adam Nemeta8945b72015-02-18 03:43:58 +0000305 return false;
306
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000307 // If PtrPartition is set omit checks between pointers of the same partition.
Adam Nemet041e6de2015-07-16 02:48:05 +0000308 if (PtrPartition && arePointersInSamePartition(*PtrPartition, I, J))
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000309 return false;
310
Adam Nemeta8945b72015-02-18 03:43:58 +0000311 return true;
312}
313
Adam Nemet7cdebac2015-07-14 22:32:44 +0000314void RuntimePointerChecking::print(
Adam Nemetec1e2bb2015-03-10 18:54:26 +0000315 raw_ostream &OS, unsigned Depth,
316 const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemete91cc6e2015-02-19 19:15:19 +0000317
318 OS.indent(Depth) << "Run-time memory checks:\n";
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000319
Adam Nemete91cc6e2015-02-19 19:15:19 +0000320 unsigned N = 0;
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000321 for (unsigned I = 0; I < CheckingGroups.size(); ++I)
322 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J)
323 if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition)) {
324 OS.indent(Depth) << "Check " << N++ << ":\n";
325 OS.indent(Depth + 2) << "Comparing group " << I << ":\n";
326
327 for (unsigned K = 0; K < CheckingGroups[I].Members.size(); ++K) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000328 OS.indent(Depth + 2)
329 << *Pointers[CheckingGroups[I].Members[K]].PointerValue << "\n";
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000330 if (PtrPartition)
331 OS << " (Partition: "
332 << (*PtrPartition)[CheckingGroups[I].Members[K]] << ")"
333 << "\n";
334 }
335
336 OS.indent(Depth + 2) << "Against group " << J << ":\n";
337
338 for (unsigned K = 0; K < CheckingGroups[J].Members.size(); ++K) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000339 OS.indent(Depth + 2)
340 << *Pointers[CheckingGroups[J].Members[K]].PointerValue << "\n";
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000341 if (PtrPartition)
342 OS << " (Partition: "
343 << (*PtrPartition)[CheckingGroups[J].Members[K]] << ")"
344 << "\n";
345 }
Adam Nemete91cc6e2015-02-19 19:15:19 +0000346 }
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000347
348 OS.indent(Depth) << "Grouped accesses:\n";
349 for (unsigned I = 0; I < CheckingGroups.size(); ++I) {
350 OS.indent(Depth + 2) << "Group " << I << ":\n";
351 OS.indent(Depth + 4) << "(Low: " << *CheckingGroups[I].Low
352 << " High: " << *CheckingGroups[I].High << ")\n";
353 for (unsigned J = 0; J < CheckingGroups[I].Members.size(); ++J) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000354 OS.indent(Depth + 6) << "Member: "
355 << *Pointers[CheckingGroups[I].Members[J]].Expr
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000356 << "\n";
357 }
358 }
Adam Nemete91cc6e2015-02-19 19:15:19 +0000359}
360
Adam Nemet7cdebac2015-07-14 22:32:44 +0000361unsigned RuntimePointerChecking::getNumberOfChecks(
Adam Nemet51870d12015-04-07 03:35:26 +0000362 const SmallVectorImpl<int> *PtrPartition) const {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000363
364 unsigned NumPartitions = CheckingGroups.size();
Silviu Baranga98a13712015-06-08 10:27:06 +0000365 unsigned CheckCount = 0;
Adam Nemet51870d12015-04-07 03:35:26 +0000366
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000367 for (unsigned I = 0; I < NumPartitions; ++I)
368 for (unsigned J = I + 1; J < NumPartitions; ++J)
369 if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition))
Silviu Baranga98a13712015-06-08 10:27:06 +0000370 CheckCount++;
371 return CheckCount;
372}
373
Adam Nemet7cdebac2015-07-14 22:32:44 +0000374bool RuntimePointerChecking::needsAnyChecking(
Silviu Baranga98a13712015-06-08 10:27:06 +0000375 const SmallVectorImpl<int> *PtrPartition) const {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000376 unsigned NumPointers = Pointers.size();
377
378 for (unsigned I = 0; I < NumPointers; ++I)
379 for (unsigned J = I + 1; J < NumPointers; ++J)
380 if (needsChecking(I, J, PtrPartition))
381 return true;
382 return false;
Adam Nemet51870d12015-04-07 03:35:26 +0000383}
384
Adam Nemet04563272015-02-01 16:56:15 +0000385namespace {
386/// \brief Analyses memory accesses in a loop.
387///
388/// Checks whether run time pointer checks are needed and builds sets for data
389/// dependence checking.
390class AccessAnalysis {
391public:
392 /// \brief Read or write access location.
393 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
394 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
395
Adam Nemete2b885c2015-04-23 20:09:20 +0000396 AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI,
Adam Nemetdee666b2015-03-10 17:40:34 +0000397 MemoryDepChecker::DepCandidates &DA)
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000398 : DL(Dl), AST(*AA), LI(LI), DepCands(DA),
399 IsRTCheckAnalysisNeeded(false) {}
Adam Nemet04563272015-02-01 16:56:15 +0000400
401 /// \brief Register a load and whether it is only read from.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000402 void addLoad(MemoryLocation &Loc, bool IsReadOnly) {
Adam Nemet04563272015-02-01 16:56:15 +0000403 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000404 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000405 Accesses.insert(MemAccessInfo(Ptr, false));
406 if (IsReadOnly)
407 ReadOnlyPtr.insert(Ptr);
408 }
409
410 /// \brief Register a store.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000411 void addStore(MemoryLocation &Loc) {
Adam Nemet04563272015-02-01 16:56:15 +0000412 Value *Ptr = const_cast<Value*>(Loc.Ptr);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000413 AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags);
Adam Nemet04563272015-02-01 16:56:15 +0000414 Accesses.insert(MemAccessInfo(Ptr, true));
415 }
416
417 /// \brief Check whether we can check the pointers at runtime for
Adam Nemetee614742015-07-09 22:17:38 +0000418 /// non-intersection.
419 ///
420 /// Returns true if we need no check or if we do and we can generate them
421 /// (i.e. the pointers have computable bounds).
Adam Nemet7cdebac2015-07-14 22:32:44 +0000422 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE,
423 Loop *TheLoop, const ValueToValueMap &Strides,
Adam Nemet04563272015-02-01 16:56:15 +0000424 bool ShouldCheckStride = false);
425
426 /// \brief Goes over all memory accesses, checks whether a RT check is needed
427 /// and builds sets of dependent accesses.
428 void buildDependenceSets() {
429 processMemAccesses();
430 }
431
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000432 /// \brief Initial processing of memory accesses determined that we need to
433 /// perform dependency checking.
434 ///
435 /// Note that this can later be cleared if we retry memcheck analysis without
436 /// dependency checking (i.e. ShouldRetryWithRuntimeCheck).
Adam Nemet04563272015-02-01 16:56:15 +0000437 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
Adam Nemetdf3dc5b2015-05-18 15:37:03 +0000438
439 /// We decided that no dependence analysis would be used. Reset the state.
440 void resetDepChecks(MemoryDepChecker &DepChecker) {
441 CheckDeps.clear();
442 DepChecker.clearInterestingDependences();
443 }
Adam Nemet04563272015-02-01 16:56:15 +0000444
445 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
446
447private:
448 typedef SetVector<MemAccessInfo> PtrAccessSet;
449
450 /// \brief Go over all memory access and check whether runtime pointer checks
Adam Nemetb41d2d32015-07-09 06:47:21 +0000451 /// are needed and build sets of dependency check candidates.
Adam Nemet04563272015-02-01 16:56:15 +0000452 void processMemAccesses();
453
454 /// Set of all accesses.
455 PtrAccessSet Accesses;
456
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000457 const DataLayout &DL;
458
Adam Nemet04563272015-02-01 16:56:15 +0000459 /// Set of accesses that need a further dependence check.
460 MemAccessInfoSet CheckDeps;
461
462 /// Set of pointers that are read only.
463 SmallPtrSet<Value*, 16> ReadOnlyPtr;
464
Adam Nemet04563272015-02-01 16:56:15 +0000465 /// An alias set tracker to partition the access set by underlying object and
466 //intrinsic property (such as TBAA metadata).
467 AliasSetTracker AST;
468
Adam Nemete2b885c2015-04-23 20:09:20 +0000469 LoopInfo *LI;
470
Adam Nemet04563272015-02-01 16:56:15 +0000471 /// Sets of potentially dependent accesses - members of one set share an
472 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
473 /// dependence check.
Adam Nemetdee666b2015-03-10 17:40:34 +0000474 MemoryDepChecker::DepCandidates &DepCands;
Adam Nemet04563272015-02-01 16:56:15 +0000475
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000476 /// \brief Initial processing of memory accesses determined that we may need
477 /// to add memchecks. Perform the analysis to determine the necessary checks.
478 ///
479 /// Note that, this is different from isDependencyCheckNeeded. When we retry
480 /// memcheck analysis without dependency checking
481 /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared
482 /// while this remains set if we have potentially dependent accesses.
483 bool IsRTCheckAnalysisNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000484};
485
486} // end anonymous namespace
487
488/// \brief Check whether a pointer can participate in a runtime bounds check.
Adam Nemet8bc61df2015-02-24 00:41:59 +0000489static bool hasComputableBounds(ScalarEvolution *SE,
490 const ValueToValueMap &Strides, Value *Ptr) {
Adam Nemet04563272015-02-01 16:56:15 +0000491 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
492 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
493 if (!AR)
494 return false;
495
496 return AR->isAffine();
497}
498
Adam Nemet7cdebac2015-07-14 22:32:44 +0000499bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck,
500 ScalarEvolution *SE, Loop *TheLoop,
501 const ValueToValueMap &StridesMap,
502 bool ShouldCheckStride) {
Adam Nemet04563272015-02-01 16:56:15 +0000503 // Find pointers with computable bounds. We are going to use this information
504 // to place a runtime bound check.
505 bool CanDoRT = true;
506
Adam Nemetee614742015-07-09 22:17:38 +0000507 bool NeedRTCheck = false;
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000508 if (!IsRTCheckAnalysisNeeded) return true;
Silviu Baranga98a13712015-06-08 10:27:06 +0000509
Adam Nemet04563272015-02-01 16:56:15 +0000510 bool IsDepCheckNeeded = isDependencyCheckNeeded();
Adam Nemet04563272015-02-01 16:56:15 +0000511
512 // We assign a consecutive id to access from different alias sets.
513 // Accesses between different groups doesn't need to be checked.
514 unsigned ASId = 1;
515 for (auto &AS : AST) {
Adam Nemet424edc62015-07-08 22:58:48 +0000516 int NumReadPtrChecks = 0;
517 int NumWritePtrChecks = 0;
518
Adam Nemet04563272015-02-01 16:56:15 +0000519 // We assign consecutive id to access from different dependence sets.
520 // Accesses within the same set don't need a runtime check.
521 unsigned RunningDepId = 1;
522 DenseMap<Value *, unsigned> DepSetId;
523
524 for (auto A : AS) {
525 Value *Ptr = A.getValue();
526 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true));
527 MemAccessInfo Access(Ptr, IsWrite);
528
Adam Nemet424edc62015-07-08 22:58:48 +0000529 if (IsWrite)
530 ++NumWritePtrChecks;
531 else
532 ++NumReadPtrChecks;
533
Adam Nemet04563272015-02-01 16:56:15 +0000534 if (hasComputableBounds(SE, StridesMap, Ptr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000535 // When we run after a failing dependency check we have to make sure
536 // we don't have wrapping pointers.
Adam Nemet04563272015-02-01 16:56:15 +0000537 (!ShouldCheckStride ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000538 isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) {
Adam Nemet04563272015-02-01 16:56:15 +0000539 // The id of the dependence set.
540 unsigned DepId;
541
542 if (IsDepCheckNeeded) {
543 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
544 unsigned &LeaderId = DepSetId[Leader];
545 if (!LeaderId)
546 LeaderId = RunningDepId++;
547 DepId = LeaderId;
548 } else
549 // Each access has its own dependence set.
550 DepId = RunningDepId++;
551
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000552 RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap);
Adam Nemet04563272015-02-01 16:56:15 +0000553
Adam Nemet339f42b2015-02-19 19:15:07 +0000554 DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000555 } else {
Adam Nemetf10ca272015-05-18 15:36:52 +0000556 DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n');
Adam Nemet04563272015-02-01 16:56:15 +0000557 CanDoRT = false;
558 }
559 }
560
Adam Nemet424edc62015-07-08 22:58:48 +0000561 // If we have at least two writes or one write and a read then we need to
562 // check them. But there is no need to checks if there is only one
563 // dependence set for this alias set.
564 //
565 // Note that this function computes CanDoRT and NeedRTCheck independently.
566 // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer
567 // for which we couldn't find the bounds but we don't actually need to emit
568 // any checks so it does not matter.
569 if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
570 NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
571 NumWritePtrChecks >= 1));
572
Adam Nemet04563272015-02-01 16:56:15 +0000573 ++ASId;
574 }
575
576 // If the pointers that we would use for the bounds comparison have different
577 // address spaces, assume the values aren't directly comparable, so we can't
578 // use them for the runtime check. We also have to assume they could
579 // overlap. In the future there should be metadata for whether address spaces
580 // are disjoint.
581 unsigned NumPointers = RtCheck.Pointers.size();
582 for (unsigned i = 0; i < NumPointers; ++i) {
583 for (unsigned j = i + 1; j < NumPointers; ++j) {
584 // Only need to check pointers between two different dependency sets.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000585 if (RtCheck.Pointers[i].DependencySetId ==
586 RtCheck.Pointers[j].DependencySetId)
Adam Nemet04563272015-02-01 16:56:15 +0000587 continue;
588 // Only need to check pointers in the same alias set.
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000589 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId)
Adam Nemet04563272015-02-01 16:56:15 +0000590 continue;
591
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000592 Value *PtrI = RtCheck.Pointers[i].PointerValue;
593 Value *PtrJ = RtCheck.Pointers[j].PointerValue;
Adam Nemet04563272015-02-01 16:56:15 +0000594
595 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
596 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
597 if (ASi != ASj) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000598 DEBUG(dbgs() << "LAA: Runtime check would require comparison between"
Adam Nemet04d41632015-02-19 19:14:34 +0000599 " different address spaces\n");
Adam Nemet04563272015-02-01 16:56:15 +0000600 return false;
601 }
602 }
603 }
604
Silviu Baranga1b6b50a2015-07-08 09:16:33 +0000605 if (NeedRTCheck && CanDoRT)
606 RtCheck.groupChecks(DepCands, IsDepCheckNeeded);
607
Adam Nemetee614742015-07-09 22:17:38 +0000608 DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks(nullptr)
609 << " pointer comparisons.\n");
610
611 RtCheck.Need = NeedRTCheck;
612
613 bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
614 if (!CanDoRTIfNeeded)
615 RtCheck.reset();
616 return CanDoRTIfNeeded;
Adam Nemet04563272015-02-01 16:56:15 +0000617}
618
619void AccessAnalysis::processMemAccesses() {
620 // We process the set twice: first we process read-write pointers, last we
621 // process read-only pointers. This allows us to skip dependence tests for
622 // read-only pointers.
623
Adam Nemet339f42b2015-02-19 19:15:07 +0000624 DEBUG(dbgs() << "LAA: Processing memory accesses...\n");
Adam Nemet04563272015-02-01 16:56:15 +0000625 DEBUG(dbgs() << " AST: "; AST.dump());
Adam Nemet9c926572015-03-10 17:40:37 +0000626 DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n");
Adam Nemet04563272015-02-01 16:56:15 +0000627 DEBUG({
628 for (auto A : Accesses)
629 dbgs() << "\t" << *A.getPointer() << " (" <<
630 (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ?
631 "read-only" : "read")) << ")\n";
632 });
633
634 // The AliasSetTracker has nicely partitioned our pointers by metadata
635 // compatibility and potential for underlying-object overlap. As a result, we
636 // only need to check for potential pointer dependencies within each alias
637 // set.
638 for (auto &AS : AST) {
639 // Note that both the alias-set tracker and the alias sets themselves used
640 // linked lists internally and so the iteration order here is deterministic
641 // (matching the original instruction order within each set).
642
643 bool SetHasWrite = false;
644
645 // Map of pointers to last access encountered.
646 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
647 UnderlyingObjToAccessMap ObjToLastAccess;
648
649 // Set of access to check after all writes have been processed.
650 PtrAccessSet DeferredAccesses;
651
652 // Iterate over each alias set twice, once to process read/write pointers,
653 // and then to process read-only pointers.
654 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) {
655 bool UseDeferred = SetIteration > 0;
656 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
657
658 for (auto AV : AS) {
659 Value *Ptr = AV.getValue();
660
661 // For a single memory access in AliasSetTracker, Accesses may contain
662 // both read and write, and they both need to be handled for CheckDeps.
663 for (auto AC : S) {
664 if (AC.getPointer() != Ptr)
665 continue;
666
667 bool IsWrite = AC.getInt();
668
669 // If we're using the deferred access set, then it contains only
670 // reads.
671 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
672 if (UseDeferred && !IsReadOnlyPtr)
673 continue;
674 // Otherwise, the pointer must be in the PtrAccessSet, either as a
675 // read or a write.
676 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
677 S.count(MemAccessInfo(Ptr, false))) &&
678 "Alias-set pointer not in the access set?");
679
680 MemAccessInfo Access(Ptr, IsWrite);
681 DepCands.insert(Access);
682
683 // Memorize read-only pointers for later processing and skip them in
684 // the first round (they need to be checked after we have seen all
685 // write pointers). Note: we also mark pointer that are not
686 // consecutive as "read-only" pointers (so that we check
687 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite".
688 if (!UseDeferred && IsReadOnlyPtr) {
689 DeferredAccesses.insert(Access);
690 continue;
691 }
692
693 // If this is a write - check other reads and writes for conflicts. If
694 // this is a read only check other writes for conflicts (but only if
695 // there is no other write to the ptr - this is an optimization to
696 // catch "a[i] = a[i] + " without having to do a dependence check).
697 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
698 CheckDeps.insert(Access);
Adam Nemet5dc3b2c2015-07-09 06:47:18 +0000699 IsRTCheckAnalysisNeeded = true;
Adam Nemet04563272015-02-01 16:56:15 +0000700 }
701
702 if (IsWrite)
703 SetHasWrite = true;
704
705 // Create sets of pointers connected by a shared alias set and
706 // underlying object.
707 typedef SmallVector<Value *, 16> ValueVector;
708 ValueVector TempObjects;
Adam Nemete2b885c2015-04-23 20:09:20 +0000709
710 GetUnderlyingObjects(Ptr, TempObjects, DL, LI);
711 DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000712 for (Value *UnderlyingObj : TempObjects) {
713 UnderlyingObjToAccessMap::iterator Prev =
714 ObjToLastAccess.find(UnderlyingObj);
715 if (Prev != ObjToLastAccess.end())
716 DepCands.unionSets(Access, Prev->second);
717
718 ObjToLastAccess[UnderlyingObj] = Access;
Adam Nemete2b885c2015-04-23 20:09:20 +0000719 DEBUG(dbgs() << " " << *UnderlyingObj << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000720 }
721 }
722 }
723 }
724 }
725}
726
Adam Nemet04563272015-02-01 16:56:15 +0000727static bool isInBoundsGep(Value *Ptr) {
728 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
729 return GEP->isInBounds();
730 return false;
731}
732
Adam Nemetc4866d22015-06-26 17:25:43 +0000733/// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping,
734/// i.e. monotonically increasing/decreasing.
735static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR,
736 ScalarEvolution *SE, const Loop *L) {
737 // FIXME: This should probably only return true for NUW.
738 if (AR->getNoWrapFlags(SCEV::NoWrapMask))
739 return true;
740
741 // Scalar evolution does not propagate the non-wrapping flags to values that
742 // are derived from a non-wrapping induction variable because non-wrapping
743 // could be flow-sensitive.
744 //
745 // Look through the potentially overflowing instruction to try to prove
746 // non-wrapping for the *specific* value of Ptr.
747
748 // The arithmetic implied by an inbounds GEP can't overflow.
749 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr);
750 if (!GEP || !GEP->isInBounds())
751 return false;
752
753 // Make sure there is only one non-const index and analyze that.
754 Value *NonConstIndex = nullptr;
755 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
756 if (!isa<ConstantInt>(*Index)) {
757 if (NonConstIndex)
758 return false;
759 NonConstIndex = *Index;
760 }
761 if (!NonConstIndex)
762 // The recurrence is on the pointer, ignore for now.
763 return false;
764
765 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW
766 // AddRec using a NSW operation.
767 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
768 if (OBO->hasNoSignedWrap() &&
769 // Assume constant for other the operand so that the AddRec can be
770 // easily found.
771 isa<ConstantInt>(OBO->getOperand(1))) {
772 auto *OpScev = SE->getSCEV(OBO->getOperand(0));
773
774 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
775 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW);
776 }
777
778 return false;
779}
780
Adam Nemet04563272015-02-01 16:56:15 +0000781/// \brief Check whether the access through \p Ptr has a constant stride.
Hao Liu32c05392015-06-08 06:39:56 +0000782int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp,
783 const ValueToValueMap &StridesMap) {
Adam Nemet04563272015-02-01 16:56:15 +0000784 const Type *Ty = Ptr->getType();
785 assert(Ty->isPointerTy() && "Unexpected non-ptr");
786
787 // Make sure that the pointer does not point to aggregate types.
788 const PointerType *PtrTy = cast<PointerType>(Ty);
789 if (PtrTy->getElementType()->isAggregateType()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000790 DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type"
791 << *Ptr << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000792 return 0;
793 }
794
795 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
796
797 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
798 if (!AR) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000799 DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer "
Adam Nemet04d41632015-02-19 19:14:34 +0000800 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000801 return 0;
802 }
803
804 // The accesss function must stride over the innermost loop.
805 if (Lp != AR->getLoop()) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000806 DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " <<
Adam Nemet04d41632015-02-19 19:14:34 +0000807 *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000808 }
809
810 // The address calculation must not wrap. Otherwise, a dependence could be
811 // inverted.
812 // An inbounds getelementptr that is a AddRec with a unit stride
813 // cannot wrap per definition. The unit stride requirement is checked later.
814 // An getelementptr without an inbounds attribute and unit stride would have
815 // to access the pointer value "0" which is undefined behavior in address
816 // space 0, therefore we can also vectorize this case.
817 bool IsInBoundsGEP = isInBoundsGep(Ptr);
Adam Nemetc4866d22015-06-26 17:25:43 +0000818 bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp);
Adam Nemet04563272015-02-01 16:56:15 +0000819 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
820 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000821 DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space "
Adam Nemet04d41632015-02-19 19:14:34 +0000822 << *Ptr << " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000823 return 0;
824 }
825
826 // Check the step is constant.
827 const SCEV *Step = AR->getStepRecurrence(*SE);
828
Adam Nemet943befe2015-07-09 00:03:22 +0000829 // Calculate the pointer stride and check if it is constant.
Adam Nemet04563272015-02-01 16:56:15 +0000830 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
831 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000832 DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr <<
Adam Nemet04d41632015-02-19 19:14:34 +0000833 " SCEV: " << *PtrScev << "\n");
Adam Nemet04563272015-02-01 16:56:15 +0000834 return 0;
835 }
836
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000837 auto &DL = Lp->getHeader()->getModule()->getDataLayout();
838 int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
Adam Nemet04563272015-02-01 16:56:15 +0000839 const APInt &APStepVal = C->getValue()->getValue();
840
841 // Huge step value - give up.
842 if (APStepVal.getBitWidth() > 64)
843 return 0;
844
845 int64_t StepVal = APStepVal.getSExtValue();
846
847 // Strided access.
848 int64_t Stride = StepVal / Size;
849 int64_t Rem = StepVal % Size;
850 if (Rem)
851 return 0;
852
853 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
854 // know we can't "wrap around the address space". In case of address space
855 // zero we know that this won't happen without triggering undefined behavior.
856 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
857 Stride != 1 && Stride != -1)
858 return 0;
859
860 return Stride;
861}
862
Adam Nemet9c926572015-03-10 17:40:37 +0000863bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) {
864 switch (Type) {
865 case NoDep:
866 case Forward:
867 case BackwardVectorizable:
868 return true;
869
870 case Unknown:
871 case ForwardButPreventsForwarding:
872 case Backward:
873 case BackwardVectorizableButPreventsForwarding:
874 return false;
875 }
David Majnemerd388e932015-03-10 20:23:29 +0000876 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000877}
878
879bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) {
880 switch (Type) {
881 case NoDep:
882 case Forward:
883 return false;
884
885 case BackwardVectorizable:
886 case Unknown:
887 case ForwardButPreventsForwarding:
888 case Backward:
889 case BackwardVectorizableButPreventsForwarding:
890 return true;
891 }
David Majnemerd388e932015-03-10 20:23:29 +0000892 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000893}
894
895bool MemoryDepChecker::Dependence::isPossiblyBackward() const {
896 switch (Type) {
897 case NoDep:
898 case Forward:
899 case ForwardButPreventsForwarding:
900 return false;
901
902 case Unknown:
903 case BackwardVectorizable:
904 case Backward:
905 case BackwardVectorizableButPreventsForwarding:
906 return true;
907 }
David Majnemerd388e932015-03-10 20:23:29 +0000908 llvm_unreachable("unexpected DepType!");
Adam Nemet9c926572015-03-10 17:40:37 +0000909}
910
Adam Nemet04563272015-02-01 16:56:15 +0000911bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
912 unsigned TypeByteSize) {
913 // If loads occur at a distance that is not a multiple of a feasible vector
914 // factor store-load forwarding does not take place.
915 // Positive dependences might cause troubles because vectorizing them might
916 // prevent store-load forwarding making vectorized code run a lot slower.
917 // a[i] = a[i-3] ^ a[i-8];
918 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
919 // hence on your typical architecture store-load forwarding does not take
920 // place. Vectorizing in such cases does not make sense.
921 // Store-load forwarding distance.
922 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
923 // Maximum vector factor.
Adam Nemetf219c642015-02-19 19:14:52 +0000924 unsigned MaxVFWithoutSLForwardIssues =
925 VectorizerParams::MaxVectorWidth * TypeByteSize;
Adam Nemet04d41632015-02-19 19:14:34 +0000926 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
Adam Nemet04563272015-02-01 16:56:15 +0000927 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
928
929 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
930 vf *= 2) {
931 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
932 MaxVFWithoutSLForwardIssues = (vf >>=1);
933 break;
934 }
935 }
936
Adam Nemet04d41632015-02-19 19:14:34 +0000937 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
Adam Nemet339f42b2015-02-19 19:15:07 +0000938 DEBUG(dbgs() << "LAA: Distance " << Distance <<
Adam Nemet04d41632015-02-19 19:14:34 +0000939 " that could cause a store-load forwarding conflict\n");
Adam Nemet04563272015-02-01 16:56:15 +0000940 return true;
941 }
942
943 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
Adam Nemetf219c642015-02-19 19:14:52 +0000944 MaxVFWithoutSLForwardIssues !=
945 VectorizerParams::MaxVectorWidth * TypeByteSize)
Adam Nemet04563272015-02-01 16:56:15 +0000946 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
947 return false;
948}
949
Hao Liu751004a2015-06-08 04:48:37 +0000950/// \brief Check the dependence for two accesses with the same stride \p Stride.
951/// \p Distance is the positive distance and \p TypeByteSize is type size in
952/// bytes.
953///
954/// \returns true if they are independent.
955static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride,
956 unsigned TypeByteSize) {
957 assert(Stride > 1 && "The stride must be greater than 1");
958 assert(TypeByteSize > 0 && "The type size in byte must be non-zero");
959 assert(Distance > 0 && "The distance must be non-zero");
960
961 // Skip if the distance is not multiple of type byte size.
962 if (Distance % TypeByteSize)
963 return false;
964
965 unsigned ScaledDist = Distance / TypeByteSize;
966
967 // No dependence if the scaled distance is not multiple of the stride.
968 // E.g.
969 // for (i = 0; i < 1024 ; i += 4)
970 // A[i+2] = A[i] + 1;
971 //
972 // Two accesses in memory (scaled distance is 2, stride is 4):
973 // | A[0] | | | | A[4] | | | |
974 // | | | A[2] | | | | A[6] | |
975 //
976 // E.g.
977 // for (i = 0; i < 1024 ; i += 3)
978 // A[i+4] = A[i] + 1;
979 //
980 // Two accesses in memory (scaled distance is 4, stride is 3):
981 // | A[0] | | | A[3] | | | A[6] | | |
982 // | | | | | A[4] | | | A[7] | |
983 return ScaledDist % Stride;
984}
985
Adam Nemet9c926572015-03-10 17:40:37 +0000986MemoryDepChecker::Dependence::DepType
987MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
988 const MemAccessInfo &B, unsigned BIdx,
989 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +0000990 assert (AIdx < BIdx && "Must pass arguments in program order");
991
992 Value *APtr = A.getPointer();
993 Value *BPtr = B.getPointer();
994 bool AIsWrite = A.getInt();
995 bool BIsWrite = B.getInt();
996
997 // Two reads are independent.
998 if (!AIsWrite && !BIsWrite)
Adam Nemet9c926572015-03-10 17:40:37 +0000999 return Dependence::NoDep;
Adam Nemet04563272015-02-01 16:56:15 +00001000
1001 // We cannot check pointers in different address spaces.
1002 if (APtr->getType()->getPointerAddressSpace() !=
1003 BPtr->getType()->getPointerAddressSpace())
Adam Nemet9c926572015-03-10 17:40:37 +00001004 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001005
1006 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
1007 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
1008
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001009 int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides);
1010 int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides);
Adam Nemet04563272015-02-01 16:56:15 +00001011
1012 const SCEV *Src = AScev;
1013 const SCEV *Sink = BScev;
1014
1015 // If the induction step is negative we have to invert source and sink of the
1016 // dependence.
1017 if (StrideAPtr < 0) {
1018 //Src = BScev;
1019 //Sink = AScev;
1020 std::swap(APtr, BPtr);
1021 std::swap(Src, Sink);
1022 std::swap(AIsWrite, BIsWrite);
1023 std::swap(AIdx, BIdx);
1024 std::swap(StrideAPtr, StrideBPtr);
1025 }
1026
1027 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
1028
Adam Nemet339f42b2015-02-19 19:15:07 +00001029 DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink
Adam Nemet04d41632015-02-19 19:14:34 +00001030 << "(Induction step: " << StrideAPtr << ")\n");
Adam Nemet339f42b2015-02-19 19:15:07 +00001031 DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to "
Adam Nemet04d41632015-02-19 19:14:34 +00001032 << *InstMap[BIdx] << ": " << *Dist << "\n");
Adam Nemet04563272015-02-01 16:56:15 +00001033
Adam Nemet943befe2015-07-09 00:03:22 +00001034 // Need accesses with constant stride. We don't want to vectorize
Adam Nemet04563272015-02-01 16:56:15 +00001035 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
1036 // the address space.
1037 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
Adam Nemet943befe2015-07-09 00:03:22 +00001038 DEBUG(dbgs() << "Pointer access with non-constant stride\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001039 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001040 }
1041
1042 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
1043 if (!C) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001044 DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n");
Adam Nemet04563272015-02-01 16:56:15 +00001045 ShouldRetryWithRuntimeCheck = true;
Adam Nemet9c926572015-03-10 17:40:37 +00001046 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001047 }
1048
1049 Type *ATy = APtr->getType()->getPointerElementType();
1050 Type *BTy = BPtr->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001051 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1052 unsigned TypeByteSize = DL.getTypeAllocSize(ATy);
Adam Nemet04563272015-02-01 16:56:15 +00001053
1054 // Negative distances are not plausible dependencies.
1055 const APInt &Val = C->getValue()->getValue();
1056 if (Val.isNegative()) {
1057 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1058 if (IsTrueDataDependence &&
1059 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
1060 ATy != BTy))
Adam Nemet9c926572015-03-10 17:40:37 +00001061 return Dependence::ForwardButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001062
Adam Nemet339f42b2015-02-19 19:15:07 +00001063 DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001064 return Dependence::Forward;
Adam Nemet04563272015-02-01 16:56:15 +00001065 }
1066
1067 // Write to the same location with the same size.
1068 // Could be improved to assert type sizes are the same (i32 == float, etc).
1069 if (Val == 0) {
1070 if (ATy == BTy)
Adam Nemet9c926572015-03-10 17:40:37 +00001071 return Dependence::NoDep;
Adam Nemet339f42b2015-02-19 19:15:07 +00001072 DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001073 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001074 }
1075
1076 assert(Val.isStrictlyPositive() && "Expect a positive value");
1077
Adam Nemet04563272015-02-01 16:56:15 +00001078 if (ATy != BTy) {
Adam Nemet04d41632015-02-19 19:14:34 +00001079 DEBUG(dbgs() <<
Adam Nemet339f42b2015-02-19 19:15:07 +00001080 "LAA: ReadWrite-Write positive dependency with different types\n");
Adam Nemet9c926572015-03-10 17:40:37 +00001081 return Dependence::Unknown;
Adam Nemet04563272015-02-01 16:56:15 +00001082 }
1083
1084 unsigned Distance = (unsigned) Val.getZExtValue();
1085
Hao Liu751004a2015-06-08 04:48:37 +00001086 unsigned Stride = std::abs(StrideAPtr);
1087 if (Stride > 1 &&
Adam Nemet0131a562015-07-08 18:47:38 +00001088 areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) {
1089 DEBUG(dbgs() << "LAA: Strided accesses are independent\n");
Hao Liu751004a2015-06-08 04:48:37 +00001090 return Dependence::NoDep;
Adam Nemet0131a562015-07-08 18:47:38 +00001091 }
Hao Liu751004a2015-06-08 04:48:37 +00001092
Adam Nemet04563272015-02-01 16:56:15 +00001093 // Bail out early if passed-in parameters make vectorization not feasible.
Adam Nemetf219c642015-02-19 19:14:52 +00001094 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ?
1095 VectorizerParams::VectorizationFactor : 1);
1096 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ?
1097 VectorizerParams::VectorizationInterleave : 1);
Hao Liu751004a2015-06-08 04:48:37 +00001098 // The minimum number of iterations for a vectorized/unrolled version.
1099 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U);
Adam Nemet04563272015-02-01 16:56:15 +00001100
Hao Liu751004a2015-06-08 04:48:37 +00001101 // It's not vectorizable if the distance is smaller than the minimum distance
1102 // needed for a vectroized/unrolled version. Vectorizing one iteration in
1103 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs
1104 // TypeByteSize (No need to plus the last gap distance).
1105 //
1106 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1107 // foo(int *A) {
1108 // int *B = (int *)((char *)A + 14);
1109 // for (i = 0 ; i < 1024 ; i += 2)
1110 // B[i] = A[i] + 1;
1111 // }
1112 //
1113 // Two accesses in memory (stride is 2):
1114 // | A[0] | | A[2] | | A[4] | | A[6] | |
1115 // | B[0] | | B[2] | | B[4] |
1116 //
1117 // Distance needs for vectorizing iterations except the last iteration:
1118 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4.
1119 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4.
1120 //
1121 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is
1122 // 12, which is less than distance.
1123 //
1124 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4),
1125 // the minimum distance needed is 28, which is greater than distance. It is
1126 // not safe to do vectorization.
1127 unsigned MinDistanceNeeded =
1128 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1129 if (MinDistanceNeeded > Distance) {
1130 DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance
1131 << '\n');
1132 return Dependence::Backward;
1133 }
1134
1135 // Unsafe if the minimum distance needed is greater than max safe distance.
1136 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1137 DEBUG(dbgs() << "LAA: Failure because it needs at least "
1138 << MinDistanceNeeded << " size in bytes");
Adam Nemet9c926572015-03-10 17:40:37 +00001139 return Dependence::Backward;
Adam Nemet04563272015-02-01 16:56:15 +00001140 }
1141
Adam Nemet9cc0c392015-02-26 17:58:48 +00001142 // Positive distance bigger than max vectorization factor.
Hao Liu751004a2015-06-08 04:48:37 +00001143 // FIXME: Should use max factor instead of max distance in bytes, which could
1144 // not handle different types.
1145 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes.
1146 // void foo (int *A, char *B) {
1147 // for (unsigned i = 0; i < 1024; i++) {
1148 // A[i+2] = A[i] + 1;
1149 // B[i+2] = B[i] + 1;
1150 // }
1151 // }
1152 //
1153 // This case is currently unsafe according to the max safe distance. If we
1154 // analyze the two accesses on array B, the max safe dependence distance
1155 // is 2. Then we analyze the accesses on array A, the minimum distance needed
1156 // is 8, which is less than 2 and forbidden vectorization, But actually
1157 // both A and B could be vectorized by 2 iterations.
1158 MaxSafeDepDistBytes =
1159 Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes;
Adam Nemet04563272015-02-01 16:56:15 +00001160
1161 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1162 if (IsTrueDataDependence &&
1163 couldPreventStoreLoadForward(Distance, TypeByteSize))
Adam Nemet9c926572015-03-10 17:40:37 +00001164 return Dependence::BackwardVectorizableButPreventsForwarding;
Adam Nemet04563272015-02-01 16:56:15 +00001165
Hao Liu751004a2015-06-08 04:48:37 +00001166 DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue()
1167 << " with max VF = "
1168 << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n');
Adam Nemet04563272015-02-01 16:56:15 +00001169
Adam Nemet9c926572015-03-10 17:40:37 +00001170 return Dependence::BackwardVectorizable;
Adam Nemet04563272015-02-01 16:56:15 +00001171}
1172
Adam Nemetdee666b2015-03-10 17:40:34 +00001173bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets,
Adam Nemet04563272015-02-01 16:56:15 +00001174 MemAccessInfoSet &CheckDeps,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001175 const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001176
1177 MaxSafeDepDistBytes = -1U;
1178 while (!CheckDeps.empty()) {
1179 MemAccessInfo CurAccess = *CheckDeps.begin();
1180
1181 // Get the relevant memory access set.
1182 EquivalenceClasses<MemAccessInfo>::iterator I =
1183 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
1184
1185 // Check accesses within this set.
1186 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
1187 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
1188
1189 // Check every access pair.
1190 while (AI != AE) {
1191 CheckDeps.erase(*AI);
1192 EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI);
1193 while (OI != AE) {
1194 // Check every accessing instruction pair in program order.
1195 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
1196 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
1197 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
1198 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
Adam Nemet9c926572015-03-10 17:40:37 +00001199 auto A = std::make_pair(&*AI, *I1);
1200 auto B = std::make_pair(&*OI, *I2);
1201
1202 assert(*I1 != *I2);
1203 if (*I1 > *I2)
1204 std::swap(A, B);
1205
1206 Dependence::DepType Type =
1207 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1208 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1209
1210 // Gather dependences unless we accumulated MaxInterestingDependence
1211 // dependences. In that case return as soon as we find the first
1212 // unsafe dependence. This puts a limit on this quadratic
1213 // algorithm.
1214 if (RecordInterestingDependences) {
1215 if (Dependence::isInterestingDependence(Type))
1216 InterestingDependences.push_back(
1217 Dependence(A.second, B.second, Type));
1218
1219 if (InterestingDependences.size() >= MaxInterestingDependence) {
1220 RecordInterestingDependences = false;
1221 InterestingDependences.clear();
1222 DEBUG(dbgs() << "Too many dependences, stopped recording\n");
1223 }
1224 }
1225 if (!RecordInterestingDependences && !SafeForVectorization)
Adam Nemet04563272015-02-01 16:56:15 +00001226 return false;
1227 }
1228 ++OI;
1229 }
1230 AI++;
1231 }
1232 }
Adam Nemet9c926572015-03-10 17:40:37 +00001233
1234 DEBUG(dbgs() << "Total Interesting Dependences: "
1235 << InterestingDependences.size() << "\n");
1236 return SafeForVectorization;
Adam Nemet04563272015-02-01 16:56:15 +00001237}
1238
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001239SmallVector<Instruction *, 4>
1240MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const {
1241 MemAccessInfo Access(Ptr, isWrite);
1242 auto &IndexVector = Accesses.find(Access)->second;
1243
1244 SmallVector<Instruction *, 4> Insts;
1245 std::transform(IndexVector.begin(), IndexVector.end(),
1246 std::back_inserter(Insts),
1247 [&](unsigned Idx) { return this->InstMap[Idx]; });
1248 return Insts;
1249}
1250
Adam Nemet58913d62015-03-10 17:40:43 +00001251const char *MemoryDepChecker::Dependence::DepName[] = {
1252 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward",
1253 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"};
1254
1255void MemoryDepChecker::Dependence::print(
1256 raw_ostream &OS, unsigned Depth,
1257 const SmallVectorImpl<Instruction *> &Instrs) const {
1258 OS.indent(Depth) << DepName[Type] << ":\n";
1259 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n";
1260 OS.indent(Depth + 2) << *Instrs[Destination] << "\n";
1261}
1262
Adam Nemet929c38e2015-02-19 19:15:10 +00001263bool LoopAccessInfo::canAnalyzeLoop() {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001264 // We need to have a loop header.
1265 DEBUG(dbgs() << "LAA: Found a loop: " <<
1266 TheLoop->getHeader()->getName() << '\n');
1267
Adam Nemet929c38e2015-02-19 19:15:10 +00001268 // We can only analyze innermost loops.
1269 if (!TheLoop->empty()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001270 DEBUG(dbgs() << "LAA: loop is not the innermost loop\n");
Adam Nemet2bd6e982015-02-19 19:15:15 +00001271 emitAnalysis(LoopAccessReport() << "loop is not the innermost loop");
Adam Nemet929c38e2015-02-19 19:15:10 +00001272 return false;
1273 }
1274
1275 // We must have a single backedge.
1276 if (TheLoop->getNumBackEdges() != 1) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001277 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001278 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001279 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001280 "loop control flow is not understood by analyzer");
1281 return false;
1282 }
1283
1284 // We must have a single exiting block.
1285 if (!TheLoop->getExitingBlock()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001286 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001287 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001288 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001289 "loop control flow is not understood by analyzer");
1290 return false;
1291 }
1292
1293 // We only handle bottom-tested loops, i.e. loop in which the condition is
1294 // checked at the end of each iteration. With that we can assume that all
1295 // instructions in the loop are executed the same number of times.
1296 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
Adam Nemet8dcb3b62015-04-17 22:43:10 +00001297 DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n");
Adam Nemet929c38e2015-02-19 19:15:10 +00001298 emitAnalysis(
Adam Nemet2bd6e982015-02-19 19:15:15 +00001299 LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001300 "loop control flow is not understood by analyzer");
1301 return false;
1302 }
1303
Adam Nemet929c38e2015-02-19 19:15:10 +00001304 // ScalarEvolution needs to be able to find the exit count.
1305 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
1306 if (ExitCount == SE->getCouldNotCompute()) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001307 emitAnalysis(LoopAccessReport() <<
Adam Nemet929c38e2015-02-19 19:15:10 +00001308 "could not determine number of loop iterations");
1309 DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n");
1310 return false;
1311 }
1312
1313 return true;
1314}
1315
Adam Nemet8bc61df2015-02-24 00:41:59 +00001316void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) {
Adam Nemet04563272015-02-01 16:56:15 +00001317
1318 typedef SmallVector<Value*, 16> ValueVector;
1319 typedef SmallPtrSet<Value*, 16> ValueSet;
1320
1321 // Holds the Load and Store *instructions*.
1322 ValueVector Loads;
1323 ValueVector Stores;
1324
1325 // Holds all the different accesses in the loop.
1326 unsigned NumReads = 0;
1327 unsigned NumReadWrites = 0;
1328
Adam Nemet7cdebac2015-07-14 22:32:44 +00001329 PtrRtChecking.Pointers.clear();
1330 PtrRtChecking.Need = false;
Adam Nemet04563272015-02-01 16:56:15 +00001331
1332 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
Adam Nemet04563272015-02-01 16:56:15 +00001333
1334 // For each block.
1335 for (Loop::block_iterator bb = TheLoop->block_begin(),
1336 be = TheLoop->block_end(); bb != be; ++bb) {
1337
1338 // Scan the BB and collect legal loads and stores.
1339 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1340 ++it) {
1341
1342 // If this is a load, save it. If this instruction can read from memory
1343 // but is not a load, then we quit. Notice that we don't handle function
1344 // calls that read or write.
1345 if (it->mayReadFromMemory()) {
1346 // Many math library functions read the rounding mode. We will only
1347 // vectorize a loop if it contains known function calls that don't set
1348 // the flag. Therefore, it is safe to ignore this read from memory.
1349 CallInst *Call = dyn_cast<CallInst>(it);
1350 if (Call && getIntrinsicIDForCall(Call, TLI))
1351 continue;
1352
Michael Zolotukhin9b3cf602015-03-17 19:46:50 +00001353 // If the function has an explicit vectorized counterpart, we can safely
1354 // assume that it can be vectorized.
1355 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() &&
1356 TLI->isFunctionVectorizable(Call->getCalledFunction()->getName()))
1357 continue;
1358
Adam Nemet04563272015-02-01 16:56:15 +00001359 LoadInst *Ld = dyn_cast<LoadInst>(it);
1360 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001361 emitAnalysis(LoopAccessReport(Ld)
Adam Nemet04563272015-02-01 16:56:15 +00001362 << "read with atomic ordering or volatile read");
Adam Nemet339f42b2015-02-19 19:15:07 +00001363 DEBUG(dbgs() << "LAA: Found a non-simple load.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001364 CanVecMem = false;
1365 return;
Adam Nemet04563272015-02-01 16:56:15 +00001366 }
1367 NumLoads++;
1368 Loads.push_back(Ld);
1369 DepChecker.addAccess(Ld);
1370 continue;
1371 }
1372
1373 // Save 'store' instructions. Abort if other instructions write to memory.
1374 if (it->mayWriteToMemory()) {
1375 StoreInst *St = dyn_cast<StoreInst>(it);
1376 if (!St) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001377 emitAnalysis(LoopAccessReport(it) <<
Adam Nemet04d41632015-02-19 19:14:34 +00001378 "instruction cannot be vectorized");
Adam Nemet436018c2015-02-19 19:15:00 +00001379 CanVecMem = false;
1380 return;
Adam Nemet04563272015-02-01 16:56:15 +00001381 }
1382 if (!St->isSimple() && !IsAnnotatedParallel) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001383 emitAnalysis(LoopAccessReport(St)
Adam Nemet04563272015-02-01 16:56:15 +00001384 << "write with atomic ordering or volatile write");
Adam Nemet339f42b2015-02-19 19:15:07 +00001385 DEBUG(dbgs() << "LAA: Found a non-simple store.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001386 CanVecMem = false;
1387 return;
Adam Nemet04563272015-02-01 16:56:15 +00001388 }
1389 NumStores++;
1390 Stores.push_back(St);
1391 DepChecker.addAccess(St);
1392 }
1393 } // Next instr.
1394 } // Next block.
1395
1396 // Now we have two lists that hold the loads and the stores.
1397 // Next, we find the pointers that they use.
1398
1399 // Check if we see any stores. If there are no stores, then we don't
1400 // care if the pointers are *restrict*.
1401 if (!Stores.size()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001402 DEBUG(dbgs() << "LAA: Found a read-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001403 CanVecMem = true;
1404 return;
Adam Nemet04563272015-02-01 16:56:15 +00001405 }
1406
Adam Nemetdee666b2015-03-10 17:40:34 +00001407 MemoryDepChecker::DepCandidates DependentAccesses;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001408 AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(),
Adam Nemete2b885c2015-04-23 20:09:20 +00001409 AA, LI, DependentAccesses);
Adam Nemet04563272015-02-01 16:56:15 +00001410
1411 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1412 // multiple times on the same object. If the ptr is accessed twice, once
1413 // for read and once for write, it will only appear once (on the write
1414 // list). This is okay, since we are going to check for conflicts between
1415 // writes and between reads and writes, but not between reads and reads.
1416 ValueSet Seen;
1417
1418 ValueVector::iterator I, IE;
1419 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1420 StoreInst *ST = cast<StoreInst>(*I);
1421 Value* Ptr = ST->getPointerOperand();
Adam Nemetce482502015-04-08 17:48:40 +00001422 // Check for store to loop invariant address.
1423 StoreToLoopInvariantAddress |= isUniform(Ptr);
Adam Nemet04563272015-02-01 16:56:15 +00001424 // If we did *not* see this pointer before, insert it to the read-write
1425 // list. At this phase it is only a 'write' list.
1426 if (Seen.insert(Ptr).second) {
1427 ++NumReadWrites;
1428
Chandler Carruthac80dc72015-06-17 07:18:54 +00001429 MemoryLocation Loc = MemoryLocation::get(ST);
Adam Nemet04563272015-02-01 16:56:15 +00001430 // The TBAA metadata could have a control dependency on the predication
1431 // condition, so we cannot rely on it when determining whether or not we
1432 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001433 if (blockNeedsPredication(ST->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001434 Loc.AATags.TBAA = nullptr;
1435
1436 Accesses.addStore(Loc);
1437 }
1438 }
1439
1440 if (IsAnnotatedParallel) {
Adam Nemet04d41632015-02-19 19:14:34 +00001441 DEBUG(dbgs()
Adam Nemet339f42b2015-02-19 19:15:07 +00001442 << "LAA: A loop annotated parallel, ignore memory dependency "
Adam Nemet04d41632015-02-19 19:14:34 +00001443 << "checks.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001444 CanVecMem = true;
1445 return;
Adam Nemet04563272015-02-01 16:56:15 +00001446 }
1447
1448 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1449 LoadInst *LD = cast<LoadInst>(*I);
1450 Value* Ptr = LD->getPointerOperand();
1451 // If we did *not* see this pointer before, insert it to the
1452 // read list. If we *did* see it before, then it is already in
1453 // the read-write list. This allows us to vectorize expressions
1454 // such as A[i] += x; Because the address of A[i] is a read-write
1455 // pointer. This only works if the index of A[i] is consecutive.
1456 // If the address of i is unknown (for example A[B[i]]) then we may
1457 // read a few words, modify, and write a few words, and some of the
1458 // words may be written to the same address.
1459 bool IsReadOnlyPtr = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001460 if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) {
Adam Nemet04563272015-02-01 16:56:15 +00001461 ++NumReads;
1462 IsReadOnlyPtr = true;
1463 }
1464
Chandler Carruthac80dc72015-06-17 07:18:54 +00001465 MemoryLocation Loc = MemoryLocation::get(LD);
Adam Nemet04563272015-02-01 16:56:15 +00001466 // The TBAA metadata could have a control dependency on the predication
1467 // condition, so we cannot rely on it when determining whether or not we
1468 // need runtime pointer checks.
Adam Nemet01abb2c2015-02-18 03:43:19 +00001469 if (blockNeedsPredication(LD->getParent(), TheLoop, DT))
Adam Nemet04563272015-02-01 16:56:15 +00001470 Loc.AATags.TBAA = nullptr;
1471
1472 Accesses.addLoad(Loc, IsReadOnlyPtr);
1473 }
1474
1475 // If we write (or read-write) to a single destination and there are no
1476 // other reads in this loop then is it safe to vectorize.
1477 if (NumReadWrites == 1 && NumReads == 0) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001478 DEBUG(dbgs() << "LAA: Found a write-only loop!\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001479 CanVecMem = true;
1480 return;
Adam Nemet04563272015-02-01 16:56:15 +00001481 }
1482
1483 // Build dependence sets and check whether we need a runtime pointer bounds
1484 // check.
1485 Accesses.buildDependenceSets();
Adam Nemet04563272015-02-01 16:56:15 +00001486
1487 // Find pointers with computable bounds. We are going to use this information
1488 // to place a runtime bound check.
Adam Nemetee614742015-07-09 22:17:38 +00001489 bool CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001490 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides);
Adam Nemetee614742015-07-09 22:17:38 +00001491 if (!CanDoRTIfNeeded) {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001492 emitAnalysis(LoopAccessReport() << "cannot identify array bounds");
Adam Nemetee614742015-07-09 22:17:38 +00001493 DEBUG(dbgs() << "LAA: We can't vectorize because we can't find "
1494 << "the array bounds.\n");
Adam Nemet436018c2015-02-19 19:15:00 +00001495 CanVecMem = false;
1496 return;
Adam Nemet04563272015-02-01 16:56:15 +00001497 }
1498
Adam Nemetee614742015-07-09 22:17:38 +00001499 DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n");
Adam Nemet04563272015-02-01 16:56:15 +00001500
Adam Nemet436018c2015-02-19 19:15:00 +00001501 CanVecMem = true;
Adam Nemet04563272015-02-01 16:56:15 +00001502 if (Accesses.isDependencyCheckNeeded()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001503 DEBUG(dbgs() << "LAA: Checking memory dependencies\n");
Adam Nemet04563272015-02-01 16:56:15 +00001504 CanVecMem = DepChecker.areDepsSafe(
1505 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
1506 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
1507
1508 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
Adam Nemet339f42b2015-02-19 19:15:07 +00001509 DEBUG(dbgs() << "LAA: Retrying with memory checks\n");
Adam Nemet04563272015-02-01 16:56:15 +00001510
1511 // Clear the dependency checks. We assume they are not needed.
Adam Nemetdf3dc5b2015-05-18 15:37:03 +00001512 Accesses.resetDepChecks(DepChecker);
Adam Nemet04563272015-02-01 16:56:15 +00001513
Adam Nemet7cdebac2015-07-14 22:32:44 +00001514 PtrRtChecking.reset();
1515 PtrRtChecking.Need = true;
Adam Nemet04563272015-02-01 16:56:15 +00001516
Adam Nemetee614742015-07-09 22:17:38 +00001517 CanDoRTIfNeeded =
Adam Nemet7cdebac2015-07-14 22:32:44 +00001518 Accesses.canCheckPtrAtRT(PtrRtChecking, SE, TheLoop, Strides, true);
Silviu Baranga98a13712015-06-08 10:27:06 +00001519
Adam Nemet949e91a2015-03-10 19:12:41 +00001520 // Check that we found the bounds for the pointer.
Adam Nemetee614742015-07-09 22:17:38 +00001521 if (!CanDoRTIfNeeded) {
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001522 emitAnalysis(LoopAccessReport()
1523 << "cannot check memory dependencies at runtime");
1524 DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n");
Adam Nemetb6dc76f2015-03-10 18:54:19 +00001525 CanVecMem = false;
1526 return;
1527 }
1528
Adam Nemet04563272015-02-01 16:56:15 +00001529 CanVecMem = true;
1530 }
1531 }
1532
Adam Nemet4bb90a72015-03-10 21:47:39 +00001533 if (CanVecMem)
1534 DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We"
Adam Nemet7cdebac2015-07-14 22:32:44 +00001535 << (PtrRtChecking.Need ? "" : " don't")
Adam Nemet0f67c6c2015-07-09 22:17:41 +00001536 << " need runtime memory checks.\n");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001537 else {
Adam Nemet2bd6e982015-02-19 19:15:15 +00001538 emitAnalysis(LoopAccessReport() <<
Adam Nemet04d41632015-02-19 19:14:34 +00001539 "unsafe dependent memory operations in loop");
Adam Nemet4bb90a72015-03-10 21:47:39 +00001540 DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n");
1541 }
Adam Nemet04563272015-02-01 16:56:15 +00001542}
1543
Adam Nemet01abb2c2015-02-18 03:43:19 +00001544bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
1545 DominatorTree *DT) {
Adam Nemet04563272015-02-01 16:56:15 +00001546 assert(TheLoop->contains(BB) && "Unknown block used");
1547
1548 // Blocks that do not dominate the latch need predication.
1549 BasicBlock* Latch = TheLoop->getLoopLatch();
1550 return !DT->dominates(BB, Latch);
1551}
1552
Adam Nemet2bd6e982015-02-19 19:15:15 +00001553void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) {
Adam Nemetc9228532015-02-19 19:14:56 +00001554 assert(!Report && "Multiple reports generated");
1555 Report = Message;
Adam Nemet04563272015-02-01 16:56:15 +00001556}
1557
Adam Nemet57ac7662015-02-19 19:15:21 +00001558bool LoopAccessInfo::isUniform(Value *V) const {
Adam Nemet04563272015-02-01 16:56:15 +00001559 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1560}
Adam Nemet7206d7a2015-02-06 18:31:04 +00001561
1562// FIXME: this function is currently a duplicate of the one in
1563// LoopVectorize.cpp.
1564static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1565 Instruction *Loc) {
1566 if (FirstInst)
1567 return FirstInst;
1568 if (Instruction *I = dyn_cast<Instruction>(V))
1569 return I->getParent() == Loc->getParent() ? I : nullptr;
1570 return nullptr;
1571}
1572
Adam Nemetec1e2bb2015-03-10 18:54:26 +00001573std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck(
1574 Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const {
Adam Nemet7cdebac2015-07-14 22:32:44 +00001575 if (!PtrRtChecking.Need)
Adam Nemet90fec842015-04-02 17:51:57 +00001576 return std::make_pair(nullptr, nullptr);
Adam Nemet7206d7a2015-02-06 18:31:04 +00001577
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001578 SmallVector<TrackingVH<Value>, 2> Starts;
1579 SmallVector<TrackingVH<Value>, 2> Ends;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001580
1581 LLVMContext &Ctx = Loc->getContext();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001582 SCEVExpander Exp(*SE, DL, "induction");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001583 Instruction *FirstInst = nullptr;
1584
Adam Nemet7cdebac2015-07-14 22:32:44 +00001585 for (unsigned i = 0; i < PtrRtChecking.CheckingGroups.size(); ++i) {
1586 const RuntimePointerChecking::CheckingPtrGroup &CG =
1587 PtrRtChecking.CheckingGroups[i];
Adam Nemet9f7dedc2015-07-14 22:32:50 +00001588 Value *Ptr = PtrRtChecking.Pointers[CG.Members[0]].PointerValue;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001589 const SCEV *Sc = SE->getSCEV(Ptr);
1590
1591 if (SE->isLoopInvariant(Sc, TheLoop)) {
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001592 DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1593 << "\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001594 Starts.push_back(Ptr);
1595 Ends.push_back(Ptr);
1596 } else {
Adam Nemet7206d7a2015-02-06 18:31:04 +00001597 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1598
1599 // Use this type for pointer arithmetic.
1600 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001601 Value *Start = nullptr, *End = nullptr;
Adam Nemet7206d7a2015-02-06 18:31:04 +00001602
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001603 DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
1604 Start = Exp.expandCodeFor(CG.Low, PtrArithTy, Loc);
1605 End = Exp.expandCodeFor(CG.High, PtrArithTy, Loc);
1606 DEBUG(dbgs() << "Start: " << *CG.Low << " End: " << *CG.High << "\n");
Adam Nemet7206d7a2015-02-06 18:31:04 +00001607 Starts.push_back(Start);
1608 Ends.push_back(End);
1609 }
1610 }
1611
1612 IRBuilder<> ChkBuilder(Loc);
1613 // Our instructions might fold to a constant.
1614 Value *MemoryRuntimeCheck = nullptr;
Adam Nemet7cdebac2015-07-14 22:32:44 +00001615 for (unsigned i = 0; i < PtrRtChecking.CheckingGroups.size(); ++i) {
1616 for (unsigned j = i + 1; j < PtrRtChecking.CheckingGroups.size(); ++j) {
1617 const RuntimePointerChecking::CheckingPtrGroup &CGI =
1618 PtrRtChecking.CheckingGroups[i];
1619 const RuntimePointerChecking::CheckingPtrGroup &CGJ =
1620 PtrRtChecking.CheckingGroups[j];
Silviu Baranga1b6b50a2015-07-08 09:16:33 +00001621
Adam Nemet7cdebac2015-07-14 22:32:44 +00001622 if (!PtrRtChecking.needsChecking(CGI, CGJ, PtrPartition))
Adam Nemet7206d7a2015-02-06 18:31:04 +00001623 continue;
1624
1625 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1626 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1627
1628 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1629 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1630 "Trying to bounds check pointers with different address spaces");
1631
1632 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1633 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1634
1635 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1636 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1637 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1638 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1639
1640 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1641 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1642 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1643 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1644 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1645 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1646 if (MemoryRuntimeCheck) {
1647 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1648 "conflict.rdx");
1649 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1650 }
1651 MemoryRuntimeCheck = IsConflict;
1652 }
1653 }
1654
Adam Nemet90fec842015-04-02 17:51:57 +00001655 if (!MemoryRuntimeCheck)
1656 return std::make_pair(nullptr, nullptr);
1657
Adam Nemet7206d7a2015-02-06 18:31:04 +00001658 // We have to do this trickery because the IRBuilder might fold the check to a
1659 // constant expression in which case there is no Instruction anchored in a
1660 // the block.
1661 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1662 ConstantInt::getTrue(Ctx));
1663 ChkBuilder.Insert(Check, "memcheck.conflict");
1664 FirstInst = getFirstInst(FirstInst, Check, Loc);
1665 return std::make_pair(FirstInst, Check);
1666}
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001667
1668LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001669 const DataLayout &DL,
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001670 const TargetLibraryInfo *TLI, AliasAnalysis *AA,
Adam Nemete2b885c2015-04-23 20:09:20 +00001671 DominatorTree *DT, LoopInfo *LI,
Adam Nemet8bc61df2015-02-24 00:41:59 +00001672 const ValueToValueMap &Strides)
Adam Nemet7cdebac2015-07-14 22:32:44 +00001673 : PtrRtChecking(SE), DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL),
1674 TLI(TLI), AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0),
Adam Nemetce482502015-04-08 17:48:40 +00001675 MaxSafeDepDistBytes(-1U), CanVecMem(false),
1676 StoreToLoopInvariantAddress(false) {
Adam Nemet929c38e2015-02-19 19:15:10 +00001677 if (canAnalyzeLoop())
1678 analyzeLoop(Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001679}
1680
Adam Nemete91cc6e2015-02-19 19:15:19 +00001681void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const {
1682 if (CanVecMem) {
Adam Nemet7cdebac2015-07-14 22:32:44 +00001683 if (PtrRtChecking.Need)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001684 OS.indent(Depth) << "Memory dependences are safe with run-time checks\n";
Adam Nemet26da8e92015-04-14 01:12:55 +00001685 else
1686 OS.indent(Depth) << "Memory dependences are safe\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001687 }
1688
1689 if (Report)
1690 OS.indent(Depth) << "Report: " << Report->str() << "\n";
1691
Adam Nemet58913d62015-03-10 17:40:43 +00001692 if (auto *InterestingDependences = DepChecker.getInterestingDependences()) {
1693 OS.indent(Depth) << "Interesting Dependences:\n";
1694 for (auto &Dep : *InterestingDependences) {
1695 Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions());
1696 OS << "\n";
1697 }
1698 } else
1699 OS.indent(Depth) << "Too many interesting dependences, not recorded\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001700
1701 // List the pair of accesses need run-time checks to prove independence.
Adam Nemet7cdebac2015-07-14 22:32:44 +00001702 PtrRtChecking.print(OS, Depth);
Adam Nemete91cc6e2015-02-19 19:15:19 +00001703 OS << "\n";
Adam Nemetc3384322015-05-18 15:36:57 +00001704
1705 OS.indent(Depth) << "Store to invariant address was "
1706 << (StoreToLoopInvariantAddress ? "" : "not ")
1707 << "found in loop.\n";
Adam Nemete91cc6e2015-02-19 19:15:19 +00001708}
1709
Adam Nemet8bc61df2015-02-24 00:41:59 +00001710const LoopAccessInfo &
1711LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) {
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001712 auto &LAI = LoopAccessInfoMap[L];
1713
1714#ifndef NDEBUG
1715 assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) &&
1716 "Symbolic strides changed for loop");
1717#endif
1718
1719 if (!LAI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001720 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Adam Nemete2b885c2015-04-23 20:09:20 +00001721 LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI,
1722 Strides);
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001723#ifndef NDEBUG
1724 LAI->NumSymbolicStrides = Strides.size();
1725#endif
1726 }
1727 return *LAI.get();
1728}
1729
Adam Nemete91cc6e2015-02-19 19:15:19 +00001730void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
1731 LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this);
1732
Adam Nemete91cc6e2015-02-19 19:15:19 +00001733 ValueToValueMap NoSymbolicStrides;
1734
1735 for (Loop *TopLevelLoop : *LI)
1736 for (Loop *L : depth_first(TopLevelLoop)) {
1737 OS.indent(2) << L->getHeader()->getName() << ":\n";
1738 auto &LAI = LAA.getInfo(L, NoSymbolicStrides);
1739 LAI.print(OS, 4);
1740 }
1741}
1742
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001743bool LoopAccessAnalysis::runOnFunction(Function &F) {
1744 SE = &getAnalysis<ScalarEvolution>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001745 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1746 TLI = TLIP ? &TLIP->getTLI() : nullptr;
1747 AA = &getAnalysis<AliasAnalysis>();
1748 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Adam Nemete2b885c2015-04-23 20:09:20 +00001749 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001750
1751 return false;
1752}
1753
1754void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
1755 AU.addRequired<ScalarEvolution>();
1756 AU.addRequired<AliasAnalysis>();
1757 AU.addRequired<DominatorTreeWrapperPass>();
Adam Nemete91cc6e2015-02-19 19:15:19 +00001758 AU.addRequired<LoopInfoWrapperPass>();
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001759
1760 AU.setPreservesAll();
1761}
1762
1763char LoopAccessAnalysis::ID = 0;
1764static const char laa_name[] = "Loop Access Analysis";
1765#define LAA_NAME "loop-accesses"
1766
1767INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1768INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1769INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1770INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Adam Nemete91cc6e2015-02-19 19:15:19 +00001771INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Adam Nemet3bfd93d2015-02-19 19:15:04 +00001772INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true)
1773
1774namespace llvm {
1775 Pass *createLAAPass() {
1776 return new LoopAccessAnalysis();
1777 }
1778}