blob: 6e4f6017cc9a0d6b634304e349bfbe9c2be14e50 [file] [log] [blame]
Sebastian Pop59b61b92012-10-11 07:32:34 +00001//===-- DependenceAnalysis.cpp - DA Implementation --------------*- C++ -*-===//
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// DependenceAnalysis is an LLVM pass that analyses dependences between memory
11// accesses. Currently, it is an (incomplete) implementation of the approach
12// described in
13//
14// Practical Dependence Testing
15// Goff, Kennedy, Tseng
16// PLDI 1991
17//
18// There's a single entry point that analyzes the dependence between a pair
19// of memory references in a function, returning either NULL, for no dependence,
20// or a more-or-less detailed description of the dependence between them.
21//
22// Currently, the implementation cannot propagate constraints between
23// coupled RDIV subscripts and lacks a multi-subscript MIV test.
24// Both of these are conservative weaknesses;
25// that is, not a source of correctness problems.
26//
Sebastian Popbf6e1c22018-03-06 21:55:59 +000027// Since Clang linearizes some array subscripts, the dependence
Sebastian Pop7ee14722013-11-13 22:37:58 +000028// analysis is using SCEV->delinearize to recover the representation of multiple
29// subscripts, and thus avoid the more expensive and less precise MIV tests. The
30// delinearization is controlled by the flag -da-delinearize.
Sebastian Pop59b61b92012-10-11 07:32:34 +000031//
32// We should pay some careful attention to the possibility of integer overflow
33// in the implementation of the various tests. This could happen with Add,
34// Subtract, or Multiply, with both APInt's and SCEV's.
35//
36// Some non-linear subscript pairs can be handled by the GCD test
37// (and perhaps other tests).
38// Should explore how often these things occur.
39//
40// Finally, it seems like certain test cases expose weaknesses in the SCEV
41// simplification, especially in the handling of sign and zero extensions.
42// It could be useful to spend time exploring these.
43//
44// Please note that this is work in progress and the interface is subject to
45// change.
46//
47//===----------------------------------------------------------------------===//
48// //
49// In memory of Ken Kennedy, 1945 - 2007 //
50// //
51//===----------------------------------------------------------------------===//
52
Sebastian Pop59b61b92012-10-11 07:32:34 +000053#include "llvm/Analysis/DependenceAnalysis.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000054#include "llvm/ADT/STLExtras.h"
Sebastian Pop59b61b92012-10-11 07:32:34 +000055#include "llvm/ADT/Statistic.h"
Benjamin Kramer71a35122012-10-25 16:15:22 +000056#include "llvm/Analysis/AliasAnalysis.h"
57#include "llvm/Analysis/LoopInfo.h"
Benjamin Kramer71a35122012-10-25 16:15:22 +000058#include "llvm/Analysis/ScalarEvolution.h"
59#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include "llvm/Analysis/ValueTracking.h"
Nico Weber432a3882018-04-30 14:59:11 +000061#include "llvm/Config/llvm-config.h"
Chandler Carruth83948572014-03-04 10:30:26 +000062#include "llvm/IR/InstIterator.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000063#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000064#include "llvm/IR/Operator.h"
Sebastian Popc62c6792013-11-12 22:47:20 +000065#include "llvm/Support/CommandLine.h"
Sebastian Pop59b61b92012-10-11 07:32:34 +000066#include "llvm/Support/Debug.h"
67#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer71a35122012-10-25 16:15:22 +000068#include "llvm/Support/raw_ostream.h"
Sebastian Pop59b61b92012-10-11 07:32:34 +000069
70using namespace llvm;
71
Chandler Carruthf1221bd2014-04-22 02:48:03 +000072#define DEBUG_TYPE "da"
73
Sebastian Pop59b61b92012-10-11 07:32:34 +000074//===----------------------------------------------------------------------===//
75// statistics
76
77STATISTIC(TotalArrayPairs, "Array pairs tested");
78STATISTIC(SeparableSubscriptPairs, "Separable subscript pairs");
79STATISTIC(CoupledSubscriptPairs, "Coupled subscript pairs");
80STATISTIC(NonlinearSubscriptPairs, "Nonlinear subscript pairs");
81STATISTIC(ZIVapplications, "ZIV applications");
82STATISTIC(ZIVindependence, "ZIV independence");
83STATISTIC(StrongSIVapplications, "Strong SIV applications");
84STATISTIC(StrongSIVsuccesses, "Strong SIV successes");
85STATISTIC(StrongSIVindependence, "Strong SIV independence");
86STATISTIC(WeakCrossingSIVapplications, "Weak-Crossing SIV applications");
87STATISTIC(WeakCrossingSIVsuccesses, "Weak-Crossing SIV successes");
88STATISTIC(WeakCrossingSIVindependence, "Weak-Crossing SIV independence");
89STATISTIC(ExactSIVapplications, "Exact SIV applications");
90STATISTIC(ExactSIVsuccesses, "Exact SIV successes");
91STATISTIC(ExactSIVindependence, "Exact SIV independence");
92STATISTIC(WeakZeroSIVapplications, "Weak-Zero SIV applications");
93STATISTIC(WeakZeroSIVsuccesses, "Weak-Zero SIV successes");
94STATISTIC(WeakZeroSIVindependence, "Weak-Zero SIV independence");
95STATISTIC(ExactRDIVapplications, "Exact RDIV applications");
96STATISTIC(ExactRDIVindependence, "Exact RDIV independence");
97STATISTIC(SymbolicRDIVapplications, "Symbolic RDIV applications");
98STATISTIC(SymbolicRDIVindependence, "Symbolic RDIV independence");
99STATISTIC(DeltaApplications, "Delta applications");
100STATISTIC(DeltaSuccesses, "Delta successes");
101STATISTIC(DeltaIndependence, "Delta independence");
102STATISTIC(DeltaPropagations, "Delta propagations");
103STATISTIC(GCDapplications, "GCD applications");
104STATISTIC(GCDsuccesses, "GCD successes");
105STATISTIC(GCDindependence, "GCD independence");
106STATISTIC(BanerjeeApplications, "Banerjee applications");
107STATISTIC(BanerjeeIndependence, "Banerjee independence");
108STATISTIC(BanerjeeSuccesses, "Banerjee successes");
109
Sebastian Popc62c6792013-11-12 22:47:20 +0000110static cl::opt<bool>
111Delinearize("da-delinearize", cl::init(false), cl::Hidden, cl::ZeroOrMore,
112 cl::desc("Try to delinearize array references."));
113
Sebastian Pop59b61b92012-10-11 07:32:34 +0000114//===----------------------------------------------------------------------===//
115// basics
116
Chandler Carruth49c22192016-05-12 22:19:39 +0000117DependenceAnalysis::Result
118DependenceAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
119 auto &AA = FAM.getResult<AAManager>(F);
120 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
121 auto &LI = FAM.getResult<LoopAnalysis>(F);
122 return DependenceInfo(&F, &AA, &SE, &LI);
123}
124
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000125AnalysisKey DependenceAnalysis::Key;
Chandler Carruth49c22192016-05-12 22:19:39 +0000126
127INITIALIZE_PASS_BEGIN(DependenceAnalysisWrapperPass, "da",
Sebastian Pop59b61b92012-10-11 07:32:34 +0000128 "Dependence Analysis", true, true)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000129INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000130INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000131INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth49c22192016-05-12 22:19:39 +0000132INITIALIZE_PASS_END(DependenceAnalysisWrapperPass, "da", "Dependence Analysis",
133 true, true)
Sebastian Pop59b61b92012-10-11 07:32:34 +0000134
Chandler Carruth49c22192016-05-12 22:19:39 +0000135char DependenceAnalysisWrapperPass::ID = 0;
Sebastian Pop59b61b92012-10-11 07:32:34 +0000136
Chandler Carruth49c22192016-05-12 22:19:39 +0000137FunctionPass *llvm::createDependenceAnalysisWrapperPass() {
138 return new DependenceAnalysisWrapperPass();
Sebastian Pop59b61b92012-10-11 07:32:34 +0000139}
140
Chandler Carruth49c22192016-05-12 22:19:39 +0000141bool DependenceAnalysisWrapperPass::runOnFunction(Function &F) {
142 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
143 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
144 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
145 info.reset(new DependenceInfo(&F, &AA, &SE, &LI));
Sebastian Pop59b61b92012-10-11 07:32:34 +0000146 return false;
147}
148
Chandler Carruth49c22192016-05-12 22:19:39 +0000149DependenceInfo &DependenceAnalysisWrapperPass::getDI() const { return *info; }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000150
Chandler Carruth49c22192016-05-12 22:19:39 +0000151void DependenceAnalysisWrapperPass::releaseMemory() { info.reset(); }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000152
Chandler Carruth49c22192016-05-12 22:19:39 +0000153void DependenceAnalysisWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000154 AU.setPreservesAll();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000155 AU.addRequiredTransitive<AAResultsWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000156 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000157 AU.addRequiredTransitive<LoopInfoWrapperPass>();
Sebastian Pop59b61b92012-10-11 07:32:34 +0000158}
159
160
161// Used to test the dependence analyzer.
Benjamin Kramer3eb15632012-11-13 12:12:02 +0000162// Looks through the function, noting loads and stores.
163// Calls depends() on every possible pair and prints out the result.
Sebastian Pop59b61b92012-10-11 07:32:34 +0000164// Ignores all other instructions.
Chandler Carruth49c22192016-05-12 22:19:39 +0000165static void dumpExampleDependence(raw_ostream &OS, DependenceInfo *DA) {
166 auto *F = DA->getFunction();
167 for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F); SrcI != SrcE;
168 ++SrcI) {
Benjamin Kramer3eb15632012-11-13 12:12:02 +0000169 if (isa<StoreInst>(*SrcI) || isa<LoadInst>(*SrcI)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000170 for (inst_iterator DstI = SrcI, DstE = inst_end(F);
171 DstI != DstE; ++DstI) {
Benjamin Kramer3eb15632012-11-13 12:12:02 +0000172 if (isa<StoreInst>(*DstI) || isa<LoadInst>(*DstI)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000173 OS << "da analyze - ";
Dylan Noblesmith2cae60e2014-08-25 00:28:39 +0000174 if (auto D = DA->depends(&*SrcI, &*DstI, true)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000175 D->dump(OS);
176 for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
177 if (D->isSplitable(Level)) {
178 OS << "da analyze - split level = " << Level;
Dylan Noblesmithd96ce662014-08-25 00:28:35 +0000179 OS << ", iteration = " << *DA->getSplitIteration(*D, Level);
Sebastian Pop59b61b92012-10-11 07:32:34 +0000180 OS << "!\n";
181 }
182 }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000183 }
184 else
185 OS << "none!\n";
Sebastian Pop59b61b92012-10-11 07:32:34 +0000186 }
187 }
188 }
189 }
190}
191
Chandler Carruth49c22192016-05-12 22:19:39 +0000192void DependenceAnalysisWrapperPass::print(raw_ostream &OS,
193 const Module *) const {
194 dumpExampleDependence(OS, info.get());
Sebastian Pop59b61b92012-10-11 07:32:34 +0000195}
196
197//===----------------------------------------------------------------------===//
198// Dependence methods
199
200// Returns true if this is an input dependence.
201bool Dependence::isInput() const {
202 return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
203}
204
205
206// Returns true if this is an output dependence.
207bool Dependence::isOutput() const {
208 return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
209}
210
211
212// Returns true if this is an flow (aka true) dependence.
213bool Dependence::isFlow() const {
214 return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
215}
216
217
218// Returns true if this is an anti dependence.
219bool Dependence::isAnti() const {
220 return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
221}
222
223
224// Returns true if a particular level is scalar; that is,
225// if no subscript in the source or destination mention the induction
226// variable associated with the loop at this level.
227// Leave this out of line, so it will serve as a virtual method anchor
228bool Dependence::isScalar(unsigned level) const {
229 return false;
230}
231
232
233//===----------------------------------------------------------------------===//
234// FullDependence methods
235
NAKAMURA Takumi478559a2015-03-05 01:25:19 +0000236FullDependence::FullDependence(Instruction *Source, Instruction *Destination,
Sebastian Pop59b61b92012-10-11 07:32:34 +0000237 bool PossiblyLoopIndependent,
NAKAMURA Takumi478559a2015-03-05 01:25:19 +0000238 unsigned CommonLevels)
239 : Dependence(Source, Destination), Levels(CommonLevels),
240 LoopIndependent(PossiblyLoopIndependent) {
NAKAMURA Takumie110d642015-03-05 01:25:06 +0000241 Consistent = true;
David Blaikie47039dc2015-07-31 21:37:09 +0000242 if (CommonLevels)
243 DV = make_unique<DVEntry[]>(CommonLevels);
NAKAMURA Takumie110d642015-03-05 01:25:06 +0000244}
Sebastian Pop59b61b92012-10-11 07:32:34 +0000245
246// The rest are simple getters that hide the implementation.
247
248// getDirection - Returns the direction associated with a particular level.
249unsigned FullDependence::getDirection(unsigned Level) const {
250 assert(0 < Level && Level <= Levels && "Level out of range");
251 return DV[Level - 1].Direction;
252}
253
254
255// Returns the distance (or NULL) associated with a particular level.
256const SCEV *FullDependence::getDistance(unsigned Level) const {
257 assert(0 < Level && Level <= Levels && "Level out of range");
258 return DV[Level - 1].Distance;
259}
260
261
262// Returns true if a particular level is scalar; that is,
263// if no subscript in the source or destination mention the induction
264// variable associated with the loop at this level.
265bool FullDependence::isScalar(unsigned Level) const {
266 assert(0 < Level && Level <= Levels && "Level out of range");
267 return DV[Level - 1].Scalar;
268}
269
270
271// Returns true if peeling the first iteration from this loop
272// will break this dependence.
273bool FullDependence::isPeelFirst(unsigned Level) const {
274 assert(0 < Level && Level <= Levels && "Level out of range");
275 return DV[Level - 1].PeelFirst;
276}
277
278
279// Returns true if peeling the last iteration from this loop
280// will break this dependence.
281bool FullDependence::isPeelLast(unsigned Level) const {
282 assert(0 < Level && Level <= Levels && "Level out of range");
283 return DV[Level - 1].PeelLast;
284}
285
286
287// Returns true if splitting this loop will break the dependence.
288bool FullDependence::isSplitable(unsigned Level) const {
289 assert(0 < Level && Level <= Levels && "Level out of range");
290 return DV[Level - 1].Splitable;
291}
292
293
294//===----------------------------------------------------------------------===//
Chandler Carruth49c22192016-05-12 22:19:39 +0000295// DependenceInfo::Constraint methods
Sebastian Pop59b61b92012-10-11 07:32:34 +0000296
297// If constraint is a point <X, Y>, returns X.
298// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000299const SCEV *DependenceInfo::Constraint::getX() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000300 assert(Kind == Point && "Kind should be Point");
301 return A;
302}
303
304
305// If constraint is a point <X, Y>, returns Y.
306// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000307const SCEV *DependenceInfo::Constraint::getY() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000308 assert(Kind == Point && "Kind should be Point");
309 return B;
310}
311
312
313// If constraint is a line AX + BY = C, returns A.
314// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000315const SCEV *DependenceInfo::Constraint::getA() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000316 assert((Kind == Line || Kind == Distance) &&
317 "Kind should be Line (or Distance)");
318 return A;
319}
320
321
322// If constraint is a line AX + BY = C, returns B.
323// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000324const SCEV *DependenceInfo::Constraint::getB() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000325 assert((Kind == Line || Kind == Distance) &&
326 "Kind should be Line (or Distance)");
327 return B;
328}
329
330
331// If constraint is a line AX + BY = C, returns C.
332// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000333const SCEV *DependenceInfo::Constraint::getC() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000334 assert((Kind == Line || Kind == Distance) &&
335 "Kind should be Line (or Distance)");
336 return C;
337}
338
339
340// If constraint is a distance, returns D.
341// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000342const SCEV *DependenceInfo::Constraint::getD() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000343 assert(Kind == Distance && "Kind should be Distance");
344 return SE->getNegativeSCEV(C);
345}
346
347
348// Returns the loop associated with this constraint.
Chandler Carruth49c22192016-05-12 22:19:39 +0000349const Loop *DependenceInfo::Constraint::getAssociatedLoop() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000350 assert((Kind == Distance || Kind == Line || Kind == Point) &&
351 "Kind should be Distance, Line, or Point");
352 return AssociatedLoop;
353}
354
Chandler Carruth49c22192016-05-12 22:19:39 +0000355void DependenceInfo::Constraint::setPoint(const SCEV *X, const SCEV *Y,
356 const Loop *CurLoop) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000357 Kind = Point;
358 A = X;
359 B = Y;
360 AssociatedLoop = CurLoop;
361}
362
Chandler Carruth49c22192016-05-12 22:19:39 +0000363void DependenceInfo::Constraint::setLine(const SCEV *AA, const SCEV *BB,
364 const SCEV *CC, const Loop *CurLoop) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000365 Kind = Line;
366 A = AA;
367 B = BB;
368 C = CC;
369 AssociatedLoop = CurLoop;
370}
371
Chandler Carruth49c22192016-05-12 22:19:39 +0000372void DependenceInfo::Constraint::setDistance(const SCEV *D,
373 const Loop *CurLoop) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000374 Kind = Distance;
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000375 A = SE->getOne(D->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +0000376 B = SE->getNegativeSCEV(A);
377 C = SE->getNegativeSCEV(D);
378 AssociatedLoop = CurLoop;
379}
380
Chandler Carruth49c22192016-05-12 22:19:39 +0000381void DependenceInfo::Constraint::setEmpty() { Kind = Empty; }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000382
Chandler Carruth49c22192016-05-12 22:19:39 +0000383void DependenceInfo::Constraint::setAny(ScalarEvolution *NewSE) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000384 SE = NewSE;
385 Kind = Any;
386}
387
Aaron Ballman615eb472017-10-15 14:32:27 +0000388#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sebastian Pop59b61b92012-10-11 07:32:34 +0000389// For debugging purposes. Dumps the constraint out to OS.
Matthias Braun8c209aa2017-01-28 02:02:38 +0000390LLVM_DUMP_METHOD void DependenceInfo::Constraint::dump(raw_ostream &OS) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000391 if (isEmpty())
392 OS << " Empty\n";
393 else if (isAny())
394 OS << " Any\n";
395 else if (isPoint())
396 OS << " Point is <" << *getX() << ", " << *getY() << ">\n";
397 else if (isDistance())
398 OS << " Distance is " << *getD() <<
399 " (" << *getA() << "*X + " << *getB() << "*Y = " << *getC() << ")\n";
400 else if (isLine())
401 OS << " Line is " << *getA() << "*X + " <<
402 *getB() << "*Y = " << *getC() << "\n";
403 else
404 llvm_unreachable("unknown constraint type in Constraint::dump");
405}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000406#endif
Sebastian Pop59b61b92012-10-11 07:32:34 +0000407
408
409// Updates X with the intersection
410// of the Constraints X and Y. Returns true if X has changed.
411// Corresponds to Figure 4 from the paper
412//
413// Practical Dependence Testing
414// Goff, Kennedy, Tseng
415// PLDI 1991
Chandler Carruth49c22192016-05-12 22:19:39 +0000416bool DependenceInfo::intersectConstraints(Constraint *X, const Constraint *Y) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000417 ++DeltaApplications;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000418 LLVM_DEBUG(dbgs() << "\tintersect constraints\n");
419 LLVM_DEBUG(dbgs() << "\t X ="; X->dump(dbgs()));
420 LLVM_DEBUG(dbgs() << "\t Y ="; Y->dump(dbgs()));
Sebastian Pop59b61b92012-10-11 07:32:34 +0000421 assert(!Y->isPoint() && "Y must not be a Point");
422 if (X->isAny()) {
423 if (Y->isAny())
424 return false;
425 *X = *Y;
426 return true;
427 }
428 if (X->isEmpty())
429 return false;
430 if (Y->isEmpty()) {
431 X->setEmpty();
432 return true;
433 }
434
435 if (X->isDistance() && Y->isDistance()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000436 LLVM_DEBUG(dbgs() << "\t intersect 2 distances\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000437 if (isKnownPredicate(CmpInst::ICMP_EQ, X->getD(), Y->getD()))
438 return false;
439 if (isKnownPredicate(CmpInst::ICMP_NE, X->getD(), Y->getD())) {
440 X->setEmpty();
441 ++DeltaSuccesses;
442 return true;
443 }
444 // Hmmm, interesting situation.
445 // I guess if either is constant, keep it and ignore the other.
446 if (isa<SCEVConstant>(Y->getD())) {
447 *X = *Y;
448 return true;
449 }
450 return false;
451 }
452
453 // At this point, the pseudo-code in Figure 4 of the paper
454 // checks if (X->isPoint() && Y->isPoint()).
455 // This case can't occur in our implementation,
456 // since a Point can only arise as the result of intersecting
457 // two Line constraints, and the right-hand value, Y, is never
458 // the result of an intersection.
459 assert(!(X->isPoint() && Y->isPoint()) &&
460 "We shouldn't ever see X->isPoint() && Y->isPoint()");
461
462 if (X->isLine() && Y->isLine()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000463 LLVM_DEBUG(dbgs() << "\t intersect 2 lines\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000464 const SCEV *Prod1 = SE->getMulExpr(X->getA(), Y->getB());
465 const SCEV *Prod2 = SE->getMulExpr(X->getB(), Y->getA());
466 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2)) {
467 // slopes are equal, so lines are parallel
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000468 LLVM_DEBUG(dbgs() << "\t\tsame slope\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000469 Prod1 = SE->getMulExpr(X->getC(), Y->getB());
470 Prod2 = SE->getMulExpr(X->getB(), Y->getC());
471 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2))
472 return false;
473 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
474 X->setEmpty();
475 ++DeltaSuccesses;
476 return true;
477 }
478 return false;
479 }
480 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
481 // slopes differ, so lines intersect
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000482 LLVM_DEBUG(dbgs() << "\t\tdifferent slopes\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000483 const SCEV *C1B2 = SE->getMulExpr(X->getC(), Y->getB());
484 const SCEV *C1A2 = SE->getMulExpr(X->getC(), Y->getA());
485 const SCEV *C2B1 = SE->getMulExpr(Y->getC(), X->getB());
486 const SCEV *C2A1 = SE->getMulExpr(Y->getC(), X->getA());
487 const SCEV *A1B2 = SE->getMulExpr(X->getA(), Y->getB());
488 const SCEV *A2B1 = SE->getMulExpr(Y->getA(), X->getB());
489 const SCEVConstant *C1A2_C2A1 =
490 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1A2, C2A1));
491 const SCEVConstant *C1B2_C2B1 =
492 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1B2, C2B1));
493 const SCEVConstant *A1B2_A2B1 =
494 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A1B2, A2B1));
495 const SCEVConstant *A2B1_A1B2 =
496 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A2B1, A1B2));
497 if (!C1B2_C2B1 || !C1A2_C2A1 ||
498 !A1B2_A2B1 || !A2B1_A1B2)
499 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000500 APInt Xtop = C1B2_C2B1->getAPInt();
501 APInt Xbot = A1B2_A2B1->getAPInt();
502 APInt Ytop = C1A2_C2A1->getAPInt();
503 APInt Ybot = A2B1_A1B2->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000504 LLVM_DEBUG(dbgs() << "\t\tXtop = " << Xtop << "\n");
505 LLVM_DEBUG(dbgs() << "\t\tXbot = " << Xbot << "\n");
506 LLVM_DEBUG(dbgs() << "\t\tYtop = " << Ytop << "\n");
507 LLVM_DEBUG(dbgs() << "\t\tYbot = " << Ybot << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000508 APInt Xq = Xtop; // these need to be initialized, even
509 APInt Xr = Xtop; // though they're just going to be overwritten
510 APInt::sdivrem(Xtop, Xbot, Xq, Xr);
511 APInt Yq = Ytop;
Jakub Staszak340c7802013-08-06 16:40:40 +0000512 APInt Yr = Ytop;
Sebastian Pop59b61b92012-10-11 07:32:34 +0000513 APInt::sdivrem(Ytop, Ybot, Yq, Yr);
514 if (Xr != 0 || Yr != 0) {
515 X->setEmpty();
516 ++DeltaSuccesses;
517 return true;
518 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000519 LLVM_DEBUG(dbgs() << "\t\tX = " << Xq << ", Y = " << Yq << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000520 if (Xq.slt(0) || Yq.slt(0)) {
521 X->setEmpty();
522 ++DeltaSuccesses;
523 return true;
524 }
525 if (const SCEVConstant *CUB =
526 collectConstantUpperBound(X->getAssociatedLoop(), Prod1->getType())) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000527 const APInt &UpperBound = CUB->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000528 LLVM_DEBUG(dbgs() << "\t\tupper bound = " << UpperBound << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000529 if (Xq.sgt(UpperBound) || Yq.sgt(UpperBound)) {
530 X->setEmpty();
531 ++DeltaSuccesses;
532 return true;
533 }
534 }
535 X->setPoint(SE->getConstant(Xq),
536 SE->getConstant(Yq),
537 X->getAssociatedLoop());
538 ++DeltaSuccesses;
539 return true;
540 }
541 return false;
542 }
543
544 // if (X->isLine() && Y->isPoint()) This case can't occur.
545 assert(!(X->isLine() && Y->isPoint()) && "This case should never occur");
546
547 if (X->isPoint() && Y->isLine()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000548 LLVM_DEBUG(dbgs() << "\t intersect Point and Line\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000549 const SCEV *A1X1 = SE->getMulExpr(Y->getA(), X->getX());
550 const SCEV *B1Y1 = SE->getMulExpr(Y->getB(), X->getY());
551 const SCEV *Sum = SE->getAddExpr(A1X1, B1Y1);
552 if (isKnownPredicate(CmpInst::ICMP_EQ, Sum, Y->getC()))
553 return false;
554 if (isKnownPredicate(CmpInst::ICMP_NE, Sum, Y->getC())) {
555 X->setEmpty();
556 ++DeltaSuccesses;
557 return true;
558 }
559 return false;
560 }
561
562 llvm_unreachable("shouldn't reach the end of Constraint intersection");
563 return false;
564}
565
566
567//===----------------------------------------------------------------------===//
Chandler Carruth49c22192016-05-12 22:19:39 +0000568// DependenceInfo methods
Sebastian Pop59b61b92012-10-11 07:32:34 +0000569
570// For debugging purposes. Dumps a dependence to OS.
571void Dependence::dump(raw_ostream &OS) const {
572 bool Splitable = false;
573 if (isConfused())
574 OS << "confused";
575 else {
576 if (isConsistent())
577 OS << "consistent ";
578 if (isFlow())
579 OS << "flow";
580 else if (isOutput())
581 OS << "output";
582 else if (isAnti())
583 OS << "anti";
584 else if (isInput())
585 OS << "input";
586 unsigned Levels = getLevels();
Preston Briggsfd0b5c82012-11-30 00:44:47 +0000587 OS << " [";
588 for (unsigned II = 1; II <= Levels; ++II) {
589 if (isSplitable(II))
590 Splitable = true;
591 if (isPeelFirst(II))
592 OS << 'p';
593 const SCEV *Distance = getDistance(II);
594 if (Distance)
595 OS << *Distance;
596 else if (isScalar(II))
597 OS << "S";
598 else {
599 unsigned Direction = getDirection(II);
600 if (Direction == DVEntry::ALL)
601 OS << "*";
Sebastian Pop59b61b92012-10-11 07:32:34 +0000602 else {
Preston Briggsfd0b5c82012-11-30 00:44:47 +0000603 if (Direction & DVEntry::LT)
604 OS << "<";
605 if (Direction & DVEntry::EQ)
606 OS << "=";
607 if (Direction & DVEntry::GT)
608 OS << ">";
Sebastian Pop59b61b92012-10-11 07:32:34 +0000609 }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000610 }
Preston Briggsfd0b5c82012-11-30 00:44:47 +0000611 if (isPeelLast(II))
612 OS << 'p';
613 if (II < Levels)
614 OS << " ";
Sebastian Pop59b61b92012-10-11 07:32:34 +0000615 }
Preston Briggsfd0b5c82012-11-30 00:44:47 +0000616 if (isLoopIndependent())
617 OS << "|<";
618 OS << "]";
619 if (Splitable)
620 OS << " splitable";
Sebastian Pop59b61b92012-10-11 07:32:34 +0000621 }
622 OS << "!\n";
623}
624
David Green5ef933b2018-04-10 11:37:21 +0000625// Returns NoAlias/MayAliass/MustAlias for two memory locations based upon their
626// underlaying objects. If LocA and LocB are known to not alias (for any reason:
627// tbaa, non-overlapping regions etc), then it is known there is no dependecy.
628// Otherwise the underlying objects are checked to see if they point to
629// different identifiable objects.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000630static AliasResult underlyingObjectsAlias(AliasAnalysis *AA,
David Green5ef933b2018-04-10 11:37:21 +0000631 const DataLayout &DL,
632 const MemoryLocation &LocA,
633 const MemoryLocation &LocB) {
634 // Check the original locations (minus size) for noalias, which can happen for
635 // tbaa, incompatible underlying object locations, etc.
636 MemoryLocation LocAS(LocA.Ptr, MemoryLocation::UnknownSize, LocA.AATags);
637 MemoryLocation LocBS(LocB.Ptr, MemoryLocation::UnknownSize, LocB.AATags);
638 if (AA->alias(LocAS, LocBS) == NoAlias)
639 return NoAlias;
640
641 // Check the underlying objects are the same
642 const Value *AObj = GetUnderlyingObject(LocA.Ptr, DL);
643 const Value *BObj = GetUnderlyingObject(LocB.Ptr, DL);
644
645 // If the underlying objects are the same, they must alias
646 if (AObj == BObj)
647 return MustAlias;
648
649 // We may have hit the recursion limit for underlying objects, or have
650 // underlying objects where we don't know they will alias.
651 if (!isIdentifiedObject(AObj) || !isIdentifiedObject(BObj))
652 return MayAlias;
653
654 // Otherwise we know the objects are different and both identified objects so
655 // must not alias.
656 return NoAlias;
Sebastian Pop59b61b92012-10-11 07:32:34 +0000657}
658
659
660// Returns true if the load or store can be analyzed. Atomic and volatile
661// operations have properties which this analysis does not understand.
662static
663bool isLoadOrStore(const Instruction *I) {
664 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
665 return LI->isUnordered();
666 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
667 return SI->isUnordered();
668 return false;
669}
670
671
Sebastian Pop59b61b92012-10-11 07:32:34 +0000672// Examines the loop nesting of the Src and Dst
673// instructions and establishes their shared loops. Sets the variables
674// CommonLevels, SrcLevels, and MaxLevels.
675// The source and destination instructions needn't be contained in the same
676// loop. The routine establishNestingLevels finds the level of most deeply
677// nested loop that contains them both, CommonLevels. An instruction that's
678// not contained in a loop is at level = 0. MaxLevels is equal to the level
679// of the source plus the level of the destination, minus CommonLevels.
680// This lets us allocate vectors MaxLevels in length, with room for every
681// distinct loop referenced in both the source and destination subscripts.
682// The variable SrcLevels is the nesting depth of the source instruction.
683// It's used to help calculate distinct loops referenced by the destination.
684// Here's the map from loops to levels:
685// 0 - unused
686// 1 - outermost common loop
687// ... - other common loops
688// CommonLevels - innermost common loop
689// ... - loops containing Src but not Dst
690// SrcLevels - innermost loop containing Src but not Dst
691// ... - loops containing Dst but not Src
692// MaxLevels - innermost loops containing Dst but not Src
693// Consider the follow code fragment:
694// for (a = ...) {
695// for (b = ...) {
696// for (c = ...) {
697// for (d = ...) {
698// A[] = ...;
699// }
700// }
701// for (e = ...) {
702// for (f = ...) {
703// for (g = ...) {
704// ... = A[];
705// }
706// }
707// }
708// }
709// }
710// If we're looking at the possibility of a dependence between the store
711// to A (the Src) and the load from A (the Dst), we'll note that they
712// have 2 loops in common, so CommonLevels will equal 2 and the direction
713// vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
714// A map from loop names to loop numbers would look like
715// a - 1
716// b - 2 = CommonLevels
717// c - 3
718// d - 4 = SrcLevels
719// e - 5
720// f - 6
721// g - 7 = MaxLevels
Chandler Carruth49c22192016-05-12 22:19:39 +0000722void DependenceInfo::establishNestingLevels(const Instruction *Src,
723 const Instruction *Dst) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000724 const BasicBlock *SrcBlock = Src->getParent();
725 const BasicBlock *DstBlock = Dst->getParent();
726 unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
727 unsigned DstLevel = LI->getLoopDepth(DstBlock);
728 const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
729 const Loop *DstLoop = LI->getLoopFor(DstBlock);
730 SrcLevels = SrcLevel;
731 MaxLevels = SrcLevel + DstLevel;
732 while (SrcLevel > DstLevel) {
733 SrcLoop = SrcLoop->getParentLoop();
734 SrcLevel--;
735 }
736 while (DstLevel > SrcLevel) {
737 DstLoop = DstLoop->getParentLoop();
738 DstLevel--;
739 }
740 while (SrcLoop != DstLoop) {
741 SrcLoop = SrcLoop->getParentLoop();
742 DstLoop = DstLoop->getParentLoop();
743 SrcLevel--;
744 }
745 CommonLevels = SrcLevel;
746 MaxLevels -= CommonLevels;
747}
748
749
750// Given one of the loops containing the source, return
751// its level index in our numbering scheme.
Chandler Carruth49c22192016-05-12 22:19:39 +0000752unsigned DependenceInfo::mapSrcLoop(const Loop *SrcLoop) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000753 return SrcLoop->getLoopDepth();
754}
755
756
757// Given one of the loops containing the destination,
758// return its level index in our numbering scheme.
Chandler Carruth49c22192016-05-12 22:19:39 +0000759unsigned DependenceInfo::mapDstLoop(const Loop *DstLoop) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000760 unsigned D = DstLoop->getLoopDepth();
761 if (D > CommonLevels)
762 return D - CommonLevels + SrcLevels;
763 else
764 return D;
765}
766
767
768// Returns true if Expression is loop invariant in LoopNest.
Chandler Carruth49c22192016-05-12 22:19:39 +0000769bool DependenceInfo::isLoopInvariant(const SCEV *Expression,
770 const Loop *LoopNest) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000771 if (!LoopNest)
772 return true;
773 return SE->isLoopInvariant(Expression, LoopNest) &&
774 isLoopInvariant(Expression, LoopNest->getParentLoop());
775}
776
777
778
779// Finds the set of loops from the LoopNest that
780// have a level <= CommonLevels and are referred to by the SCEV Expression.
Chandler Carruth49c22192016-05-12 22:19:39 +0000781void DependenceInfo::collectCommonLoops(const SCEV *Expression,
782 const Loop *LoopNest,
783 SmallBitVector &Loops) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000784 while (LoopNest) {
785 unsigned Level = LoopNest->getLoopDepth();
786 if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
787 Loops.set(Level);
788 LoopNest = LoopNest->getParentLoop();
789 }
790}
791
Chandler Carruth49c22192016-05-12 22:19:39 +0000792void DependenceInfo::unifySubscriptType(ArrayRef<Subscript *> Pairs) {
Jingyue Wua84feb12015-05-29 16:58:08 +0000793
794 unsigned widestWidthSeen = 0;
795 Type *widestType;
796
797 // Go through each pair and find the widest bit to which we need
798 // to extend all of them.
Benjamin Krameraa209152016-06-26 17:27:42 +0000799 for (Subscript *Pair : Pairs) {
800 const SCEV *Src = Pair->Src;
801 const SCEV *Dst = Pair->Dst;
Jingyue Wua84feb12015-05-29 16:58:08 +0000802 IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
803 IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
804 if (SrcTy == nullptr || DstTy == nullptr) {
805 assert(SrcTy == DstTy && "This function only unify integer types and "
806 "expect Src and Dst share the same type "
807 "otherwise.");
808 continue;
809 }
810 if (SrcTy->getBitWidth() > widestWidthSeen) {
811 widestWidthSeen = SrcTy->getBitWidth();
812 widestType = SrcTy;
813 }
814 if (DstTy->getBitWidth() > widestWidthSeen) {
815 widestWidthSeen = DstTy->getBitWidth();
816 widestType = DstTy;
817 }
Jingyue Wu0fa125a2014-11-16 16:52:44 +0000818 }
Jingyue Wua84feb12015-05-29 16:58:08 +0000819
820
821 assert(widestWidthSeen > 0);
822
823 // Now extend each pair to the widest seen.
Benjamin Krameraa209152016-06-26 17:27:42 +0000824 for (Subscript *Pair : Pairs) {
825 const SCEV *Src = Pair->Src;
826 const SCEV *Dst = Pair->Dst;
Jingyue Wua84feb12015-05-29 16:58:08 +0000827 IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
828 IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
829 if (SrcTy == nullptr || DstTy == nullptr) {
830 assert(SrcTy == DstTy && "This function only unify integer types and "
831 "expect Src and Dst share the same type "
832 "otherwise.");
833 continue;
834 }
835 if (SrcTy->getBitWidth() < widestWidthSeen)
836 // Sign-extend Src to widestType
Benjamin Krameraa209152016-06-26 17:27:42 +0000837 Pair->Src = SE->getSignExtendExpr(Src, widestType);
Jingyue Wua84feb12015-05-29 16:58:08 +0000838 if (DstTy->getBitWidth() < widestWidthSeen) {
839 // Sign-extend Dst to widestType
Benjamin Krameraa209152016-06-26 17:27:42 +0000840 Pair->Dst = SE->getSignExtendExpr(Dst, widestType);
Jingyue Wua84feb12015-05-29 16:58:08 +0000841 }
Jingyue Wu0fa125a2014-11-16 16:52:44 +0000842 }
843}
Sebastian Pop59b61b92012-10-11 07:32:34 +0000844
845// removeMatchingExtensions - Examines a subscript pair.
846// If the source and destination are identically sign (or zero)
847// extended, it strips off the extension in an effect to simplify
848// the actual analysis.
Chandler Carruth49c22192016-05-12 22:19:39 +0000849void DependenceInfo::removeMatchingExtensions(Subscript *Pair) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000850 const SCEV *Src = Pair->Src;
851 const SCEV *Dst = Pair->Dst;
852 if ((isa<SCEVZeroExtendExpr>(Src) && isa<SCEVZeroExtendExpr>(Dst)) ||
853 (isa<SCEVSignExtendExpr>(Src) && isa<SCEVSignExtendExpr>(Dst))) {
854 const SCEVCastExpr *SrcCast = cast<SCEVCastExpr>(Src);
855 const SCEVCastExpr *DstCast = cast<SCEVCastExpr>(Dst);
Jingyue Wu0fa125a2014-11-16 16:52:44 +0000856 const SCEV *SrcCastOp = SrcCast->getOperand();
857 const SCEV *DstCastOp = DstCast->getOperand();
858 if (SrcCastOp->getType() == DstCastOp->getType()) {
859 Pair->Src = SrcCastOp;
860 Pair->Dst = DstCastOp;
Sebastian Pop59b61b92012-10-11 07:32:34 +0000861 }
862 }
863}
864
865
866// Examine the scev and return true iff it's linear.
867// Collect any loops mentioned in the set of "Loops".
Chandler Carruth49c22192016-05-12 22:19:39 +0000868bool DependenceInfo::checkSrcSubscript(const SCEV *Src, const Loop *LoopNest,
869 SmallBitVector &Loops) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000870 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Src);
871 if (!AddRec)
872 return isLoopInvariant(Src, LoopNest);
873 const SCEV *Start = AddRec->getStart();
874 const SCEV *Step = AddRec->getStepRecurrence(*SE);
James Molloyc0661ae2015-05-15 12:17:22 +0000875 const SCEV *UB = SE->getBackedgeTakenCount(AddRec->getLoop());
876 if (!isa<SCEVCouldNotCompute>(UB)) {
877 if (SE->getTypeSizeInBits(Start->getType()) <
878 SE->getTypeSizeInBits(UB->getType())) {
879 if (!AddRec->getNoWrapFlags())
880 return false;
881 }
882 }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000883 if (!isLoopInvariant(Step, LoopNest))
884 return false;
885 Loops.set(mapSrcLoop(AddRec->getLoop()));
886 return checkSrcSubscript(Start, LoopNest, Loops);
887}
888
889
890
891// Examine the scev and return true iff it's linear.
892// Collect any loops mentioned in the set of "Loops".
Chandler Carruth49c22192016-05-12 22:19:39 +0000893bool DependenceInfo::checkDstSubscript(const SCEV *Dst, const Loop *LoopNest,
894 SmallBitVector &Loops) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000895 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Dst);
896 if (!AddRec)
897 return isLoopInvariant(Dst, LoopNest);
898 const SCEV *Start = AddRec->getStart();
899 const SCEV *Step = AddRec->getStepRecurrence(*SE);
James Molloyc0661ae2015-05-15 12:17:22 +0000900 const SCEV *UB = SE->getBackedgeTakenCount(AddRec->getLoop());
901 if (!isa<SCEVCouldNotCompute>(UB)) {
902 if (SE->getTypeSizeInBits(Start->getType()) <
903 SE->getTypeSizeInBits(UB->getType())) {
904 if (!AddRec->getNoWrapFlags())
905 return false;
906 }
907 }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000908 if (!isLoopInvariant(Step, LoopNest))
909 return false;
910 Loops.set(mapDstLoop(AddRec->getLoop()));
911 return checkDstSubscript(Start, LoopNest, Loops);
912}
913
914
915// Examines the subscript pair (the Src and Dst SCEVs)
916// and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
917// Collects the associated loops in a set.
Chandler Carruth49c22192016-05-12 22:19:39 +0000918DependenceInfo::Subscript::ClassificationKind
919DependenceInfo::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
920 const SCEV *Dst, const Loop *DstLoopNest,
921 SmallBitVector &Loops) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000922 SmallBitVector SrcLoops(MaxLevels + 1);
923 SmallBitVector DstLoops(MaxLevels + 1);
924 if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
925 return Subscript::NonLinear;
926 if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
927 return Subscript::NonLinear;
928 Loops = SrcLoops;
929 Loops |= DstLoops;
930 unsigned N = Loops.count();
931 if (N == 0)
932 return Subscript::ZIV;
933 if (N == 1)
934 return Subscript::SIV;
935 if (N == 2 && (SrcLoops.count() == 0 ||
936 DstLoops.count() == 0 ||
937 (SrcLoops.count() == 1 && DstLoops.count() == 1)))
938 return Subscript::RDIV;
939 return Subscript::MIV;
940}
941
942
943// A wrapper around SCEV::isKnownPredicate.
944// Looks for cases where we're interested in comparing for equality.
945// If both X and Y have been identically sign or zero extended,
946// it strips off the (confusing) extensions before invoking
947// SCEV::isKnownPredicate. Perhaps, someday, the ScalarEvolution package
948// will be similarly updated.
949//
950// If SCEV::isKnownPredicate can't prove the predicate,
951// we try simple subtraction, which seems to help in some cases
952// involving symbolics.
Chandler Carruth49c22192016-05-12 22:19:39 +0000953bool DependenceInfo::isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *X,
954 const SCEV *Y) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000955 if (Pred == CmpInst::ICMP_EQ ||
956 Pred == CmpInst::ICMP_NE) {
957 if ((isa<SCEVSignExtendExpr>(X) &&
958 isa<SCEVSignExtendExpr>(Y)) ||
959 (isa<SCEVZeroExtendExpr>(X) &&
960 isa<SCEVZeroExtendExpr>(Y))) {
961 const SCEVCastExpr *CX = cast<SCEVCastExpr>(X);
962 const SCEVCastExpr *CY = cast<SCEVCastExpr>(Y);
963 const SCEV *Xop = CX->getOperand();
964 const SCEV *Yop = CY->getOperand();
965 if (Xop->getType() == Yop->getType()) {
966 X = Xop;
967 Y = Yop;
968 }
969 }
970 }
971 if (SE->isKnownPredicate(Pred, X, Y))
972 return true;
973 // If SE->isKnownPredicate can't prove the condition,
974 // we try the brute-force approach of subtracting
975 // and testing the difference.
976 // By testing with SE->isKnownPredicate first, we avoid
977 // the possibility of overflow when the arguments are constants.
978 const SCEV *Delta = SE->getMinusSCEV(X, Y);
979 switch (Pred) {
980 case CmpInst::ICMP_EQ:
981 return Delta->isZero();
982 case CmpInst::ICMP_NE:
983 return SE->isKnownNonZero(Delta);
984 case CmpInst::ICMP_SGE:
985 return SE->isKnownNonNegative(Delta);
986 case CmpInst::ICMP_SLE:
987 return SE->isKnownNonPositive(Delta);
988 case CmpInst::ICMP_SGT:
989 return SE->isKnownPositive(Delta);
990 case CmpInst::ICMP_SLT:
991 return SE->isKnownNegative(Delta);
992 default:
993 llvm_unreachable("unexpected predicate in isKnownPredicate");
994 }
995}
996
997
998// All subscripts are all the same type.
999// Loop bound may be smaller (e.g., a char).
1000// Should zero extend loop bound, since it's always >= 0.
James Molloyc0661ae2015-05-15 12:17:22 +00001001// This routine collects upper bound and extends or truncates if needed.
1002// Truncating is safe when subscripts are known not to wrap. Cases without
1003// nowrap flags should have been rejected earlier.
Sebastian Pop59b61b92012-10-11 07:32:34 +00001004// Return null if no bound available.
Chandler Carruth49c22192016-05-12 22:19:39 +00001005const SCEV *DependenceInfo::collectUpperBound(const Loop *L, Type *T) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001006 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
1007 const SCEV *UB = SE->getBackedgeTakenCount(L);
James Molloyc0661ae2015-05-15 12:17:22 +00001008 return SE->getTruncateOrZeroExtend(UB, T);
Sebastian Pop59b61b92012-10-11 07:32:34 +00001009 }
Craig Topper9f008862014-04-15 04:59:12 +00001010 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00001011}
1012
1013
1014// Calls collectUpperBound(), then attempts to cast it to SCEVConstant.
1015// If the cast fails, returns NULL.
Chandler Carruth49c22192016-05-12 22:19:39 +00001016const SCEVConstant *DependenceInfo::collectConstantUpperBound(const Loop *L,
1017 Type *T) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001018 if (const SCEV *UB = collectUpperBound(L, T))
1019 return dyn_cast<SCEVConstant>(UB);
Craig Topper9f008862014-04-15 04:59:12 +00001020 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00001021}
1022
1023
1024// testZIV -
1025// When we have a pair of subscripts of the form [c1] and [c2],
1026// where c1 and c2 are both loop invariant, we attack it using
1027// the ZIV test. Basically, we test by comparing the two values,
1028// but there are actually three possible results:
1029// 1) the values are equal, so there's a dependence
1030// 2) the values are different, so there's no dependence
1031// 3) the values might be equal, so we have to assume a dependence.
1032//
1033// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001034bool DependenceInfo::testZIV(const SCEV *Src, const SCEV *Dst,
1035 FullDependence &Result) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001036 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
1037 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001038 ++ZIVapplications;
1039 if (isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001040 LLVM_DEBUG(dbgs() << " provably dependent\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001041 return false; // provably dependent
1042 }
1043 if (isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001044 LLVM_DEBUG(dbgs() << " provably independent\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001045 ++ZIVindependence;
1046 return true; // provably independent
1047 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001048 LLVM_DEBUG(dbgs() << " possibly dependent\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001049 Result.Consistent = false;
1050 return false; // possibly dependent
1051}
1052
1053
1054// strongSIVtest -
1055// From the paper, Practical Dependence Testing, Section 4.2.1
1056//
1057// When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
1058// where i is an induction variable, c1 and c2 are loop invariant,
1059// and a is a constant, we can solve it exactly using the Strong SIV test.
1060//
1061// Can prove independence. Failing that, can compute distance (and direction).
1062// In the presence of symbolic terms, we can sometimes make progress.
1063//
1064// If there's a dependence,
1065//
1066// c1 + a*i = c2 + a*i'
1067//
1068// The dependence distance is
1069//
1070// d = i' - i = (c1 - c2)/a
1071//
1072// A dependence only exists if d is an integer and abs(d) <= U, where U is the
1073// loop's upper bound. If a dependence exists, the dependence direction is
1074// defined as
1075//
1076// { < if d > 0
1077// direction = { = if d = 0
1078// { > if d < 0
1079//
1080// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001081bool DependenceInfo::strongSIVtest(const SCEV *Coeff, const SCEV *SrcConst,
1082 const SCEV *DstConst, const Loop *CurLoop,
1083 unsigned Level, FullDependence &Result,
1084 Constraint &NewConstraint) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001085 LLVM_DEBUG(dbgs() << "\tStrong SIV test\n");
1086 LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff);
1087 LLVM_DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
1088 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst);
1089 LLVM_DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
1090 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst);
1091 LLVM_DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001092 ++StrongSIVapplications;
1093 assert(0 < Level && Level <= CommonLevels && "level out of range");
1094 Level--;
1095
1096 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001097 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta);
1098 LLVM_DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001099
1100 // check that |Delta| < iteration count
1101 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001102 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound);
1103 LLVM_DEBUG(dbgs() << ", " << *UpperBound->getType() << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001104 const SCEV *AbsDelta =
1105 SE->isKnownNonNegative(Delta) ? Delta : SE->getNegativeSCEV(Delta);
1106 const SCEV *AbsCoeff =
1107 SE->isKnownNonNegative(Coeff) ? Coeff : SE->getNegativeSCEV(Coeff);
1108 const SCEV *Product = SE->getMulExpr(UpperBound, AbsCoeff);
1109 if (isKnownPredicate(CmpInst::ICMP_SGT, AbsDelta, Product)) {
1110 // Distance greater than trip count - no dependence
1111 ++StrongSIVindependence;
1112 ++StrongSIVsuccesses;
1113 return true;
1114 }
1115 }
1116
1117 // Can we compute distance?
1118 if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001119 APInt ConstDelta = cast<SCEVConstant>(Delta)->getAPInt();
1120 APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00001121 APInt Distance = ConstDelta; // these need to be initialized
1122 APInt Remainder = ConstDelta;
1123 APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001124 LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1125 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001126 // Make sure Coeff divides Delta exactly
1127 if (Remainder != 0) {
1128 // Coeff doesn't divide Distance, no dependence
1129 ++StrongSIVindependence;
1130 ++StrongSIVsuccesses;
1131 return true;
1132 }
1133 Result.DV[Level].Distance = SE->getConstant(Distance);
1134 NewConstraint.setDistance(SE->getConstant(Distance), CurLoop);
1135 if (Distance.sgt(0))
1136 Result.DV[Level].Direction &= Dependence::DVEntry::LT;
1137 else if (Distance.slt(0))
1138 Result.DV[Level].Direction &= Dependence::DVEntry::GT;
1139 else
1140 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1141 ++StrongSIVsuccesses;
1142 }
1143 else if (Delta->isZero()) {
1144 // since 0/X == 0
1145 Result.DV[Level].Distance = Delta;
1146 NewConstraint.setDistance(Delta, CurLoop);
1147 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1148 ++StrongSIVsuccesses;
1149 }
1150 else {
1151 if (Coeff->isOne()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001152 LLVM_DEBUG(dbgs() << "\t Distance = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001153 Result.DV[Level].Distance = Delta; // since X/1 == X
1154 NewConstraint.setDistance(Delta, CurLoop);
1155 }
1156 else {
1157 Result.Consistent = false;
1158 NewConstraint.setLine(Coeff,
1159 SE->getNegativeSCEV(Coeff),
1160 SE->getNegativeSCEV(Delta), CurLoop);
1161 }
1162
1163 // maybe we can get a useful direction
1164 bool DeltaMaybeZero = !SE->isKnownNonZero(Delta);
1165 bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
1166 bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
1167 bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
1168 bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
1169 // The double negatives above are confusing.
1170 // It helps to read !SE->isKnownNonZero(Delta)
1171 // as "Delta might be Zero"
1172 unsigned NewDirection = Dependence::DVEntry::NONE;
1173 if ((DeltaMaybePositive && CoeffMaybePositive) ||
1174 (DeltaMaybeNegative && CoeffMaybeNegative))
1175 NewDirection = Dependence::DVEntry::LT;
1176 if (DeltaMaybeZero)
1177 NewDirection |= Dependence::DVEntry::EQ;
1178 if ((DeltaMaybeNegative && CoeffMaybePositive) ||
1179 (DeltaMaybePositive && CoeffMaybeNegative))
1180 NewDirection |= Dependence::DVEntry::GT;
1181 if (NewDirection < Result.DV[Level].Direction)
1182 ++StrongSIVsuccesses;
1183 Result.DV[Level].Direction &= NewDirection;
1184 }
1185 return false;
1186}
1187
1188
1189// weakCrossingSIVtest -
1190// From the paper, Practical Dependence Testing, Section 4.2.2
1191//
1192// When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
1193// where i is an induction variable, c1 and c2 are loop invariant,
1194// and a is a constant, we can solve it exactly using the
1195// Weak-Crossing SIV test.
1196//
1197// Given c1 + a*i = c2 - a*i', we can look for the intersection of
1198// the two lines, where i = i', yielding
1199//
1200// c1 + a*i = c2 - a*i
1201// 2a*i = c2 - c1
1202// i = (c2 - c1)/2a
1203//
1204// If i < 0, there is no dependence.
1205// If i > upperbound, there is no dependence.
1206// If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
1207// If i = upperbound, there's a dependence with distance = 0.
1208// If i is integral, there's a dependence (all directions).
1209// If the non-integer part = 1/2, there's a dependence (<> directions).
1210// Otherwise, there's no dependence.
1211//
1212// Can prove independence. Failing that,
1213// can sometimes refine the directions.
1214// Can determine iteration for splitting.
1215//
1216// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001217bool DependenceInfo::weakCrossingSIVtest(
1218 const SCEV *Coeff, const SCEV *SrcConst, const SCEV *DstConst,
1219 const Loop *CurLoop, unsigned Level, FullDependence &Result,
1220 Constraint &NewConstraint, const SCEV *&SplitIter) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001221 LLVM_DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
1222 LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff << "\n");
1223 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1224 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001225 ++WeakCrossingSIVapplications;
1226 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1227 Level--;
1228 Result.Consistent = false;
1229 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001230 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001231 NewConstraint.setLine(Coeff, Coeff, Delta, CurLoop);
1232 if (Delta->isZero()) {
Sebastian Pope96232612012-10-12 02:04:32 +00001233 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1234 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
Sebastian Pop59b61b92012-10-11 07:32:34 +00001235 ++WeakCrossingSIVsuccesses;
1236 if (!Result.DV[Level].Direction) {
1237 ++WeakCrossingSIVindependence;
1238 return true;
1239 }
1240 Result.DV[Level].Distance = Delta; // = 0
1241 return false;
1242 }
1243 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
1244 if (!ConstCoeff)
1245 return false;
1246
1247 Result.DV[Level].Splitable = true;
1248 if (SE->isKnownNegative(ConstCoeff)) {
1249 ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff));
1250 assert(ConstCoeff &&
1251 "dynamic cast of negative of ConstCoeff should yield constant");
1252 Delta = SE->getNegativeSCEV(Delta);
1253 }
1254 assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive");
1255
Chandler Carruth49c22192016-05-12 22:19:39 +00001256 // compute SplitIter for use by DependenceInfo::getSplitIteration()
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001257 SplitIter = SE->getUDivExpr(
1258 SE->getSMaxExpr(SE->getZero(Delta->getType()), Delta),
1259 SE->getMulExpr(SE->getConstant(Delta->getType(), 2), ConstCoeff));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001260 LLVM_DEBUG(dbgs() << "\t Split iter = " << *SplitIter << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001261
1262 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1263 if (!ConstDelta)
1264 return false;
1265
1266 // We're certain that ConstCoeff > 0; therefore,
1267 // if Delta < 0, then no dependence.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001268 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1269 LLVM_DEBUG(dbgs() << "\t ConstCoeff = " << *ConstCoeff << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001270 if (SE->isKnownNegative(Delta)) {
1271 // No dependence, Delta < 0
1272 ++WeakCrossingSIVindependence;
1273 ++WeakCrossingSIVsuccesses;
1274 return true;
1275 }
1276
1277 // We're certain that Delta > 0 and ConstCoeff > 0.
1278 // Check Delta/(2*ConstCoeff) against upper loop bound
1279 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001280 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001281 const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2);
1282 const SCEV *ML = SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound),
1283 ConstantTwo);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001284 LLVM_DEBUG(dbgs() << "\t ML = " << *ML << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001285 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) {
1286 // Delta too big, no dependence
1287 ++WeakCrossingSIVindependence;
1288 ++WeakCrossingSIVsuccesses;
1289 return true;
1290 }
1291 if (isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) {
1292 // i = i' = UB
Sebastian Pope96232612012-10-12 02:04:32 +00001293 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1294 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
Sebastian Pop59b61b92012-10-11 07:32:34 +00001295 ++WeakCrossingSIVsuccesses;
1296 if (!Result.DV[Level].Direction) {
1297 ++WeakCrossingSIVindependence;
1298 return true;
1299 }
1300 Result.DV[Level].Splitable = false;
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001301 Result.DV[Level].Distance = SE->getZero(Delta->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +00001302 return false;
1303 }
1304 }
1305
1306 // check that Coeff divides Delta
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001307 APInt APDelta = ConstDelta->getAPInt();
1308 APInt APCoeff = ConstCoeff->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00001309 APInt Distance = APDelta; // these need to be initialzed
1310 APInt Remainder = APDelta;
1311 APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001312 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001313 if (Remainder != 0) {
1314 // Coeff doesn't divide Delta, no dependence
1315 ++WeakCrossingSIVindependence;
1316 ++WeakCrossingSIVsuccesses;
1317 return true;
1318 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001319 LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001320
1321 // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
1322 APInt Two = APInt(Distance.getBitWidth(), 2, true);
1323 Remainder = Distance.srem(Two);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001324 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001325 if (Remainder != 0) {
1326 // Equal direction isn't possible
Sebastian Pope96232612012-10-12 02:04:32 +00001327 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::EQ);
Sebastian Pop59b61b92012-10-11 07:32:34 +00001328 ++WeakCrossingSIVsuccesses;
1329 }
1330 return false;
1331}
1332
1333
1334// Kirch's algorithm, from
1335//
1336// Optimizing Supercompilers for Supercomputers
1337// Michael Wolfe
1338// MIT Press, 1989
1339//
1340// Program 2.1, page 29.
1341// Computes the GCD of AM and BM.
Mingjie Xing9deac1b2014-01-07 01:54:16 +00001342// Also finds a solution to the equation ax - by = gcd(a, b).
1343// Returns true if dependence disproved; i.e., gcd does not divide Delta.
Benjamin Kramerc321e532016-06-08 19:09:22 +00001344static bool findGCD(unsigned Bits, const APInt &AM, const APInt &BM,
1345 const APInt &Delta, APInt &G, APInt &X, APInt &Y) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001346 APInt A0(Bits, 1, true), A1(Bits, 0, true);
1347 APInt B0(Bits, 0, true), B1(Bits, 1, true);
1348 APInt G0 = AM.abs();
1349 APInt G1 = BM.abs();
1350 APInt Q = G0; // these need to be initialized
1351 APInt R = G0;
1352 APInt::sdivrem(G0, G1, Q, R);
1353 while (R != 0) {
1354 APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
1355 APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
1356 G0 = G1; G1 = R;
1357 APInt::sdivrem(G0, G1, Q, R);
1358 }
1359 G = G1;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001360 LLVM_DEBUG(dbgs() << "\t GCD = " << G << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001361 X = AM.slt(0) ? -A1 : A1;
1362 Y = BM.slt(0) ? B1 : -B1;
1363
1364 // make sure gcd divides Delta
1365 R = Delta.srem(G);
1366 if (R != 0)
1367 return true; // gcd doesn't divide Delta, no dependence
1368 Q = Delta.sdiv(G);
1369 X *= Q;
1370 Y *= Q;
1371 return false;
1372}
1373
Benjamin Kramerc321e532016-06-08 19:09:22 +00001374static APInt floorOfQuotient(const APInt &A, const APInt &B) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001375 APInt Q = A; // these need to be initialized
1376 APInt R = A;
1377 APInt::sdivrem(A, B, Q, R);
1378 if (R == 0)
1379 return Q;
1380 if ((A.sgt(0) && B.sgt(0)) ||
1381 (A.slt(0) && B.slt(0)))
1382 return Q;
1383 else
1384 return Q - 1;
1385}
1386
Benjamin Kramerc321e532016-06-08 19:09:22 +00001387static APInt ceilingOfQuotient(const APInt &A, const APInt &B) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001388 APInt Q = A; // these need to be initialized
1389 APInt R = A;
1390 APInt::sdivrem(A, B, Q, R);
1391 if (R == 0)
1392 return Q;
1393 if ((A.sgt(0) && B.sgt(0)) ||
1394 (A.slt(0) && B.slt(0)))
1395 return Q + 1;
1396 else
1397 return Q;
1398}
1399
1400
1401static
1402APInt maxAPInt(APInt A, APInt B) {
1403 return A.sgt(B) ? A : B;
1404}
1405
1406
1407static
1408APInt minAPInt(APInt A, APInt B) {
1409 return A.slt(B) ? A : B;
1410}
1411
1412
1413// exactSIVtest -
1414// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
1415// where i is an induction variable, c1 and c2 are loop invariant, and a1
1416// and a2 are constant, we can solve it exactly using an algorithm developed
1417// by Banerjee and Wolfe. See Section 2.5.3 in
1418//
1419// Optimizing Supercompilers for Supercomputers
1420// Michael Wolfe
1421// MIT Press, 1989
1422//
1423// It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
1424// so use them if possible. They're also a bit better with symbolics and,
1425// in the case of the strong SIV test, can compute Distances.
1426//
1427// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001428bool DependenceInfo::exactSIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
1429 const SCEV *SrcConst, const SCEV *DstConst,
1430 const Loop *CurLoop, unsigned Level,
1431 FullDependence &Result,
1432 Constraint &NewConstraint) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001433 LLVM_DEBUG(dbgs() << "\tExact SIV test\n");
1434 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1435 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1436 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1437 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001438 ++ExactSIVapplications;
1439 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1440 Level--;
1441 Result.Consistent = false;
1442 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001443 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001444 NewConstraint.setLine(SrcCoeff, SE->getNegativeSCEV(DstCoeff),
1445 Delta, CurLoop);
1446 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1447 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1448 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1449 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1450 return false;
1451
1452 // find gcd
1453 APInt G, X, Y;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001454 APInt AM = ConstSrcCoeff->getAPInt();
1455 APInt BM = ConstDstCoeff->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00001456 unsigned Bits = AM.getBitWidth();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001457 if (findGCD(Bits, AM, BM, ConstDelta->getAPInt(), G, X, Y)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001458 // gcd doesn't divide Delta, no dependence
1459 ++ExactSIVindependence;
1460 ++ExactSIVsuccesses;
1461 return true;
1462 }
1463
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001464 LLVM_DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001465
1466 // since SCEV construction normalizes, LM = 0
1467 APInt UM(Bits, 1, true);
1468 bool UMvalid = false;
1469 // UM is perhaps unavailable, let's check
1470 if (const SCEVConstant *CUB =
1471 collectConstantUpperBound(CurLoop, Delta->getType())) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001472 UM = CUB->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001473 LLVM_DEBUG(dbgs() << "\t UM = " << UM << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001474 UMvalid = true;
1475 }
1476
1477 APInt TU(APInt::getSignedMaxValue(Bits));
1478 APInt TL(APInt::getSignedMinValue(Bits));
1479
1480 // test(BM/G, LM-X) and test(-BM/G, X-UM)
1481 APInt TMUL = BM.sdiv(G);
1482 if (TMUL.sgt(0)) {
1483 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001484 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001485 if (UMvalid) {
1486 TU = minAPInt(TU, floorOfQuotient(UM - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001487 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001488 }
1489 }
1490 else {
1491 TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001492 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001493 if (UMvalid) {
1494 TL = maxAPInt(TL, ceilingOfQuotient(UM - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001495 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001496 }
1497 }
1498
1499 // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1500 TMUL = AM.sdiv(G);
1501 if (TMUL.sgt(0)) {
1502 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001503 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001504 if (UMvalid) {
1505 TU = minAPInt(TU, floorOfQuotient(UM - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001506 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001507 }
1508 }
1509 else {
1510 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001511 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001512 if (UMvalid) {
1513 TL = maxAPInt(TL, ceilingOfQuotient(UM - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001514 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001515 }
1516 }
1517 if (TL.sgt(TU)) {
1518 ++ExactSIVindependence;
1519 ++ExactSIVsuccesses;
1520 return true;
1521 }
1522
1523 // explore directions
1524 unsigned NewDirection = Dependence::DVEntry::NONE;
1525
1526 // less than
1527 APInt SaveTU(TU); // save these
1528 APInt SaveTL(TL);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001529 LLVM_DEBUG(dbgs() << "\t exploring LT direction\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001530 TMUL = AM - BM;
1531 if (TMUL.sgt(0)) {
1532 TL = maxAPInt(TL, ceilingOfQuotient(X - Y + 1, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001533 LLVM_DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001534 }
1535 else {
1536 TU = minAPInt(TU, floorOfQuotient(X - Y + 1, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001537 LLVM_DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001538 }
1539 if (TL.sle(TU)) {
1540 NewDirection |= Dependence::DVEntry::LT;
1541 ++ExactSIVsuccesses;
1542 }
1543
1544 // equal
1545 TU = SaveTU; // restore
1546 TL = SaveTL;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001547 LLVM_DEBUG(dbgs() << "\t exploring EQ direction\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001548 if (TMUL.sgt(0)) {
1549 TL = maxAPInt(TL, ceilingOfQuotient(X - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001550 LLVM_DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001551 }
1552 else {
1553 TU = minAPInt(TU, floorOfQuotient(X - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001554 LLVM_DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001555 }
1556 TMUL = BM - AM;
1557 if (TMUL.sgt(0)) {
1558 TL = maxAPInt(TL, ceilingOfQuotient(Y - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001559 LLVM_DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001560 }
1561 else {
1562 TU = minAPInt(TU, floorOfQuotient(Y - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001563 LLVM_DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001564 }
1565 if (TL.sle(TU)) {
1566 NewDirection |= Dependence::DVEntry::EQ;
1567 ++ExactSIVsuccesses;
1568 }
1569
1570 // greater than
1571 TU = SaveTU; // restore
1572 TL = SaveTL;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001573 LLVM_DEBUG(dbgs() << "\t exploring GT direction\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001574 if (TMUL.sgt(0)) {
1575 TL = maxAPInt(TL, ceilingOfQuotient(Y - X + 1, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001576 LLVM_DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001577 }
1578 else {
1579 TU = minAPInt(TU, floorOfQuotient(Y - X + 1, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001580 LLVM_DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001581 }
1582 if (TL.sle(TU)) {
1583 NewDirection |= Dependence::DVEntry::GT;
1584 ++ExactSIVsuccesses;
1585 }
1586
1587 // finished
1588 Result.DV[Level].Direction &= NewDirection;
1589 if (Result.DV[Level].Direction == Dependence::DVEntry::NONE)
1590 ++ExactSIVindependence;
1591 return Result.DV[Level].Direction == Dependence::DVEntry::NONE;
1592}
1593
1594
1595
1596// Return true if the divisor evenly divides the dividend.
1597static
1598bool isRemainderZero(const SCEVConstant *Dividend,
1599 const SCEVConstant *Divisor) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001600 const APInt &ConstDividend = Dividend->getAPInt();
1601 const APInt &ConstDivisor = Divisor->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00001602 return ConstDividend.srem(ConstDivisor) == 0;
1603}
1604
1605
1606// weakZeroSrcSIVtest -
1607// From the paper, Practical Dependence Testing, Section 4.2.2
1608//
1609// When we have a pair of subscripts of the form [c1] and [c2 + a*i],
1610// where i is an induction variable, c1 and c2 are loop invariant,
1611// and a is a constant, we can solve it exactly using the
1612// Weak-Zero SIV test.
1613//
1614// Given
1615//
1616// c1 = c2 + a*i
1617//
1618// we get
1619//
1620// (c1 - c2)/a = i
1621//
1622// If i is not an integer, there's no dependence.
1623// If i < 0 or > UB, there's no dependence.
David Green2911b3a2018-05-31 14:55:29 +00001624// If i = 0, the direction is >= and peeling the
Sebastian Pop59b61b92012-10-11 07:32:34 +00001625// 1st iteration will break the dependence.
David Green2911b3a2018-05-31 14:55:29 +00001626// If i = UB, the direction is <= and peeling the
Sebastian Pop59b61b92012-10-11 07:32:34 +00001627// last iteration will break the dependence.
1628// Otherwise, the direction is *.
1629//
1630// Can prove independence. Failing that, we can sometimes refine
1631// the directions. Can sometimes show that first or last
1632// iteration carries all the dependences (so worth peeling).
1633//
1634// (see also weakZeroDstSIVtest)
1635//
1636// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001637bool DependenceInfo::weakZeroSrcSIVtest(const SCEV *DstCoeff,
1638 const SCEV *SrcConst,
1639 const SCEV *DstConst,
1640 const Loop *CurLoop, unsigned Level,
1641 FullDependence &Result,
1642 Constraint &NewConstraint) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001643 // For the WeakSIV test, it's possible the loop isn't common to
1644 // the Src and Dst loops. If it isn't, then there's no need to
1645 // record a direction.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001646 LLVM_DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
1647 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << "\n");
1648 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1649 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001650 ++WeakZeroSIVapplications;
1651 assert(0 < Level && Level <= MaxLevels && "Level out of range");
1652 Level--;
1653 Result.Consistent = false;
1654 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001655 NewConstraint.setLine(SE->getZero(Delta->getType()), DstCoeff, Delta,
1656 CurLoop);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001657 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001658 if (isKnownPredicate(CmpInst::ICMP_EQ, SrcConst, DstConst)) {
1659 if (Level < CommonLevels) {
David Green2911b3a2018-05-31 14:55:29 +00001660 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
Sebastian Pop59b61b92012-10-11 07:32:34 +00001661 Result.DV[Level].PeelFirst = true;
1662 ++WeakZeroSIVsuccesses;
1663 }
1664 return false; // dependences caused by first iteration
1665 }
1666 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1667 if (!ConstCoeff)
1668 return false;
1669 const SCEV *AbsCoeff =
1670 SE->isKnownNegative(ConstCoeff) ?
1671 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1672 const SCEV *NewDelta =
1673 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1674
1675 // check that Delta/SrcCoeff < iteration count
1676 // really check NewDelta < count*AbsCoeff
1677 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001678 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001679 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1680 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1681 ++WeakZeroSIVindependence;
1682 ++WeakZeroSIVsuccesses;
1683 return true;
1684 }
1685 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1686 // dependences caused by last iteration
1687 if (Level < CommonLevels) {
David Green2911b3a2018-05-31 14:55:29 +00001688 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
Sebastian Pop59b61b92012-10-11 07:32:34 +00001689 Result.DV[Level].PeelLast = true;
1690 ++WeakZeroSIVsuccesses;
1691 }
1692 return false;
1693 }
1694 }
1695
1696 // check that Delta/SrcCoeff >= 0
1697 // really check that NewDelta >= 0
1698 if (SE->isKnownNegative(NewDelta)) {
1699 // No dependence, newDelta < 0
1700 ++WeakZeroSIVindependence;
1701 ++WeakZeroSIVsuccesses;
1702 return true;
1703 }
1704
1705 // if SrcCoeff doesn't divide Delta, then no dependence
1706 if (isa<SCEVConstant>(Delta) &&
1707 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1708 ++WeakZeroSIVindependence;
1709 ++WeakZeroSIVsuccesses;
1710 return true;
1711 }
1712 return false;
1713}
1714
1715
1716// weakZeroDstSIVtest -
1717// From the paper, Practical Dependence Testing, Section 4.2.2
1718//
1719// When we have a pair of subscripts of the form [c1 + a*i] and [c2],
1720// where i is an induction variable, c1 and c2 are loop invariant,
1721// and a is a constant, we can solve it exactly using the
1722// Weak-Zero SIV test.
1723//
1724// Given
1725//
1726// c1 + a*i = c2
1727//
1728// we get
1729//
1730// i = (c2 - c1)/a
1731//
1732// If i is not an integer, there's no dependence.
1733// If i < 0 or > UB, there's no dependence.
1734// If i = 0, the direction is <= and peeling the
1735// 1st iteration will break the dependence.
1736// If i = UB, the direction is >= and peeling the
1737// last iteration will break the dependence.
1738// Otherwise, the direction is *.
1739//
1740// Can prove independence. Failing that, we can sometimes refine
1741// the directions. Can sometimes show that first or last
1742// iteration carries all the dependences (so worth peeling).
1743//
1744// (see also weakZeroSrcSIVtest)
1745//
1746// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001747bool DependenceInfo::weakZeroDstSIVtest(const SCEV *SrcCoeff,
1748 const SCEV *SrcConst,
1749 const SCEV *DstConst,
1750 const Loop *CurLoop, unsigned Level,
1751 FullDependence &Result,
1752 Constraint &NewConstraint) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001753 // For the WeakSIV test, it's possible the loop isn't common to the
1754 // Src and Dst loops. If it isn't, then there's no need to record a direction.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001755 LLVM_DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
1756 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << "\n");
1757 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1758 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001759 ++WeakZeroSIVapplications;
1760 assert(0 < Level && Level <= SrcLevels && "Level out of range");
1761 Level--;
1762 Result.Consistent = false;
1763 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001764 NewConstraint.setLine(SrcCoeff, SE->getZero(Delta->getType()), Delta,
1765 CurLoop);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001766 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001767 if (isKnownPredicate(CmpInst::ICMP_EQ, DstConst, SrcConst)) {
1768 if (Level < CommonLevels) {
1769 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1770 Result.DV[Level].PeelFirst = true;
1771 ++WeakZeroSIVsuccesses;
1772 }
1773 return false; // dependences caused by first iteration
1774 }
1775 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1776 if (!ConstCoeff)
1777 return false;
1778 const SCEV *AbsCoeff =
1779 SE->isKnownNegative(ConstCoeff) ?
1780 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1781 const SCEV *NewDelta =
1782 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1783
1784 // check that Delta/SrcCoeff < iteration count
1785 // really check NewDelta < count*AbsCoeff
1786 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001787 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001788 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1789 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1790 ++WeakZeroSIVindependence;
1791 ++WeakZeroSIVsuccesses;
1792 return true;
1793 }
1794 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1795 // dependences caused by last iteration
1796 if (Level < CommonLevels) {
1797 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1798 Result.DV[Level].PeelLast = true;
1799 ++WeakZeroSIVsuccesses;
1800 }
1801 return false;
1802 }
1803 }
1804
1805 // check that Delta/SrcCoeff >= 0
1806 // really check that NewDelta >= 0
1807 if (SE->isKnownNegative(NewDelta)) {
1808 // No dependence, newDelta < 0
1809 ++WeakZeroSIVindependence;
1810 ++WeakZeroSIVsuccesses;
1811 return true;
1812 }
1813
1814 // if SrcCoeff doesn't divide Delta, then no dependence
1815 if (isa<SCEVConstant>(Delta) &&
1816 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1817 ++WeakZeroSIVindependence;
1818 ++WeakZeroSIVsuccesses;
1819 return true;
1820 }
1821 return false;
1822}
1823
1824
1825// exactRDIVtest - Tests the RDIV subscript pair for dependence.
1826// Things of the form [c1 + a*i] and [c2 + b*j],
1827// where i and j are induction variable, c1 and c2 are loop invariant,
1828// and a and b are constants.
1829// Returns true if any possible dependence is disproved.
Benjamin Kramerc914ab62012-10-31 11:25:32 +00001830// Marks the result as inconsistent.
Sebastian Pop59b61b92012-10-11 07:32:34 +00001831// Works in some cases that symbolicRDIVtest doesn't, and vice versa.
Chandler Carruth49c22192016-05-12 22:19:39 +00001832bool DependenceInfo::exactRDIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
1833 const SCEV *SrcConst, const SCEV *DstConst,
1834 const Loop *SrcLoop, const Loop *DstLoop,
1835 FullDependence &Result) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001836 LLVM_DEBUG(dbgs() << "\tExact RDIV test\n");
1837 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1838 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1839 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1840 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001841 ++ExactRDIVapplications;
1842 Result.Consistent = false;
1843 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001844 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001845 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1846 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1847 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1848 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1849 return false;
1850
1851 // find gcd
1852 APInt G, X, Y;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001853 APInt AM = ConstSrcCoeff->getAPInt();
1854 APInt BM = ConstDstCoeff->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00001855 unsigned Bits = AM.getBitWidth();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001856 if (findGCD(Bits, AM, BM, ConstDelta->getAPInt(), G, X, Y)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001857 // gcd doesn't divide Delta, no dependence
1858 ++ExactRDIVindependence;
1859 return true;
1860 }
1861
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001862 LLVM_DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001863
1864 // since SCEV construction seems to normalize, LM = 0
1865 APInt SrcUM(Bits, 1, true);
1866 bool SrcUMvalid = false;
1867 // SrcUM is perhaps unavailable, let's check
1868 if (const SCEVConstant *UpperBound =
1869 collectConstantUpperBound(SrcLoop, Delta->getType())) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001870 SrcUM = UpperBound->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001871 LLVM_DEBUG(dbgs() << "\t SrcUM = " << SrcUM << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001872 SrcUMvalid = true;
1873 }
1874
1875 APInt DstUM(Bits, 1, true);
1876 bool DstUMvalid = false;
1877 // UM is perhaps unavailable, let's check
1878 if (const SCEVConstant *UpperBound =
1879 collectConstantUpperBound(DstLoop, Delta->getType())) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001880 DstUM = UpperBound->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001881 LLVM_DEBUG(dbgs() << "\t DstUM = " << DstUM << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001882 DstUMvalid = true;
1883 }
1884
1885 APInt TU(APInt::getSignedMaxValue(Bits));
1886 APInt TL(APInt::getSignedMinValue(Bits));
1887
1888 // test(BM/G, LM-X) and test(-BM/G, X-UM)
1889 APInt TMUL = BM.sdiv(G);
1890 if (TMUL.sgt(0)) {
1891 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001892 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001893 if (SrcUMvalid) {
1894 TU = minAPInt(TU, floorOfQuotient(SrcUM - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001895 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001896 }
1897 }
1898 else {
1899 TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001900 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001901 if (SrcUMvalid) {
1902 TL = maxAPInt(TL, ceilingOfQuotient(SrcUM - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001903 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001904 }
1905 }
1906
1907 // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1908 TMUL = AM.sdiv(G);
1909 if (TMUL.sgt(0)) {
1910 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001911 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001912 if (DstUMvalid) {
1913 TU = minAPInt(TU, floorOfQuotient(DstUM - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001914 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001915 }
1916 }
1917 else {
1918 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001919 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001920 if (DstUMvalid) {
1921 TL = maxAPInt(TL, ceilingOfQuotient(DstUM - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001922 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001923 }
1924 }
1925 if (TL.sgt(TU))
1926 ++ExactRDIVindependence;
1927 return TL.sgt(TU);
1928}
1929
1930
1931// symbolicRDIVtest -
1932// In Section 4.5 of the Practical Dependence Testing paper,the authors
1933// introduce a special case of Banerjee's Inequalities (also called the
1934// Extreme-Value Test) that can handle some of the SIV and RDIV cases,
1935// particularly cases with symbolics. Since it's only able to disprove
1936// dependence (not compute distances or directions), we'll use it as a
1937// fall back for the other tests.
1938//
1939// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
1940// where i and j are induction variables and c1 and c2 are loop invariants,
1941// we can use the symbolic tests to disprove some dependences, serving as a
1942// backup for the RDIV test. Note that i and j can be the same variable,
1943// letting this test serve as a backup for the various SIV tests.
1944//
1945// For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some
1946// 0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized)
1947// loop bounds for the i and j loops, respectively. So, ...
1948//
1949// c1 + a1*i = c2 + a2*j
1950// a1*i - a2*j = c2 - c1
1951//
1952// To test for a dependence, we compute c2 - c1 and make sure it's in the
1953// range of the maximum and minimum possible values of a1*i - a2*j.
1954// Considering the signs of a1 and a2, we have 4 possible cases:
1955//
1956// 1) If a1 >= 0 and a2 >= 0, then
1957// a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0
1958// -a2*N2 <= c2 - c1 <= a1*N1
1959//
1960// 2) If a1 >= 0 and a2 <= 0, then
1961// a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2
1962// 0 <= c2 - c1 <= a1*N1 - a2*N2
1963//
1964// 3) If a1 <= 0 and a2 >= 0, then
1965// a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0
1966// a1*N1 - a2*N2 <= c2 - c1 <= 0
1967//
1968// 4) If a1 <= 0 and a2 <= 0, then
1969// a1*N1 - a2*0 <= c2 - c1 <= a1*0 - a2*N2
1970// a1*N1 <= c2 - c1 <= -a2*N2
1971//
1972// return true if dependence disproved
Chandler Carruth49c22192016-05-12 22:19:39 +00001973bool DependenceInfo::symbolicRDIVtest(const SCEV *A1, const SCEV *A2,
1974 const SCEV *C1, const SCEV *C2,
1975 const Loop *Loop1,
1976 const Loop *Loop2) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001977 ++SymbolicRDIVapplications;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001978 LLVM_DEBUG(dbgs() << "\ttry symbolic RDIV test\n");
1979 LLVM_DEBUG(dbgs() << "\t A1 = " << *A1);
1980 LLVM_DEBUG(dbgs() << ", type = " << *A1->getType() << "\n");
1981 LLVM_DEBUG(dbgs() << "\t A2 = " << *A2 << "\n");
1982 LLVM_DEBUG(dbgs() << "\t C1 = " << *C1 << "\n");
1983 LLVM_DEBUG(dbgs() << "\t C2 = " << *C2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001984 const SCEV *N1 = collectUpperBound(Loop1, A1->getType());
1985 const SCEV *N2 = collectUpperBound(Loop2, A1->getType());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001986 LLVM_DEBUG(if (N1) dbgs() << "\t N1 = " << *N1 << "\n");
1987 LLVM_DEBUG(if (N2) dbgs() << "\t N2 = " << *N2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001988 const SCEV *C2_C1 = SE->getMinusSCEV(C2, C1);
1989 const SCEV *C1_C2 = SE->getMinusSCEV(C1, C2);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001990 LLVM_DEBUG(dbgs() << "\t C2 - C1 = " << *C2_C1 << "\n");
1991 LLVM_DEBUG(dbgs() << "\t C1 - C2 = " << *C1_C2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001992 if (SE->isKnownNonNegative(A1)) {
1993 if (SE->isKnownNonNegative(A2)) {
1994 // A1 >= 0 && A2 >= 0
1995 if (N1) {
1996 // make sure that c2 - c1 <= a1*N1
1997 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001998 LLVM_DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001999 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1)) {
2000 ++SymbolicRDIVindependence;
2001 return true;
2002 }
2003 }
2004 if (N2) {
2005 // make sure that -a2*N2 <= c2 - c1, or a2*N2 >= c1 - c2
2006 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002007 LLVM_DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002008 if (isKnownPredicate(CmpInst::ICMP_SLT, A2N2, C1_C2)) {
2009 ++SymbolicRDIVindependence;
2010 return true;
2011 }
2012 }
2013 }
2014 else if (SE->isKnownNonPositive(A2)) {
2015 // a1 >= 0 && a2 <= 0
2016 if (N1 && N2) {
2017 // make sure that c2 - c1 <= a1*N1 - a2*N2
2018 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2019 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2020 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002021 LLVM_DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002022 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1_A2N2)) {
2023 ++SymbolicRDIVindependence;
2024 return true;
2025 }
2026 }
2027 // make sure that 0 <= c2 - c1
2028 if (SE->isKnownNegative(C2_C1)) {
2029 ++SymbolicRDIVindependence;
2030 return true;
2031 }
2032 }
2033 }
2034 else if (SE->isKnownNonPositive(A1)) {
2035 if (SE->isKnownNonNegative(A2)) {
2036 // a1 <= 0 && a2 >= 0
2037 if (N1 && N2) {
2038 // make sure that a1*N1 - a2*N2 <= c2 - c1
2039 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2040 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2041 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002042 LLVM_DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002043 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1_A2N2, C2_C1)) {
2044 ++SymbolicRDIVindependence;
2045 return true;
2046 }
2047 }
2048 // make sure that c2 - c1 <= 0
2049 if (SE->isKnownPositive(C2_C1)) {
2050 ++SymbolicRDIVindependence;
2051 return true;
2052 }
2053 }
2054 else if (SE->isKnownNonPositive(A2)) {
2055 // a1 <= 0 && a2 <= 0
2056 if (N1) {
2057 // make sure that a1*N1 <= c2 - c1
2058 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002059 LLVM_DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002060 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1, C2_C1)) {
2061 ++SymbolicRDIVindependence;
2062 return true;
2063 }
2064 }
2065 if (N2) {
2066 // make sure that c2 - c1 <= -a2*N2, or c1 - c2 >= a2*N2
2067 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002068 LLVM_DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002069 if (isKnownPredicate(CmpInst::ICMP_SLT, C1_C2, A2N2)) {
2070 ++SymbolicRDIVindependence;
2071 return true;
2072 }
2073 }
2074 }
2075 }
2076 return false;
2077}
2078
2079
2080// testSIV -
2081// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
2082// where i is an induction variable, c1 and c2 are loop invariant, and a1 and
2083// a2 are constant, we attack it with an SIV test. While they can all be
2084// solved with the Exact SIV test, it's worthwhile to use simpler tests when
2085// they apply; they're cheaper and sometimes more precise.
2086//
2087// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00002088bool DependenceInfo::testSIV(const SCEV *Src, const SCEV *Dst, unsigned &Level,
2089 FullDependence &Result, Constraint &NewConstraint,
2090 const SCEV *&SplitIter) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002091 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2092 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002093 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2094 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2095 if (SrcAddRec && DstAddRec) {
2096 const SCEV *SrcConst = SrcAddRec->getStart();
2097 const SCEV *DstConst = DstAddRec->getStart();
2098 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2099 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2100 const Loop *CurLoop = SrcAddRec->getLoop();
2101 assert(CurLoop == DstAddRec->getLoop() &&
2102 "both loops in SIV should be same");
2103 Level = mapSrcLoop(CurLoop);
2104 bool disproven;
2105 if (SrcCoeff == DstCoeff)
2106 disproven = strongSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2107 Level, Result, NewConstraint);
2108 else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
2109 disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2110 Level, Result, NewConstraint, SplitIter);
2111 else
2112 disproven = exactSIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop,
2113 Level, Result, NewConstraint);
2114 return disproven ||
2115 gcdMIVtest(Src, Dst, Result) ||
2116 symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop, CurLoop);
2117 }
2118 if (SrcAddRec) {
2119 const SCEV *SrcConst = SrcAddRec->getStart();
2120 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2121 const SCEV *DstConst = Dst;
2122 const Loop *CurLoop = SrcAddRec->getLoop();
2123 Level = mapSrcLoop(CurLoop);
2124 return weakZeroDstSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2125 Level, Result, NewConstraint) ||
2126 gcdMIVtest(Src, Dst, Result);
2127 }
2128 if (DstAddRec) {
2129 const SCEV *DstConst = DstAddRec->getStart();
2130 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2131 const SCEV *SrcConst = Src;
2132 const Loop *CurLoop = DstAddRec->getLoop();
2133 Level = mapDstLoop(CurLoop);
2134 return weakZeroSrcSIVtest(DstCoeff, SrcConst, DstConst,
2135 CurLoop, Level, Result, NewConstraint) ||
2136 gcdMIVtest(Src, Dst, Result);
2137 }
2138 llvm_unreachable("SIV test expected at least one AddRec");
2139 return false;
2140}
2141
2142
2143// testRDIV -
2144// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2145// where i and j are induction variables, c1 and c2 are loop invariant,
2146// and a1 and a2 are constant, we can solve it exactly with an easy adaptation
2147// of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
2148// It doesn't make sense to talk about distance or direction in this case,
2149// so there's no point in making special versions of the Strong SIV test or
2150// the Weak-crossing SIV test.
2151//
2152// With minor algebra, this test can also be used for things like
2153// [c1 + a1*i + a2*j][c2].
2154//
2155// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00002156bool DependenceInfo::testRDIV(const SCEV *Src, const SCEV *Dst,
2157 FullDependence &Result) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002158 // we have 3 possible situations here:
2159 // 1) [a*i + b] and [c*j + d]
2160 // 2) [a*i + c*j + b] and [d]
2161 // 3) [b] and [a*i + c*j + d]
2162 // We need to find what we've got and get organized
2163
2164 const SCEV *SrcConst, *DstConst;
2165 const SCEV *SrcCoeff, *DstCoeff;
2166 const Loop *SrcLoop, *DstLoop;
2167
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002168 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2169 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002170 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2171 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2172 if (SrcAddRec && DstAddRec) {
2173 SrcConst = SrcAddRec->getStart();
2174 SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2175 SrcLoop = SrcAddRec->getLoop();
2176 DstConst = DstAddRec->getStart();
2177 DstCoeff = DstAddRec->getStepRecurrence(*SE);
2178 DstLoop = DstAddRec->getLoop();
2179 }
2180 else if (SrcAddRec) {
2181 if (const SCEVAddRecExpr *tmpAddRec =
2182 dyn_cast<SCEVAddRecExpr>(SrcAddRec->getStart())) {
2183 SrcConst = tmpAddRec->getStart();
2184 SrcCoeff = tmpAddRec->getStepRecurrence(*SE);
2185 SrcLoop = tmpAddRec->getLoop();
2186 DstConst = Dst;
2187 DstCoeff = SE->getNegativeSCEV(SrcAddRec->getStepRecurrence(*SE));
2188 DstLoop = SrcAddRec->getLoop();
2189 }
2190 else
2191 llvm_unreachable("RDIV reached by surprising SCEVs");
2192 }
2193 else if (DstAddRec) {
2194 if (const SCEVAddRecExpr *tmpAddRec =
2195 dyn_cast<SCEVAddRecExpr>(DstAddRec->getStart())) {
2196 DstConst = tmpAddRec->getStart();
2197 DstCoeff = tmpAddRec->getStepRecurrence(*SE);
2198 DstLoop = tmpAddRec->getLoop();
2199 SrcConst = Src;
2200 SrcCoeff = SE->getNegativeSCEV(DstAddRec->getStepRecurrence(*SE));
2201 SrcLoop = DstAddRec->getLoop();
2202 }
2203 else
2204 llvm_unreachable("RDIV reached by surprising SCEVs");
2205 }
2206 else
2207 llvm_unreachable("RDIV expected at least one AddRec");
2208 return exactRDIVtest(SrcCoeff, DstCoeff,
2209 SrcConst, DstConst,
2210 SrcLoop, DstLoop,
2211 Result) ||
2212 gcdMIVtest(Src, Dst, Result) ||
2213 symbolicRDIVtest(SrcCoeff, DstCoeff,
2214 SrcConst, DstConst,
2215 SrcLoop, DstLoop);
2216}
2217
2218
2219// Tests the single-subscript MIV pair (Src and Dst) for dependence.
2220// Return true if dependence disproved.
2221// Can sometimes refine direction vectors.
Chandler Carruth49c22192016-05-12 22:19:39 +00002222bool DependenceInfo::testMIV(const SCEV *Src, const SCEV *Dst,
2223 const SmallBitVector &Loops,
2224 FullDependence &Result) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002225 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2226 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002227 Result.Consistent = false;
2228 return gcdMIVtest(Src, Dst, Result) ||
2229 banerjeeMIVtest(Src, Dst, Loops, Result);
2230}
2231
2232
2233// Given a product, e.g., 10*X*Y, returns the first constant operand,
2234// in this case 10. If there is no constant part, returns NULL.
2235static
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002236const SCEVConstant *getConstantPart(const SCEV *Expr) {
2237 if (const auto *Constant = dyn_cast<SCEVConstant>(Expr))
2238 return Constant;
2239 else if (const auto *Product = dyn_cast<SCEVMulExpr>(Expr))
2240 if (const auto *Constant = dyn_cast<SCEVConstant>(Product->getOperand(0)))
Sebastian Pop59b61b92012-10-11 07:32:34 +00002241 return Constant;
Craig Topper9f008862014-04-15 04:59:12 +00002242 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00002243}
2244
2245
2246//===----------------------------------------------------------------------===//
2247// gcdMIVtest -
2248// Tests an MIV subscript pair for dependence.
2249// Returns true if any possible dependence is disproved.
Benjamin Kramerc914ab62012-10-31 11:25:32 +00002250// Marks the result as inconsistent.
Sebastian Pop59b61b92012-10-11 07:32:34 +00002251// Can sometimes disprove the equal direction for 1 or more loops,
2252// as discussed in Michael Wolfe's book,
2253// High Performance Compilers for Parallel Computing, page 235.
2254//
2255// We spend some effort (code!) to handle cases like
2256// [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
2257// but M and N are just loop-invariant variables.
2258// This should help us handle linearized subscripts;
2259// also makes this test a useful backup to the various SIV tests.
2260//
2261// It occurs to me that the presence of loop-invariant variables
2262// changes the nature of the test from "greatest common divisor"
Preston Briggs4eb7ee52012-11-29 04:30:52 +00002263// to "a common divisor".
Chandler Carruth49c22192016-05-12 22:19:39 +00002264bool DependenceInfo::gcdMIVtest(const SCEV *Src, const SCEV *Dst,
2265 FullDependence &Result) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002266 LLVM_DEBUG(dbgs() << "starting gcd\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002267 ++GCDapplications;
Preston Briggs3ad39492012-11-21 23:50:04 +00002268 unsigned BitWidth = SE->getTypeSizeInBits(Src->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +00002269 APInt RunningGCD = APInt::getNullValue(BitWidth);
2270
2271 // Examine Src coefficients.
2272 // Compute running GCD and record source constant.
2273 // Because we're looking for the constant at the end of the chain,
2274 // we can't quit the loop just because the GCD == 1.
2275 const SCEV *Coefficients = Src;
2276 while (const SCEVAddRecExpr *AddRec =
2277 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2278 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002279 // If the coefficient is the product of a constant and other stuff,
2280 // we can use the constant in the GCD computation.
2281 const auto *Constant = getConstantPart(Coeff);
Sebastian Pop59b61b92012-10-11 07:32:34 +00002282 if (!Constant)
2283 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002284 APInt ConstCoeff = Constant->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002285 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2286 Coefficients = AddRec->getStart();
2287 }
2288 const SCEV *SrcConst = Coefficients;
2289
2290 // Examine Dst coefficients.
2291 // Compute running GCD and record destination constant.
2292 // Because we're looking for the constant at the end of the chain,
2293 // we can't quit the loop just because the GCD == 1.
2294 Coefficients = Dst;
2295 while (const SCEVAddRecExpr *AddRec =
2296 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2297 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002298 // If the coefficient is the product of a constant and other stuff,
2299 // we can use the constant in the GCD computation.
2300 const auto *Constant = getConstantPart(Coeff);
Sebastian Pop59b61b92012-10-11 07:32:34 +00002301 if (!Constant)
2302 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002303 APInt ConstCoeff = Constant->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002304 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2305 Coefficients = AddRec->getStart();
2306 }
2307 const SCEV *DstConst = Coefficients;
2308
2309 APInt ExtraGCD = APInt::getNullValue(BitWidth);
2310 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002311 LLVM_DEBUG(dbgs() << " Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002312 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
2313 if (const SCEVAddExpr *Sum = dyn_cast<SCEVAddExpr>(Delta)) {
2314 // If Delta is a sum of products, we may be able to make further progress.
2315 for (unsigned Op = 0, Ops = Sum->getNumOperands(); Op < Ops; Op++) {
2316 const SCEV *Operand = Sum->getOperand(Op);
2317 if (isa<SCEVConstant>(Operand)) {
2318 assert(!Constant && "Surprised to find multiple constants");
2319 Constant = cast<SCEVConstant>(Operand);
2320 }
Benjamin Kramer24c643b2012-10-31 09:20:38 +00002321 else if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Operand)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002322 // Search for constant operand to participate in GCD;
2323 // If none found; return false.
Benjamin Kramer24c643b2012-10-31 09:20:38 +00002324 const SCEVConstant *ConstOp = getConstantPart(Product);
2325 if (!ConstOp)
2326 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002327 APInt ConstOpValue = ConstOp->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002328 ExtraGCD = APIntOps::GreatestCommonDivisor(ExtraGCD,
2329 ConstOpValue.abs());
2330 }
2331 else
2332 return false;
2333 }
2334 }
2335 if (!Constant)
2336 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002337 APInt ConstDelta = cast<SCEVConstant>(Constant)->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002338 LLVM_DEBUG(dbgs() << " ConstDelta = " << ConstDelta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002339 if (ConstDelta == 0)
2340 return false;
2341 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ExtraGCD);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002342 LLVM_DEBUG(dbgs() << " RunningGCD = " << RunningGCD << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002343 APInt Remainder = ConstDelta.srem(RunningGCD);
2344 if (Remainder != 0) {
2345 ++GCDindependence;
2346 return true;
2347 }
2348
2349 // Try to disprove equal directions.
2350 // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
2351 // the code above can't disprove the dependence because the GCD = 1.
2352 // So we consider what happen if i = i' and what happens if j = j'.
2353 // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
2354 // which is infeasible, so we can disallow the = direction for the i level.
2355 // Setting j = j' doesn't help matters, so we end up with a direction vector
2356 // of [<>, *]
2357 //
2358 // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5],
2359 // we need to remember that the constant part is 5 and the RunningGCD should
2360 // be initialized to ExtraGCD = 30.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002361 LLVM_DEBUG(dbgs() << " ExtraGCD = " << ExtraGCD << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002362
2363 bool Improved = false;
2364 Coefficients = Src;
2365 while (const SCEVAddRecExpr *AddRec =
2366 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2367 Coefficients = AddRec->getStart();
2368 const Loop *CurLoop = AddRec->getLoop();
2369 RunningGCD = ExtraGCD;
2370 const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
2371 const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff);
2372 const SCEV *Inner = Src;
2373 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2374 AddRec = cast<SCEVAddRecExpr>(Inner);
2375 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2376 if (CurLoop == AddRec->getLoop())
2377 ; // SrcCoeff == Coeff
2378 else {
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002379 // If the coefficient is the product of a constant and other stuff,
2380 // we can use the constant in the GCD computation.
2381 Constant = getConstantPart(Coeff);
Brendon Cahoon86f783e2016-04-04 18:13:18 +00002382 if (!Constant)
2383 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002384 APInt ConstCoeff = Constant->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002385 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2386 }
2387 Inner = AddRec->getStart();
2388 }
2389 Inner = Dst;
2390 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2391 AddRec = cast<SCEVAddRecExpr>(Inner);
2392 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2393 if (CurLoop == AddRec->getLoop())
2394 DstCoeff = Coeff;
2395 else {
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002396 // If the coefficient is the product of a constant and other stuff,
2397 // we can use the constant in the GCD computation.
2398 Constant = getConstantPart(Coeff);
Brendon Cahoon86f783e2016-04-04 18:13:18 +00002399 if (!Constant)
2400 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002401 APInt ConstCoeff = Constant->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002402 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2403 }
2404 Inner = AddRec->getStart();
2405 }
2406 Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff);
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002407 // If the coefficient is the product of a constant and other stuff,
2408 // we can use the constant in the GCD computation.
2409 Constant = getConstantPart(Delta);
2410 if (!Constant)
Sebastian Pop59b61b92012-10-11 07:32:34 +00002411 // The difference of the two coefficients might not be a product
2412 // or constant, in which case we give up on this direction.
2413 continue;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002414 APInt ConstCoeff = Constant->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002415 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002416 LLVM_DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002417 if (RunningGCD != 0) {
2418 Remainder = ConstDelta.srem(RunningGCD);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002419 LLVM_DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002420 if (Remainder != 0) {
2421 unsigned Level = mapSrcLoop(CurLoop);
Sebastian Pope96232612012-10-12 02:04:32 +00002422 Result.DV[Level - 1].Direction &= unsigned(~Dependence::DVEntry::EQ);
Sebastian Pop59b61b92012-10-11 07:32:34 +00002423 Improved = true;
2424 }
2425 }
2426 }
2427 if (Improved)
2428 ++GCDsuccesses;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002429 LLVM_DEBUG(dbgs() << "all done\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002430 return false;
2431}
2432
2433
2434//===----------------------------------------------------------------------===//
2435// banerjeeMIVtest -
2436// Use Banerjee's Inequalities to test an MIV subscript pair.
2437// (Wolfe, in the race-car book, calls this the Extreme Value Test.)
2438// Generally follows the discussion in Section 2.5.2 of
2439//
2440// Optimizing Supercompilers for Supercomputers
2441// Michael Wolfe
2442//
2443// The inequalities given on page 25 are simplified in that loops are
2444// normalized so that the lower bound is always 0 and the stride is always 1.
2445// For example, Wolfe gives
2446//
2447// LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2448//
2449// where A_k is the coefficient of the kth index in the source subscript,
2450// B_k is the coefficient of the kth index in the destination subscript,
2451// U_k is the upper bound of the kth index, L_k is the lower bound of the Kth
2452// index, and N_k is the stride of the kth index. Since all loops are normalized
2453// by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the
2454// equation to
2455//
2456// LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1
2457// = (A^-_k - B_k)^- (U_k - 1) - B_k
2458//
2459// Similar simplifications are possible for the other equations.
2460//
2461// When we can't determine the number of iterations for a loop,
2462// we use NULL as an indicator for the worst case, infinity.
2463// When computing the upper bound, NULL denotes +inf;
2464// for the lower bound, NULL denotes -inf.
2465//
2466// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00002467bool DependenceInfo::banerjeeMIVtest(const SCEV *Src, const SCEV *Dst,
2468 const SmallBitVector &Loops,
2469 FullDependence &Result) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002470 LLVM_DEBUG(dbgs() << "starting Banerjee\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002471 ++BanerjeeApplications;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002472 LLVM_DEBUG(dbgs() << " Src = " << *Src << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002473 const SCEV *A0;
Dylan Noblesmith4ffafef2014-08-26 02:03:38 +00002474 CoefficientInfo *A = collectCoeffInfo(Src, true, A0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002475 LLVM_DEBUG(dbgs() << " Dst = " << *Dst << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002476 const SCEV *B0;
Dylan Noblesmith4ffafef2014-08-26 02:03:38 +00002477 CoefficientInfo *B = collectCoeffInfo(Dst, false, B0);
2478 BoundInfo *Bound = new BoundInfo[MaxLevels + 1];
Sebastian Pop59b61b92012-10-11 07:32:34 +00002479 const SCEV *Delta = SE->getMinusSCEV(B0, A0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002480 LLVM_DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002481
2482 // Compute bounds for all the * directions.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002483 LLVM_DEBUG(dbgs() << "\tBounds[*]\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002484 for (unsigned K = 1; K <= MaxLevels; ++K) {
2485 Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations;
2486 Bound[K].Direction = Dependence::DVEntry::ALL;
2487 Bound[K].DirSet = Dependence::DVEntry::NONE;
2488 findBoundsALL(A, B, Bound, K);
2489#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002490 LLVM_DEBUG(dbgs() << "\t " << K << '\t');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002491 if (Bound[K].Lower[Dependence::DVEntry::ALL])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002492 LLVM_DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002493 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002494 LLVM_DEBUG(dbgs() << "-inf\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002495 if (Bound[K].Upper[Dependence::DVEntry::ALL])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002496 LLVM_DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002497 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002498 LLVM_DEBUG(dbgs() << "+inf\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002499#endif
2500 }
2501
2502 // Test the *, *, *, ... case.
2503 bool Disproved = false;
2504 if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
2505 // Explore the direction vector hierarchy.
2506 unsigned DepthExpanded = 0;
2507 unsigned NewDeps = exploreDirections(1, A, B, Bound,
2508 Loops, DepthExpanded, Delta);
2509 if (NewDeps > 0) {
2510 bool Improved = false;
2511 for (unsigned K = 1; K <= CommonLevels; ++K) {
2512 if (Loops[K]) {
2513 unsigned Old = Result.DV[K - 1].Direction;
2514 Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
2515 Improved |= Old != Result.DV[K - 1].Direction;
2516 if (!Result.DV[K - 1].Direction) {
2517 Improved = false;
2518 Disproved = true;
2519 break;
2520 }
2521 }
2522 }
2523 if (Improved)
2524 ++BanerjeeSuccesses;
2525 }
2526 else {
2527 ++BanerjeeIndependence;
2528 Disproved = true;
2529 }
2530 }
2531 else {
2532 ++BanerjeeIndependence;
2533 Disproved = true;
2534 }
Dylan Noblesmith4ffafef2014-08-26 02:03:38 +00002535 delete [] Bound;
2536 delete [] A;
2537 delete [] B;
Sebastian Pop59b61b92012-10-11 07:32:34 +00002538 return Disproved;
2539}
2540
2541
2542// Hierarchically expands the direction vector
2543// search space, combining the directions of discovered dependences
2544// in the DirSet field of Bound. Returns the number of distinct
2545// dependences discovered. If the dependence is disproved,
2546// it will return 0.
Chandler Carruth49c22192016-05-12 22:19:39 +00002547unsigned DependenceInfo::exploreDirections(unsigned Level, CoefficientInfo *A,
2548 CoefficientInfo *B, BoundInfo *Bound,
2549 const SmallBitVector &Loops,
2550 unsigned &DepthExpanded,
2551 const SCEV *Delta) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002552 if (Level > CommonLevels) {
2553 // record result
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002554 LLVM_DEBUG(dbgs() << "\t[");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002555 for (unsigned K = 1; K <= CommonLevels; ++K) {
2556 if (Loops[K]) {
2557 Bound[K].DirSet |= Bound[K].Direction;
2558#ifndef NDEBUG
2559 switch (Bound[K].Direction) {
2560 case Dependence::DVEntry::LT:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002561 LLVM_DEBUG(dbgs() << " <");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002562 break;
2563 case Dependence::DVEntry::EQ:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002564 LLVM_DEBUG(dbgs() << " =");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002565 break;
2566 case Dependence::DVEntry::GT:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002567 LLVM_DEBUG(dbgs() << " >");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002568 break;
2569 case Dependence::DVEntry::ALL:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002570 LLVM_DEBUG(dbgs() << " *");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002571 break;
2572 default:
2573 llvm_unreachable("unexpected Bound[K].Direction");
2574 }
2575#endif
2576 }
2577 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002578 LLVM_DEBUG(dbgs() << " ]\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002579 return 1;
2580 }
2581 if (Loops[Level]) {
2582 if (Level > DepthExpanded) {
2583 DepthExpanded = Level;
2584 // compute bounds for <, =, > at current level
2585 findBoundsLT(A, B, Bound, Level);
2586 findBoundsGT(A, B, Bound, Level);
2587 findBoundsEQ(A, B, Bound, Level);
2588#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002589 LLVM_DEBUG(dbgs() << "\tBound for level = " << Level << '\n');
2590 LLVM_DEBUG(dbgs() << "\t <\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002591 if (Bound[Level].Lower[Dependence::DVEntry::LT])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002592 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT]
2593 << '\t');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002594 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002595 LLVM_DEBUG(dbgs() << "-inf\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002596 if (Bound[Level].Upper[Dependence::DVEntry::LT])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002597 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT]
2598 << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002599 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002600 LLVM_DEBUG(dbgs() << "+inf\n");
2601 LLVM_DEBUG(dbgs() << "\t =\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002602 if (Bound[Level].Lower[Dependence::DVEntry::EQ])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002603 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ]
2604 << '\t');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002605 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002606 LLVM_DEBUG(dbgs() << "-inf\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002607 if (Bound[Level].Upper[Dependence::DVEntry::EQ])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002608 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ]
2609 << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002610 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002611 LLVM_DEBUG(dbgs() << "+inf\n");
2612 LLVM_DEBUG(dbgs() << "\t >\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002613 if (Bound[Level].Lower[Dependence::DVEntry::GT])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002614 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT]
2615 << '\t');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002616 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002617 LLVM_DEBUG(dbgs() << "-inf\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002618 if (Bound[Level].Upper[Dependence::DVEntry::GT])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002619 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT]
2620 << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002621 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002622 LLVM_DEBUG(dbgs() << "+inf\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002623#endif
2624 }
2625
2626 unsigned NewDeps = 0;
2627
2628 // test bounds for <, *, *, ...
2629 if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta))
2630 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2631 Loops, DepthExpanded, Delta);
2632
2633 // Test bounds for =, *, *, ...
2634 if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta))
2635 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2636 Loops, DepthExpanded, Delta);
2637
2638 // test bounds for >, *, *, ...
2639 if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta))
2640 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2641 Loops, DepthExpanded, Delta);
2642
2643 Bound[Level].Direction = Dependence::DVEntry::ALL;
2644 return NewDeps;
2645 }
2646 else
2647 return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded, Delta);
2648}
2649
2650
2651// Returns true iff the current bounds are plausible.
Chandler Carruth49c22192016-05-12 22:19:39 +00002652bool DependenceInfo::testBounds(unsigned char DirKind, unsigned Level,
2653 BoundInfo *Bound, const SCEV *Delta) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002654 Bound[Level].Direction = DirKind;
2655 if (const SCEV *LowerBound = getLowerBound(Bound))
2656 if (isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta))
2657 return false;
2658 if (const SCEV *UpperBound = getUpperBound(Bound))
2659 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound))
2660 return false;
2661 return true;
2662}
2663
2664
2665// Computes the upper and lower bounds for level K
2666// using the * direction. Records them in Bound.
2667// Wolfe gives the equations
2668//
2669// LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k
2670// UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k
2671//
2672// Since we normalize loops, we can simplify these equations to
2673//
2674// LB^*_k = (A^-_k - B^+_k)U_k
2675// UB^*_k = (A^+_k - B^-_k)U_k
2676//
2677// We must be careful to handle the case where the upper bound is unknown.
2678// Note that the lower bound is always <= 0
2679// and the upper bound is always >= 0.
Chandler Carruth49c22192016-05-12 22:19:39 +00002680void DependenceInfo::findBoundsALL(CoefficientInfo *A, CoefficientInfo *B,
2681 BoundInfo *Bound, unsigned K) const {
Craig Topper9f008862014-04-15 04:59:12 +00002682 Bound[K].Lower[Dependence::DVEntry::ALL] = nullptr; // Default value = -infinity.
2683 Bound[K].Upper[Dependence::DVEntry::ALL] = nullptr; // Default value = +infinity.
Sebastian Pop59b61b92012-10-11 07:32:34 +00002684 if (Bound[K].Iterations) {
2685 Bound[K].Lower[Dependence::DVEntry::ALL] =
2686 SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart),
2687 Bound[K].Iterations);
2688 Bound[K].Upper[Dependence::DVEntry::ALL] =
2689 SE->getMulExpr(SE->getMinusSCEV(A[K].PosPart, B[K].NegPart),
2690 Bound[K].Iterations);
2691 }
2692 else {
2693 // If the difference is 0, we won't need to know the number of iterations.
2694 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart))
2695 Bound[K].Lower[Dependence::DVEntry::ALL] =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002696 SE->getZero(A[K].Coeff->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +00002697 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart))
2698 Bound[K].Upper[Dependence::DVEntry::ALL] =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002699 SE->getZero(A[K].Coeff->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +00002700 }
2701}
2702
2703
2704// Computes the upper and lower bounds for level K
2705// using the = direction. Records them in Bound.
2706// Wolfe gives the equations
2707//
2708// LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k
2709// UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k
2710//
2711// Since we normalize loops, we can simplify these equations to
2712//
2713// LB^=_k = (A_k - B_k)^- U_k
2714// UB^=_k = (A_k - B_k)^+ U_k
2715//
2716// We must be careful to handle the case where the upper bound is unknown.
2717// Note that the lower bound is always <= 0
2718// and the upper bound is always >= 0.
Chandler Carruth49c22192016-05-12 22:19:39 +00002719void DependenceInfo::findBoundsEQ(CoefficientInfo *A, CoefficientInfo *B,
2720 BoundInfo *Bound, unsigned K) const {
Craig Topper9f008862014-04-15 04:59:12 +00002721 Bound[K].Lower[Dependence::DVEntry::EQ] = nullptr; // Default value = -infinity.
2722 Bound[K].Upper[Dependence::DVEntry::EQ] = nullptr; // Default value = +infinity.
Sebastian Pop59b61b92012-10-11 07:32:34 +00002723 if (Bound[K].Iterations) {
2724 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2725 const SCEV *NegativePart = getNegativePart(Delta);
2726 Bound[K].Lower[Dependence::DVEntry::EQ] =
2727 SE->getMulExpr(NegativePart, Bound[K].Iterations);
2728 const SCEV *PositivePart = getPositivePart(Delta);
2729 Bound[K].Upper[Dependence::DVEntry::EQ] =
2730 SE->getMulExpr(PositivePart, Bound[K].Iterations);
2731 }
2732 else {
2733 // If the positive/negative part of the difference is 0,
2734 // we won't need to know the number of iterations.
2735 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2736 const SCEV *NegativePart = getNegativePart(Delta);
2737 if (NegativePart->isZero())
2738 Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero
2739 const SCEV *PositivePart = getPositivePart(Delta);
2740 if (PositivePart->isZero())
2741 Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero
2742 }
2743}
2744
2745
2746// Computes the upper and lower bounds for level K
2747// using the < direction. Records them in Bound.
2748// Wolfe gives the equations
2749//
2750// LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2751// UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2752//
2753// Since we normalize loops, we can simplify these equations to
2754//
2755// LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k
2756// UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k
2757//
2758// We must be careful to handle the case where the upper bound is unknown.
Chandler Carruth49c22192016-05-12 22:19:39 +00002759void DependenceInfo::findBoundsLT(CoefficientInfo *A, CoefficientInfo *B,
2760 BoundInfo *Bound, unsigned K) const {
Craig Topper9f008862014-04-15 04:59:12 +00002761 Bound[K].Lower[Dependence::DVEntry::LT] = nullptr; // Default value = -infinity.
2762 Bound[K].Upper[Dependence::DVEntry::LT] = nullptr; // Default value = +infinity.
Sebastian Pop59b61b92012-10-11 07:32:34 +00002763 if (Bound[K].Iterations) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002764 const SCEV *Iter_1 = SE->getMinusSCEV(
2765 Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00002766 const SCEV *NegPart =
2767 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2768 Bound[K].Lower[Dependence::DVEntry::LT] =
2769 SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff);
2770 const SCEV *PosPart =
2771 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2772 Bound[K].Upper[Dependence::DVEntry::LT] =
2773 SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff);
2774 }
2775 else {
2776 // If the positive/negative part of the difference is 0,
2777 // we won't need to know the number of iterations.
2778 const SCEV *NegPart =
2779 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2780 if (NegPart->isZero())
2781 Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2782 const SCEV *PosPart =
2783 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2784 if (PosPart->isZero())
2785 Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2786 }
2787}
2788
2789
2790// Computes the upper and lower bounds for level K
2791// using the > direction. Records them in Bound.
2792// Wolfe gives the equations
2793//
2794// LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2795// UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2796//
2797// Since we normalize loops, we can simplify these equations to
2798//
2799// LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k
2800// UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k
2801//
2802// We must be careful to handle the case where the upper bound is unknown.
Chandler Carruth49c22192016-05-12 22:19:39 +00002803void DependenceInfo::findBoundsGT(CoefficientInfo *A, CoefficientInfo *B,
2804 BoundInfo *Bound, unsigned K) const {
Craig Topper9f008862014-04-15 04:59:12 +00002805 Bound[K].Lower[Dependence::DVEntry::GT] = nullptr; // Default value = -infinity.
2806 Bound[K].Upper[Dependence::DVEntry::GT] = nullptr; // Default value = +infinity.
Sebastian Pop59b61b92012-10-11 07:32:34 +00002807 if (Bound[K].Iterations) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002808 const SCEV *Iter_1 = SE->getMinusSCEV(
2809 Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00002810 const SCEV *NegPart =
2811 getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2812 Bound[K].Lower[Dependence::DVEntry::GT] =
2813 SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff);
2814 const SCEV *PosPart =
2815 getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2816 Bound[K].Upper[Dependence::DVEntry::GT] =
2817 SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff);
2818 }
2819 else {
2820 // If the positive/negative part of the difference is 0,
2821 // we won't need to know the number of iterations.
2822 const SCEV *NegPart = getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2823 if (NegPart->isZero())
2824 Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff;
2825 const SCEV *PosPart = getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2826 if (PosPart->isZero())
2827 Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff;
2828 }
2829}
2830
2831
2832// X^+ = max(X, 0)
Chandler Carruth49c22192016-05-12 22:19:39 +00002833const SCEV *DependenceInfo::getPositivePart(const SCEV *X) const {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002834 return SE->getSMaxExpr(X, SE->getZero(X->getType()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00002835}
2836
2837
2838// X^- = min(X, 0)
Chandler Carruth49c22192016-05-12 22:19:39 +00002839const SCEV *DependenceInfo::getNegativePart(const SCEV *X) const {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002840 return SE->getSMinExpr(X, SE->getZero(X->getType()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00002841}
2842
2843
2844// Walks through the subscript,
2845// collecting each coefficient, the associated loop bounds,
2846// and recording its positive and negative parts for later use.
Chandler Carruth49c22192016-05-12 22:19:39 +00002847DependenceInfo::CoefficientInfo *
2848DependenceInfo::collectCoeffInfo(const SCEV *Subscript, bool SrcFlag,
2849 const SCEV *&Constant) const {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002850 const SCEV *Zero = SE->getZero(Subscript->getType());
Dylan Noblesmith4ffafef2014-08-26 02:03:38 +00002851 CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1];
Sebastian Pop59b61b92012-10-11 07:32:34 +00002852 for (unsigned K = 1; K <= MaxLevels; ++K) {
2853 CI[K].Coeff = Zero;
2854 CI[K].PosPart = Zero;
2855 CI[K].NegPart = Zero;
Craig Topper9f008862014-04-15 04:59:12 +00002856 CI[K].Iterations = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00002857 }
2858 while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
2859 const Loop *L = AddRec->getLoop();
2860 unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L);
2861 CI[K].Coeff = AddRec->getStepRecurrence(*SE);
2862 CI[K].PosPart = getPositivePart(CI[K].Coeff);
2863 CI[K].NegPart = getNegativePart(CI[K].Coeff);
2864 CI[K].Iterations = collectUpperBound(L, Subscript->getType());
2865 Subscript = AddRec->getStart();
2866 }
2867 Constant = Subscript;
2868#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002869 LLVM_DEBUG(dbgs() << "\tCoefficient Info\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002870 for (unsigned K = 1; K <= MaxLevels; ++K) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002871 LLVM_DEBUG(dbgs() << "\t " << K << "\t" << *CI[K].Coeff);
2872 LLVM_DEBUG(dbgs() << "\tPos Part = ");
2873 LLVM_DEBUG(dbgs() << *CI[K].PosPart);
2874 LLVM_DEBUG(dbgs() << "\tNeg Part = ");
2875 LLVM_DEBUG(dbgs() << *CI[K].NegPart);
2876 LLVM_DEBUG(dbgs() << "\tUpper Bound = ");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002877 if (CI[K].Iterations)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002878 LLVM_DEBUG(dbgs() << *CI[K].Iterations);
Sebastian Pop59b61b92012-10-11 07:32:34 +00002879 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002880 LLVM_DEBUG(dbgs() << "+inf");
2881 LLVM_DEBUG(dbgs() << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002882 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002883 LLVM_DEBUG(dbgs() << "\t Constant = " << *Subscript << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002884#endif
2885 return CI;
2886}
2887
2888
2889// Looks through all the bounds info and
2890// computes the lower bound given the current direction settings
2891// at each level. If the lower bound for any level is -inf,
2892// the result is -inf.
Chandler Carruth49c22192016-05-12 22:19:39 +00002893const SCEV *DependenceInfo::getLowerBound(BoundInfo *Bound) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002894 const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
2895 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2896 if (Bound[K].Lower[Bound[K].Direction])
2897 Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
2898 else
Craig Topper9f008862014-04-15 04:59:12 +00002899 Sum = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00002900 }
2901 return Sum;
2902}
2903
2904
2905// Looks through all the bounds info and
2906// computes the upper bound given the current direction settings
2907// at each level. If the upper bound at any level is +inf,
2908// the result is +inf.
Chandler Carruth49c22192016-05-12 22:19:39 +00002909const SCEV *DependenceInfo::getUpperBound(BoundInfo *Bound) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002910 const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
2911 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2912 if (Bound[K].Upper[Bound[K].Direction])
2913 Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
2914 else
Craig Topper9f008862014-04-15 04:59:12 +00002915 Sum = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00002916 }
2917 return Sum;
2918}
2919
2920
2921//===----------------------------------------------------------------------===//
2922// Constraint manipulation for Delta test.
2923
2924// Given a linear SCEV,
2925// return the coefficient (the step)
2926// corresponding to the specified loop.
2927// If there isn't one, return 0.
Jingyue Wua84feb12015-05-29 16:58:08 +00002928// For example, given a*i + b*j + c*k, finding the coefficient
Sebastian Pop59b61b92012-10-11 07:32:34 +00002929// corresponding to the j loop would yield b.
Chandler Carruth49c22192016-05-12 22:19:39 +00002930const SCEV *DependenceInfo::findCoefficient(const SCEV *Expr,
2931 const Loop *TargetLoop) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002932 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2933 if (!AddRec)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002934 return SE->getZero(Expr->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +00002935 if (AddRec->getLoop() == TargetLoop)
2936 return AddRec->getStepRecurrence(*SE);
2937 return findCoefficient(AddRec->getStart(), TargetLoop);
2938}
2939
2940
2941// Given a linear SCEV,
2942// return the SCEV given by zeroing out the coefficient
2943// corresponding to the specified loop.
2944// For example, given a*i + b*j + c*k, zeroing the coefficient
2945// corresponding to the j loop would yield a*i + c*k.
Chandler Carruth49c22192016-05-12 22:19:39 +00002946const SCEV *DependenceInfo::zeroCoefficient(const SCEV *Expr,
2947 const Loop *TargetLoop) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002948 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2949 if (!AddRec)
2950 return Expr; // ignore
2951 if (AddRec->getLoop() == TargetLoop)
2952 return AddRec->getStart();
2953 return SE->getAddRecExpr(zeroCoefficient(AddRec->getStart(), TargetLoop),
2954 AddRec->getStepRecurrence(*SE),
2955 AddRec->getLoop(),
2956 AddRec->getNoWrapFlags());
2957}
2958
2959
2960// Given a linear SCEV Expr,
2961// return the SCEV given by adding some Value to the
2962// coefficient corresponding to the specified TargetLoop.
2963// For example, given a*i + b*j + c*k, adding 1 to the coefficient
2964// corresponding to the j loop would yield a*i + (b+1)*j + c*k.
Chandler Carruth49c22192016-05-12 22:19:39 +00002965const SCEV *DependenceInfo::addToCoefficient(const SCEV *Expr,
2966 const Loop *TargetLoop,
2967 const SCEV *Value) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002968 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2969 if (!AddRec) // create a new addRec
2970 return SE->getAddRecExpr(Expr,
2971 Value,
2972 TargetLoop,
2973 SCEV::FlagAnyWrap); // Worst case, with no info.
2974 if (AddRec->getLoop() == TargetLoop) {
2975 const SCEV *Sum = SE->getAddExpr(AddRec->getStepRecurrence(*SE), Value);
2976 if (Sum->isZero())
2977 return AddRec->getStart();
2978 return SE->getAddRecExpr(AddRec->getStart(),
2979 Sum,
2980 AddRec->getLoop(),
2981 AddRec->getNoWrapFlags());
2982 }
Preston Briggs6c286b62013-06-28 18:44:48 +00002983 if (SE->isLoopInvariant(AddRec, TargetLoop))
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +00002984 return SE->getAddRecExpr(AddRec, Value, TargetLoop, SCEV::FlagAnyWrap);
2985 return SE->getAddRecExpr(
2986 addToCoefficient(AddRec->getStart(), TargetLoop, Value),
2987 AddRec->getStepRecurrence(*SE), AddRec->getLoop(),
2988 AddRec->getNoWrapFlags());
Sebastian Pop59b61b92012-10-11 07:32:34 +00002989}
2990
2991
2992// Review the constraints, looking for opportunities
2993// to simplify a subscript pair (Src and Dst).
2994// Return true if some simplification occurs.
2995// If the simplification isn't exact (that is, if it is conservative
2996// in terms of dependence), set consistent to false.
2997// Corresponds to Figure 5 from the paper
2998//
2999// Practical Dependence Testing
3000// Goff, Kennedy, Tseng
3001// PLDI 1991
Chandler Carruth49c22192016-05-12 22:19:39 +00003002bool DependenceInfo::propagate(const SCEV *&Src, const SCEV *&Dst,
3003 SmallBitVector &Loops,
3004 SmallVectorImpl<Constraint> &Constraints,
3005 bool &Consistent) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003006 bool Result = false;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003007 for (unsigned LI : Loops.set_bits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003008 LLVM_DEBUG(dbgs() << "\t Constraint[" << LI << "] is");
3009 LLVM_DEBUG(Constraints[LI].dump(dbgs()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00003010 if (Constraints[LI].isDistance())
3011 Result |= propagateDistance(Src, Dst, Constraints[LI], Consistent);
3012 else if (Constraints[LI].isLine())
3013 Result |= propagateLine(Src, Dst, Constraints[LI], Consistent);
3014 else if (Constraints[LI].isPoint())
3015 Result |= propagatePoint(Src, Dst, Constraints[LI]);
3016 }
3017 return Result;
3018}
3019
3020
3021// Attempt to propagate a distance
3022// constraint into a subscript pair (Src and Dst).
3023// Return true if some simplification occurs.
3024// If the simplification isn't exact (that is, if it is conservative
3025// in terms of dependence), set consistent to false.
Chandler Carruth49c22192016-05-12 22:19:39 +00003026bool DependenceInfo::propagateDistance(const SCEV *&Src, const SCEV *&Dst,
3027 Constraint &CurConstraint,
3028 bool &Consistent) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003029 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003030 LLVM_DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003031 const SCEV *A_K = findCoefficient(Src, CurLoop);
3032 if (A_K->isZero())
3033 return false;
3034 const SCEV *DA_K = SE->getMulExpr(A_K, CurConstraint.getD());
3035 Src = SE->getMinusSCEV(Src, DA_K);
3036 Src = zeroCoefficient(Src, CurLoop);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003037 LLVM_DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3038 LLVM_DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003039 Dst = addToCoefficient(Dst, CurLoop, SE->getNegativeSCEV(A_K));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003040 LLVM_DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003041 if (!findCoefficient(Dst, CurLoop)->isZero())
3042 Consistent = false;
3043 return true;
3044}
3045
3046
3047// Attempt to propagate a line
3048// constraint into a subscript pair (Src and Dst).
3049// Return true if some simplification occurs.
3050// If the simplification isn't exact (that is, if it is conservative
3051// in terms of dependence), set consistent to false.
Chandler Carruth49c22192016-05-12 22:19:39 +00003052bool DependenceInfo::propagateLine(const SCEV *&Src, const SCEV *&Dst,
3053 Constraint &CurConstraint,
3054 bool &Consistent) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003055 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3056 const SCEV *A = CurConstraint.getA();
3057 const SCEV *B = CurConstraint.getB();
3058 const SCEV *C = CurConstraint.getC();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003059 LLVM_DEBUG(dbgs() << "\t\tA = " << *A << ", B = " << *B << ", C = " << *C
3060 << "\n");
3061 LLVM_DEBUG(dbgs() << "\t\tSrc = " << *Src << "\n");
3062 LLVM_DEBUG(dbgs() << "\t\tDst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003063 if (A->isZero()) {
3064 const SCEVConstant *Bconst = dyn_cast<SCEVConstant>(B);
3065 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3066 if (!Bconst || !Cconst) return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003067 APInt Beta = Bconst->getAPInt();
3068 APInt Charlie = Cconst->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00003069 APInt CdivB = Charlie.sdiv(Beta);
3070 assert(Charlie.srem(Beta) == 0 && "C should be evenly divisible by B");
3071 const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3072 // Src = SE->getAddExpr(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3073 Src = SE->getMinusSCEV(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3074 Dst = zeroCoefficient(Dst, CurLoop);
3075 if (!findCoefficient(Src, CurLoop)->isZero())
3076 Consistent = false;
3077 }
3078 else if (B->isZero()) {
3079 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3080 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3081 if (!Aconst || !Cconst) return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003082 APInt Alpha = Aconst->getAPInt();
3083 APInt Charlie = Cconst->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00003084 APInt CdivA = Charlie.sdiv(Alpha);
3085 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3086 const SCEV *A_K = findCoefficient(Src, CurLoop);
3087 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3088 Src = zeroCoefficient(Src, CurLoop);
3089 if (!findCoefficient(Dst, CurLoop)->isZero())
3090 Consistent = false;
3091 }
3092 else if (isKnownPredicate(CmpInst::ICMP_EQ, A, B)) {
3093 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3094 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3095 if (!Aconst || !Cconst) return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003096 APInt Alpha = Aconst->getAPInt();
3097 APInt Charlie = Cconst->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00003098 APInt CdivA = Charlie.sdiv(Alpha);
3099 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3100 const SCEV *A_K = findCoefficient(Src, CurLoop);
3101 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3102 Src = zeroCoefficient(Src, CurLoop);
3103 Dst = addToCoefficient(Dst, CurLoop, A_K);
3104 if (!findCoefficient(Dst, CurLoop)->isZero())
3105 Consistent = false;
3106 }
3107 else {
3108 // paper is incorrect here, or perhaps just misleading
3109 const SCEV *A_K = findCoefficient(Src, CurLoop);
3110 Src = SE->getMulExpr(Src, A);
3111 Dst = SE->getMulExpr(Dst, A);
3112 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, C));
3113 Src = zeroCoefficient(Src, CurLoop);
3114 Dst = addToCoefficient(Dst, CurLoop, SE->getMulExpr(A_K, B));
3115 if (!findCoefficient(Dst, CurLoop)->isZero())
3116 Consistent = false;
3117 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003118 LLVM_DEBUG(dbgs() << "\t\tnew Src = " << *Src << "\n");
3119 LLVM_DEBUG(dbgs() << "\t\tnew Dst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003120 return true;
3121}
3122
3123
3124// Attempt to propagate a point
3125// constraint into a subscript pair (Src and Dst).
3126// Return true if some simplification occurs.
Chandler Carruth49c22192016-05-12 22:19:39 +00003127bool DependenceInfo::propagatePoint(const SCEV *&Src, const SCEV *&Dst,
3128 Constraint &CurConstraint) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003129 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3130 const SCEV *A_K = findCoefficient(Src, CurLoop);
3131 const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3132 const SCEV *XA_K = SE->getMulExpr(A_K, CurConstraint.getX());
3133 const SCEV *YAP_K = SE->getMulExpr(AP_K, CurConstraint.getY());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003134 LLVM_DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003135 Src = SE->getAddExpr(Src, SE->getMinusSCEV(XA_K, YAP_K));
3136 Src = zeroCoefficient(Src, CurLoop);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003137 LLVM_DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3138 LLVM_DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003139 Dst = zeroCoefficient(Dst, CurLoop);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003140 LLVM_DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003141 return true;
3142}
3143
3144
3145// Update direction vector entry based on the current constraint.
Chandler Carruth49c22192016-05-12 22:19:39 +00003146void DependenceInfo::updateDirection(Dependence::DVEntry &Level,
3147 const Constraint &CurConstraint) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003148 LLVM_DEBUG(dbgs() << "\tUpdate direction, constraint =");
3149 LLVM_DEBUG(CurConstraint.dump(dbgs()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00003150 if (CurConstraint.isAny())
3151 ; // use defaults
3152 else if (CurConstraint.isDistance()) {
3153 // this one is consistent, the others aren't
3154 Level.Scalar = false;
3155 Level.Distance = CurConstraint.getD();
3156 unsigned NewDirection = Dependence::DVEntry::NONE;
3157 if (!SE->isKnownNonZero(Level.Distance)) // if may be zero
3158 NewDirection = Dependence::DVEntry::EQ;
3159 if (!SE->isKnownNonPositive(Level.Distance)) // if may be positive
3160 NewDirection |= Dependence::DVEntry::LT;
3161 if (!SE->isKnownNonNegative(Level.Distance)) // if may be negative
3162 NewDirection |= Dependence::DVEntry::GT;
3163 Level.Direction &= NewDirection;
3164 }
3165 else if (CurConstraint.isLine()) {
3166 Level.Scalar = false;
Craig Topper9f008862014-04-15 04:59:12 +00003167 Level.Distance = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003168 // direction should be accurate
3169 }
3170 else if (CurConstraint.isPoint()) {
3171 Level.Scalar = false;
Craig Topper9f008862014-04-15 04:59:12 +00003172 Level.Distance = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003173 unsigned NewDirection = Dependence::DVEntry::NONE;
3174 if (!isKnownPredicate(CmpInst::ICMP_NE,
3175 CurConstraint.getY(),
3176 CurConstraint.getX()))
3177 // if X may be = Y
3178 NewDirection |= Dependence::DVEntry::EQ;
3179 if (!isKnownPredicate(CmpInst::ICMP_SLE,
3180 CurConstraint.getY(),
3181 CurConstraint.getX()))
3182 // if Y may be > X
3183 NewDirection |= Dependence::DVEntry::LT;
3184 if (!isKnownPredicate(CmpInst::ICMP_SGE,
3185 CurConstraint.getY(),
3186 CurConstraint.getX()))
3187 // if Y may be < X
3188 NewDirection |= Dependence::DVEntry::GT;
3189 Level.Direction &= NewDirection;
3190 }
3191 else
3192 llvm_unreachable("constraint has unexpected kind");
3193}
3194
Sebastian Popc62c6792013-11-12 22:47:20 +00003195/// Check if we can delinearize the subscripts. If the SCEVs representing the
3196/// source and destination array references are recurrences on a nested loop,
Alp Tokercb402912014-01-24 17:20:08 +00003197/// this function flattens the nested recurrences into separate recurrences
Sebastian Popc62c6792013-11-12 22:47:20 +00003198/// for each loop level.
Chandler Carruth49c22192016-05-12 22:19:39 +00003199bool DependenceInfo::tryDelinearize(Instruction *Src, Instruction *Dst,
3200 SmallVectorImpl<Subscript> &Pair) {
Renato Golin038ede22018-03-09 21:05:58 +00003201 assert(isLoadOrStore(Src) && "instruction is not load or store");
3202 assert(isLoadOrStore(Dst) && "instruction is not load or store");
3203 Value *SrcPtr = getLoadStorePointerOperand(Src);
3204 Value *DstPtr = getLoadStorePointerOperand(Dst);
Hal Finkel0ef2b102015-08-19 02:56:36 +00003205
3206 Loop *SrcLoop = LI->getLoopFor(Src->getParent());
3207 Loop *DstLoop = LI->getLoopFor(Dst->getParent());
3208
3209 // Below code mimics the code in Delinearization.cpp
3210 const SCEV *SrcAccessFn =
3211 SE->getSCEVAtScope(SrcPtr, SrcLoop);
3212 const SCEV *DstAccessFn =
3213 SE->getSCEVAtScope(DstPtr, DstLoop);
3214
Sebastian Pop28e6b972014-05-27 22:41:51 +00003215 const SCEVUnknown *SrcBase =
Hal Finkel0ef2b102015-08-19 02:56:36 +00003216 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
Sebastian Pop28e6b972014-05-27 22:41:51 +00003217 const SCEVUnknown *DstBase =
Hal Finkel0ef2b102015-08-19 02:56:36 +00003218 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
Sebastian Pop28e6b972014-05-27 22:41:51 +00003219
3220 if (!SrcBase || !DstBase || SrcBase != DstBase)
3221 return false;
3222
Hal Finkel0ef2b102015-08-19 02:56:36 +00003223 const SCEV *ElementSize = SE->getElementSize(Src);
3224 if (ElementSize != SE->getElementSize(Dst))
3225 return false;
3226
3227 const SCEV *SrcSCEV = SE->getMinusSCEV(SrcAccessFn, SrcBase);
3228 const SCEV *DstSCEV = SE->getMinusSCEV(DstAccessFn, DstBase);
Sebastian Pop28e6b972014-05-27 22:41:51 +00003229
Sebastian Popc62c6792013-11-12 22:47:20 +00003230 const SCEVAddRecExpr *SrcAR = dyn_cast<SCEVAddRecExpr>(SrcSCEV);
3231 const SCEVAddRecExpr *DstAR = dyn_cast<SCEVAddRecExpr>(DstSCEV);
3232 if (!SrcAR || !DstAR || !SrcAR->isAffine() || !DstAR->isAffine())
3233 return false;
3234
Sebastian Pop448712b2014-05-07 18:01:20 +00003235 // First step: collect parametric terms in both array references.
3236 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00003237 SE->collectParametricTerms(SrcAR, Terms);
3238 SE->collectParametricTerms(DstAR, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00003239
Sebastian Pop448712b2014-05-07 18:01:20 +00003240 // Second step: find subscript sizes.
3241 SmallVector<const SCEV *, 4> Sizes;
Sebastian Popa6e58602014-05-27 22:41:45 +00003242 SE->findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop448712b2014-05-07 18:01:20 +00003243
3244 // Third step: compute the access functions for each subscript.
3245 SmallVector<const SCEV *, 4> SrcSubscripts, DstSubscripts;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00003246 SE->computeAccessFunctions(SrcAR, SrcSubscripts, Sizes);
3247 SE->computeAccessFunctions(DstAR, DstSubscripts, Sizes);
Sebastian Pop448712b2014-05-07 18:01:20 +00003248
Sebastian Pop5133d2e2014-02-21 18:15:07 +00003249 // Fail when there is only a subscript: that's a linearized access function.
Sebastian Pop448712b2014-05-07 18:01:20 +00003250 if (SrcSubscripts.size() < 2 || DstSubscripts.size() < 2 ||
3251 SrcSubscripts.size() != DstSubscripts.size())
Sebastian Popc62c6792013-11-12 22:47:20 +00003252 return false;
3253
Sebastian Pop448712b2014-05-07 18:01:20 +00003254 int size = SrcSubscripts.size();
Sebastian Pop29026d32014-02-21 18:15:11 +00003255
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003256 LLVM_DEBUG({
3257 dbgs() << "\nSrcSubscripts: ";
Sebastian Pop448712b2014-05-07 18:01:20 +00003258 for (int i = 0; i < size; i++)
3259 dbgs() << *SrcSubscripts[i];
3260 dbgs() << "\nDstSubscripts: ";
3261 for (int i = 0; i < size; i++)
3262 dbgs() << *DstSubscripts[i];
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003263 });
Sebastian Popc62c6792013-11-12 22:47:20 +00003264
Sebastian Pop7ee14722013-11-13 22:37:58 +00003265 // The delinearization transforms a single-subscript MIV dependence test into
3266 // a multi-subscript SIV dependence test that is easier to compute. So we
3267 // resize Pair to contain as many pairs of subscripts as the delinearization
3268 // has found, and then initialize the pairs following the delinearization.
Sebastian Popc62c6792013-11-12 22:47:20 +00003269 Pair.resize(size);
3270 for (int i = 0; i < size; ++i) {
3271 Pair[i].Src = SrcSubscripts[i];
3272 Pair[i].Dst = DstSubscripts[i];
Jingyue Wu0fa125a2014-11-16 16:52:44 +00003273 unifySubscriptType(&Pair[i]);
Sebastian Pop7ee14722013-11-13 22:37:58 +00003274
3275 // FIXME: we should record the bounds SrcSizes[i] and DstSizes[i] that the
3276 // delinearization has found, and add these constraints to the dependence
3277 // check to avoid memory accesses overflow from one dimension into another.
3278 // This is related to the problem of determining the existence of data
3279 // dependences in array accesses using a different number of subscripts: in
3280 // C one can access an array A[100][100]; as A[0][9999], *A[9999], etc.
Sebastian Popc62c6792013-11-12 22:47:20 +00003281 }
3282
3283 return true;
3284}
Sebastian Pop59b61b92012-10-11 07:32:34 +00003285
3286//===----------------------------------------------------------------------===//
3287
3288#ifndef NDEBUG
3289// For debugging purposes, dump a small bit vector to dbgs().
3290static void dumpSmallBitVector(SmallBitVector &BV) {
3291 dbgs() << "{";
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003292 for (unsigned VI : BV.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003293 dbgs() << VI;
3294 if (BV.find_next(VI) >= 0)
3295 dbgs() << ' ';
3296 }
3297 dbgs() << "}\n";
3298}
3299#endif
3300
Sebastian Pop59b61b92012-10-11 07:32:34 +00003301// depends -
3302// Returns NULL if there is no dependence.
3303// Otherwise, return a Dependence with as many details as possible.
3304// Corresponds to Section 3.1 in the paper
3305//
3306// Practical Dependence Testing
3307// Goff, Kennedy, Tseng
3308// PLDI 1991
3309//
Preston Briggs3ad39492012-11-21 23:50:04 +00003310// Care is required to keep the routine below, getSplitIteration(),
3311// up to date with respect to this routine.
Dylan Noblesmith2cae60e2014-08-25 00:28:39 +00003312std::unique_ptr<Dependence>
Chandler Carruth49c22192016-05-12 22:19:39 +00003313DependenceInfo::depends(Instruction *Src, Instruction *Dst,
3314 bool PossiblyLoopIndependent) {
Preston Briggs1084fa22012-11-27 06:41:46 +00003315 if (Src == Dst)
3316 PossiblyLoopIndependent = false;
3317
Sebastian Pop59b61b92012-10-11 07:32:34 +00003318 if ((!Src->mayReadFromMemory() && !Src->mayWriteToMemory()) ||
3319 (!Dst->mayReadFromMemory() && !Dst->mayWriteToMemory()))
3320 // if both instructions don't reference memory, there's no dependence
Craig Topper9f008862014-04-15 04:59:12 +00003321 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003322
Preston Briggs3ad39492012-11-21 23:50:04 +00003323 if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003324 // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003325 LLVM_DEBUG(dbgs() << "can only handle simple loads and stores\n");
Dylan Noblesmith2cae60e2014-08-25 00:28:39 +00003326 return make_unique<Dependence>(Src, Dst);
Preston Briggs3ad39492012-11-21 23:50:04 +00003327 }
Sebastian Pop59b61b92012-10-11 07:32:34 +00003328
Renato Golin038ede22018-03-09 21:05:58 +00003329 assert(isLoadOrStore(Src) && "instruction is not load or store");
3330 assert(isLoadOrStore(Dst) && "instruction is not load or store");
3331 Value *SrcPtr = getLoadStorePointerOperand(Src);
3332 Value *DstPtr = getLoadStorePointerOperand(Dst);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003333
David Green5ef933b2018-04-10 11:37:21 +00003334 switch (underlyingObjectsAlias(AA, F->getParent()->getDataLayout(),
3335 MemoryLocation::get(Dst),
3336 MemoryLocation::get(Src))) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00003337 case MayAlias:
3338 case PartialAlias:
Sebastian Pop59b61b92012-10-11 07:32:34 +00003339 // cannot analyse objects if we don't understand their aliasing.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003340 LLVM_DEBUG(dbgs() << "can't analyze may or partial alias\n");
Dylan Noblesmith2cae60e2014-08-25 00:28:39 +00003341 return make_unique<Dependence>(Src, Dst);
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00003342 case NoAlias:
Sebastian Pop59b61b92012-10-11 07:32:34 +00003343 // If the objects noalias, they are distinct, accesses are independent.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003344 LLVM_DEBUG(dbgs() << "no alias\n");
Craig Topper9f008862014-04-15 04:59:12 +00003345 return nullptr;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00003346 case MustAlias:
Sebastian Pop59b61b92012-10-11 07:32:34 +00003347 break; // The underlying objects alias; test accesses for dependence.
3348 }
3349
Sebastian Pop59b61b92012-10-11 07:32:34 +00003350 // establish loop nesting levels
3351 establishNestingLevels(Src, Dst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003352 LLVM_DEBUG(dbgs() << " common nesting levels = " << CommonLevels << "\n");
3353 LLVM_DEBUG(dbgs() << " maximum nesting levels = " << MaxLevels << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003354
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003355 FullDependence Result(Src, Dst, PossiblyLoopIndependent, CommonLevels);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003356 ++TotalArrayPairs;
3357
Sebastian Popbf6e1c22018-03-06 21:55:59 +00003358 unsigned Pairs = 1;
3359 SmallVector<Subscript, 2> Pair(Pairs);
3360 const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3361 const SCEV *DstSCEV = SE->getSCEV(DstPtr);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003362 LLVM_DEBUG(dbgs() << " SrcSCEV = " << *SrcSCEV << "\n");
3363 LLVM_DEBUG(dbgs() << " DstSCEV = " << *DstSCEV << "\n");
Sebastian Popbf6e1c22018-03-06 21:55:59 +00003364 Pair[0].Src = SrcSCEV;
3365 Pair[0].Dst = DstSCEV;
Preston Briggs3ad39492012-11-21 23:50:04 +00003366
Sebastian Popbf6e1c22018-03-06 21:55:59 +00003367 if (Delinearize) {
Hal Finkel0ef2b102015-08-19 02:56:36 +00003368 if (tryDelinearize(Src, Dst, Pair)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003369 LLVM_DEBUG(dbgs() << " delinearized\n");
Hal Finkel0ef2b102015-08-19 02:56:36 +00003370 Pairs = Pair.size();
3371 }
Sebastian Popc62c6792013-11-12 22:47:20 +00003372 }
3373
Preston Briggs3ad39492012-11-21 23:50:04 +00003374 for (unsigned P = 0; P < Pairs; ++P) {
3375 Pair[P].Loops.resize(MaxLevels + 1);
3376 Pair[P].GroupLoops.resize(MaxLevels + 1);
3377 Pair[P].Group.resize(Pairs);
3378 removeMatchingExtensions(&Pair[P]);
3379 Pair[P].Classification =
3380 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3381 Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
3382 Pair[P].Loops);
3383 Pair[P].GroupLoops = Pair[P].Loops;
3384 Pair[P].Group.set(P);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003385 LLVM_DEBUG(dbgs() << " subscript " << P << "\n");
3386 LLVM_DEBUG(dbgs() << "\tsrc = " << *Pair[P].Src << "\n");
3387 LLVM_DEBUG(dbgs() << "\tdst = " << *Pair[P].Dst << "\n");
3388 LLVM_DEBUG(dbgs() << "\tclass = " << Pair[P].Classification << "\n");
3389 LLVM_DEBUG(dbgs() << "\tloops = ");
3390 LLVM_DEBUG(dumpSmallBitVector(Pair[P].Loops));
Sebastian Pop59b61b92012-10-11 07:32:34 +00003391 }
3392
3393 SmallBitVector Separable(Pairs);
3394 SmallBitVector Coupled(Pairs);
3395
3396 // Partition subscripts into separable and minimally-coupled groups
3397 // Algorithm in paper is algorithmically better;
3398 // this may be faster in practice. Check someday.
3399 //
3400 // Here's an example of how it works. Consider this code:
3401 //
3402 // for (i = ...) {
3403 // for (j = ...) {
3404 // for (k = ...) {
3405 // for (l = ...) {
3406 // for (m = ...) {
3407 // A[i][j][k][m] = ...;
3408 // ... = A[0][j][l][i + j];
3409 // }
3410 // }
3411 // }
3412 // }
3413 // }
3414 //
3415 // There are 4 subscripts here:
3416 // 0 [i] and [0]
3417 // 1 [j] and [j]
3418 // 2 [k] and [l]
3419 // 3 [m] and [i + j]
3420 //
3421 // We've already classified each subscript pair as ZIV, SIV, etc.,
3422 // and collected all the loops mentioned by pair P in Pair[P].Loops.
3423 // In addition, we've initialized Pair[P].GroupLoops to Pair[P].Loops
3424 // and set Pair[P].Group = {P}.
3425 //
3426 // Src Dst Classification Loops GroupLoops Group
3427 // 0 [i] [0] SIV {1} {1} {0}
3428 // 1 [j] [j] SIV {2} {2} {1}
3429 // 2 [k] [l] RDIV {3,4} {3,4} {2}
3430 // 3 [m] [i + j] MIV {1,2,5} {1,2,5} {3}
3431 //
3432 // For each subscript SI 0 .. 3, we consider each remaining subscript, SJ.
3433 // So, 0 is compared against 1, 2, and 3; 1 is compared against 2 and 3, etc.
3434 //
3435 // We begin by comparing 0 and 1. The intersection of the GroupLoops is empty.
3436 // Next, 0 and 2. Again, the intersection of their GroupLoops is empty.
3437 // Next 0 and 3. The intersection of their GroupLoop = {1}, not empty,
3438 // so Pair[3].Group = {0,3} and Done = false (that is, 0 will not be added
3439 // to either Separable or Coupled).
3440 //
3441 // Next, we consider 1 and 2. The intersection of the GroupLoops is empty.
3442 // Next, 1 and 3. The intersectionof their GroupLoops = {2}, not empty,
3443 // so Pair[3].Group = {0, 1, 3} and Done = false.
3444 //
3445 // Next, we compare 2 against 3. The intersection of the GroupLoops is empty.
3446 // Since Done remains true, we add 2 to the set of Separable pairs.
3447 //
3448 // Finally, we consider 3. There's nothing to compare it with,
3449 // so Done remains true and we add it to the Coupled set.
3450 // Pair[3].Group = {0, 1, 3} and GroupLoops = {1, 2, 5}.
3451 //
3452 // In the end, we've got 1 separable subscript and 1 coupled group.
3453 for (unsigned SI = 0; SI < Pairs; ++SI) {
3454 if (Pair[SI].Classification == Subscript::NonLinear) {
3455 // ignore these, but collect loops for later
3456 ++NonlinearSubscriptPairs;
3457 collectCommonLoops(Pair[SI].Src,
3458 LI->getLoopFor(Src->getParent()),
3459 Pair[SI].Loops);
3460 collectCommonLoops(Pair[SI].Dst,
3461 LI->getLoopFor(Dst->getParent()),
3462 Pair[SI].Loops);
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003463 Result.Consistent = false;
NAKAMURA Takumi478559a2015-03-05 01:25:19 +00003464 } else if (Pair[SI].Classification == Subscript::ZIV) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003465 // always separable
3466 Separable.set(SI);
3467 }
3468 else {
3469 // SIV, RDIV, or MIV, so check for coupled group
3470 bool Done = true;
3471 for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
3472 SmallBitVector Intersection = Pair[SI].GroupLoops;
3473 Intersection &= Pair[SJ].GroupLoops;
3474 if (Intersection.any()) {
3475 // accumulate set of all the loops in group
3476 Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
3477 // accumulate set of all subscripts in group
3478 Pair[SJ].Group |= Pair[SI].Group;
3479 Done = false;
3480 }
3481 }
3482 if (Done) {
3483 if (Pair[SI].Group.count() == 1) {
3484 Separable.set(SI);
3485 ++SeparableSubscriptPairs;
3486 }
3487 else {
3488 Coupled.set(SI);
3489 ++CoupledSubscriptPairs;
3490 }
3491 }
3492 }
3493 }
3494
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003495 LLVM_DEBUG(dbgs() << " Separable = ");
3496 LLVM_DEBUG(dumpSmallBitVector(Separable));
3497 LLVM_DEBUG(dbgs() << " Coupled = ");
3498 LLVM_DEBUG(dumpSmallBitVector(Coupled));
Sebastian Pop59b61b92012-10-11 07:32:34 +00003499
3500 Constraint NewConstraint;
3501 NewConstraint.setAny(SE);
3502
3503 // test separable subscripts
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003504 for (unsigned SI : Separable.set_bits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003505 LLVM_DEBUG(dbgs() << "testing subscript " << SI);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003506 switch (Pair[SI].Classification) {
3507 case Subscript::ZIV:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003508 LLVM_DEBUG(dbgs() << ", ZIV\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003509 if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003510 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003511 break;
3512 case Subscript::SIV: {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003513 LLVM_DEBUG(dbgs() << ", SIV\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003514 unsigned Level;
Craig Topper9f008862014-04-15 04:59:12 +00003515 const SCEV *SplitIter = nullptr;
NAKAMURA Takumi478559a2015-03-05 01:25:19 +00003516 if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level, Result, NewConstraint,
3517 SplitIter))
Craig Topper9f008862014-04-15 04:59:12 +00003518 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003519 break;
3520 }
3521 case Subscript::RDIV:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003522 LLVM_DEBUG(dbgs() << ", RDIV\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003523 if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003524 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003525 break;
3526 case Subscript::MIV:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003527 LLVM_DEBUG(dbgs() << ", MIV\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003528 if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003529 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003530 break;
3531 default:
3532 llvm_unreachable("subscript has unexpected classification");
3533 }
3534 }
3535
3536 if (Coupled.count()) {
3537 // test coupled subscript groups
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003538 LLVM_DEBUG(dbgs() << "starting on coupled subscripts\n");
3539 LLVM_DEBUG(dbgs() << "MaxLevels + 1 = " << MaxLevels + 1 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003540 SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
3541 for (unsigned II = 0; II <= MaxLevels; ++II)
3542 Constraints[II].setAny(SE);
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003543 for (unsigned SI : Coupled.set_bits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003544 LLVM_DEBUG(dbgs() << "testing subscript group " << SI << " { ");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003545 SmallBitVector Group(Pair[SI].Group);
3546 SmallBitVector Sivs(Pairs);
3547 SmallBitVector Mivs(Pairs);
3548 SmallBitVector ConstrainedLevels(MaxLevels + 1);
Jingyue Wua84feb12015-05-29 16:58:08 +00003549 SmallVector<Subscript *, 4> PairsInGroup;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003550 for (unsigned SJ : Group.set_bits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003551 LLVM_DEBUG(dbgs() << SJ << " ");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003552 if (Pair[SJ].Classification == Subscript::SIV)
3553 Sivs.set(SJ);
3554 else
3555 Mivs.set(SJ);
Jingyue Wua84feb12015-05-29 16:58:08 +00003556 PairsInGroup.push_back(&Pair[SJ]);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003557 }
Jingyue Wua84feb12015-05-29 16:58:08 +00003558 unifySubscriptType(PairsInGroup);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003559 LLVM_DEBUG(dbgs() << "}\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003560 while (Sivs.any()) {
3561 bool Changed = false;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003562 for (unsigned SJ : Sivs.set_bits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003563 LLVM_DEBUG(dbgs() << "testing subscript " << SJ << ", SIV\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003564 // SJ is an SIV subscript that's part of the current coupled group
3565 unsigned Level;
Craig Topper9f008862014-04-15 04:59:12 +00003566 const SCEV *SplitIter = nullptr;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003567 LLVM_DEBUG(dbgs() << "SIV\n");
NAKAMURA Takumi478559a2015-03-05 01:25:19 +00003568 if (testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level, Result, NewConstraint,
3569 SplitIter))
Craig Topper9f008862014-04-15 04:59:12 +00003570 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003571 ConstrainedLevels.set(Level);
3572 if (intersectConstraints(&Constraints[Level], &NewConstraint)) {
3573 if (Constraints[Level].isEmpty()) {
3574 ++DeltaIndependence;
Craig Topper9f008862014-04-15 04:59:12 +00003575 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003576 }
3577 Changed = true;
3578 }
3579 Sivs.reset(SJ);
3580 }
3581 if (Changed) {
3582 // propagate, possibly creating new SIVs and ZIVs
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003583 LLVM_DEBUG(dbgs() << " propagating\n");
3584 LLVM_DEBUG(dbgs() << "\tMivs = ");
3585 LLVM_DEBUG(dumpSmallBitVector(Mivs));
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003586 for (unsigned SJ : Mivs.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003587 // SJ is an MIV subscript that's part of the current coupled group
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003588 LLVM_DEBUG(dbgs() << "\tSJ = " << SJ << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003589 if (propagate(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops,
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003590 Constraints, Result.Consistent)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003591 LLVM_DEBUG(dbgs() << "\t Changed\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003592 ++DeltaPropagations;
3593 Pair[SJ].Classification =
3594 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
3595 Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
3596 Pair[SJ].Loops);
3597 switch (Pair[SJ].Classification) {
3598 case Subscript::ZIV:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003599 LLVM_DEBUG(dbgs() << "ZIV\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003600 if (testZIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003601 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003602 Mivs.reset(SJ);
3603 break;
3604 case Subscript::SIV:
3605 Sivs.set(SJ);
3606 Mivs.reset(SJ);
3607 break;
3608 case Subscript::RDIV:
3609 case Subscript::MIV:
3610 break;
3611 default:
3612 llvm_unreachable("bad subscript classification");
3613 }
3614 }
3615 }
3616 }
3617 }
3618
3619 // test & propagate remaining RDIVs
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003620 for (unsigned SJ : Mivs.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003621 if (Pair[SJ].Classification == Subscript::RDIV) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003622 LLVM_DEBUG(dbgs() << "RDIV test\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003623 if (testRDIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003624 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003625 // I don't yet understand how to propagate RDIV results
3626 Mivs.reset(SJ);
3627 }
3628 }
3629
3630 // test remaining MIVs
3631 // This code is temporary.
3632 // Better to somehow test all remaining subscripts simultaneously.
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003633 for (unsigned SJ : Mivs.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003634 if (Pair[SJ].Classification == Subscript::MIV) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003635 LLVM_DEBUG(dbgs() << "MIV test\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003636 if (testMIV(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003637 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003638 }
3639 else
3640 llvm_unreachable("expected only MIV subscripts at this point");
3641 }
3642
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003643 // update Result.DV from constraint vector
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003644 LLVM_DEBUG(dbgs() << " updating\n");
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003645 for (unsigned SJ : ConstrainedLevels.set_bits()) {
3646 if (SJ > CommonLevels)
Karthik Bhat8d7f7ed2015-03-10 14:32:02 +00003647 break;
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003648 updateDirection(Result.DV[SJ - 1], Constraints[SJ]);
3649 if (Result.DV[SJ - 1].Direction == Dependence::DVEntry::NONE)
Craig Topper9f008862014-04-15 04:59:12 +00003650 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003651 }
3652 }
3653 }
3654
Preston Briggs4eb7ee52012-11-29 04:30:52 +00003655 // Make sure the Scalar flags are set correctly.
Sebastian Pop59b61b92012-10-11 07:32:34 +00003656 SmallBitVector CompleteLoops(MaxLevels + 1);
3657 for (unsigned SI = 0; SI < Pairs; ++SI)
3658 CompleteLoops |= Pair[SI].Loops;
3659 for (unsigned II = 1; II <= CommonLevels; ++II)
3660 if (CompleteLoops[II])
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003661 Result.DV[II - 1].Scalar = false;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003662
Sebastian Pop59b61b92012-10-11 07:32:34 +00003663 if (PossiblyLoopIndependent) {
Preston Briggs5cb8cfa2012-11-27 19:12:26 +00003664 // Make sure the LoopIndependent flag is set correctly.
3665 // All directions must include equal, otherwise no
3666 // loop-independent dependence is possible.
Sebastian Pop59b61b92012-10-11 07:32:34 +00003667 for (unsigned II = 1; II <= CommonLevels; ++II) {
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003668 if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) {
3669 Result.LoopIndependent = false;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003670 break;
3671 }
3672 }
3673 }
Preston Briggs5cb8cfa2012-11-27 19:12:26 +00003674 else {
3675 // On the other hand, if all directions are equal and there's no
3676 // loop-independent dependence possible, then no dependence exists.
3677 bool AllEqual = true;
3678 for (unsigned II = 1; II <= CommonLevels; ++II) {
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003679 if (Result.getDirection(II) != Dependence::DVEntry::EQ) {
Preston Briggs4eb7ee52012-11-29 04:30:52 +00003680 AllEqual = false;
3681 break;
Preston Briggs5cb8cfa2012-11-27 19:12:26 +00003682 }
3683 }
3684 if (AllEqual)
Craig Topper9f008862014-04-15 04:59:12 +00003685 return nullptr;
Preston Briggs5cb8cfa2012-11-27 19:12:26 +00003686 }
Sebastian Pop59b61b92012-10-11 07:32:34 +00003687
David Blaikie47039dc2015-07-31 21:37:09 +00003688 return make_unique<FullDependence>(std::move(Result));
Sebastian Pop59b61b92012-10-11 07:32:34 +00003689}
3690
3691
3692
3693//===----------------------------------------------------------------------===//
3694// getSplitIteration -
3695// Rather than spend rarely-used space recording the splitting iteration
3696// during the Weak-Crossing SIV test, we re-compute it on demand.
3697// The re-computation is basically a repeat of the entire dependence test,
3698// though simplified since we know that the dependence exists.
3699// It's tedious, since we must go through all propagations, etc.
3700//
Preston Briggs3ad39492012-11-21 23:50:04 +00003701// Care is required to keep this code up to date with respect to the routine
3702// above, depends().
Sebastian Pop59b61b92012-10-11 07:32:34 +00003703//
3704// Generally, the dependence analyzer will be used to build
3705// a dependence graph for a function (basically a map from instructions
3706// to dependences). Looking for cycles in the graph shows us loops
3707// that cannot be trivially vectorized/parallelized.
3708//
3709// We can try to improve the situation by examining all the dependences
3710// that make up the cycle, looking for ones we can break.
3711// Sometimes, peeling the first or last iteration of a loop will break
3712// dependences, and we've got flags for those possibilities.
3713// Sometimes, splitting a loop at some other iteration will do the trick,
3714// and we've got a flag for that case. Rather than waste the space to
3715// record the exact iteration (since we rarely know), we provide
3716// a method that calculates the iteration. It's a drag that it must work
3717// from scratch, but wonderful in that it's possible.
3718//
3719// Here's an example:
3720//
3721// for (i = 0; i < 10; i++)
3722// A[i] = ...
3723// ... = A[11 - i]
3724//
3725// There's a loop-carried flow dependence from the store to the load,
3726// found by the weak-crossing SIV test. The dependence will have a flag,
3727// indicating that the dependence can be broken by splitting the loop.
3728// Calling getSplitIteration will return 5.
3729// Splitting the loop breaks the dependence, like so:
3730//
3731// for (i = 0; i <= 5; i++)
3732// A[i] = ...
3733// ... = A[11 - i]
3734// for (i = 6; i < 10; i++)
3735// A[i] = ...
3736// ... = A[11 - i]
3737//
3738// breaks the dependence and allows us to vectorize/parallelize
3739// both loops.
Chandler Carruth49c22192016-05-12 22:19:39 +00003740const SCEV *DependenceInfo::getSplitIteration(const Dependence &Dep,
3741 unsigned SplitLevel) {
Dylan Noblesmithd96ce662014-08-25 00:28:35 +00003742 assert(Dep.isSplitable(SplitLevel) &&
Sebastian Pop59b61b92012-10-11 07:32:34 +00003743 "Dep should be splitable at SplitLevel");
Dylan Noblesmithd96ce662014-08-25 00:28:35 +00003744 Instruction *Src = Dep.getSrc();
3745 Instruction *Dst = Dep.getDst();
Sebastian Pop59b61b92012-10-11 07:32:34 +00003746 assert(Src->mayReadFromMemory() || Src->mayWriteToMemory());
3747 assert(Dst->mayReadFromMemory() || Dst->mayWriteToMemory());
3748 assert(isLoadOrStore(Src));
3749 assert(isLoadOrStore(Dst));
Renato Golin038ede22018-03-09 21:05:58 +00003750 Value *SrcPtr = getLoadStorePointerOperand(Src);
3751 Value *DstPtr = getLoadStorePointerOperand(Dst);
David Green5ef933b2018-04-10 11:37:21 +00003752 assert(underlyingObjectsAlias(AA, F->getParent()->getDataLayout(),
3753 MemoryLocation::get(Dst),
3754 MemoryLocation::get(Src)) == MustAlias);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003755
3756 // establish loop nesting levels
3757 establishNestingLevels(Src, Dst);
3758
3759 FullDependence Result(Src, Dst, false, CommonLevels);
3760
Sebastian Popbf6e1c22018-03-06 21:55:59 +00003761 unsigned Pairs = 1;
3762 SmallVector<Subscript, 2> Pair(Pairs);
3763 const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3764 const SCEV *DstSCEV = SE->getSCEV(DstPtr);
3765 Pair[0].Src = SrcSCEV;
3766 Pair[0].Dst = DstSCEV;
Preston Briggs3ad39492012-11-21 23:50:04 +00003767
Sebastian Popbf6e1c22018-03-06 21:55:59 +00003768 if (Delinearize) {
Hal Finkel0ef2b102015-08-19 02:56:36 +00003769 if (tryDelinearize(Src, Dst, Pair)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003770 LLVM_DEBUG(dbgs() << " delinearized\n");
Hal Finkel0ef2b102015-08-19 02:56:36 +00003771 Pairs = Pair.size();
3772 }
Sebastian Popc62c6792013-11-12 22:47:20 +00003773 }
3774
Preston Briggs3ad39492012-11-21 23:50:04 +00003775 for (unsigned P = 0; P < Pairs; ++P) {
3776 Pair[P].Loops.resize(MaxLevels + 1);
3777 Pair[P].GroupLoops.resize(MaxLevels + 1);
3778 Pair[P].Group.resize(Pairs);
3779 removeMatchingExtensions(&Pair[P]);
3780 Pair[P].Classification =
3781 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3782 Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
3783 Pair[P].Loops);
3784 Pair[P].GroupLoops = Pair[P].Loops;
3785 Pair[P].Group.set(P);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003786 }
3787
3788 SmallBitVector Separable(Pairs);
3789 SmallBitVector Coupled(Pairs);
3790
3791 // partition subscripts into separable and minimally-coupled groups
3792 for (unsigned SI = 0; SI < Pairs; ++SI) {
3793 if (Pair[SI].Classification == Subscript::NonLinear) {
3794 // ignore these, but collect loops for later
3795 collectCommonLoops(Pair[SI].Src,
3796 LI->getLoopFor(Src->getParent()),
3797 Pair[SI].Loops);
3798 collectCommonLoops(Pair[SI].Dst,
3799 LI->getLoopFor(Dst->getParent()),
3800 Pair[SI].Loops);
3801 Result.Consistent = false;
3802 }
3803 else if (Pair[SI].Classification == Subscript::ZIV)
3804 Separable.set(SI);
3805 else {
3806 // SIV, RDIV, or MIV, so check for coupled group
3807 bool Done = true;
3808 for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
3809 SmallBitVector Intersection = Pair[SI].GroupLoops;
3810 Intersection &= Pair[SJ].GroupLoops;
3811 if (Intersection.any()) {
3812 // accumulate set of all the loops in group
3813 Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
3814 // accumulate set of all subscripts in group
3815 Pair[SJ].Group |= Pair[SI].Group;
3816 Done = false;
3817 }
3818 }
3819 if (Done) {
3820 if (Pair[SI].Group.count() == 1)
3821 Separable.set(SI);
3822 else
3823 Coupled.set(SI);
3824 }
3825 }
3826 }
3827
3828 Constraint NewConstraint;
3829 NewConstraint.setAny(SE);
3830
3831 // test separable subscripts
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003832 for (unsigned SI : Separable.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003833 switch (Pair[SI].Classification) {
3834 case Subscript::SIV: {
3835 unsigned Level;
Craig Topper9f008862014-04-15 04:59:12 +00003836 const SCEV *SplitIter = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003837 (void) testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
3838 Result, NewConstraint, SplitIter);
3839 if (Level == SplitLevel) {
Craig Topper9f008862014-04-15 04:59:12 +00003840 assert(SplitIter != nullptr);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003841 return SplitIter;
3842 }
3843 break;
3844 }
3845 case Subscript::ZIV:
3846 case Subscript::RDIV:
3847 case Subscript::MIV:
3848 break;
3849 default:
3850 llvm_unreachable("subscript has unexpected classification");
3851 }
3852 }
3853
3854 if (Coupled.count()) {
3855 // test coupled subscript groups
3856 SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
3857 for (unsigned II = 0; II <= MaxLevels; ++II)
3858 Constraints[II].setAny(SE);
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003859 for (unsigned SI : Coupled.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003860 SmallBitVector Group(Pair[SI].Group);
3861 SmallBitVector Sivs(Pairs);
3862 SmallBitVector Mivs(Pairs);
3863 SmallBitVector ConstrainedLevels(MaxLevels + 1);
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003864 for (unsigned SJ : Group.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003865 if (Pair[SJ].Classification == Subscript::SIV)
3866 Sivs.set(SJ);
3867 else
3868 Mivs.set(SJ);
3869 }
3870 while (Sivs.any()) {
3871 bool Changed = false;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003872 for (unsigned SJ : Sivs.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003873 // SJ is an SIV subscript that's part of the current coupled group
3874 unsigned Level;
Craig Topper9f008862014-04-15 04:59:12 +00003875 const SCEV *SplitIter = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003876 (void) testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
3877 Result, NewConstraint, SplitIter);
3878 if (Level == SplitLevel && SplitIter)
3879 return SplitIter;
3880 ConstrainedLevels.set(Level);
3881 if (intersectConstraints(&Constraints[Level], &NewConstraint))
3882 Changed = true;
3883 Sivs.reset(SJ);
3884 }
3885 if (Changed) {
3886 // propagate, possibly creating new SIVs and ZIVs
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003887 for (unsigned SJ : Mivs.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003888 // SJ is an MIV subscript that's part of the current coupled group
3889 if (propagate(Pair[SJ].Src, Pair[SJ].Dst,
3890 Pair[SJ].Loops, Constraints, Result.Consistent)) {
3891 Pair[SJ].Classification =
3892 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
3893 Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
3894 Pair[SJ].Loops);
3895 switch (Pair[SJ].Classification) {
3896 case Subscript::ZIV:
3897 Mivs.reset(SJ);
3898 break;
3899 case Subscript::SIV:
3900 Sivs.set(SJ);
3901 Mivs.reset(SJ);
3902 break;
3903 case Subscript::RDIV:
3904 case Subscript::MIV:
3905 break;
3906 default:
3907 llvm_unreachable("bad subscript classification");
3908 }
3909 }
3910 }
3911 }
3912 }
3913 }
3914 }
3915 llvm_unreachable("somehow reached end of routine");
Craig Topper9f008862014-04-15 04:59:12 +00003916 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003917}