1 //===-- DependenceAnalysis.cpp - DA Implementation --------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // DependenceAnalysis is an LLVM pass that analyses dependences between memory
10 // accesses. Currently, it is an (incomplete) implementation of the approach
11 // described in
12 //
13 //            Practical Dependence Testing
14 //            Goff, Kennedy, Tseng
15 //            PLDI 1991
16 //
17 // There's a single entry point that analyzes the dependence between a pair
18 // of memory references in a function, returning either NULL, for no dependence,
19 // or a more-or-less detailed description of the dependence between them.
20 //
21 // Currently, the implementation cannot propagate constraints between
22 // coupled RDIV subscripts and lacks a multi-subscript MIV test.
23 // Both of these are conservative weaknesses;
24 // that is, not a source of correctness problems.
25 //
26 // Since Clang linearizes some array subscripts, the dependence
27 // analysis is using SCEV->delinearize to recover the representation of multiple
28 // subscripts, and thus avoid the more expensive and less precise MIV tests. The
29 // delinearization is controlled by the flag -da-delinearize.
30 //
31 // We should pay some careful attention to the possibility of integer overflow
32 // in the implementation of the various tests. This could happen with Add,
33 // Subtract, or Multiply, with both APInt's and SCEV's.
34 //
35 // Some non-linear subscript pairs can be handled by the GCD test
36 // (and perhaps other tests).
37 // Should explore how often these things occur.
38 //
39 // Finally, it seems like certain test cases expose weaknesses in the SCEV
40 // simplification, especially in the handling of sign and zero extensions.
41 // It could be useful to spend time exploring these.
42 //
43 // Please note that this is work in progress and the interface is subject to
44 // change.
45 //
46 //===----------------------------------------------------------------------===//
47 //                                                                            //
48 //                   In memory of Ken Kennedy, 1945 - 2007                    //
49 //                                                                            //
50 //===----------------------------------------------------------------------===//
51 
52 #include "llvm/Analysis/DependenceAnalysis.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/LoopInfo.h"
57 #include "llvm/Analysis/ScalarEvolution.h"
58 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
59 #include "llvm/Analysis/ValueTracking.h"
60 #include "llvm/Config/llvm-config.h"
61 #include "llvm/IR/InstIterator.h"
62 #include "llvm/IR/Module.h"
63 #include "llvm/IR/Operator.h"
64 #include "llvm/InitializePasses.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/ErrorHandling.h"
68 #include "llvm/Support/raw_ostream.h"
69 
70 using namespace llvm;
71 
72 #define DEBUG_TYPE "da"
73 
74 //===----------------------------------------------------------------------===//
75 // statistics
76 
77 STATISTIC(TotalArrayPairs, "Array pairs tested");
78 STATISTIC(SeparableSubscriptPairs, "Separable subscript pairs");
79 STATISTIC(CoupledSubscriptPairs, "Coupled subscript pairs");
80 STATISTIC(NonlinearSubscriptPairs, "Nonlinear subscript pairs");
81 STATISTIC(ZIVapplications, "ZIV applications");
82 STATISTIC(ZIVindependence, "ZIV independence");
83 STATISTIC(StrongSIVapplications, "Strong SIV applications");
84 STATISTIC(StrongSIVsuccesses, "Strong SIV successes");
85 STATISTIC(StrongSIVindependence, "Strong SIV independence");
86 STATISTIC(WeakCrossingSIVapplications, "Weak-Crossing SIV applications");
87 STATISTIC(WeakCrossingSIVsuccesses, "Weak-Crossing SIV successes");
88 STATISTIC(WeakCrossingSIVindependence, "Weak-Crossing SIV independence");
89 STATISTIC(ExactSIVapplications, "Exact SIV applications");
90 STATISTIC(ExactSIVsuccesses, "Exact SIV successes");
91 STATISTIC(ExactSIVindependence, "Exact SIV independence");
92 STATISTIC(WeakZeroSIVapplications, "Weak-Zero SIV applications");
93 STATISTIC(WeakZeroSIVsuccesses, "Weak-Zero SIV successes");
94 STATISTIC(WeakZeroSIVindependence, "Weak-Zero SIV independence");
95 STATISTIC(ExactRDIVapplications, "Exact RDIV applications");
96 STATISTIC(ExactRDIVindependence, "Exact RDIV independence");
97 STATISTIC(SymbolicRDIVapplications, "Symbolic RDIV applications");
98 STATISTIC(SymbolicRDIVindependence, "Symbolic RDIV independence");
99 STATISTIC(DeltaApplications, "Delta applications");
100 STATISTIC(DeltaSuccesses, "Delta successes");
101 STATISTIC(DeltaIndependence, "Delta independence");
102 STATISTIC(DeltaPropagations, "Delta propagations");
103 STATISTIC(GCDapplications, "GCD applications");
104 STATISTIC(GCDsuccesses, "GCD successes");
105 STATISTIC(GCDindependence, "GCD independence");
106 STATISTIC(BanerjeeApplications, "Banerjee applications");
107 STATISTIC(BanerjeeIndependence, "Banerjee independence");
108 STATISTIC(BanerjeeSuccesses, "Banerjee successes");
109 
110 static cl::opt<bool>
111     Delinearize("da-delinearize", cl::init(true), cl::Hidden, cl::ZeroOrMore,
112                 cl::desc("Try to delinearize array references."));
113 static cl::opt<bool> DisableDelinearizationChecks(
114     "da-disable-delinearization-checks", cl::init(false), cl::Hidden,
115     cl::ZeroOrMore,
116     cl::desc(
117         "Disable checks that try to statically verify validity of "
118         "delinearized subscripts. Enabling this option may result in incorrect "
119         "dependence vectors for languages that allow the subscript of one "
120         "dimension to underflow or overflow into another dimension."));
121 
122 //===----------------------------------------------------------------------===//
123 // basics
124 
125 DependenceAnalysis::Result
126 DependenceAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
127   auto &AA = FAM.getResult<AAManager>(F);
128   auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
129   auto &LI = FAM.getResult<LoopAnalysis>(F);
130   return DependenceInfo(&F, &AA, &SE, &LI);
131 }
132 
133 AnalysisKey DependenceAnalysis::Key;
134 
135 INITIALIZE_PASS_BEGIN(DependenceAnalysisWrapperPass, "da",
136                       "Dependence Analysis", true, true)
137 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
138 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
139 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
140 INITIALIZE_PASS_END(DependenceAnalysisWrapperPass, "da", "Dependence Analysis",
141                     true, true)
142 
143 char DependenceAnalysisWrapperPass::ID = 0;
144 
145 DependenceAnalysisWrapperPass::DependenceAnalysisWrapperPass()
146     : FunctionPass(ID) {
147   initializeDependenceAnalysisWrapperPassPass(*PassRegistry::getPassRegistry());
148 }
149 
150 FunctionPass *llvm::createDependenceAnalysisWrapperPass() {
151   return new DependenceAnalysisWrapperPass();
152 }
153 
154 bool DependenceAnalysisWrapperPass::runOnFunction(Function &F) {
155   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
156   auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
157   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
158   info.reset(new DependenceInfo(&F, &AA, &SE, &LI));
159   return false;
160 }
161 
162 DependenceInfo &DependenceAnalysisWrapperPass::getDI() const { return *info; }
163 
164 void DependenceAnalysisWrapperPass::releaseMemory() { info.reset(); }
165 
166 void DependenceAnalysisWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
167   AU.setPreservesAll();
168   AU.addRequiredTransitive<AAResultsWrapperPass>();
169   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
170   AU.addRequiredTransitive<LoopInfoWrapperPass>();
171 }
172 
173 // Used to test the dependence analyzer.
174 // Looks through the function, noting instructions that may access memory.
175 // Calls depends() on every possible pair and prints out the result.
176 // Ignores all other instructions.
177 static void dumpExampleDependence(raw_ostream &OS, DependenceInfo *DA) {
178   auto *F = DA->getFunction();
179   for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F); SrcI != SrcE;
180        ++SrcI) {
181     if (SrcI->mayReadOrWriteMemory()) {
182       for (inst_iterator DstI = SrcI, DstE = inst_end(F);
183            DstI != DstE; ++DstI) {
184         if (DstI->mayReadOrWriteMemory()) {
185           OS << "Src:" << *SrcI << " --> Dst:" << *DstI << "\n";
186           OS << "  da analyze - ";
187           if (auto D = DA->depends(&*SrcI, &*DstI, true)) {
188             D->dump(OS);
189             for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
190               if (D->isSplitable(Level)) {
191                 OS << "  da analyze - split level = " << Level;
192                 OS << ", iteration = " << *DA->getSplitIteration(*D, Level);
193                 OS << "!\n";
194               }
195             }
196           }
197           else
198             OS << "none!\n";
199         }
200       }
201     }
202   }
203 }
204 
205 void DependenceAnalysisWrapperPass::print(raw_ostream &OS,
206                                           const Module *) const {
207   dumpExampleDependence(OS, info.get());
208 }
209 
210 PreservedAnalyses
211 DependenceAnalysisPrinterPass::run(Function &F, FunctionAnalysisManager &FAM) {
212   OS << "'Dependence Analysis' for function '" << F.getName() << "':\n";
213   dumpExampleDependence(OS, &FAM.getResult<DependenceAnalysis>(F));
214   return PreservedAnalyses::all();
215 }
216 
217 //===----------------------------------------------------------------------===//
218 // Dependence methods
219 
220 // Returns true if this is an input dependence.
221 bool Dependence::isInput() const {
222   return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
223 }
224 
225 
226 // Returns true if this is an output dependence.
227 bool Dependence::isOutput() const {
228   return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
229 }
230 
231 
232 // Returns true if this is an flow (aka true)  dependence.
233 bool Dependence::isFlow() const {
234   return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
235 }
236 
237 
238 // Returns true if this is an anti dependence.
239 bool Dependence::isAnti() const {
240   return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
241 }
242 
243 
244 // Returns true if a particular level is scalar; that is,
245 // if no subscript in the source or destination mention the induction
246 // variable associated with the loop at this level.
247 // Leave this out of line, so it will serve as a virtual method anchor
248 bool Dependence::isScalar(unsigned level) const {
249   return false;
250 }
251 
252 
253 //===----------------------------------------------------------------------===//
254 // FullDependence methods
255 
256 FullDependence::FullDependence(Instruction *Source, Instruction *Destination,
257                                bool PossiblyLoopIndependent,
258                                unsigned CommonLevels)
259     : Dependence(Source, Destination), Levels(CommonLevels),
260       LoopIndependent(PossiblyLoopIndependent) {
261   Consistent = true;
262   if (CommonLevels)
263     DV = std::make_unique<DVEntry[]>(CommonLevels);
264 }
265 
266 // The rest are simple getters that hide the implementation.
267 
268 // getDirection - Returns the direction associated with a particular level.
269 unsigned FullDependence::getDirection(unsigned Level) const {
270   assert(0 < Level && Level <= Levels && "Level out of range");
271   return DV[Level - 1].Direction;
272 }
273 
274 
275 // Returns the distance (or NULL) associated with a particular level.
276 const SCEV *FullDependence::getDistance(unsigned Level) const {
277   assert(0 < Level && Level <= Levels && "Level out of range");
278   return DV[Level - 1].Distance;
279 }
280 
281 
282 // Returns true if a particular level is scalar; that is,
283 // if no subscript in the source or destination mention the induction
284 // variable associated with the loop at this level.
285 bool FullDependence::isScalar(unsigned Level) const {
286   assert(0 < Level && Level <= Levels && "Level out of range");
287   return DV[Level - 1].Scalar;
288 }
289 
290 
291 // Returns true if peeling the first iteration from this loop
292 // will break this dependence.
293 bool FullDependence::isPeelFirst(unsigned Level) const {
294   assert(0 < Level && Level <= Levels && "Level out of range");
295   return DV[Level - 1].PeelFirst;
296 }
297 
298 
299 // Returns true if peeling the last iteration from this loop
300 // will break this dependence.
301 bool FullDependence::isPeelLast(unsigned Level) const {
302   assert(0 < Level && Level <= Levels && "Level out of range");
303   return DV[Level - 1].PeelLast;
304 }
305 
306 
307 // Returns true if splitting this loop will break the dependence.
308 bool FullDependence::isSplitable(unsigned Level) const {
309   assert(0 < Level && Level <= Levels && "Level out of range");
310   return DV[Level - 1].Splitable;
311 }
312 
313 
314 //===----------------------------------------------------------------------===//
315 // DependenceInfo::Constraint methods
316 
317 // If constraint is a point <X, Y>, returns X.
318 // Otherwise assert.
319 const SCEV *DependenceInfo::Constraint::getX() const {
320   assert(Kind == Point && "Kind should be Point");
321   return A;
322 }
323 
324 
325 // If constraint is a point <X, Y>, returns Y.
326 // Otherwise assert.
327 const SCEV *DependenceInfo::Constraint::getY() const {
328   assert(Kind == Point && "Kind should be Point");
329   return B;
330 }
331 
332 
333 // If constraint is a line AX + BY = C, returns A.
334 // Otherwise assert.
335 const SCEV *DependenceInfo::Constraint::getA() const {
336   assert((Kind == Line || Kind == Distance) &&
337          "Kind should be Line (or Distance)");
338   return A;
339 }
340 
341 
342 // If constraint is a line AX + BY = C, returns B.
343 // Otherwise assert.
344 const SCEV *DependenceInfo::Constraint::getB() const {
345   assert((Kind == Line || Kind == Distance) &&
346          "Kind should be Line (or Distance)");
347   return B;
348 }
349 
350 
351 // If constraint is a line AX + BY = C, returns C.
352 // Otherwise assert.
353 const SCEV *DependenceInfo::Constraint::getC() const {
354   assert((Kind == Line || Kind == Distance) &&
355          "Kind should be Line (or Distance)");
356   return C;
357 }
358 
359 
360 // If constraint is a distance, returns D.
361 // Otherwise assert.
362 const SCEV *DependenceInfo::Constraint::getD() const {
363   assert(Kind == Distance && "Kind should be Distance");
364   return SE->getNegativeSCEV(C);
365 }
366 
367 
368 // Returns the loop associated with this constraint.
369 const Loop *DependenceInfo::Constraint::getAssociatedLoop() const {
370   assert((Kind == Distance || Kind == Line || Kind == Point) &&
371          "Kind should be Distance, Line, or Point");
372   return AssociatedLoop;
373 }
374 
375 void DependenceInfo::Constraint::setPoint(const SCEV *X, const SCEV *Y,
376                                           const Loop *CurLoop) {
377   Kind = Point;
378   A = X;
379   B = Y;
380   AssociatedLoop = CurLoop;
381 }
382 
383 void DependenceInfo::Constraint::setLine(const SCEV *AA, const SCEV *BB,
384                                          const SCEV *CC, const Loop *CurLoop) {
385   Kind = Line;
386   A = AA;
387   B = BB;
388   C = CC;
389   AssociatedLoop = CurLoop;
390 }
391 
392 void DependenceInfo::Constraint::setDistance(const SCEV *D,
393                                              const Loop *CurLoop) {
394   Kind = Distance;
395   A = SE->getOne(D->getType());
396   B = SE->getNegativeSCEV(A);
397   C = SE->getNegativeSCEV(D);
398   AssociatedLoop = CurLoop;
399 }
400 
401 void DependenceInfo::Constraint::setEmpty() { Kind = Empty; }
402 
403 void DependenceInfo::Constraint::setAny(ScalarEvolution *NewSE) {
404   SE = NewSE;
405   Kind = Any;
406 }
407 
408 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
409 // For debugging purposes. Dumps the constraint out to OS.
410 LLVM_DUMP_METHOD void DependenceInfo::Constraint::dump(raw_ostream &OS) const {
411   if (isEmpty())
412     OS << " Empty\n";
413   else if (isAny())
414     OS << " Any\n";
415   else if (isPoint())
416     OS << " Point is <" << *getX() << ", " << *getY() << ">\n";
417   else if (isDistance())
418     OS << " Distance is " << *getD() <<
419       " (" << *getA() << "*X + " << *getB() << "*Y = " << *getC() << ")\n";
420   else if (isLine())
421     OS << " Line is " << *getA() << "*X + " <<
422       *getB() << "*Y = " << *getC() << "\n";
423   else
424     llvm_unreachable("unknown constraint type in Constraint::dump");
425 }
426 #endif
427 
428 
429 // Updates X with the intersection
430 // of the Constraints X and Y. Returns true if X has changed.
431 // Corresponds to Figure 4 from the paper
432 //
433 //            Practical Dependence Testing
434 //            Goff, Kennedy, Tseng
435 //            PLDI 1991
436 bool DependenceInfo::intersectConstraints(Constraint *X, const Constraint *Y) {
437   ++DeltaApplications;
438   LLVM_DEBUG(dbgs() << "\tintersect constraints\n");
439   LLVM_DEBUG(dbgs() << "\t    X ="; X->dump(dbgs()));
440   LLVM_DEBUG(dbgs() << "\t    Y ="; Y->dump(dbgs()));
441   assert(!Y->isPoint() && "Y must not be a Point");
442   if (X->isAny()) {
443     if (Y->isAny())
444       return false;
445     *X = *Y;
446     return true;
447   }
448   if (X->isEmpty())
449     return false;
450   if (Y->isEmpty()) {
451     X->setEmpty();
452     return true;
453   }
454 
455   if (X->isDistance() && Y->isDistance()) {
456     LLVM_DEBUG(dbgs() << "\t    intersect 2 distances\n");
457     if (isKnownPredicate(CmpInst::ICMP_EQ, X->getD(), Y->getD()))
458       return false;
459     if (isKnownPredicate(CmpInst::ICMP_NE, X->getD(), Y->getD())) {
460       X->setEmpty();
461       ++DeltaSuccesses;
462       return true;
463     }
464     // Hmmm, interesting situation.
465     // I guess if either is constant, keep it and ignore the other.
466     if (isa<SCEVConstant>(Y->getD())) {
467       *X = *Y;
468       return true;
469     }
470     return false;
471   }
472 
473   // At this point, the pseudo-code in Figure 4 of the paper
474   // checks if (X->isPoint() && Y->isPoint()).
475   // This case can't occur in our implementation,
476   // since a Point can only arise as the result of intersecting
477   // two Line constraints, and the right-hand value, Y, is never
478   // the result of an intersection.
479   assert(!(X->isPoint() && Y->isPoint()) &&
480          "We shouldn't ever see X->isPoint() && Y->isPoint()");
481 
482   if (X->isLine() && Y->isLine()) {
483     LLVM_DEBUG(dbgs() << "\t    intersect 2 lines\n");
484     const SCEV *Prod1 = SE->getMulExpr(X->getA(), Y->getB());
485     const SCEV *Prod2 = SE->getMulExpr(X->getB(), Y->getA());
486     if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2)) {
487       // slopes are equal, so lines are parallel
488       LLVM_DEBUG(dbgs() << "\t\tsame slope\n");
489       Prod1 = SE->getMulExpr(X->getC(), Y->getB());
490       Prod2 = SE->getMulExpr(X->getB(), Y->getC());
491       if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2))
492         return false;
493       if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
494         X->setEmpty();
495         ++DeltaSuccesses;
496         return true;
497       }
498       return false;
499     }
500     if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
501       // slopes differ, so lines intersect
502       LLVM_DEBUG(dbgs() << "\t\tdifferent slopes\n");
503       const SCEV *C1B2 = SE->getMulExpr(X->getC(), Y->getB());
504       const SCEV *C1A2 = SE->getMulExpr(X->getC(), Y->getA());
505       const SCEV *C2B1 = SE->getMulExpr(Y->getC(), X->getB());
506       const SCEV *C2A1 = SE->getMulExpr(Y->getC(), X->getA());
507       const SCEV *A1B2 = SE->getMulExpr(X->getA(), Y->getB());
508       const SCEV *A2B1 = SE->getMulExpr(Y->getA(), X->getB());
509       const SCEVConstant *C1A2_C2A1 =
510         dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1A2, C2A1));
511       const SCEVConstant *C1B2_C2B1 =
512         dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1B2, C2B1));
513       const SCEVConstant *A1B2_A2B1 =
514         dyn_cast<SCEVConstant>(SE->getMinusSCEV(A1B2, A2B1));
515       const SCEVConstant *A2B1_A1B2 =
516         dyn_cast<SCEVConstant>(SE->getMinusSCEV(A2B1, A1B2));
517       if (!C1B2_C2B1 || !C1A2_C2A1 ||
518           !A1B2_A2B1 || !A2B1_A1B2)
519         return false;
520       APInt Xtop = C1B2_C2B1->getAPInt();
521       APInt Xbot = A1B2_A2B1->getAPInt();
522       APInt Ytop = C1A2_C2A1->getAPInt();
523       APInt Ybot = A2B1_A1B2->getAPInt();
524       LLVM_DEBUG(dbgs() << "\t\tXtop = " << Xtop << "\n");
525       LLVM_DEBUG(dbgs() << "\t\tXbot = " << Xbot << "\n");
526       LLVM_DEBUG(dbgs() << "\t\tYtop = " << Ytop << "\n");
527       LLVM_DEBUG(dbgs() << "\t\tYbot = " << Ybot << "\n");
528       APInt Xq = Xtop; // these need to be initialized, even
529       APInt Xr = Xtop; // though they're just going to be overwritten
530       APInt::sdivrem(Xtop, Xbot, Xq, Xr);
531       APInt Yq = Ytop;
532       APInt Yr = Ytop;
533       APInt::sdivrem(Ytop, Ybot, Yq, Yr);
534       if (Xr != 0 || Yr != 0) {
535         X->setEmpty();
536         ++DeltaSuccesses;
537         return true;
538       }
539       LLVM_DEBUG(dbgs() << "\t\tX = " << Xq << ", Y = " << Yq << "\n");
540       if (Xq.slt(0) || Yq.slt(0)) {
541         X->setEmpty();
542         ++DeltaSuccesses;
543         return true;
544       }
545       if (const SCEVConstant *CUB =
546           collectConstantUpperBound(X->getAssociatedLoop(), Prod1->getType())) {
547         const APInt &UpperBound = CUB->getAPInt();
548         LLVM_DEBUG(dbgs() << "\t\tupper bound = " << UpperBound << "\n");
549         if (Xq.sgt(UpperBound) || Yq.sgt(UpperBound)) {
550           X->setEmpty();
551           ++DeltaSuccesses;
552           return true;
553         }
554       }
555       X->setPoint(SE->getConstant(Xq),
556                   SE->getConstant(Yq),
557                   X->getAssociatedLoop());
558       ++DeltaSuccesses;
559       return true;
560     }
561     return false;
562   }
563 
564   // if (X->isLine() && Y->isPoint()) This case can't occur.
565   assert(!(X->isLine() && Y->isPoint()) && "This case should never occur");
566 
567   if (X->isPoint() && Y->isLine()) {
568     LLVM_DEBUG(dbgs() << "\t    intersect Point and Line\n");
569     const SCEV *A1X1 = SE->getMulExpr(Y->getA(), X->getX());
570     const SCEV *B1Y1 = SE->getMulExpr(Y->getB(), X->getY());
571     const SCEV *Sum = SE->getAddExpr(A1X1, B1Y1);
572     if (isKnownPredicate(CmpInst::ICMP_EQ, Sum, Y->getC()))
573       return false;
574     if (isKnownPredicate(CmpInst::ICMP_NE, Sum, Y->getC())) {
575       X->setEmpty();
576       ++DeltaSuccesses;
577       return true;
578     }
579     return false;
580   }
581 
582   llvm_unreachable("shouldn't reach the end of Constraint intersection");
583   return false;
584 }
585 
586 
587 //===----------------------------------------------------------------------===//
588 // DependenceInfo methods
589 
590 // For debugging purposes. Dumps a dependence to OS.
591 void Dependence::dump(raw_ostream &OS) const {
592   bool Splitable = false;
593   if (isConfused())
594     OS << "confused";
595   else {
596     if (isConsistent())
597       OS << "consistent ";
598     if (isFlow())
599       OS << "flow";
600     else if (isOutput())
601       OS << "output";
602     else if (isAnti())
603       OS << "anti";
604     else if (isInput())
605       OS << "input";
606     unsigned Levels = getLevels();
607     OS << " [";
608     for (unsigned II = 1; II <= Levels; ++II) {
609       if (isSplitable(II))
610         Splitable = true;
611       if (isPeelFirst(II))
612         OS << 'p';
613       const SCEV *Distance = getDistance(II);
614       if (Distance)
615         OS << *Distance;
616       else if (isScalar(II))
617         OS << "S";
618       else {
619         unsigned Direction = getDirection(II);
620         if (Direction == DVEntry::ALL)
621           OS << "*";
622         else {
623           if (Direction & DVEntry::LT)
624             OS << "<";
625           if (Direction & DVEntry::EQ)
626             OS << "=";
627           if (Direction & DVEntry::GT)
628             OS << ">";
629         }
630       }
631       if (isPeelLast(II))
632         OS << 'p';
633       if (II < Levels)
634         OS << " ";
635     }
636     if (isLoopIndependent())
637       OS << "|<";
638     OS << "]";
639     if (Splitable)
640       OS << " splitable";
641   }
642   OS << "!\n";
643 }
644 
645 // Returns NoAlias/MayAliass/MustAlias for two memory locations based upon their
646 // underlaying objects. If LocA and LocB are known to not alias (for any reason:
647 // tbaa, non-overlapping regions etc), then it is known there is no dependecy.
648 // Otherwise the underlying objects are checked to see if they point to
649 // different identifiable objects.
650 static AliasResult underlyingObjectsAlias(AAResults *AA,
651                                           const DataLayout &DL,
652                                           const MemoryLocation &LocA,
653                                           const MemoryLocation &LocB) {
654   // Check the original locations (minus size) for noalias, which can happen for
655   // tbaa, incompatible underlying object locations, etc.
656   MemoryLocation LocAS(LocA.Ptr, LocationSize::unknown(), LocA.AATags);
657   MemoryLocation LocBS(LocB.Ptr, LocationSize::unknown(), LocB.AATags);
658   if (AA->alias(LocAS, LocBS) == NoAlias)
659     return NoAlias;
660 
661   // Check the underlying objects are the same
662   const Value *AObj = GetUnderlyingObject(LocA.Ptr, DL);
663   const Value *BObj = GetUnderlyingObject(LocB.Ptr, DL);
664 
665   // If the underlying objects are the same, they must alias
666   if (AObj == BObj)
667     return MustAlias;
668 
669   // We may have hit the recursion limit for underlying objects, or have
670   // underlying objects where we don't know they will alias.
671   if (!isIdentifiedObject(AObj) || !isIdentifiedObject(BObj))
672     return MayAlias;
673 
674   // Otherwise we know the objects are different and both identified objects so
675   // must not alias.
676   return NoAlias;
677 }
678 
679 
680 // Returns true if the load or store can be analyzed. Atomic and volatile
681 // operations have properties which this analysis does not understand.
682 static
683 bool isLoadOrStore(const Instruction *I) {
684   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
685     return LI->isUnordered();
686   else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
687     return SI->isUnordered();
688   return false;
689 }
690 
691 
692 // Examines the loop nesting of the Src and Dst
693 // instructions and establishes their shared loops. Sets the variables
694 // CommonLevels, SrcLevels, and MaxLevels.
695 // The source and destination instructions needn't be contained in the same
696 // loop. The routine establishNestingLevels finds the level of most deeply
697 // nested loop that contains them both, CommonLevels. An instruction that's
698 // not contained in a loop is at level = 0. MaxLevels is equal to the level
699 // of the source plus the level of the destination, minus CommonLevels.
700 // This lets us allocate vectors MaxLevels in length, with room for every
701 // distinct loop referenced in both the source and destination subscripts.
702 // The variable SrcLevels is the nesting depth of the source instruction.
703 // It's used to help calculate distinct loops referenced by the destination.
704 // Here's the map from loops to levels:
705 //            0 - unused
706 //            1 - outermost common loop
707 //          ... - other common loops
708 // CommonLevels - innermost common loop
709 //          ... - loops containing Src but not Dst
710 //    SrcLevels - innermost loop containing Src but not Dst
711 //          ... - loops containing Dst but not Src
712 //    MaxLevels - innermost loops containing Dst but not Src
713 // Consider the follow code fragment:
714 //   for (a = ...) {
715 //     for (b = ...) {
716 //       for (c = ...) {
717 //         for (d = ...) {
718 //           A[] = ...;
719 //         }
720 //       }
721 //       for (e = ...) {
722 //         for (f = ...) {
723 //           for (g = ...) {
724 //             ... = A[];
725 //           }
726 //         }
727 //       }
728 //     }
729 //   }
730 // If we're looking at the possibility of a dependence between the store
731 // to A (the Src) and the load from A (the Dst), we'll note that they
732 // have 2 loops in common, so CommonLevels will equal 2 and the direction
733 // vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
734 // A map from loop names to loop numbers would look like
735 //     a - 1
736 //     b - 2 = CommonLevels
737 //     c - 3
738 //     d - 4 = SrcLevels
739 //     e - 5
740 //     f - 6
741 //     g - 7 = MaxLevels
742 void DependenceInfo::establishNestingLevels(const Instruction *Src,
743                                             const Instruction *Dst) {
744   const BasicBlock *SrcBlock = Src->getParent();
745   const BasicBlock *DstBlock = Dst->getParent();
746   unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
747   unsigned DstLevel = LI->getLoopDepth(DstBlock);
748   const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
749   const Loop *DstLoop = LI->getLoopFor(DstBlock);
750   SrcLevels = SrcLevel;
751   MaxLevels = SrcLevel + DstLevel;
752   while (SrcLevel > DstLevel) {
753     SrcLoop = SrcLoop->getParentLoop();
754     SrcLevel--;
755   }
756   while (DstLevel > SrcLevel) {
757     DstLoop = DstLoop->getParentLoop();
758     DstLevel--;
759   }
760   while (SrcLoop != DstLoop) {
761     SrcLoop = SrcLoop->getParentLoop();
762     DstLoop = DstLoop->getParentLoop();
763     SrcLevel--;
764   }
765   CommonLevels = SrcLevel;
766   MaxLevels -= CommonLevels;
767 }
768 
769 
770 // Given one of the loops containing the source, return
771 // its level index in our numbering scheme.
772 unsigned DependenceInfo::mapSrcLoop(const Loop *SrcLoop) const {
773   return SrcLoop->getLoopDepth();
774 }
775 
776 
777 // Given one of the loops containing the destination,
778 // return its level index in our numbering scheme.
779 unsigned DependenceInfo::mapDstLoop(const Loop *DstLoop) const {
780   unsigned D = DstLoop->getLoopDepth();
781   if (D > CommonLevels)
782     return D - CommonLevels + SrcLevels;
783   else
784     return D;
785 }
786 
787 
788 // Returns true if Expression is loop invariant in LoopNest.
789 bool DependenceInfo::isLoopInvariant(const SCEV *Expression,
790                                      const Loop *LoopNest) const {
791   if (!LoopNest)
792     return true;
793   return SE->isLoopInvariant(Expression, LoopNest) &&
794     isLoopInvariant(Expression, LoopNest->getParentLoop());
795 }
796 
797 
798 
799 // Finds the set of loops from the LoopNest that
800 // have a level <= CommonLevels and are referred to by the SCEV Expression.
801 void DependenceInfo::collectCommonLoops(const SCEV *Expression,
802                                         const Loop *LoopNest,
803                                         SmallBitVector &Loops) const {
804   while (LoopNest) {
805     unsigned Level = LoopNest->getLoopDepth();
806     if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
807       Loops.set(Level);
808     LoopNest = LoopNest->getParentLoop();
809   }
810 }
811 
812 void DependenceInfo::unifySubscriptType(ArrayRef<Subscript *> Pairs) {
813 
814   unsigned widestWidthSeen = 0;
815   Type *widestType;
816 
817   // Go through each pair and find the widest bit to which we need
818   // to extend all of them.
819   for (Subscript *Pair : Pairs) {
820     const SCEV *Src = Pair->Src;
821     const SCEV *Dst = Pair->Dst;
822     IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
823     IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
824     if (SrcTy == nullptr || DstTy == nullptr) {
825       assert(SrcTy == DstTy && "This function only unify integer types and "
826              "expect Src and Dst share the same type "
827              "otherwise.");
828       continue;
829     }
830     if (SrcTy->getBitWidth() > widestWidthSeen) {
831       widestWidthSeen = SrcTy->getBitWidth();
832       widestType = SrcTy;
833     }
834     if (DstTy->getBitWidth() > widestWidthSeen) {
835       widestWidthSeen = DstTy->getBitWidth();
836       widestType = DstTy;
837     }
838   }
839 
840 
841   assert(widestWidthSeen > 0);
842 
843   // Now extend each pair to the widest seen.
844   for (Subscript *Pair : Pairs) {
845     const SCEV *Src = Pair->Src;
846     const SCEV *Dst = Pair->Dst;
847     IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
848     IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
849     if (SrcTy == nullptr || DstTy == nullptr) {
850       assert(SrcTy == DstTy && "This function only unify integer types and "
851              "expect Src and Dst share the same type "
852              "otherwise.");
853       continue;
854     }
855     if (SrcTy->getBitWidth() < widestWidthSeen)
856       // Sign-extend Src to widestType
857       Pair->Src = SE->getSignExtendExpr(Src, widestType);
858     if (DstTy->getBitWidth() < widestWidthSeen) {
859       // Sign-extend Dst to widestType
860       Pair->Dst = SE->getSignExtendExpr(Dst, widestType);
861     }
862   }
863 }
864 
865 // removeMatchingExtensions - Examines a subscript pair.
866 // If the source and destination are identically sign (or zero)
867 // extended, it strips off the extension in an effect to simplify
868 // the actual analysis.
869 void DependenceInfo::removeMatchingExtensions(Subscript *Pair) {
870   const SCEV *Src = Pair->Src;
871   const SCEV *Dst = Pair->Dst;
872   if ((isa<SCEVZeroExtendExpr>(Src) && isa<SCEVZeroExtendExpr>(Dst)) ||
873       (isa<SCEVSignExtendExpr>(Src) && isa<SCEVSignExtendExpr>(Dst))) {
874     const SCEVCastExpr *SrcCast = cast<SCEVCastExpr>(Src);
875     const SCEVCastExpr *DstCast = cast<SCEVCastExpr>(Dst);
876     const SCEV *SrcCastOp = SrcCast->getOperand();
877     const SCEV *DstCastOp = DstCast->getOperand();
878     if (SrcCastOp->getType() == DstCastOp->getType()) {
879       Pair->Src = SrcCastOp;
880       Pair->Dst = DstCastOp;
881     }
882   }
883 }
884 
885 // Examine the scev and return true iff it's linear.
886 // Collect any loops mentioned in the set of "Loops".
887 bool DependenceInfo::checkSubscript(const SCEV *Expr, const Loop *LoopNest,
888                                     SmallBitVector &Loops, bool IsSrc) {
889   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
890   if (!AddRec)
891     return isLoopInvariant(Expr, LoopNest);
892   const SCEV *Start = AddRec->getStart();
893   const SCEV *Step = AddRec->getStepRecurrence(*SE);
894   const SCEV *UB = SE->getBackedgeTakenCount(AddRec->getLoop());
895   if (!isa<SCEVCouldNotCompute>(UB)) {
896     if (SE->getTypeSizeInBits(Start->getType()) <
897         SE->getTypeSizeInBits(UB->getType())) {
898       if (!AddRec->getNoWrapFlags())
899         return false;
900     }
901   }
902   if (!isLoopInvariant(Step, LoopNest))
903     return false;
904   if (IsSrc)
905     Loops.set(mapSrcLoop(AddRec->getLoop()));
906   else
907     Loops.set(mapDstLoop(AddRec->getLoop()));
908   return checkSubscript(Start, LoopNest, Loops, IsSrc);
909 }
910 
911 // Examine the scev and return true iff it's linear.
912 // Collect any loops mentioned in the set of "Loops".
913 bool DependenceInfo::checkSrcSubscript(const SCEV *Src, const Loop *LoopNest,
914                                        SmallBitVector &Loops) {
915   return checkSubscript(Src, LoopNest, Loops, true);
916 }
917 
918 // Examine the scev and return true iff it's linear.
919 // Collect any loops mentioned in the set of "Loops".
920 bool DependenceInfo::checkDstSubscript(const SCEV *Dst, const Loop *LoopNest,
921                                        SmallBitVector &Loops) {
922   return checkSubscript(Dst, LoopNest, Loops, false);
923 }
924 
925 
926 // Examines the subscript pair (the Src and Dst SCEVs)
927 // and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
928 // Collects the associated loops in a set.
929 DependenceInfo::Subscript::ClassificationKind
930 DependenceInfo::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
931                              const SCEV *Dst, const Loop *DstLoopNest,
932                              SmallBitVector &Loops) {
933   SmallBitVector SrcLoops(MaxLevels + 1);
934   SmallBitVector DstLoops(MaxLevels + 1);
935   if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
936     return Subscript::NonLinear;
937   if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
938     return Subscript::NonLinear;
939   Loops = SrcLoops;
940   Loops |= DstLoops;
941   unsigned N = Loops.count();
942   if (N == 0)
943     return Subscript::ZIV;
944   if (N == 1)
945     return Subscript::SIV;
946   if (N == 2 && (SrcLoops.count() == 0 ||
947                  DstLoops.count() == 0 ||
948                  (SrcLoops.count() == 1 && DstLoops.count() == 1)))
949     return Subscript::RDIV;
950   return Subscript::MIV;
951 }
952 
953 
954 // A wrapper around SCEV::isKnownPredicate.
955 // Looks for cases where we're interested in comparing for equality.
956 // If both X and Y have been identically sign or zero extended,
957 // it strips off the (confusing) extensions before invoking
958 // SCEV::isKnownPredicate. Perhaps, someday, the ScalarEvolution package
959 // will be similarly updated.
960 //
961 // If SCEV::isKnownPredicate can't prove the predicate,
962 // we try simple subtraction, which seems to help in some cases
963 // involving symbolics.
964 bool DependenceInfo::isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *X,
965                                       const SCEV *Y) const {
966   if (Pred == CmpInst::ICMP_EQ ||
967       Pred == CmpInst::ICMP_NE) {
968     if ((isa<SCEVSignExtendExpr>(X) &&
969          isa<SCEVSignExtendExpr>(Y)) ||
970         (isa<SCEVZeroExtendExpr>(X) &&
971          isa<SCEVZeroExtendExpr>(Y))) {
972       const SCEVCastExpr *CX = cast<SCEVCastExpr>(X);
973       const SCEVCastExpr *CY = cast<SCEVCastExpr>(Y);
974       const SCEV *Xop = CX->getOperand();
975       const SCEV *Yop = CY->getOperand();
976       if (Xop->getType() == Yop->getType()) {
977         X = Xop;
978         Y = Yop;
979       }
980     }
981   }
982   if (SE->isKnownPredicate(Pred, X, Y))
983     return true;
984   // If SE->isKnownPredicate can't prove the condition,
985   // we try the brute-force approach of subtracting
986   // and testing the difference.
987   // By testing with SE->isKnownPredicate first, we avoid
988   // the possibility of overflow when the arguments are constants.
989   const SCEV *Delta = SE->getMinusSCEV(X, Y);
990   switch (Pred) {
991   case CmpInst::ICMP_EQ:
992     return Delta->isZero();
993   case CmpInst::ICMP_NE:
994     return SE->isKnownNonZero(Delta);
995   case CmpInst::ICMP_SGE:
996     return SE->isKnownNonNegative(Delta);
997   case CmpInst::ICMP_SLE:
998     return SE->isKnownNonPositive(Delta);
999   case CmpInst::ICMP_SGT:
1000     return SE->isKnownPositive(Delta);
1001   case CmpInst::ICMP_SLT:
1002     return SE->isKnownNegative(Delta);
1003   default:
1004     llvm_unreachable("unexpected predicate in isKnownPredicate");
1005   }
1006 }
1007 
1008 /// Compare to see if S is less than Size, using isKnownNegative(S - max(Size, 1))
1009 /// with some extra checking if S is an AddRec and we can prove less-than using
1010 /// the loop bounds.
1011 bool DependenceInfo::isKnownLessThan(const SCEV *S, const SCEV *Size) const {
1012   // First unify to the same type
1013   auto *SType = dyn_cast<IntegerType>(S->getType());
1014   auto *SizeType = dyn_cast<IntegerType>(Size->getType());
1015   if (!SType || !SizeType)
1016     return false;
1017   Type *MaxType =
1018       (SType->getBitWidth() >= SizeType->getBitWidth()) ? SType : SizeType;
1019   S = SE->getTruncateOrZeroExtend(S, MaxType);
1020   Size = SE->getTruncateOrZeroExtend(Size, MaxType);
1021 
1022   // Special check for addrecs using BE taken count
1023   const SCEV *Bound = SE->getMinusSCEV(S, Size);
1024   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Bound)) {
1025     if (AddRec->isAffine()) {
1026       const SCEV *BECount = SE->getBackedgeTakenCount(AddRec->getLoop());
1027       if (!isa<SCEVCouldNotCompute>(BECount)) {
1028         const SCEV *Limit = AddRec->evaluateAtIteration(BECount, *SE);
1029         if (SE->isKnownNegative(Limit))
1030           return true;
1031       }
1032     }
1033   }
1034 
1035   // Check using normal isKnownNegative
1036   const SCEV *LimitedBound =
1037       SE->getMinusSCEV(S, SE->getSMaxExpr(Size, SE->getOne(Size->getType())));
1038   return SE->isKnownNegative(LimitedBound);
1039 }
1040 
1041 bool DependenceInfo::isKnownNonNegative(const SCEV *S, const Value *Ptr) const {
1042   bool Inbounds = false;
1043   if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(Ptr))
1044     Inbounds = SrcGEP->isInBounds();
1045   if (Inbounds) {
1046     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
1047       if (AddRec->isAffine()) {
1048         // We know S is for Ptr, the operand on a load/store, so doesn't wrap.
1049         // If both parts are NonNegative, the end result will be NonNegative
1050         if (SE->isKnownNonNegative(AddRec->getStart()) &&
1051             SE->isKnownNonNegative(AddRec->getOperand(1)))
1052           return true;
1053       }
1054     }
1055   }
1056 
1057   return SE->isKnownNonNegative(S);
1058 }
1059 
1060 // All subscripts are all the same type.
1061 // Loop bound may be smaller (e.g., a char).
1062 // Should zero extend loop bound, since it's always >= 0.
1063 // This routine collects upper bound and extends or truncates if needed.
1064 // Truncating is safe when subscripts are known not to wrap. Cases without
1065 // nowrap flags should have been rejected earlier.
1066 // Return null if no bound available.
1067 const SCEV *DependenceInfo::collectUpperBound(const Loop *L, Type *T) const {
1068   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
1069     const SCEV *UB = SE->getBackedgeTakenCount(L);
1070     return SE->getTruncateOrZeroExtend(UB, T);
1071   }
1072   return nullptr;
1073 }
1074 
1075 
1076 // Calls collectUpperBound(), then attempts to cast it to SCEVConstant.
1077 // If the cast fails, returns NULL.
1078 const SCEVConstant *DependenceInfo::collectConstantUpperBound(const Loop *L,
1079                                                               Type *T) const {
1080   if (const SCEV *UB = collectUpperBound(L, T))
1081     return dyn_cast<SCEVConstant>(UB);
1082   return nullptr;
1083 }
1084 
1085 
1086 // testZIV -
1087 // When we have a pair of subscripts of the form [c1] and [c2],
1088 // where c1 and c2 are both loop invariant, we attack it using
1089 // the ZIV test. Basically, we test by comparing the two values,
1090 // but there are actually three possible results:
1091 // 1) the values are equal, so there's a dependence
1092 // 2) the values are different, so there's no dependence
1093 // 3) the values might be equal, so we have to assume a dependence.
1094 //
1095 // Return true if dependence disproved.
1096 bool DependenceInfo::testZIV(const SCEV *Src, const SCEV *Dst,
1097                              FullDependence &Result) const {
1098   LLVM_DEBUG(dbgs() << "    src = " << *Src << "\n");
1099   LLVM_DEBUG(dbgs() << "    dst = " << *Dst << "\n");
1100   ++ZIVapplications;
1101   if (isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
1102     LLVM_DEBUG(dbgs() << "    provably dependent\n");
1103     return false; // provably dependent
1104   }
1105   if (isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
1106     LLVM_DEBUG(dbgs() << "    provably independent\n");
1107     ++ZIVindependence;
1108     return true; // provably independent
1109   }
1110   LLVM_DEBUG(dbgs() << "    possibly dependent\n");
1111   Result.Consistent = false;
1112   return false; // possibly dependent
1113 }
1114 
1115 
1116 // strongSIVtest -
1117 // From the paper, Practical Dependence Testing, Section 4.2.1
1118 //
1119 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
1120 // where i is an induction variable, c1 and c2 are loop invariant,
1121 //  and a is a constant, we can solve it exactly using the Strong SIV test.
1122 //
1123 // Can prove independence. Failing that, can compute distance (and direction).
1124 // In the presence of symbolic terms, we can sometimes make progress.
1125 //
1126 // If there's a dependence,
1127 //
1128 //    c1 + a*i = c2 + a*i'
1129 //
1130 // The dependence distance is
1131 //
1132 //    d = i' - i = (c1 - c2)/a
1133 //
1134 // A dependence only exists if d is an integer and abs(d) <= U, where U is the
1135 // loop's upper bound. If a dependence exists, the dependence direction is
1136 // defined as
1137 //
1138 //                { < if d > 0
1139 //    direction = { = if d = 0
1140 //                { > if d < 0
1141 //
1142 // Return true if dependence disproved.
1143 bool DependenceInfo::strongSIVtest(const SCEV *Coeff, const SCEV *SrcConst,
1144                                    const SCEV *DstConst, const Loop *CurLoop,
1145                                    unsigned Level, FullDependence &Result,
1146                                    Constraint &NewConstraint) const {
1147   LLVM_DEBUG(dbgs() << "\tStrong SIV test\n");
1148   LLVM_DEBUG(dbgs() << "\t    Coeff = " << *Coeff);
1149   LLVM_DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
1150   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst);
1151   LLVM_DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
1152   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst);
1153   LLVM_DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
1154   ++StrongSIVapplications;
1155   assert(0 < Level && Level <= CommonLevels && "level out of range");
1156   Level--;
1157 
1158   const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
1159   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta);
1160   LLVM_DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
1161 
1162   // check that |Delta| < iteration count
1163   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1164     LLVM_DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound);
1165     LLVM_DEBUG(dbgs() << ", " << *UpperBound->getType() << "\n");
1166     const SCEV *AbsDelta =
1167       SE->isKnownNonNegative(Delta) ? Delta : SE->getNegativeSCEV(Delta);
1168     const SCEV *AbsCoeff =
1169       SE->isKnownNonNegative(Coeff) ? Coeff : SE->getNegativeSCEV(Coeff);
1170     const SCEV *Product = SE->getMulExpr(UpperBound, AbsCoeff);
1171     if (isKnownPredicate(CmpInst::ICMP_SGT, AbsDelta, Product)) {
1172       // Distance greater than trip count - no dependence
1173       ++StrongSIVindependence;
1174       ++StrongSIVsuccesses;
1175       return true;
1176     }
1177   }
1178 
1179   // Can we compute distance?
1180   if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
1181     APInt ConstDelta = cast<SCEVConstant>(Delta)->getAPInt();
1182     APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getAPInt();
1183     APInt Distance  = ConstDelta; // these need to be initialized
1184     APInt Remainder = ConstDelta;
1185     APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
1186     LLVM_DEBUG(dbgs() << "\t    Distance = " << Distance << "\n");
1187     LLVM_DEBUG(dbgs() << "\t    Remainder = " << Remainder << "\n");
1188     // Make sure Coeff divides Delta exactly
1189     if (Remainder != 0) {
1190       // Coeff doesn't divide Distance, no dependence
1191       ++StrongSIVindependence;
1192       ++StrongSIVsuccesses;
1193       return true;
1194     }
1195     Result.DV[Level].Distance = SE->getConstant(Distance);
1196     NewConstraint.setDistance(SE->getConstant(Distance), CurLoop);
1197     if (Distance.sgt(0))
1198       Result.DV[Level].Direction &= Dependence::DVEntry::LT;
1199     else if (Distance.slt(0))
1200       Result.DV[Level].Direction &= Dependence::DVEntry::GT;
1201     else
1202       Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1203     ++StrongSIVsuccesses;
1204   }
1205   else if (Delta->isZero()) {
1206     // since 0/X == 0
1207     Result.DV[Level].Distance = Delta;
1208     NewConstraint.setDistance(Delta, CurLoop);
1209     Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1210     ++StrongSIVsuccesses;
1211   }
1212   else {
1213     if (Coeff->isOne()) {
1214       LLVM_DEBUG(dbgs() << "\t    Distance = " << *Delta << "\n");
1215       Result.DV[Level].Distance = Delta; // since X/1 == X
1216       NewConstraint.setDistance(Delta, CurLoop);
1217     }
1218     else {
1219       Result.Consistent = false;
1220       NewConstraint.setLine(Coeff,
1221                             SE->getNegativeSCEV(Coeff),
1222                             SE->getNegativeSCEV(Delta), CurLoop);
1223     }
1224 
1225     // maybe we can get a useful direction
1226     bool DeltaMaybeZero     = !SE->isKnownNonZero(Delta);
1227     bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
1228     bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
1229     bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
1230     bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
1231     // The double negatives above are confusing.
1232     // It helps to read !SE->isKnownNonZero(Delta)
1233     // as "Delta might be Zero"
1234     unsigned NewDirection = Dependence::DVEntry::NONE;
1235     if ((DeltaMaybePositive && CoeffMaybePositive) ||
1236         (DeltaMaybeNegative && CoeffMaybeNegative))
1237       NewDirection = Dependence::DVEntry::LT;
1238     if (DeltaMaybeZero)
1239       NewDirection |= Dependence::DVEntry::EQ;
1240     if ((DeltaMaybeNegative && CoeffMaybePositive) ||
1241         (DeltaMaybePositive && CoeffMaybeNegative))
1242       NewDirection |= Dependence::DVEntry::GT;
1243     if (NewDirection < Result.DV[Level].Direction)
1244       ++StrongSIVsuccesses;
1245     Result.DV[Level].Direction &= NewDirection;
1246   }
1247   return false;
1248 }
1249 
1250 
1251 // weakCrossingSIVtest -
1252 // From the paper, Practical Dependence Testing, Section 4.2.2
1253 //
1254 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
1255 // where i is an induction variable, c1 and c2 are loop invariant,
1256 // and a is a constant, we can solve it exactly using the
1257 // Weak-Crossing SIV test.
1258 //
1259 // Given c1 + a*i = c2 - a*i', we can look for the intersection of
1260 // the two lines, where i = i', yielding
1261 //
1262 //    c1 + a*i = c2 - a*i
1263 //    2a*i = c2 - c1
1264 //    i = (c2 - c1)/2a
1265 //
1266 // If i < 0, there is no dependence.
1267 // If i > upperbound, there is no dependence.
1268 // If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
1269 // If i = upperbound, there's a dependence with distance = 0.
1270 // If i is integral, there's a dependence (all directions).
1271 // If the non-integer part = 1/2, there's a dependence (<> directions).
1272 // Otherwise, there's no dependence.
1273 //
1274 // Can prove independence. Failing that,
1275 // can sometimes refine the directions.
1276 // Can determine iteration for splitting.
1277 //
1278 // Return true if dependence disproved.
1279 bool DependenceInfo::weakCrossingSIVtest(
1280     const SCEV *Coeff, const SCEV *SrcConst, const SCEV *DstConst,
1281     const Loop *CurLoop, unsigned Level, FullDependence &Result,
1282     Constraint &NewConstraint, const SCEV *&SplitIter) const {
1283   LLVM_DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
1284   LLVM_DEBUG(dbgs() << "\t    Coeff = " << *Coeff << "\n");
1285   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
1286   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
1287   ++WeakCrossingSIVapplications;
1288   assert(0 < Level && Level <= CommonLevels && "Level out of range");
1289   Level--;
1290   Result.Consistent = false;
1291   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1292   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1293   NewConstraint.setLine(Coeff, Coeff, Delta, CurLoop);
1294   if (Delta->isZero()) {
1295     Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1296     Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
1297     ++WeakCrossingSIVsuccesses;
1298     if (!Result.DV[Level].Direction) {
1299       ++WeakCrossingSIVindependence;
1300       return true;
1301     }
1302     Result.DV[Level].Distance = Delta; // = 0
1303     return false;
1304   }
1305   const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
1306   if (!ConstCoeff)
1307     return false;
1308 
1309   Result.DV[Level].Splitable = true;
1310   if (SE->isKnownNegative(ConstCoeff)) {
1311     ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff));
1312     assert(ConstCoeff &&
1313            "dynamic cast of negative of ConstCoeff should yield constant");
1314     Delta = SE->getNegativeSCEV(Delta);
1315   }
1316   assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive");
1317 
1318   // compute SplitIter for use by DependenceInfo::getSplitIteration()
1319   SplitIter = SE->getUDivExpr(
1320       SE->getSMaxExpr(SE->getZero(Delta->getType()), Delta),
1321       SE->getMulExpr(SE->getConstant(Delta->getType(), 2), ConstCoeff));
1322   LLVM_DEBUG(dbgs() << "\t    Split iter = " << *SplitIter << "\n");
1323 
1324   const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1325   if (!ConstDelta)
1326     return false;
1327 
1328   // We're certain that ConstCoeff > 0; therefore,
1329   // if Delta < 0, then no dependence.
1330   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1331   LLVM_DEBUG(dbgs() << "\t    ConstCoeff = " << *ConstCoeff << "\n");
1332   if (SE->isKnownNegative(Delta)) {
1333     // No dependence, Delta < 0
1334     ++WeakCrossingSIVindependence;
1335     ++WeakCrossingSIVsuccesses;
1336     return true;
1337   }
1338 
1339   // We're certain that Delta > 0 and ConstCoeff > 0.
1340   // Check Delta/(2*ConstCoeff) against upper loop bound
1341   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1342     LLVM_DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound << "\n");
1343     const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2);
1344     const SCEV *ML = SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound),
1345                                     ConstantTwo);
1346     LLVM_DEBUG(dbgs() << "\t    ML = " << *ML << "\n");
1347     if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) {
1348       // Delta too big, no dependence
1349       ++WeakCrossingSIVindependence;
1350       ++WeakCrossingSIVsuccesses;
1351       return true;
1352     }
1353     if (isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) {
1354       // i = i' = UB
1355       Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1356       Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
1357       ++WeakCrossingSIVsuccesses;
1358       if (!Result.DV[Level].Direction) {
1359         ++WeakCrossingSIVindependence;
1360         return true;
1361       }
1362       Result.DV[Level].Splitable = false;
1363       Result.DV[Level].Distance = SE->getZero(Delta->getType());
1364       return false;
1365     }
1366   }
1367 
1368   // check that Coeff divides Delta
1369   APInt APDelta = ConstDelta->getAPInt();
1370   APInt APCoeff = ConstCoeff->getAPInt();
1371   APInt Distance = APDelta; // these need to be initialzed
1372   APInt Remainder = APDelta;
1373   APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
1374   LLVM_DEBUG(dbgs() << "\t    Remainder = " << Remainder << "\n");
1375   if (Remainder != 0) {
1376     // Coeff doesn't divide Delta, no dependence
1377     ++WeakCrossingSIVindependence;
1378     ++WeakCrossingSIVsuccesses;
1379     return true;
1380   }
1381   LLVM_DEBUG(dbgs() << "\t    Distance = " << Distance << "\n");
1382 
1383   // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
1384   APInt Two = APInt(Distance.getBitWidth(), 2, true);
1385   Remainder = Distance.srem(Two);
1386   LLVM_DEBUG(dbgs() << "\t    Remainder = " << Remainder << "\n");
1387   if (Remainder != 0) {
1388     // Equal direction isn't possible
1389     Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::EQ);
1390     ++WeakCrossingSIVsuccesses;
1391   }
1392   return false;
1393 }
1394 
1395 
1396 // Kirch's algorithm, from
1397 //
1398 //        Optimizing Supercompilers for Supercomputers
1399 //        Michael Wolfe
1400 //        MIT Press, 1989
1401 //
1402 // Program 2.1, page 29.
1403 // Computes the GCD of AM and BM.
1404 // Also finds a solution to the equation ax - by = gcd(a, b).
1405 // Returns true if dependence disproved; i.e., gcd does not divide Delta.
1406 static bool findGCD(unsigned Bits, const APInt &AM, const APInt &BM,
1407                     const APInt &Delta, APInt &G, APInt &X, APInt &Y) {
1408   APInt A0(Bits, 1, true), A1(Bits, 0, true);
1409   APInt B0(Bits, 0, true), B1(Bits, 1, true);
1410   APInt G0 = AM.abs();
1411   APInt G1 = BM.abs();
1412   APInt Q = G0; // these need to be initialized
1413   APInt R = G0;
1414   APInt::sdivrem(G0, G1, Q, R);
1415   while (R != 0) {
1416     APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
1417     APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
1418     G0 = G1; G1 = R;
1419     APInt::sdivrem(G0, G1, Q, R);
1420   }
1421   G = G1;
1422   LLVM_DEBUG(dbgs() << "\t    GCD = " << G << "\n");
1423   X = AM.slt(0) ? -A1 : A1;
1424   Y = BM.slt(0) ? B1 : -B1;
1425 
1426   // make sure gcd divides Delta
1427   R = Delta.srem(G);
1428   if (R != 0)
1429     return true; // gcd doesn't divide Delta, no dependence
1430   Q = Delta.sdiv(G);
1431   X *= Q;
1432   Y *= Q;
1433   return false;
1434 }
1435 
1436 static APInt floorOfQuotient(const APInt &A, const APInt &B) {
1437   APInt Q = A; // these need to be initialized
1438   APInt R = A;
1439   APInt::sdivrem(A, B, Q, R);
1440   if (R == 0)
1441     return Q;
1442   if ((A.sgt(0) && B.sgt(0)) ||
1443       (A.slt(0) && B.slt(0)))
1444     return Q;
1445   else
1446     return Q - 1;
1447 }
1448 
1449 static APInt ceilingOfQuotient(const APInt &A, const APInt &B) {
1450   APInt Q = A; // these need to be initialized
1451   APInt R = A;
1452   APInt::sdivrem(A, B, Q, R);
1453   if (R == 0)
1454     return Q;
1455   if ((A.sgt(0) && B.sgt(0)) ||
1456       (A.slt(0) && B.slt(0)))
1457     return Q + 1;
1458   else
1459     return Q;
1460 }
1461 
1462 
1463 static
1464 APInt maxAPInt(APInt A, APInt B) {
1465   return A.sgt(B) ? A : B;
1466 }
1467 
1468 
1469 static
1470 APInt minAPInt(APInt A, APInt B) {
1471   return A.slt(B) ? A : B;
1472 }
1473 
1474 
1475 // exactSIVtest -
1476 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
1477 // where i is an induction variable, c1 and c2 are loop invariant, and a1
1478 // and a2 are constant, we can solve it exactly using an algorithm developed
1479 // by Banerjee and Wolfe. See Section 2.5.3 in
1480 //
1481 //        Optimizing Supercompilers for Supercomputers
1482 //        Michael Wolfe
1483 //        MIT Press, 1989
1484 //
1485 // It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
1486 // so use them if possible. They're also a bit better with symbolics and,
1487 // in the case of the strong SIV test, can compute Distances.
1488 //
1489 // Return true if dependence disproved.
1490 bool DependenceInfo::exactSIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
1491                                   const SCEV *SrcConst, const SCEV *DstConst,
1492                                   const Loop *CurLoop, unsigned Level,
1493                                   FullDependence &Result,
1494                                   Constraint &NewConstraint) const {
1495   LLVM_DEBUG(dbgs() << "\tExact SIV test\n");
1496   LLVM_DEBUG(dbgs() << "\t    SrcCoeff = " << *SrcCoeff << " = AM\n");
1497   LLVM_DEBUG(dbgs() << "\t    DstCoeff = " << *DstCoeff << " = BM\n");
1498   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
1499   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
1500   ++ExactSIVapplications;
1501   assert(0 < Level && Level <= CommonLevels && "Level out of range");
1502   Level--;
1503   Result.Consistent = false;
1504   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1505   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1506   NewConstraint.setLine(SrcCoeff, SE->getNegativeSCEV(DstCoeff),
1507                         Delta, CurLoop);
1508   const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1509   const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1510   const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1511   if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1512     return false;
1513 
1514   // find gcd
1515   APInt G, X, Y;
1516   APInt AM = ConstSrcCoeff->getAPInt();
1517   APInt BM = ConstDstCoeff->getAPInt();
1518   unsigned Bits = AM.getBitWidth();
1519   if (findGCD(Bits, AM, BM, ConstDelta->getAPInt(), G, X, Y)) {
1520     // gcd doesn't divide Delta, no dependence
1521     ++ExactSIVindependence;
1522     ++ExactSIVsuccesses;
1523     return true;
1524   }
1525 
1526   LLVM_DEBUG(dbgs() << "\t    X = " << X << ", Y = " << Y << "\n");
1527 
1528   // since SCEV construction normalizes, LM = 0
1529   APInt UM(Bits, 1, true);
1530   bool UMvalid = false;
1531   // UM is perhaps unavailable, let's check
1532   if (const SCEVConstant *CUB =
1533       collectConstantUpperBound(CurLoop, Delta->getType())) {
1534     UM = CUB->getAPInt();
1535     LLVM_DEBUG(dbgs() << "\t    UM = " << UM << "\n");
1536     UMvalid = true;
1537   }
1538 
1539   APInt TU(APInt::getSignedMaxValue(Bits));
1540   APInt TL(APInt::getSignedMinValue(Bits));
1541 
1542   // test(BM/G, LM-X) and test(-BM/G, X-UM)
1543   APInt TMUL = BM.sdiv(G);
1544   if (TMUL.sgt(0)) {
1545     TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
1546     LLVM_DEBUG(dbgs() << "\t    TL = " << TL << "\n");
1547     if (UMvalid) {
1548       TU = minAPInt(TU, floorOfQuotient(UM - X, TMUL));
1549       LLVM_DEBUG(dbgs() << "\t    TU = " << TU << "\n");
1550     }
1551   }
1552   else {
1553     TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
1554     LLVM_DEBUG(dbgs() << "\t    TU = " << TU << "\n");
1555     if (UMvalid) {
1556       TL = maxAPInt(TL, ceilingOfQuotient(UM - X, TMUL));
1557       LLVM_DEBUG(dbgs() << "\t    TL = " << TL << "\n");
1558     }
1559   }
1560 
1561   // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1562   TMUL = AM.sdiv(G);
1563   if (TMUL.sgt(0)) {
1564     TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
1565     LLVM_DEBUG(dbgs() << "\t    TL = " << TL << "\n");
1566     if (UMvalid) {
1567       TU = minAPInt(TU, floorOfQuotient(UM - Y, TMUL));
1568       LLVM_DEBUG(dbgs() << "\t    TU = " << TU << "\n");
1569     }
1570   }
1571   else {
1572     TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
1573     LLVM_DEBUG(dbgs() << "\t    TU = " << TU << "\n");
1574     if (UMvalid) {
1575       TL = maxAPInt(TL, ceilingOfQuotient(UM - Y, TMUL));
1576       LLVM_DEBUG(dbgs() << "\t    TL = " << TL << "\n");
1577     }
1578   }
1579   if (TL.sgt(TU)) {
1580     ++ExactSIVindependence;
1581     ++ExactSIVsuccesses;
1582     return true;
1583   }
1584 
1585   // explore directions
1586   unsigned NewDirection = Dependence::DVEntry::NONE;
1587 
1588   // less than
1589   APInt SaveTU(TU); // save these
1590   APInt SaveTL(TL);
1591   LLVM_DEBUG(dbgs() << "\t    exploring LT direction\n");
1592   TMUL = AM - BM;
1593   if (TMUL.sgt(0)) {
1594     TL = maxAPInt(TL, ceilingOfQuotient(X - Y + 1, TMUL));
1595     LLVM_DEBUG(dbgs() << "\t\t    TL = " << TL << "\n");
1596   }
1597   else {
1598     TU = minAPInt(TU, floorOfQuotient(X - Y + 1, TMUL));
1599     LLVM_DEBUG(dbgs() << "\t\t    TU = " << TU << "\n");
1600   }
1601   if (TL.sle(TU)) {
1602     NewDirection |= Dependence::DVEntry::LT;
1603     ++ExactSIVsuccesses;
1604   }
1605 
1606   // equal
1607   TU = SaveTU; // restore
1608   TL = SaveTL;
1609   LLVM_DEBUG(dbgs() << "\t    exploring EQ direction\n");
1610   if (TMUL.sgt(0)) {
1611     TL = maxAPInt(TL, ceilingOfQuotient(X - Y, TMUL));
1612     LLVM_DEBUG(dbgs() << "\t\t    TL = " << TL << "\n");
1613   }
1614   else {
1615     TU = minAPInt(TU, floorOfQuotient(X - Y, TMUL));
1616     LLVM_DEBUG(dbgs() << "\t\t    TU = " << TU << "\n");
1617   }
1618   TMUL = BM - AM;
1619   if (TMUL.sgt(0)) {
1620     TL = maxAPInt(TL, ceilingOfQuotient(Y - X, TMUL));
1621     LLVM_DEBUG(dbgs() << "\t\t    TL = " << TL << "\n");
1622   }
1623   else {
1624     TU = minAPInt(TU, floorOfQuotient(Y - X, TMUL));
1625     LLVM_DEBUG(dbgs() << "\t\t    TU = " << TU << "\n");
1626   }
1627   if (TL.sle(TU)) {
1628     NewDirection |= Dependence::DVEntry::EQ;
1629     ++ExactSIVsuccesses;
1630   }
1631 
1632   // greater than
1633   TU = SaveTU; // restore
1634   TL = SaveTL;
1635   LLVM_DEBUG(dbgs() << "\t    exploring GT direction\n");
1636   if (TMUL.sgt(0)) {
1637     TL = maxAPInt(TL, ceilingOfQuotient(Y - X + 1, TMUL));
1638     LLVM_DEBUG(dbgs() << "\t\t    TL = " << TL << "\n");
1639   }
1640   else {
1641     TU = minAPInt(TU, floorOfQuotient(Y - X + 1, TMUL));
1642     LLVM_DEBUG(dbgs() << "\t\t    TU = " << TU << "\n");
1643   }
1644   if (TL.sle(TU)) {
1645     NewDirection |= Dependence::DVEntry::GT;
1646     ++ExactSIVsuccesses;
1647   }
1648 
1649   // finished
1650   Result.DV[Level].Direction &= NewDirection;
1651   if (Result.DV[Level].Direction == Dependence::DVEntry::NONE)
1652     ++ExactSIVindependence;
1653   return Result.DV[Level].Direction == Dependence::DVEntry::NONE;
1654 }
1655 
1656 
1657 
1658 // Return true if the divisor evenly divides the dividend.
1659 static
1660 bool isRemainderZero(const SCEVConstant *Dividend,
1661                      const SCEVConstant *Divisor) {
1662   const APInt &ConstDividend = Dividend->getAPInt();
1663   const APInt &ConstDivisor = Divisor->getAPInt();
1664   return ConstDividend.srem(ConstDivisor) == 0;
1665 }
1666 
1667 
1668 // weakZeroSrcSIVtest -
1669 // From the paper, Practical Dependence Testing, Section 4.2.2
1670 //
1671 // When we have a pair of subscripts of the form [c1] and [c2 + a*i],
1672 // where i is an induction variable, c1 and c2 are loop invariant,
1673 // and a is a constant, we can solve it exactly using the
1674 // Weak-Zero SIV test.
1675 //
1676 // Given
1677 //
1678 //    c1 = c2 + a*i
1679 //
1680 // we get
1681 //
1682 //    (c1 - c2)/a = i
1683 //
1684 // If i is not an integer, there's no dependence.
1685 // If i < 0 or > UB, there's no dependence.
1686 // If i = 0, the direction is >= and peeling the
1687 // 1st iteration will break the dependence.
1688 // If i = UB, the direction is <= and peeling the
1689 // last iteration will break the dependence.
1690 // Otherwise, the direction is *.
1691 //
1692 // Can prove independence. Failing that, we can sometimes refine
1693 // the directions. Can sometimes show that first or last
1694 // iteration carries all the dependences (so worth peeling).
1695 //
1696 // (see also weakZeroDstSIVtest)
1697 //
1698 // Return true if dependence disproved.
1699 bool DependenceInfo::weakZeroSrcSIVtest(const SCEV *DstCoeff,
1700                                         const SCEV *SrcConst,
1701                                         const SCEV *DstConst,
1702                                         const Loop *CurLoop, unsigned Level,
1703                                         FullDependence &Result,
1704                                         Constraint &NewConstraint) const {
1705   // For the WeakSIV test, it's possible the loop isn't common to
1706   // the Src and Dst loops. If it isn't, then there's no need to
1707   // record a direction.
1708   LLVM_DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
1709   LLVM_DEBUG(dbgs() << "\t    DstCoeff = " << *DstCoeff << "\n");
1710   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
1711   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
1712   ++WeakZeroSIVapplications;
1713   assert(0 < Level && Level <= MaxLevels && "Level out of range");
1714   Level--;
1715   Result.Consistent = false;
1716   const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
1717   NewConstraint.setLine(SE->getZero(Delta->getType()), DstCoeff, Delta,
1718                         CurLoop);
1719   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1720   if (isKnownPredicate(CmpInst::ICMP_EQ, SrcConst, DstConst)) {
1721     if (Level < CommonLevels) {
1722       Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1723       Result.DV[Level].PeelFirst = true;
1724       ++WeakZeroSIVsuccesses;
1725     }
1726     return false; // dependences caused by first iteration
1727   }
1728   const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1729   if (!ConstCoeff)
1730     return false;
1731   const SCEV *AbsCoeff =
1732     SE->isKnownNegative(ConstCoeff) ?
1733     SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1734   const SCEV *NewDelta =
1735     SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1736 
1737   // check that Delta/SrcCoeff < iteration count
1738   // really check NewDelta < count*AbsCoeff
1739   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1740     LLVM_DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound << "\n");
1741     const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1742     if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1743       ++WeakZeroSIVindependence;
1744       ++WeakZeroSIVsuccesses;
1745       return true;
1746     }
1747     if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1748       // dependences caused by last iteration
1749       if (Level < CommonLevels) {
1750         Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1751         Result.DV[Level].PeelLast = true;
1752         ++WeakZeroSIVsuccesses;
1753       }
1754       return false;
1755     }
1756   }
1757 
1758   // check that Delta/SrcCoeff >= 0
1759   // really check that NewDelta >= 0
1760   if (SE->isKnownNegative(NewDelta)) {
1761     // No dependence, newDelta < 0
1762     ++WeakZeroSIVindependence;
1763     ++WeakZeroSIVsuccesses;
1764     return true;
1765   }
1766 
1767   // if SrcCoeff doesn't divide Delta, then no dependence
1768   if (isa<SCEVConstant>(Delta) &&
1769       !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1770     ++WeakZeroSIVindependence;
1771     ++WeakZeroSIVsuccesses;
1772     return true;
1773   }
1774   return false;
1775 }
1776 
1777 
1778 // weakZeroDstSIVtest -
1779 // From the paper, Practical Dependence Testing, Section 4.2.2
1780 //
1781 // When we have a pair of subscripts of the form [c1 + a*i] and [c2],
1782 // where i is an induction variable, c1 and c2 are loop invariant,
1783 // and a is a constant, we can solve it exactly using the
1784 // Weak-Zero SIV test.
1785 //
1786 // Given
1787 //
1788 //    c1 + a*i = c2
1789 //
1790 // we get
1791 //
1792 //    i = (c2 - c1)/a
1793 //
1794 // If i is not an integer, there's no dependence.
1795 // If i < 0 or > UB, there's no dependence.
1796 // If i = 0, the direction is <= and peeling the
1797 // 1st iteration will break the dependence.
1798 // If i = UB, the direction is >= and peeling the
1799 // last iteration will break the dependence.
1800 // Otherwise, the direction is *.
1801 //
1802 // Can prove independence. Failing that, we can sometimes refine
1803 // the directions. Can sometimes show that first or last
1804 // iteration carries all the dependences (so worth peeling).
1805 //
1806 // (see also weakZeroSrcSIVtest)
1807 //
1808 // Return true if dependence disproved.
1809 bool DependenceInfo::weakZeroDstSIVtest(const SCEV *SrcCoeff,
1810                                         const SCEV *SrcConst,
1811                                         const SCEV *DstConst,
1812                                         const Loop *CurLoop, unsigned Level,
1813                                         FullDependence &Result,
1814                                         Constraint &NewConstraint) const {
1815   // For the WeakSIV test, it's possible the loop isn't common to the
1816   // Src and Dst loops. If it isn't, then there's no need to record a direction.
1817   LLVM_DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
1818   LLVM_DEBUG(dbgs() << "\t    SrcCoeff = " << *SrcCoeff << "\n");
1819   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
1820   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
1821   ++WeakZeroSIVapplications;
1822   assert(0 < Level && Level <= SrcLevels && "Level out of range");
1823   Level--;
1824   Result.Consistent = false;
1825   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1826   NewConstraint.setLine(SrcCoeff, SE->getZero(Delta->getType()), Delta,
1827                         CurLoop);
1828   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1829   if (isKnownPredicate(CmpInst::ICMP_EQ, DstConst, SrcConst)) {
1830     if (Level < CommonLevels) {
1831       Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1832       Result.DV[Level].PeelFirst = true;
1833       ++WeakZeroSIVsuccesses;
1834     }
1835     return false; // dependences caused by first iteration
1836   }
1837   const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1838   if (!ConstCoeff)
1839     return false;
1840   const SCEV *AbsCoeff =
1841     SE->isKnownNegative(ConstCoeff) ?
1842     SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1843   const SCEV *NewDelta =
1844     SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1845 
1846   // check that Delta/SrcCoeff < iteration count
1847   // really check NewDelta < count*AbsCoeff
1848   if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
1849     LLVM_DEBUG(dbgs() << "\t    UpperBound = " << *UpperBound << "\n");
1850     const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1851     if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1852       ++WeakZeroSIVindependence;
1853       ++WeakZeroSIVsuccesses;
1854       return true;
1855     }
1856     if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1857       // dependences caused by last iteration
1858       if (Level < CommonLevels) {
1859         Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1860         Result.DV[Level].PeelLast = true;
1861         ++WeakZeroSIVsuccesses;
1862       }
1863       return false;
1864     }
1865   }
1866 
1867   // check that Delta/SrcCoeff >= 0
1868   // really check that NewDelta >= 0
1869   if (SE->isKnownNegative(NewDelta)) {
1870     // No dependence, newDelta < 0
1871     ++WeakZeroSIVindependence;
1872     ++WeakZeroSIVsuccesses;
1873     return true;
1874   }
1875 
1876   // if SrcCoeff doesn't divide Delta, then no dependence
1877   if (isa<SCEVConstant>(Delta) &&
1878       !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1879     ++WeakZeroSIVindependence;
1880     ++WeakZeroSIVsuccesses;
1881     return true;
1882   }
1883   return false;
1884 }
1885 
1886 
1887 // exactRDIVtest - Tests the RDIV subscript pair for dependence.
1888 // Things of the form [c1 + a*i] and [c2 + b*j],
1889 // where i and j are induction variable, c1 and c2 are loop invariant,
1890 // and a and b are constants.
1891 // Returns true if any possible dependence is disproved.
1892 // Marks the result as inconsistent.
1893 // Works in some cases that symbolicRDIVtest doesn't, and vice versa.
1894 bool DependenceInfo::exactRDIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
1895                                    const SCEV *SrcConst, const SCEV *DstConst,
1896                                    const Loop *SrcLoop, const Loop *DstLoop,
1897                                    FullDependence &Result) const {
1898   LLVM_DEBUG(dbgs() << "\tExact RDIV test\n");
1899   LLVM_DEBUG(dbgs() << "\t    SrcCoeff = " << *SrcCoeff << " = AM\n");
1900   LLVM_DEBUG(dbgs() << "\t    DstCoeff = " << *DstCoeff << " = BM\n");
1901   LLVM_DEBUG(dbgs() << "\t    SrcConst = " << *SrcConst << "\n");
1902   LLVM_DEBUG(dbgs() << "\t    DstConst = " << *DstConst << "\n");
1903   ++ExactRDIVapplications;
1904   Result.Consistent = false;
1905   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1906   LLVM_DEBUG(dbgs() << "\t    Delta = " << *Delta << "\n");
1907   const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1908   const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1909   const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1910   if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1911     return false;
1912 
1913   // find gcd
1914   APInt G, X, Y;
1915   APInt AM = ConstSrcCoeff->getAPInt();
1916   APInt BM = ConstDstCoeff->getAPInt();
1917   unsigned Bits = AM.getBitWidth();
1918   if (findGCD(Bits, AM, BM, ConstDelta->getAPInt(), G, X, Y)) {
1919     // gcd doesn't divide Delta, no dependence
1920     ++ExactRDIVindependence;
1921     return true;
1922   }
1923 
1924   LLVM_DEBUG(dbgs() << "\t    X = " << X << ", Y = " << Y << "\n");
1925 
1926   // since SCEV construction seems to normalize, LM = 0
1927   APInt SrcUM(Bits, 1, true);
1928   bool SrcUMvalid = false;
1929   // SrcUM is perhaps unavailable, let's check
1930   if (const SCEVConstant *UpperBound =
1931       collectConstantUpperBound(SrcLoop, Delta->getType())) {
1932     SrcUM = UpperBound->getAPInt();
1933     LLVM_DEBUG(dbgs() << "\t    SrcUM = " << SrcUM << "\n");
1934     SrcUMvalid = true;
1935   }
1936 
1937   APInt DstUM(Bits, 1, true);
1938   bool DstUMvalid = false;
1939   // UM is perhaps unavailable, let's check
1940   if (const SCEVConstant *UpperBound =
1941       collectConstantUpperBound(DstLoop, Delta->getType())) {
1942     DstUM = UpperBound->getAPInt();
1943     LLVM_DEBUG(dbgs() << "\t    DstUM = " << DstUM << "\n");
1944     DstUMvalid = true;
1945   }
1946 
1947   APInt TU(APInt::getSignedMaxValue(Bits));
1948   APInt TL(APInt::getSignedMinValue(Bits));
1949 
1950   // test(BM/G, LM-X) and test(-BM/G, X-UM)
1951   APInt TMUL = BM.sdiv(G);
1952   if (TMUL.sgt(0)) {
1953     TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
1954     LLVM_DEBUG(dbgs() << "\t    TL = " << TL << "\n");
1955     if (SrcUMvalid) {
1956       TU = minAPInt(TU, floorOfQuotient(SrcUM - X, TMUL));
1957       LLVM_DEBUG(dbgs() << "\t    TU = " << TU << "\n");
1958     }
1959   }
1960   else {
1961     TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
1962     LLVM_DEBUG(dbgs() << "\t    TU = " << TU << "\n");
1963     if (SrcUMvalid) {
1964       TL = maxAPInt(TL, ceilingOfQuotient(SrcUM - X, TMUL));
1965       LLVM_DEBUG(dbgs() << "\t    TL = " << TL << "\n");
1966     }
1967   }
1968 
1969   // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1970   TMUL = AM.sdiv(G);
1971   if (TMUL.sgt(0)) {
1972     TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
1973     LLVM_DEBUG(dbgs() << "\t    TL = " << TL << "\n");
1974     if (DstUMvalid) {
1975       TU = minAPInt(TU, floorOfQuotient(DstUM - Y, TMUL));
1976       LLVM_DEBUG(dbgs() << "\t    TU = " << TU << "\n");
1977     }
1978   }
1979   else {
1980     TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
1981     LLVM_DEBUG(dbgs() << "\t    TU = " << TU << "\n");
1982     if (DstUMvalid) {
1983       TL = maxAPInt(TL, ceilingOfQuotient(DstUM - Y, TMUL));
1984       LLVM_DEBUG(dbgs() << "\t    TL = " << TL << "\n");
1985     }
1986   }
1987   if (TL.sgt(TU))
1988     ++ExactRDIVindependence;
1989   return TL.sgt(TU);
1990 }
1991 
1992 
1993 // symbolicRDIVtest -
1994 // In Section 4.5 of the Practical Dependence Testing paper,the authors
1995 // introduce a special case of Banerjee's Inequalities (also called the
1996 // Extreme-Value Test) that can handle some of the SIV and RDIV cases,
1997 // particularly cases with symbolics. Since it's only able to disprove
1998 // dependence (not compute distances or directions), we'll use it as a
1999 // fall back for the other tests.
2000 //
2001 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2002 // where i and j are induction variables and c1 and c2 are loop invariants,
2003 // we can use the symbolic tests to disprove some dependences, serving as a
2004 // backup for the RDIV test. Note that i and j can be the same variable,
2005 // letting this test serve as a backup for the various SIV tests.
2006 //
2007 // For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some
2008 //  0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized)
2009 // loop bounds for the i and j loops, respectively. So, ...
2010 //
2011 // c1 + a1*i = c2 + a2*j
2012 // a1*i - a2*j = c2 - c1
2013 //
2014 // To test for a dependence, we compute c2 - c1 and make sure it's in the
2015 // range of the maximum and minimum possible values of a1*i - a2*j.
2016 // Considering the signs of a1 and a2, we have 4 possible cases:
2017 //
2018 // 1) If a1 >= 0 and a2 >= 0, then
2019 //        a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0
2020 //              -a2*N2 <= c2 - c1 <= a1*N1
2021 //
2022 // 2) If a1 >= 0 and a2 <= 0, then
2023 //        a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2
2024 //                  0 <= c2 - c1 <= a1*N1 - a2*N2
2025 //
2026 // 3) If a1 <= 0 and a2 >= 0, then
2027 //        a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0
2028 //        a1*N1 - a2*N2 <= c2 - c1 <= 0
2029 //
2030 // 4) If a1 <= 0 and a2 <= 0, then
2031 //        a1*N1 - a2*0  <= c2 - c1 <= a1*0 - a2*N2
2032 //        a1*N1         <= c2 - c1 <=       -a2*N2
2033 //
2034 // return true if dependence disproved
2035 bool DependenceInfo::symbolicRDIVtest(const SCEV *A1, const SCEV *A2,
2036                                       const SCEV *C1, const SCEV *C2,
2037                                       const Loop *Loop1,
2038                                       const Loop *Loop2) const {
2039   ++SymbolicRDIVapplications;
2040   LLVM_DEBUG(dbgs() << "\ttry symbolic RDIV test\n");
2041   LLVM_DEBUG(dbgs() << "\t    A1 = " << *A1);
2042   LLVM_DEBUG(dbgs() << ", type = " << *A1->getType() << "\n");
2043   LLVM_DEBUG(dbgs() << "\t    A2 = " << *A2 << "\n");
2044   LLVM_DEBUG(dbgs() << "\t    C1 = " << *C1 << "\n");
2045   LLVM_DEBUG(dbgs() << "\t    C2 = " << *C2 << "\n");
2046   const SCEV *N1 = collectUpperBound(Loop1, A1->getType());
2047   const SCEV *N2 = collectUpperBound(Loop2, A1->getType());
2048   LLVM_DEBUG(if (N1) dbgs() << "\t    N1 = " << *N1 << "\n");
2049   LLVM_DEBUG(if (N2) dbgs() << "\t    N2 = " << *N2 << "\n");
2050   const SCEV *C2_C1 = SE->getMinusSCEV(C2, C1);
2051   const SCEV *C1_C2 = SE->getMinusSCEV(C1, C2);
2052   LLVM_DEBUG(dbgs() << "\t    C2 - C1 = " << *C2_C1 << "\n");
2053   LLVM_DEBUG(dbgs() << "\t    C1 - C2 = " << *C1_C2 << "\n");
2054   if (SE->isKnownNonNegative(A1)) {
2055     if (SE->isKnownNonNegative(A2)) {
2056       // A1 >= 0 && A2 >= 0
2057       if (N1) {
2058         // make sure that c2 - c1 <= a1*N1
2059         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2060         LLVM_DEBUG(dbgs() << "\t    A1*N1 = " << *A1N1 << "\n");
2061         if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1)) {
2062           ++SymbolicRDIVindependence;
2063           return true;
2064         }
2065       }
2066       if (N2) {
2067         // make sure that -a2*N2 <= c2 - c1, or a2*N2 >= c1 - c2
2068         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2069         LLVM_DEBUG(dbgs() << "\t    A2*N2 = " << *A2N2 << "\n");
2070         if (isKnownPredicate(CmpInst::ICMP_SLT, A2N2, C1_C2)) {
2071           ++SymbolicRDIVindependence;
2072           return true;
2073         }
2074       }
2075     }
2076     else if (SE->isKnownNonPositive(A2)) {
2077       // a1 >= 0 && a2 <= 0
2078       if (N1 && N2) {
2079         // make sure that c2 - c1 <= a1*N1 - a2*N2
2080         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2081         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2082         const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
2083         LLVM_DEBUG(dbgs() << "\t    A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
2084         if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1_A2N2)) {
2085           ++SymbolicRDIVindependence;
2086           return true;
2087         }
2088       }
2089       // make sure that 0 <= c2 - c1
2090       if (SE->isKnownNegative(C2_C1)) {
2091         ++SymbolicRDIVindependence;
2092         return true;
2093       }
2094     }
2095   }
2096   else if (SE->isKnownNonPositive(A1)) {
2097     if (SE->isKnownNonNegative(A2)) {
2098       // a1 <= 0 && a2 >= 0
2099       if (N1 && N2) {
2100         // make sure that a1*N1 - a2*N2 <= c2 - c1
2101         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2102         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2103         const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
2104         LLVM_DEBUG(dbgs() << "\t    A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
2105         if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1_A2N2, C2_C1)) {
2106           ++SymbolicRDIVindependence;
2107           return true;
2108         }
2109       }
2110       // make sure that c2 - c1 <= 0
2111       if (SE->isKnownPositive(C2_C1)) {
2112         ++SymbolicRDIVindependence;
2113         return true;
2114       }
2115     }
2116     else if (SE->isKnownNonPositive(A2)) {
2117       // a1 <= 0 && a2 <= 0
2118       if (N1) {
2119         // make sure that a1*N1 <= c2 - c1
2120         const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2121         LLVM_DEBUG(dbgs() << "\t    A1*N1 = " << *A1N1 << "\n");
2122         if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1, C2_C1)) {
2123           ++SymbolicRDIVindependence;
2124           return true;
2125         }
2126       }
2127       if (N2) {
2128         // make sure that c2 - c1 <= -a2*N2, or c1 - c2 >= a2*N2
2129         const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2130         LLVM_DEBUG(dbgs() << "\t    A2*N2 = " << *A2N2 << "\n");
2131         if (isKnownPredicate(CmpInst::ICMP_SLT, C1_C2, A2N2)) {
2132           ++SymbolicRDIVindependence;
2133           return true;
2134         }
2135       }
2136     }
2137   }
2138   return false;
2139 }
2140 
2141 
2142 // testSIV -
2143 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
2144 // where i is an induction variable, c1 and c2 are loop invariant, and a1 and
2145 // a2 are constant, we attack it with an SIV test. While they can all be
2146 // solved with the Exact SIV test, it's worthwhile to use simpler tests when
2147 // they apply; they're cheaper and sometimes more precise.
2148 //
2149 // Return true if dependence disproved.
2150 bool DependenceInfo::testSIV(const SCEV *Src, const SCEV *Dst, unsigned &Level,
2151                              FullDependence &Result, Constraint &NewConstraint,
2152                              const SCEV *&SplitIter) const {
2153   LLVM_DEBUG(dbgs() << "    src = " << *Src << "\n");
2154   LLVM_DEBUG(dbgs() << "    dst = " << *Dst << "\n");
2155   const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2156   const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2157   if (SrcAddRec && DstAddRec) {
2158     const SCEV *SrcConst = SrcAddRec->getStart();
2159     const SCEV *DstConst = DstAddRec->getStart();
2160     const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2161     const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2162     const Loop *CurLoop = SrcAddRec->getLoop();
2163     assert(CurLoop == DstAddRec->getLoop() &&
2164            "both loops in SIV should be same");
2165     Level = mapSrcLoop(CurLoop);
2166     bool disproven;
2167     if (SrcCoeff == DstCoeff)
2168       disproven = strongSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2169                                 Level, Result, NewConstraint);
2170     else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
2171       disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2172                                       Level, Result, NewConstraint, SplitIter);
2173     else
2174       disproven = exactSIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop,
2175                                Level, Result, NewConstraint);
2176     return disproven ||
2177       gcdMIVtest(Src, Dst, Result) ||
2178       symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop, CurLoop);
2179   }
2180   if (SrcAddRec) {
2181     const SCEV *SrcConst = SrcAddRec->getStart();
2182     const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2183     const SCEV *DstConst = Dst;
2184     const Loop *CurLoop = SrcAddRec->getLoop();
2185     Level = mapSrcLoop(CurLoop);
2186     return weakZeroDstSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2187                               Level, Result, NewConstraint) ||
2188       gcdMIVtest(Src, Dst, Result);
2189   }
2190   if (DstAddRec) {
2191     const SCEV *DstConst = DstAddRec->getStart();
2192     const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2193     const SCEV *SrcConst = Src;
2194     const Loop *CurLoop = DstAddRec->getLoop();
2195     Level = mapDstLoop(CurLoop);
2196     return weakZeroSrcSIVtest(DstCoeff, SrcConst, DstConst,
2197                               CurLoop, Level, Result, NewConstraint) ||
2198       gcdMIVtest(Src, Dst, Result);
2199   }
2200   llvm_unreachable("SIV test expected at least one AddRec");
2201   return false;
2202 }
2203 
2204 
2205 // testRDIV -
2206 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2207 // where i and j are induction variables, c1 and c2 are loop invariant,
2208 // and a1 and a2 are constant, we can solve it exactly with an easy adaptation
2209 // of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
2210 // It doesn't make sense to talk about distance or direction in this case,
2211 // so there's no point in making special versions of the Strong SIV test or
2212 // the Weak-crossing SIV test.
2213 //
2214 // With minor algebra, this test can also be used for things like
2215 // [c1 + a1*i + a2*j][c2].
2216 //
2217 // Return true if dependence disproved.
2218 bool DependenceInfo::testRDIV(const SCEV *Src, const SCEV *Dst,
2219                               FullDependence &Result) const {
2220   // we have 3 possible situations here:
2221   //   1) [a*i + b] and [c*j + d]
2222   //   2) [a*i + c*j + b] and [d]
2223   //   3) [b] and [a*i + c*j + d]
2224   // We need to find what we've got and get organized
2225 
2226   const SCEV *SrcConst, *DstConst;
2227   const SCEV *SrcCoeff, *DstCoeff;
2228   const Loop *SrcLoop, *DstLoop;
2229 
2230   LLVM_DEBUG(dbgs() << "    src = " << *Src << "\n");
2231   LLVM_DEBUG(dbgs() << "    dst = " << *Dst << "\n");
2232   const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2233   const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2234   if (SrcAddRec && DstAddRec) {
2235     SrcConst = SrcAddRec->getStart();
2236     SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2237     SrcLoop = SrcAddRec->getLoop();
2238     DstConst = DstAddRec->getStart();
2239     DstCoeff = DstAddRec->getStepRecurrence(*SE);
2240     DstLoop = DstAddRec->getLoop();
2241   }
2242   else if (SrcAddRec) {
2243     if (const SCEVAddRecExpr *tmpAddRec =
2244         dyn_cast<SCEVAddRecExpr>(SrcAddRec->getStart())) {
2245       SrcConst = tmpAddRec->getStart();
2246       SrcCoeff = tmpAddRec->getStepRecurrence(*SE);
2247       SrcLoop = tmpAddRec->getLoop();
2248       DstConst = Dst;
2249       DstCoeff = SE->getNegativeSCEV(SrcAddRec->getStepRecurrence(*SE));
2250       DstLoop = SrcAddRec->getLoop();
2251     }
2252     else
2253       llvm_unreachable("RDIV reached by surprising SCEVs");
2254   }
2255   else if (DstAddRec) {
2256     if (const SCEVAddRecExpr *tmpAddRec =
2257         dyn_cast<SCEVAddRecExpr>(DstAddRec->getStart())) {
2258       DstConst = tmpAddRec->getStart();
2259       DstCoeff = tmpAddRec->getStepRecurrence(*SE);
2260       DstLoop = tmpAddRec->getLoop();
2261       SrcConst = Src;
2262       SrcCoeff = SE->getNegativeSCEV(DstAddRec->getStepRecurrence(*SE));
2263       SrcLoop = DstAddRec->getLoop();
2264     }
2265     else
2266       llvm_unreachable("RDIV reached by surprising SCEVs");
2267   }
2268   else
2269     llvm_unreachable("RDIV expected at least one AddRec");
2270   return exactRDIVtest(SrcCoeff, DstCoeff,
2271                        SrcConst, DstConst,
2272                        SrcLoop, DstLoop,
2273                        Result) ||
2274     gcdMIVtest(Src, Dst, Result) ||
2275     symbolicRDIVtest(SrcCoeff, DstCoeff,
2276                      SrcConst, DstConst,
2277                      SrcLoop, DstLoop);
2278 }
2279 
2280 
2281 // Tests the single-subscript MIV pair (Src and Dst) for dependence.
2282 // Return true if dependence disproved.
2283 // Can sometimes refine direction vectors.
2284 bool DependenceInfo::testMIV(const SCEV *Src, const SCEV *Dst,
2285                              const SmallBitVector &Loops,
2286                              FullDependence &Result) const {
2287   LLVM_DEBUG(dbgs() << "    src = " << *Src << "\n");
2288   LLVM_DEBUG(dbgs() << "    dst = " << *Dst << "\n");
2289   Result.Consistent = false;
2290   return gcdMIVtest(Src, Dst, Result) ||
2291     banerjeeMIVtest(Src, Dst, Loops, Result);
2292 }
2293 
2294 
2295 // Given a product, e.g., 10*X*Y, returns the first constant operand,
2296 // in this case 10. If there is no constant part, returns NULL.
2297 static
2298 const SCEVConstant *getConstantPart(const SCEV *Expr) {
2299   if (const auto *Constant = dyn_cast<SCEVConstant>(Expr))
2300     return Constant;
2301   else if (const auto *Product = dyn_cast<SCEVMulExpr>(Expr))
2302     if (const auto *Constant = dyn_cast<SCEVConstant>(Product->getOperand(0)))
2303       return Constant;
2304   return nullptr;
2305 }
2306 
2307 
2308 //===----------------------------------------------------------------------===//
2309 // gcdMIVtest -
2310 // Tests an MIV subscript pair for dependence.
2311 // Returns true if any possible dependence is disproved.
2312 // Marks the result as inconsistent.
2313 // Can sometimes disprove the equal direction for 1 or more loops,
2314 // as discussed in Michael Wolfe's book,
2315 // High Performance Compilers for Parallel Computing, page 235.
2316 //
2317 // We spend some effort (code!) to handle cases like
2318 // [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
2319 // but M and N are just loop-invariant variables.
2320 // This should help us handle linearized subscripts;
2321 // also makes this test a useful backup to the various SIV tests.
2322 //
2323 // It occurs to me that the presence of loop-invariant variables
2324 // changes the nature of the test from "greatest common divisor"
2325 // to "a common divisor".
2326 bool DependenceInfo::gcdMIVtest(const SCEV *Src, const SCEV *Dst,
2327                                 FullDependence &Result) const {
2328   LLVM_DEBUG(dbgs() << "starting gcd\n");
2329   ++GCDapplications;
2330   unsigned BitWidth = SE->getTypeSizeInBits(Src->getType());
2331   APInt RunningGCD = APInt::getNullValue(BitWidth);
2332 
2333   // Examine Src coefficients.
2334   // Compute running GCD and record source constant.
2335   // Because we're looking for the constant at the end of the chain,
2336   // we can't quit the loop just because the GCD == 1.
2337   const SCEV *Coefficients = Src;
2338   while (const SCEVAddRecExpr *AddRec =
2339          dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2340     const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2341     // If the coefficient is the product of a constant and other stuff,
2342     // we can use the constant in the GCD computation.
2343     const auto *Constant = getConstantPart(Coeff);
2344     if (!Constant)
2345       return false;
2346     APInt ConstCoeff = Constant->getAPInt();
2347     RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2348     Coefficients = AddRec->getStart();
2349   }
2350   const SCEV *SrcConst = Coefficients;
2351 
2352   // Examine Dst coefficients.
2353   // Compute running GCD and record destination constant.
2354   // Because we're looking for the constant at the end of the chain,
2355   // we can't quit the loop just because the GCD == 1.
2356   Coefficients = Dst;
2357   while (const SCEVAddRecExpr *AddRec =
2358          dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2359     const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2360     // If the coefficient is the product of a constant and other stuff,
2361     // we can use the constant in the GCD computation.
2362     const auto *Constant = getConstantPart(Coeff);
2363     if (!Constant)
2364       return false;
2365     APInt ConstCoeff = Constant->getAPInt();
2366     RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2367     Coefficients = AddRec->getStart();
2368   }
2369   const SCEV *DstConst = Coefficients;
2370 
2371   APInt ExtraGCD = APInt::getNullValue(BitWidth);
2372   const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
2373   LLVM_DEBUG(dbgs() << "    Delta = " << *Delta << "\n");
2374   const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
2375   if (const SCEVAddExpr *Sum = dyn_cast<SCEVAddExpr>(Delta)) {
2376     // If Delta is a sum of products, we may be able to make further progress.
2377     for (unsigned Op = 0, Ops = Sum->getNumOperands(); Op < Ops; Op++) {
2378       const SCEV *Operand = Sum->getOperand(Op);
2379       if (isa<SCEVConstant>(Operand)) {
2380         assert(!Constant && "Surprised to find multiple constants");
2381         Constant = cast<SCEVConstant>(Operand);
2382       }
2383       else if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Operand)) {
2384         // Search for constant operand to participate in GCD;
2385         // If none found; return false.
2386         const SCEVConstant *ConstOp = getConstantPart(Product);
2387         if (!ConstOp)
2388           return false;
2389         APInt ConstOpValue = ConstOp->getAPInt();
2390         ExtraGCD = APIntOps::GreatestCommonDivisor(ExtraGCD,
2391                                                    ConstOpValue.abs());
2392       }
2393       else
2394         return false;
2395     }
2396   }
2397   if (!Constant)
2398     return false;
2399   APInt ConstDelta = cast<SCEVConstant>(Constant)->getAPInt();
2400   LLVM_DEBUG(dbgs() << "    ConstDelta = " << ConstDelta << "\n");
2401   if (ConstDelta == 0)
2402     return false;
2403   RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ExtraGCD);
2404   LLVM_DEBUG(dbgs() << "    RunningGCD = " << RunningGCD << "\n");
2405   APInt Remainder = ConstDelta.srem(RunningGCD);
2406   if (Remainder != 0) {
2407     ++GCDindependence;
2408     return true;
2409   }
2410 
2411   // Try to disprove equal directions.
2412   // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
2413   // the code above can't disprove the dependence because the GCD = 1.
2414   // So we consider what happen if i = i' and what happens if j = j'.
2415   // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
2416   // which is infeasible, so we can disallow the = direction for the i level.
2417   // Setting j = j' doesn't help matters, so we end up with a direction vector
2418   // of [<>, *]
2419   //
2420   // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5],
2421   // we need to remember that the constant part is 5 and the RunningGCD should
2422   // be initialized to ExtraGCD = 30.
2423   LLVM_DEBUG(dbgs() << "    ExtraGCD = " << ExtraGCD << '\n');
2424 
2425   bool Improved = false;
2426   Coefficients = Src;
2427   while (const SCEVAddRecExpr *AddRec =
2428          dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2429     Coefficients = AddRec->getStart();
2430     const Loop *CurLoop = AddRec->getLoop();
2431     RunningGCD = ExtraGCD;
2432     const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
2433     const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff);
2434     const SCEV *Inner = Src;
2435     while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2436       AddRec = cast<SCEVAddRecExpr>(Inner);
2437       const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2438       if (CurLoop == AddRec->getLoop())
2439         ; // SrcCoeff == Coeff
2440       else {
2441         // If the coefficient is the product of a constant and other stuff,
2442         // we can use the constant in the GCD computation.
2443         Constant = getConstantPart(Coeff);
2444         if (!Constant)
2445           return false;
2446         APInt ConstCoeff = Constant->getAPInt();
2447         RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2448       }
2449       Inner = AddRec->getStart();
2450     }
2451     Inner = Dst;
2452     while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2453       AddRec = cast<SCEVAddRecExpr>(Inner);
2454       const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2455       if (CurLoop == AddRec->getLoop())
2456         DstCoeff = Coeff;
2457       else {
2458         // If the coefficient is the product of a constant and other stuff,
2459         // we can use the constant in the GCD computation.
2460         Constant = getConstantPart(Coeff);
2461         if (!Constant)
2462           return false;
2463         APInt ConstCoeff = Constant->getAPInt();
2464         RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2465       }
2466       Inner = AddRec->getStart();
2467     }
2468     Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff);
2469     // If the coefficient is the product of a constant and other stuff,
2470     // we can use the constant in the GCD computation.
2471     Constant = getConstantPart(Delta);
2472     if (!Constant)
2473       // The difference of the two coefficients might not be a product
2474       // or constant, in which case we give up on this direction.
2475       continue;
2476     APInt ConstCoeff = Constant->getAPInt();
2477     RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2478     LLVM_DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
2479     if (RunningGCD != 0) {
2480       Remainder = ConstDelta.srem(RunningGCD);
2481       LLVM_DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
2482       if (Remainder != 0) {
2483         unsigned Level = mapSrcLoop(CurLoop);
2484         Result.DV[Level - 1].Direction &= unsigned(~Dependence::DVEntry::EQ);
2485         Improved = true;
2486       }
2487     }
2488   }
2489   if (Improved)
2490     ++GCDsuccesses;
2491   LLVM_DEBUG(dbgs() << "all done\n");
2492   return false;
2493 }
2494 
2495 
2496 //===----------------------------------------------------------------------===//
2497 // banerjeeMIVtest -
2498 // Use Banerjee's Inequalities to test an MIV subscript pair.
2499 // (Wolfe, in the race-car book, calls this the Extreme Value Test.)
2500 // Generally follows the discussion in Section 2.5.2 of
2501 //
2502 //    Optimizing Supercompilers for Supercomputers
2503 //    Michael Wolfe
2504 //
2505 // The inequalities given on page 25 are simplified in that loops are
2506 // normalized so that the lower bound is always 0 and the stride is always 1.
2507 // For example, Wolfe gives
2508 //
2509 //     LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2510 //
2511 // where A_k is the coefficient of the kth index in the source subscript,
2512 // B_k is the coefficient of the kth index in the destination subscript,
2513 // U_k is the upper bound of the kth index, L_k is the lower bound of the Kth
2514 // index, and N_k is the stride of the kth index. Since all loops are normalized
2515 // by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the
2516 // equation to
2517 //
2518 //     LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1
2519 //            = (A^-_k - B_k)^- (U_k - 1)  - B_k
2520 //
2521 // Similar simplifications are possible for the other equations.
2522 //
2523 // When we can't determine the number of iterations for a loop,
2524 // we use NULL as an indicator for the worst case, infinity.
2525 // When computing the upper bound, NULL denotes +inf;
2526 // for the lower bound, NULL denotes -inf.
2527 //
2528 // Return true if dependence disproved.
2529 bool DependenceInfo::banerjeeMIVtest(const SCEV *Src, const SCEV *Dst,
2530                                      const SmallBitVector &Loops,
2531                                      FullDependence &Result) const {
2532   LLVM_DEBUG(dbgs() << "starting Banerjee\n");
2533   ++BanerjeeApplications;
2534   LLVM_DEBUG(dbgs() << "    Src = " << *Src << '\n');
2535   const SCEV *A0;
2536   CoefficientInfo *A = collectCoeffInfo(Src, true, A0);
2537   LLVM_DEBUG(dbgs() << "    Dst = " << *Dst << '\n');
2538   const SCEV *B0;
2539   CoefficientInfo *B = collectCoeffInfo(Dst, false, B0);
2540   BoundInfo *Bound = new BoundInfo[MaxLevels + 1];
2541   const SCEV *Delta = SE->getMinusSCEV(B0, A0);
2542   LLVM_DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
2543 
2544   // Compute bounds for all the * directions.
2545   LLVM_DEBUG(dbgs() << "\tBounds[*]\n");
2546   for (unsigned K = 1; K <= MaxLevels; ++K) {
2547     Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations;
2548     Bound[K].Direction = Dependence::DVEntry::ALL;
2549     Bound[K].DirSet = Dependence::DVEntry::NONE;
2550     findBoundsALL(A, B, Bound, K);
2551 #ifndef NDEBUG
2552     LLVM_DEBUG(dbgs() << "\t    " << K << '\t');
2553     if (Bound[K].Lower[Dependence::DVEntry::ALL])
2554       LLVM_DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t');
2555     else
2556       LLVM_DEBUG(dbgs() << "-inf\t");
2557     if (Bound[K].Upper[Dependence::DVEntry::ALL])
2558       LLVM_DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n');
2559     else
2560       LLVM_DEBUG(dbgs() << "+inf\n");
2561 #endif
2562   }
2563 
2564   // Test the *, *, *, ... case.
2565   bool Disproved = false;
2566   if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
2567     // Explore the direction vector hierarchy.
2568     unsigned DepthExpanded = 0;
2569     unsigned NewDeps = exploreDirections(1, A, B, Bound,
2570                                          Loops, DepthExpanded, Delta);
2571     if (NewDeps > 0) {
2572       bool Improved = false;
2573       for (unsigned K = 1; K <= CommonLevels; ++K) {
2574         if (Loops[K]) {
2575           unsigned Old = Result.DV[K - 1].Direction;
2576           Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
2577           Improved |= Old != Result.DV[K - 1].Direction;
2578           if (!Result.DV[K - 1].Direction) {
2579             Improved = false;
2580             Disproved = true;
2581             break;
2582           }
2583         }
2584       }
2585       if (Improved)
2586         ++BanerjeeSuccesses;
2587     }
2588     else {
2589       ++BanerjeeIndependence;
2590       Disproved = true;
2591     }
2592   }
2593   else {
2594     ++BanerjeeIndependence;
2595     Disproved = true;
2596   }
2597   delete [] Bound;
2598   delete [] A;
2599   delete [] B;
2600   return Disproved;
2601 }
2602 
2603 
2604 // Hierarchically expands the direction vector
2605 // search space, combining the directions of discovered dependences
2606 // in the DirSet field of Bound. Returns the number of distinct
2607 // dependences discovered. If the dependence is disproved,
2608 // it will return 0.
2609 unsigned DependenceInfo::exploreDirections(unsigned Level, CoefficientInfo *A,
2610                                            CoefficientInfo *B, BoundInfo *Bound,
2611                                            const SmallBitVector &Loops,
2612                                            unsigned &DepthExpanded,
2613                                            const SCEV *Delta) const {
2614   if (Level > CommonLevels) {
2615     // record result
2616     LLVM_DEBUG(dbgs() << "\t[");
2617     for (unsigned K = 1; K <= CommonLevels; ++K) {
2618       if (Loops[K]) {
2619         Bound[K].DirSet |= Bound[K].Direction;
2620 #ifndef NDEBUG
2621         switch (Bound[K].Direction) {
2622         case Dependence::DVEntry::LT:
2623           LLVM_DEBUG(dbgs() << " <");
2624           break;
2625         case Dependence::DVEntry::EQ:
2626           LLVM_DEBUG(dbgs() << " =");
2627           break;
2628         case Dependence::DVEntry::GT:
2629           LLVM_DEBUG(dbgs() << " >");
2630           break;
2631         case Dependence::DVEntry::ALL:
2632           LLVM_DEBUG(dbgs() << " *");
2633           break;
2634         default:
2635           llvm_unreachable("unexpected Bound[K].Direction");
2636         }
2637 #endif
2638       }
2639     }
2640     LLVM_DEBUG(dbgs() << " ]\n");
2641     return 1;
2642   }
2643   if (Loops[Level]) {
2644     if (Level > DepthExpanded) {
2645       DepthExpanded = Level;
2646       // compute bounds for <, =, > at current level
2647       findBoundsLT(A, B, Bound, Level);
2648       findBoundsGT(A, B, Bound, Level);
2649       findBoundsEQ(A, B, Bound, Level);
2650 #ifndef NDEBUG
2651       LLVM_DEBUG(dbgs() << "\tBound for level = " << Level << '\n');
2652       LLVM_DEBUG(dbgs() << "\t    <\t");
2653       if (Bound[Level].Lower[Dependence::DVEntry::LT])
2654         LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT]
2655                           << '\t');
2656       else
2657         LLVM_DEBUG(dbgs() << "-inf\t");
2658       if (Bound[Level].Upper[Dependence::DVEntry::LT])
2659         LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT]
2660                           << '\n');
2661       else
2662         LLVM_DEBUG(dbgs() << "+inf\n");
2663       LLVM_DEBUG(dbgs() << "\t    =\t");
2664       if (Bound[Level].Lower[Dependence::DVEntry::EQ])
2665         LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ]
2666                           << '\t');
2667       else
2668         LLVM_DEBUG(dbgs() << "-inf\t");
2669       if (Bound[Level].Upper[Dependence::DVEntry::EQ])
2670         LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ]
2671                           << '\n');
2672       else
2673         LLVM_DEBUG(dbgs() << "+inf\n");
2674       LLVM_DEBUG(dbgs() << "\t    >\t");
2675       if (Bound[Level].Lower[Dependence::DVEntry::GT])
2676         LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT]
2677                           << '\t');
2678       else
2679         LLVM_DEBUG(dbgs() << "-inf\t");
2680       if (Bound[Level].Upper[Dependence::DVEntry::GT])
2681         LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT]
2682                           << '\n');
2683       else
2684         LLVM_DEBUG(dbgs() << "+inf\n");
2685 #endif
2686     }
2687 
2688     unsigned NewDeps = 0;
2689 
2690     // test bounds for <, *, *, ...
2691     if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta))
2692       NewDeps += exploreDirections(Level + 1, A, B, Bound,
2693                                    Loops, DepthExpanded, Delta);
2694 
2695     // Test bounds for =, *, *, ...
2696     if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta))
2697       NewDeps += exploreDirections(Level + 1, A, B, Bound,
2698                                    Loops, DepthExpanded, Delta);
2699 
2700     // test bounds for >, *, *, ...
2701     if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta))
2702       NewDeps += exploreDirections(Level + 1, A, B, Bound,
2703                                    Loops, DepthExpanded, Delta);
2704 
2705     Bound[Level].Direction = Dependence::DVEntry::ALL;
2706     return NewDeps;
2707   }
2708   else
2709     return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded, Delta);
2710 }
2711 
2712 
2713 // Returns true iff the current bounds are plausible.
2714 bool DependenceInfo::testBounds(unsigned char DirKind, unsigned Level,
2715                                 BoundInfo *Bound, const SCEV *Delta) const {
2716   Bound[Level].Direction = DirKind;
2717   if (const SCEV *LowerBound = getLowerBound(Bound))
2718     if (isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta))
2719       return false;
2720   if (const SCEV *UpperBound = getUpperBound(Bound))
2721     if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound))
2722       return false;
2723   return true;
2724 }
2725 
2726 
2727 // Computes the upper and lower bounds for level K
2728 // using the * direction. Records them in Bound.
2729 // Wolfe gives the equations
2730 //
2731 //    LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k
2732 //    UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k
2733 //
2734 // Since we normalize loops, we can simplify these equations to
2735 //
2736 //    LB^*_k = (A^-_k - B^+_k)U_k
2737 //    UB^*_k = (A^+_k - B^-_k)U_k
2738 //
2739 // We must be careful to handle the case where the upper bound is unknown.
2740 // Note that the lower bound is always <= 0
2741 // and the upper bound is always >= 0.
2742 void DependenceInfo::findBoundsALL(CoefficientInfo *A, CoefficientInfo *B,
2743                                    BoundInfo *Bound, unsigned K) const {
2744   Bound[K].Lower[Dependence::DVEntry::ALL] = nullptr; // Default value = -infinity.
2745   Bound[K].Upper[Dependence::DVEntry::ALL] = nullptr; // Default value = +infinity.
2746   if (Bound[K].Iterations) {
2747     Bound[K].Lower[Dependence::DVEntry::ALL] =
2748       SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart),
2749                      Bound[K].Iterations);
2750     Bound[K].Upper[Dependence::DVEntry::ALL] =
2751       SE->getMulExpr(SE->getMinusSCEV(A[K].PosPart, B[K].NegPart),
2752                      Bound[K].Iterations);
2753   }
2754   else {
2755     // If the difference is 0, we won't need to know the number of iterations.
2756     if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart))
2757       Bound[K].Lower[Dependence::DVEntry::ALL] =
2758           SE->getZero(A[K].Coeff->getType());
2759     if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart))
2760       Bound[K].Upper[Dependence::DVEntry::ALL] =
2761           SE->getZero(A[K].Coeff->getType());
2762   }
2763 }
2764 
2765 
2766 // Computes the upper and lower bounds for level K
2767 // using the = direction. Records them in Bound.
2768 // Wolfe gives the equations
2769 //
2770 //    LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k
2771 //    UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k
2772 //
2773 // Since we normalize loops, we can simplify these equations to
2774 //
2775 //    LB^=_k = (A_k - B_k)^- U_k
2776 //    UB^=_k = (A_k - B_k)^+ U_k
2777 //
2778 // We must be careful to handle the case where the upper bound is unknown.
2779 // Note that the lower bound is always <= 0
2780 // and the upper bound is always >= 0.
2781 void DependenceInfo::findBoundsEQ(CoefficientInfo *A, CoefficientInfo *B,
2782                                   BoundInfo *Bound, unsigned K) const {
2783   Bound[K].Lower[Dependence::DVEntry::EQ] = nullptr; // Default value = -infinity.
2784   Bound[K].Upper[Dependence::DVEntry::EQ] = nullptr; // Default value = +infinity.
2785   if (Bound[K].Iterations) {
2786     const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2787     const SCEV *NegativePart = getNegativePart(Delta);
2788     Bound[K].Lower[Dependence::DVEntry::EQ] =
2789       SE->getMulExpr(NegativePart, Bound[K].Iterations);
2790     const SCEV *PositivePart = getPositivePart(Delta);
2791     Bound[K].Upper[Dependence::DVEntry::EQ] =
2792       SE->getMulExpr(PositivePart, Bound[K].Iterations);
2793   }
2794   else {
2795     // If the positive/negative part of the difference is 0,
2796     // we won't need to know the number of iterations.
2797     const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2798     const SCEV *NegativePart = getNegativePart(Delta);
2799     if (NegativePart->isZero())
2800       Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero
2801     const SCEV *PositivePart = getPositivePart(Delta);
2802     if (PositivePart->isZero())
2803       Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero
2804   }
2805 }
2806 
2807 
2808 // Computes the upper and lower bounds for level K
2809 // using the < direction. Records them in Bound.
2810 // Wolfe gives the equations
2811 //
2812 //    LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2813 //    UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2814 //
2815 // Since we normalize loops, we can simplify these equations to
2816 //
2817 //    LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k
2818 //    UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k
2819 //
2820 // We must be careful to handle the case where the upper bound is unknown.
2821 void DependenceInfo::findBoundsLT(CoefficientInfo *A, CoefficientInfo *B,
2822                                   BoundInfo *Bound, unsigned K) const {
2823   Bound[K].Lower[Dependence::DVEntry::LT] = nullptr; // Default value = -infinity.
2824   Bound[K].Upper[Dependence::DVEntry::LT] = nullptr; // Default value = +infinity.
2825   if (Bound[K].Iterations) {
2826     const SCEV *Iter_1 = SE->getMinusSCEV(
2827         Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
2828     const SCEV *NegPart =
2829       getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2830     Bound[K].Lower[Dependence::DVEntry::LT] =
2831       SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff);
2832     const SCEV *PosPart =
2833       getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2834     Bound[K].Upper[Dependence::DVEntry::LT] =
2835       SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff);
2836   }
2837   else {
2838     // If the positive/negative part of the difference is 0,
2839     // we won't need to know the number of iterations.
2840     const SCEV *NegPart =
2841       getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2842     if (NegPart->isZero())
2843       Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2844     const SCEV *PosPart =
2845       getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2846     if (PosPart->isZero())
2847       Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2848   }
2849 }
2850 
2851 
2852 // Computes the upper and lower bounds for level K
2853 // using the > direction. Records them in Bound.
2854 // Wolfe gives the equations
2855 //
2856 //    LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2857 //    UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2858 //
2859 // Since we normalize loops, we can simplify these equations to
2860 //
2861 //    LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k
2862 //    UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k
2863 //
2864 // We must be careful to handle the case where the upper bound is unknown.
2865 void DependenceInfo::findBoundsGT(CoefficientInfo *A, CoefficientInfo *B,
2866                                   BoundInfo *Bound, unsigned K) const {
2867   Bound[K].Lower[Dependence::DVEntry::GT] = nullptr; // Default value = -infinity.
2868   Bound[K].Upper[Dependence::DVEntry::GT] = nullptr; // Default value = +infinity.
2869   if (Bound[K].Iterations) {
2870     const SCEV *Iter_1 = SE->getMinusSCEV(
2871         Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
2872     const SCEV *NegPart =
2873       getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2874     Bound[K].Lower[Dependence::DVEntry::GT] =
2875       SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff);
2876     const SCEV *PosPart =
2877       getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2878     Bound[K].Upper[Dependence::DVEntry::GT] =
2879       SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff);
2880   }
2881   else {
2882     // If the positive/negative part of the difference is 0,
2883     // we won't need to know the number of iterations.
2884     const SCEV *NegPart = getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2885     if (NegPart->isZero())
2886       Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff;
2887     const SCEV *PosPart = getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2888     if (PosPart->isZero())
2889       Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff;
2890   }
2891 }
2892 
2893 
2894 // X^+ = max(X, 0)
2895 const SCEV *DependenceInfo::getPositivePart(const SCEV *X) const {
2896   return SE->getSMaxExpr(X, SE->getZero(X->getType()));
2897 }
2898 
2899 
2900 // X^- = min(X, 0)
2901 const SCEV *DependenceInfo::getNegativePart(const SCEV *X) const {
2902   return SE->getSMinExpr(X, SE->getZero(X->getType()));
2903 }
2904 
2905 
2906 // Walks through the subscript,
2907 // collecting each coefficient, the associated loop bounds,
2908 // and recording its positive and negative parts for later use.
2909 DependenceInfo::CoefficientInfo *
2910 DependenceInfo::collectCoeffInfo(const SCEV *Subscript, bool SrcFlag,
2911                                  const SCEV *&Constant) const {
2912   const SCEV *Zero = SE->getZero(Subscript->getType());
2913   CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1];
2914   for (unsigned K = 1; K <= MaxLevels; ++K) {
2915     CI[K].Coeff = Zero;
2916     CI[K].PosPart = Zero;
2917     CI[K].NegPart = Zero;
2918     CI[K].Iterations = nullptr;
2919   }
2920   while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
2921     const Loop *L = AddRec->getLoop();
2922     unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L);
2923     CI[K].Coeff = AddRec->getStepRecurrence(*SE);
2924     CI[K].PosPart = getPositivePart(CI[K].Coeff);
2925     CI[K].NegPart = getNegativePart(CI[K].Coeff);
2926     CI[K].Iterations = collectUpperBound(L, Subscript->getType());
2927     Subscript = AddRec->getStart();
2928   }
2929   Constant = Subscript;
2930 #ifndef NDEBUG
2931   LLVM_DEBUG(dbgs() << "\tCoefficient Info\n");
2932   for (unsigned K = 1; K <= MaxLevels; ++K) {
2933     LLVM_DEBUG(dbgs() << "\t    " << K << "\t" << *CI[K].Coeff);
2934     LLVM_DEBUG(dbgs() << "\tPos Part = ");
2935     LLVM_DEBUG(dbgs() << *CI[K].PosPart);
2936     LLVM_DEBUG(dbgs() << "\tNeg Part = ");
2937     LLVM_DEBUG(dbgs() << *CI[K].NegPart);
2938     LLVM_DEBUG(dbgs() << "\tUpper Bound = ");
2939     if (CI[K].Iterations)
2940       LLVM_DEBUG(dbgs() << *CI[K].Iterations);
2941     else
2942       LLVM_DEBUG(dbgs() << "+inf");
2943     LLVM_DEBUG(dbgs() << '\n');
2944   }
2945   LLVM_DEBUG(dbgs() << "\t    Constant = " << *Subscript << '\n');
2946 #endif
2947   return CI;
2948 }
2949 
2950 
2951 // Looks through all the bounds info and
2952 // computes the lower bound given the current direction settings
2953 // at each level. If the lower bound for any level is -inf,
2954 // the result is -inf.
2955 const SCEV *DependenceInfo::getLowerBound(BoundInfo *Bound) const {
2956   const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
2957   for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2958     if (Bound[K].Lower[Bound[K].Direction])
2959       Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
2960     else
2961       Sum = nullptr;
2962   }
2963   return Sum;
2964 }
2965 
2966 
2967 // Looks through all the bounds info and
2968 // computes the upper bound given the current direction settings
2969 // at each level. If the upper bound at any level is +inf,
2970 // the result is +inf.
2971 const SCEV *DependenceInfo::getUpperBound(BoundInfo *Bound) const {
2972   const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
2973   for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2974     if (Bound[K].Upper[Bound[K].Direction])
2975       Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
2976     else
2977       Sum = nullptr;
2978   }
2979   return Sum;
2980 }
2981 
2982 
2983 //===----------------------------------------------------------------------===//
2984 // Constraint manipulation for Delta test.
2985 
2986 // Given a linear SCEV,
2987 // return the coefficient (the step)
2988 // corresponding to the specified loop.
2989 // If there isn't one, return 0.
2990 // For example, given a*i + b*j + c*k, finding the coefficient
2991 // corresponding to the j loop would yield b.
2992 const SCEV *DependenceInfo::findCoefficient(const SCEV *Expr,
2993                                             const Loop *TargetLoop) const {
2994   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2995   if (!AddRec)
2996     return SE->getZero(Expr->getType());
2997   if (AddRec->getLoop() == TargetLoop)
2998     return AddRec->getStepRecurrence(*SE);
2999   return findCoefficient(AddRec->getStart(), TargetLoop);
3000 }
3001 
3002 
3003 // Given a linear SCEV,
3004 // return the SCEV given by zeroing out the coefficient
3005 // corresponding to the specified loop.
3006 // For example, given a*i + b*j + c*k, zeroing the coefficient
3007 // corresponding to the j loop would yield a*i + c*k.
3008 const SCEV *DependenceInfo::zeroCoefficient(const SCEV *Expr,
3009                                             const Loop *TargetLoop) const {
3010   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
3011   if (!AddRec)
3012     return Expr; // ignore
3013   if (AddRec->getLoop() == TargetLoop)
3014     return AddRec->getStart();
3015   return SE->getAddRecExpr(zeroCoefficient(AddRec->getStart(), TargetLoop),
3016                            AddRec->getStepRecurrence(*SE),
3017                            AddRec->getLoop(),
3018                            AddRec->getNoWrapFlags());
3019 }
3020 
3021 
3022 // Given a linear SCEV Expr,
3023 // return the SCEV given by adding some Value to the
3024 // coefficient corresponding to the specified TargetLoop.
3025 // For example, given a*i + b*j + c*k, adding 1 to the coefficient
3026 // corresponding to the j loop would yield a*i + (b+1)*j + c*k.
3027 const SCEV *DependenceInfo::addToCoefficient(const SCEV *Expr,
3028                                              const Loop *TargetLoop,
3029                                              const SCEV *Value) const {
3030   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
3031   if (!AddRec) // create a new addRec
3032     return SE->getAddRecExpr(Expr,
3033                              Value,
3034                              TargetLoop,
3035                              SCEV::FlagAnyWrap); // Worst case, with no info.
3036   if (AddRec->getLoop() == TargetLoop) {
3037     const SCEV *Sum = SE->getAddExpr(AddRec->getStepRecurrence(*SE), Value);
3038     if (Sum->isZero())
3039       return AddRec->getStart();
3040     return SE->getAddRecExpr(AddRec->getStart(),
3041                              Sum,
3042                              AddRec->getLoop(),
3043                              AddRec->getNoWrapFlags());
3044   }
3045   if (SE->isLoopInvariant(AddRec, TargetLoop))
3046     return SE->getAddRecExpr(AddRec, Value, TargetLoop, SCEV::FlagAnyWrap);
3047   return SE->getAddRecExpr(
3048       addToCoefficient(AddRec->getStart(), TargetLoop, Value),
3049       AddRec->getStepRecurrence(*SE), AddRec->getLoop(),
3050       AddRec->getNoWrapFlags());
3051 }
3052 
3053 
3054 // Review the constraints, looking for opportunities
3055 // to simplify a subscript pair (Src and Dst).
3056 // Return true if some simplification occurs.
3057 // If the simplification isn't exact (that is, if it is conservative
3058 // in terms of dependence), set consistent to false.
3059 // Corresponds to Figure 5 from the paper
3060 //
3061 //            Practical Dependence Testing
3062 //            Goff, Kennedy, Tseng
3063 //            PLDI 1991
3064 bool DependenceInfo::propagate(const SCEV *&Src, const SCEV *&Dst,
3065                                SmallBitVector &Loops,
3066                                SmallVectorImpl<Constraint> &Constraints,
3067                                bool &Consistent) {
3068   bool Result = false;
3069   for (unsigned LI : Loops.set_bits()) {
3070     LLVM_DEBUG(dbgs() << "\t    Constraint[" << LI << "] is");
3071     LLVM_DEBUG(Constraints[LI].dump(dbgs()));
3072     if (Constraints[LI].isDistance())
3073       Result |= propagateDistance(Src, Dst, Constraints[LI], Consistent);
3074     else if (Constraints[LI].isLine())
3075       Result |= propagateLine(Src, Dst, Constraints[LI], Consistent);
3076     else if (Constraints[LI].isPoint())
3077       Result |= propagatePoint(Src, Dst, Constraints[LI]);
3078   }
3079   return Result;
3080 }
3081 
3082 
3083 // Attempt to propagate a distance
3084 // constraint into a subscript pair (Src and Dst).
3085 // Return true if some simplification occurs.
3086 // If the simplification isn't exact (that is, if it is conservative
3087 // in terms of dependence), set consistent to false.
3088 bool DependenceInfo::propagateDistance(const SCEV *&Src, const SCEV *&Dst,
3089                                        Constraint &CurConstraint,
3090                                        bool &Consistent) {
3091   const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3092   LLVM_DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
3093   const SCEV *A_K = findCoefficient(Src, CurLoop);
3094   if (A_K->isZero())
3095     return false;
3096   const SCEV *DA_K = SE->getMulExpr(A_K, CurConstraint.getD());
3097   Src = SE->getMinusSCEV(Src, DA_K);
3098   Src = zeroCoefficient(Src, CurLoop);
3099   LLVM_DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3100   LLVM_DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
3101   Dst = addToCoefficient(Dst, CurLoop, SE->getNegativeSCEV(A_K));
3102   LLVM_DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
3103   if (!findCoefficient(Dst, CurLoop)->isZero())
3104     Consistent = false;
3105   return true;
3106 }
3107 
3108 
3109 // Attempt to propagate a line
3110 // constraint into a subscript pair (Src and Dst).
3111 // Return true if some simplification occurs.
3112 // If the simplification isn't exact (that is, if it is conservative
3113 // in terms of dependence), set consistent to false.
3114 bool DependenceInfo::propagateLine(const SCEV *&Src, const SCEV *&Dst,
3115                                    Constraint &CurConstraint,
3116                                    bool &Consistent) {
3117   const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3118   const SCEV *A = CurConstraint.getA();
3119   const SCEV *B = CurConstraint.getB();
3120   const SCEV *C = CurConstraint.getC();
3121   LLVM_DEBUG(dbgs() << "\t\tA = " << *A << ", B = " << *B << ", C = " << *C
3122                     << "\n");
3123   LLVM_DEBUG(dbgs() << "\t\tSrc = " << *Src << "\n");
3124   LLVM_DEBUG(dbgs() << "\t\tDst = " << *Dst << "\n");
3125   if (A->isZero()) {
3126     const SCEVConstant *Bconst = dyn_cast<SCEVConstant>(B);
3127     const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3128     if (!Bconst || !Cconst) return false;
3129     APInt Beta = Bconst->getAPInt();
3130     APInt Charlie = Cconst->getAPInt();
3131     APInt CdivB = Charlie.sdiv(Beta);
3132     assert(Charlie.srem(Beta) == 0 && "C should be evenly divisible by B");
3133     const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3134     //    Src = SE->getAddExpr(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3135     Src = SE->getMinusSCEV(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3136     Dst = zeroCoefficient(Dst, CurLoop);
3137     if (!findCoefficient(Src, CurLoop)->isZero())
3138       Consistent = false;
3139   }
3140   else if (B->isZero()) {
3141     const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3142     const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3143     if (!Aconst || !Cconst) return false;
3144     APInt Alpha = Aconst->getAPInt();
3145     APInt Charlie = Cconst->getAPInt();
3146     APInt CdivA = Charlie.sdiv(Alpha);
3147     assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3148     const SCEV *A_K = findCoefficient(Src, CurLoop);
3149     Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3150     Src = zeroCoefficient(Src, CurLoop);
3151     if (!findCoefficient(Dst, CurLoop)->isZero())
3152       Consistent = false;
3153   }
3154   else if (isKnownPredicate(CmpInst::ICMP_EQ, A, B)) {
3155     const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3156     const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3157     if (!Aconst || !Cconst) return false;
3158     APInt Alpha = Aconst->getAPInt();
3159     APInt Charlie = Cconst->getAPInt();
3160     APInt CdivA = Charlie.sdiv(Alpha);
3161     assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3162     const SCEV *A_K = findCoefficient(Src, CurLoop);
3163     Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3164     Src = zeroCoefficient(Src, CurLoop);
3165     Dst = addToCoefficient(Dst, CurLoop, A_K);
3166     if (!findCoefficient(Dst, CurLoop)->isZero())
3167       Consistent = false;
3168   }
3169   else {
3170     // paper is incorrect here, or perhaps just misleading
3171     const SCEV *A_K = findCoefficient(Src, CurLoop);
3172     Src = SE->getMulExpr(Src, A);
3173     Dst = SE->getMulExpr(Dst, A);
3174     Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, C));
3175     Src = zeroCoefficient(Src, CurLoop);
3176     Dst = addToCoefficient(Dst, CurLoop, SE->getMulExpr(A_K, B));
3177     if (!findCoefficient(Dst, CurLoop)->isZero())
3178       Consistent = false;
3179   }
3180   LLVM_DEBUG(dbgs() << "\t\tnew Src = " << *Src << "\n");
3181   LLVM_DEBUG(dbgs() << "\t\tnew Dst = " << *Dst << "\n");
3182   return true;
3183 }
3184 
3185 
3186 // Attempt to propagate a point
3187 // constraint into a subscript pair (Src and Dst).
3188 // Return true if some simplification occurs.
3189 bool DependenceInfo::propagatePoint(const SCEV *&Src, const SCEV *&Dst,
3190                                     Constraint &CurConstraint) {
3191   const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3192   const SCEV *A_K = findCoefficient(Src, CurLoop);
3193   const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3194   const SCEV *XA_K = SE->getMulExpr(A_K, CurConstraint.getX());
3195   const SCEV *YAP_K = SE->getMulExpr(AP_K, CurConstraint.getY());
3196   LLVM_DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
3197   Src = SE->getAddExpr(Src, SE->getMinusSCEV(XA_K, YAP_K));
3198   Src = zeroCoefficient(Src, CurLoop);
3199   LLVM_DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3200   LLVM_DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
3201   Dst = zeroCoefficient(Dst, CurLoop);
3202   LLVM_DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
3203   return true;
3204 }
3205 
3206 
3207 // Update direction vector entry based on the current constraint.
3208 void DependenceInfo::updateDirection(Dependence::DVEntry &Level,
3209                                      const Constraint &CurConstraint) const {
3210   LLVM_DEBUG(dbgs() << "\tUpdate direction, constraint =");
3211   LLVM_DEBUG(CurConstraint.dump(dbgs()));
3212   if (CurConstraint.isAny())
3213     ; // use defaults
3214   else if (CurConstraint.isDistance()) {
3215     // this one is consistent, the others aren't
3216     Level.Scalar = false;
3217     Level.Distance = CurConstraint.getD();
3218     unsigned NewDirection = Dependence::DVEntry::NONE;
3219     if (!SE->isKnownNonZero(Level.Distance)) // if may be zero
3220       NewDirection = Dependence::DVEntry::EQ;
3221     if (!SE->isKnownNonPositive(Level.Distance)) // if may be positive
3222       NewDirection |= Dependence::DVEntry::LT;
3223     if (!SE->isKnownNonNegative(Level.Distance)) // if may be negative
3224       NewDirection |= Dependence::DVEntry::GT;
3225     Level.Direction &= NewDirection;
3226   }
3227   else if (CurConstraint.isLine()) {
3228     Level.Scalar = false;
3229     Level.Distance = nullptr;
3230     // direction should be accurate
3231   }
3232   else if (CurConstraint.isPoint()) {
3233     Level.Scalar = false;
3234     Level.Distance = nullptr;
3235     unsigned NewDirection = Dependence::DVEntry::NONE;
3236     if (!isKnownPredicate(CmpInst::ICMP_NE,
3237                           CurConstraint.getY(),
3238                           CurConstraint.getX()))
3239       // if X may be = Y
3240       NewDirection |= Dependence::DVEntry::EQ;
3241     if (!isKnownPredicate(CmpInst::ICMP_SLE,
3242                           CurConstraint.getY(),
3243                           CurConstraint.getX()))
3244       // if Y may be > X
3245       NewDirection |= Dependence::DVEntry::LT;
3246     if (!isKnownPredicate(CmpInst::ICMP_SGE,
3247                           CurConstraint.getY(),
3248                           CurConstraint.getX()))
3249       // if Y may be < X
3250       NewDirection |= Dependence::DVEntry::GT;
3251     Level.Direction &= NewDirection;
3252   }
3253   else
3254     llvm_unreachable("constraint has unexpected kind");
3255 }
3256 
3257 /// Check if we can delinearize the subscripts. If the SCEVs representing the
3258 /// source and destination array references are recurrences on a nested loop,
3259 /// this function flattens the nested recurrences into separate recurrences
3260 /// for each loop level.
3261 bool DependenceInfo::tryDelinearize(Instruction *Src, Instruction *Dst,
3262                                     SmallVectorImpl<Subscript> &Pair) {
3263   assert(isLoadOrStore(Src) && "instruction is not load or store");
3264   assert(isLoadOrStore(Dst) && "instruction is not load or store");
3265   Value *SrcPtr = getLoadStorePointerOperand(Src);
3266   Value *DstPtr = getLoadStorePointerOperand(Dst);
3267   Loop *SrcLoop = LI->getLoopFor(Src->getParent());
3268   Loop *DstLoop = LI->getLoopFor(Dst->getParent());
3269   const SCEV *SrcAccessFn = SE->getSCEVAtScope(SrcPtr, SrcLoop);
3270   const SCEV *DstAccessFn = SE->getSCEVAtScope(DstPtr, DstLoop);
3271   const SCEVUnknown *SrcBase =
3272       dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3273   const SCEVUnknown *DstBase =
3274       dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3275 
3276   if (!SrcBase || !DstBase || SrcBase != DstBase)
3277     return false;
3278 
3279   SmallVector<const SCEV *, 4> SrcSubscripts, DstSubscripts;
3280 
3281   if (!tryDelinearizeFixedSize(Src, Dst, SrcAccessFn, DstAccessFn,
3282                                SrcSubscripts, DstSubscripts) &&
3283       !tryDelinearizeParametricSize(Src, Dst, SrcAccessFn, DstAccessFn,
3284                                     SrcSubscripts, DstSubscripts))
3285     return false;
3286 
3287   int Size = SrcSubscripts.size();
3288   LLVM_DEBUG({
3289     dbgs() << "\nSrcSubscripts: ";
3290     for (int I = 0; I < Size; I++)
3291       dbgs() << *SrcSubscripts[I];
3292     dbgs() << "\nDstSubscripts: ";
3293     for (int I = 0; I < Size; I++)
3294       dbgs() << *DstSubscripts[I];
3295   });
3296 
3297   // The delinearization transforms a single-subscript MIV dependence test into
3298   // a multi-subscript SIV dependence test that is easier to compute. So we
3299   // resize Pair to contain as many pairs of subscripts as the delinearization
3300   // has found, and then initialize the pairs following the delinearization.
3301   Pair.resize(Size);
3302   for (int I = 0; I < Size; ++I) {
3303     Pair[I].Src = SrcSubscripts[I];
3304     Pair[I].Dst = DstSubscripts[I];
3305     unifySubscriptType(&Pair[I]);
3306   }
3307 
3308   return true;
3309 }
3310 
3311 bool DependenceInfo::tryDelinearizeFixedSize(
3312     Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
3313     const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
3314     SmallVectorImpl<const SCEV *> &DstSubscripts) {
3315 
3316   // In general we cannot safely assume that the subscripts recovered from GEPs
3317   // are in the range of values defined for their corresponding array
3318   // dimensions. For example some C language usage/interpretation make it
3319   // impossible to verify this at compile-time. As such we give up here unless
3320   // we can assume that the subscripts do not overlap into neighboring
3321   // dimensions and that the number of dimensions matches the number of
3322   // subscripts being recovered.
3323   if (!DisableDelinearizationChecks)
3324     return false;
3325 
3326   Value *SrcPtr = getLoadStorePointerOperand(Src);
3327   Value *DstPtr = getLoadStorePointerOperand(Dst);
3328   const SCEVUnknown *SrcBase =
3329       dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3330   const SCEVUnknown *DstBase =
3331       dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3332   assert(SrcBase && DstBase && SrcBase == DstBase &&
3333          "expected src and dst scev unknowns to be equal");
3334 
3335   // Check the simple case where the array dimensions are fixed size.
3336   auto *SrcGEP = dyn_cast<GetElementPtrInst>(SrcPtr);
3337   auto *DstGEP = dyn_cast<GetElementPtrInst>(DstPtr);
3338   if (!SrcGEP || !DstGEP)
3339     return false;
3340 
3341   SmallVector<int, 4> SrcSizes, DstSizes;
3342   SE->getIndexExpressionsFromGEP(SrcGEP, SrcSubscripts, SrcSizes);
3343   SE->getIndexExpressionsFromGEP(DstGEP, DstSubscripts, DstSizes);
3344 
3345   // Check that the two size arrays are non-empty and equal in length and
3346   // value.
3347   if (SrcSizes.empty() || SrcSubscripts.size() <= 1 ||
3348       SrcSizes.size() != DstSizes.size() ||
3349       !std::equal(SrcSizes.begin(), SrcSizes.end(), DstSizes.begin())) {
3350     SrcSubscripts.clear();
3351     DstSubscripts.clear();
3352     return false;
3353   }
3354 
3355   Value *SrcBasePtr = SrcGEP->getOperand(0);
3356   Value *DstBasePtr = DstGEP->getOperand(0);
3357   while (auto *PCast = dyn_cast<BitCastInst>(SrcBasePtr))
3358     SrcBasePtr = PCast->getOperand(0);
3359   while (auto *PCast = dyn_cast<BitCastInst>(DstBasePtr))
3360     DstBasePtr = PCast->getOperand(0);
3361 
3362   // Check that for identical base pointers we do not miss index offsets
3363   // that have been added before this GEP is applied.
3364   if (SrcBasePtr == SrcBase->getValue() && DstBasePtr == DstBase->getValue()) {
3365     assert(SrcSubscripts.size() == DstSubscripts.size() &&
3366            SrcSubscripts.size() == SrcSizes.size() + 1 &&
3367            "Expected equal number of entries in the list of sizes and "
3368            "subscripts.");
3369     LLVM_DEBUG({
3370       dbgs() << "Delinearized subscripts of fixed-size array\n"
3371              << "SrcGEP:" << *SrcGEP << "\n"
3372              << "DstGEP:" << *DstGEP << "\n";
3373     });
3374     return true;
3375   }
3376 
3377   SrcSubscripts.clear();
3378   DstSubscripts.clear();
3379   return false;
3380 }
3381 
3382 bool DependenceInfo::tryDelinearizeParametricSize(
3383     Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
3384     const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
3385     SmallVectorImpl<const SCEV *> &DstSubscripts) {
3386 
3387   Value *SrcPtr = getLoadStorePointerOperand(Src);
3388   Value *DstPtr = getLoadStorePointerOperand(Dst);
3389   const SCEVUnknown *SrcBase =
3390       dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3391   const SCEVUnknown *DstBase =
3392       dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3393   assert(SrcBase && DstBase && SrcBase == DstBase &&
3394          "expected src and dst scev unknowns to be equal");
3395 
3396   const SCEV *ElementSize = SE->getElementSize(Src);
3397   if (ElementSize != SE->getElementSize(Dst))
3398     return false;
3399 
3400   const SCEV *SrcSCEV = SE->getMinusSCEV(SrcAccessFn, SrcBase);
3401   const SCEV *DstSCEV = SE->getMinusSCEV(DstAccessFn, DstBase);
3402 
3403   const SCEVAddRecExpr *SrcAR = dyn_cast<SCEVAddRecExpr>(SrcSCEV);
3404   const SCEVAddRecExpr *DstAR = dyn_cast<SCEVAddRecExpr>(DstSCEV);
3405   if (!SrcAR || !DstAR || !SrcAR->isAffine() || !DstAR->isAffine())
3406     return false;
3407 
3408   // First step: collect parametric terms in both array references.
3409   SmallVector<const SCEV *, 4> Terms;
3410   SE->collectParametricTerms(SrcAR, Terms);
3411   SE->collectParametricTerms(DstAR, Terms);
3412 
3413   // Second step: find subscript sizes.
3414   SmallVector<const SCEV *, 4> Sizes;
3415   SE->findArrayDimensions(Terms, Sizes, ElementSize);
3416 
3417   // Third step: compute the access functions for each subscript.
3418   SE->computeAccessFunctions(SrcAR, SrcSubscripts, Sizes);
3419   SE->computeAccessFunctions(DstAR, DstSubscripts, Sizes);
3420 
3421   // Fail when there is only a subscript: that's a linearized access function.
3422   if (SrcSubscripts.size() < 2 || DstSubscripts.size() < 2 ||
3423       SrcSubscripts.size() != DstSubscripts.size())
3424     return false;
3425 
3426   size_t Size = SrcSubscripts.size();
3427 
3428   // Statically check that the array bounds are in-range. The first subscript we
3429   // don't have a size for and it cannot overflow into another subscript, so is
3430   // always safe. The others need to be 0 <= subscript[i] < bound, for both src
3431   // and dst.
3432   // FIXME: It may be better to record these sizes and add them as constraints
3433   // to the dependency checks.
3434   if (!DisableDelinearizationChecks)
3435     for (size_t I = 1; I < Size; ++I) {
3436       if (!isKnownNonNegative(SrcSubscripts[I], SrcPtr))
3437         return false;
3438 
3439       if (!isKnownLessThan(SrcSubscripts[I], Sizes[I - 1]))
3440         return false;
3441 
3442       if (!isKnownNonNegative(DstSubscripts[I], DstPtr))
3443         return false;
3444 
3445       if (!isKnownLessThan(DstSubscripts[I], Sizes[I - 1]))
3446         return false;
3447     }
3448 
3449   return true;
3450 }
3451 
3452 //===----------------------------------------------------------------------===//
3453 
3454 #ifndef NDEBUG
3455 // For debugging purposes, dump a small bit vector to dbgs().
3456 static void dumpSmallBitVector(SmallBitVector &BV) {
3457   dbgs() << "{";
3458   for (unsigned VI : BV.set_bits()) {
3459     dbgs() << VI;
3460     if (BV.find_next(VI) >= 0)
3461       dbgs() << ' ';
3462   }
3463   dbgs() << "}\n";
3464 }
3465 #endif
3466 
3467 bool DependenceInfo::invalidate(Function &F, const PreservedAnalyses &PA,
3468                                 FunctionAnalysisManager::Invalidator &Inv) {
3469   // Check if the analysis itself has been invalidated.
3470   auto PAC = PA.getChecker<DependenceAnalysis>();
3471   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
3472     return true;
3473 
3474   // Check transitive dependencies.
3475   return Inv.invalidate<AAManager>(F, PA) ||
3476          Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
3477          Inv.invalidate<LoopAnalysis>(F, PA);
3478 }
3479 
3480 // depends -
3481 // Returns NULL if there is no dependence.
3482 // Otherwise, return a Dependence with as many details as possible.
3483 // Corresponds to Section 3.1 in the paper
3484 //
3485 //            Practical Dependence Testing
3486 //            Goff, Kennedy, Tseng
3487 //            PLDI 1991
3488 //
3489 // Care is required to keep the routine below, getSplitIteration(),
3490 // up to date with respect to this routine.
3491 std::unique_ptr<Dependence>
3492 DependenceInfo::depends(Instruction *Src, Instruction *Dst,
3493                         bool PossiblyLoopIndependent) {
3494   if (Src == Dst)
3495     PossiblyLoopIndependent = false;
3496 
3497   if (!(Src->mayReadOrWriteMemory() && Dst->mayReadOrWriteMemory()))
3498     // if both instructions don't reference memory, there's no dependence
3499     return nullptr;
3500 
3501   if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
3502     // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
3503     LLVM_DEBUG(dbgs() << "can only handle simple loads and stores\n");
3504     return std::make_unique<Dependence>(Src, Dst);
3505   }
3506 
3507   assert(isLoadOrStore(Src) && "instruction is not load or store");
3508   assert(isLoadOrStore(Dst) && "instruction is not load or store");
3509   Value *SrcPtr = getLoadStorePointerOperand(Src);
3510   Value *DstPtr = getLoadStorePointerOperand(Dst);
3511 
3512   switch (underlyingObjectsAlias(AA, F->getParent()->getDataLayout(),
3513                                  MemoryLocation::get(Dst),
3514                                  MemoryLocation::get(Src))) {
3515   case MayAlias:
3516   case PartialAlias:
3517     // cannot analyse objects if we don't understand their aliasing.
3518     LLVM_DEBUG(dbgs() << "can't analyze may or partial alias\n");
3519     return std::make_unique<Dependence>(Src, Dst);
3520   case NoAlias:
3521     // If the objects noalias, they are distinct, accesses are independent.
3522     LLVM_DEBUG(dbgs() << "no alias\n");
3523     return nullptr;
3524   case MustAlias:
3525     break; // The underlying objects alias; test accesses for dependence.
3526   }
3527 
3528   // establish loop nesting levels
3529   establishNestingLevels(Src, Dst);
3530   LLVM_DEBUG(dbgs() << "    common nesting levels = " << CommonLevels << "\n");
3531   LLVM_DEBUG(dbgs() << "    maximum nesting levels = " << MaxLevels << "\n");
3532 
3533   FullDependence Result(Src, Dst, PossiblyLoopIndependent, CommonLevels);
3534   ++TotalArrayPairs;
3535 
3536   unsigned Pairs = 1;
3537   SmallVector<Subscript, 2> Pair(Pairs);
3538   const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3539   const SCEV *DstSCEV = SE->getSCEV(DstPtr);
3540   LLVM_DEBUG(dbgs() << "    SrcSCEV = " << *SrcSCEV << "\n");
3541   LLVM_DEBUG(dbgs() << "    DstSCEV = " << *DstSCEV << "\n");
3542   Pair[0].Src = SrcSCEV;
3543   Pair[0].Dst = DstSCEV;
3544 
3545   if (Delinearize) {
3546     if (tryDelinearize(Src, Dst, Pair)) {
3547       LLVM_DEBUG(dbgs() << "    delinearized\n");
3548       Pairs = Pair.size();
3549     }
3550   }
3551 
3552   for (unsigned P = 0; P < Pairs; ++P) {
3553     Pair[P].Loops.resize(MaxLevels + 1);
3554     Pair[P].GroupLoops.resize(MaxLevels + 1);
3555     Pair[P].Group.resize(Pairs);
3556     removeMatchingExtensions(&Pair[P]);
3557     Pair[P].Classification =
3558       classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3559                    Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
3560                    Pair[P].Loops);
3561     Pair[P].GroupLoops = Pair[P].Loops;
3562     Pair[P].Group.set(P);
3563     LLVM_DEBUG(dbgs() << "    subscript " << P << "\n");
3564     LLVM_DEBUG(dbgs() << "\tsrc = " << *Pair[P].Src << "\n");
3565     LLVM_DEBUG(dbgs() << "\tdst = " << *Pair[P].Dst << "\n");
3566     LLVM_DEBUG(dbgs() << "\tclass = " << Pair[P].Classification << "\n");
3567     LLVM_DEBUG(dbgs() << "\tloops = ");
3568     LLVM_DEBUG(dumpSmallBitVector(Pair[P].Loops));
3569   }
3570 
3571   SmallBitVector Separable(Pairs);
3572   SmallBitVector Coupled(Pairs);
3573 
3574   // Partition subscripts into separable and minimally-coupled groups
3575   // Algorithm in paper is algorithmically better;
3576   // this may be faster in practice. Check someday.
3577   //
3578   // Here's an example of how it works. Consider this code:
3579   //
3580   //   for (i = ...) {
3581   //     for (j = ...) {
3582   //       for (k = ...) {
3583   //         for (l = ...) {
3584   //           for (m = ...) {
3585   //             A[i][j][k][m] = ...;
3586   //             ... = A[0][j][l][i + j];
3587   //           }
3588   //         }
3589   //       }
3590   //     }
3591   //   }
3592   //
3593   // There are 4 subscripts here:
3594   //    0 [i] and [0]
3595   //    1 [j] and [j]
3596   //    2 [k] and [l]
3597   //    3 [m] and [i + j]
3598   //
3599   // We've already classified each subscript pair as ZIV, SIV, etc.,
3600   // and collected all the loops mentioned by pair P in Pair[P].Loops.
3601   // In addition, we've initialized Pair[P].GroupLoops to Pair[P].Loops
3602   // and set Pair[P].Group = {P}.
3603   //
3604   //      Src Dst    Classification Loops  GroupLoops Group
3605   //    0 [i] [0]         SIV       {1}      {1}        {0}
3606   //    1 [j] [j]         SIV       {2}      {2}        {1}
3607   //    2 [k] [l]         RDIV      {3,4}    {3,4}      {2}
3608   //    3 [m] [i + j]     MIV       {1,2,5}  {1,2,5}    {3}
3609   //
3610   // For each subscript SI 0 .. 3, we consider each remaining subscript, SJ.
3611   // So, 0 is compared against 1, 2, and 3; 1 is compared against 2 and 3, etc.
3612   //
3613   // We begin by comparing 0 and 1. The intersection of the GroupLoops is empty.
3614   // Next, 0 and 2. Again, the intersection of their GroupLoops is empty.
3615   // Next 0 and 3. The intersection of their GroupLoop = {1}, not empty,
3616   // so Pair[3].Group = {0,3} and Done = false (that is, 0 will not be added
3617   // to either Separable or Coupled).
3618   //
3619   // Next, we consider 1 and 2. The intersection of the GroupLoops is empty.
3620   // Next, 1 and 3. The intersection of their GroupLoops = {2}, not empty,
3621   // so Pair[3].Group = {0, 1, 3} and Done = false.
3622   //
3623   // Next, we compare 2 against 3. The intersection of the GroupLoops is empty.
3624   // Since Done remains true, we add 2 to the set of Separable pairs.
3625   //
3626   // Finally, we consider 3. There's nothing to compare it with,
3627   // so Done remains true and we add it to the Coupled set.
3628   // Pair[3].Group = {0, 1, 3} and GroupLoops = {1, 2, 5}.
3629   //
3630   // In the end, we've got 1 separable subscript and 1 coupled group.
3631   for (unsigned SI = 0; SI < Pairs; ++SI) {
3632     if (Pair[SI].Classification == Subscript::NonLinear) {
3633       // ignore these, but collect loops for later
3634       ++NonlinearSubscriptPairs;
3635       collectCommonLoops(Pair[SI].Src,
3636                          LI->getLoopFor(Src->getParent()),
3637                          Pair[SI].Loops);
3638       collectCommonLoops(Pair[SI].Dst,
3639                          LI->getLoopFor(Dst->getParent()),
3640                          Pair[SI].Loops);
3641       Result.Consistent = false;
3642     } else if (Pair[SI].Classification == Subscript::ZIV) {
3643       // always separable
3644       Separable.set(SI);
3645     }
3646     else {
3647       // SIV, RDIV, or MIV, so check for coupled group
3648       bool Done = true;
3649       for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
3650         SmallBitVector Intersection = Pair[SI].GroupLoops;
3651         Intersection &= Pair[SJ].GroupLoops;
3652         if (Intersection.any()) {
3653           // accumulate set of all the loops in group
3654           Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
3655           // accumulate set of all subscripts in group
3656           Pair[SJ].Group |= Pair[SI].Group;
3657           Done = false;
3658         }
3659       }
3660       if (Done) {
3661         if (Pair[SI].Group.count() == 1) {
3662           Separable.set(SI);
3663           ++SeparableSubscriptPairs;
3664         }
3665         else {
3666           Coupled.set(SI);
3667           ++CoupledSubscriptPairs;
3668         }
3669       }
3670     }
3671   }
3672 
3673   LLVM_DEBUG(dbgs() << "    Separable = ");
3674   LLVM_DEBUG(dumpSmallBitVector(Separable));
3675   LLVM_DEBUG(dbgs() << "    Coupled = ");
3676   LLVM_DEBUG(dumpSmallBitVector(Coupled));
3677 
3678   Constraint NewConstraint;
3679   NewConstraint.setAny(SE);
3680 
3681   // test separable subscripts
3682   for (unsigned SI : Separable.set_bits()) {
3683     LLVM_DEBUG(dbgs() << "testing subscript " << SI);
3684     switch (Pair[SI].Classification) {
3685     case Subscript::ZIV:
3686       LLVM_DEBUG(dbgs() << ", ZIV\n");
3687       if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
3688         return nullptr;
3689       break;
3690     case Subscript::SIV: {
3691       LLVM_DEBUG(dbgs() << ", SIV\n");
3692       unsigned Level;
3693       const SCEV *SplitIter = nullptr;
3694       if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level, Result, NewConstraint,
3695                   SplitIter))
3696         return nullptr;
3697       break;
3698     }
3699     case Subscript::RDIV:
3700       LLVM_DEBUG(dbgs() << ", RDIV\n");
3701       if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
3702         return nullptr;
3703       break;
3704     case Subscript::MIV:
3705       LLVM_DEBUG(dbgs() << ", MIV\n");
3706       if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
3707         return nullptr;
3708       break;
3709     default:
3710       llvm_unreachable("subscript has unexpected classification");
3711     }
3712   }
3713 
3714   if (Coupled.count()) {
3715     // test coupled subscript groups
3716     LLVM_DEBUG(dbgs() << "starting on coupled subscripts\n");
3717     LLVM_DEBUG(dbgs() << "MaxLevels + 1 = " << MaxLevels + 1 << "\n");
3718     SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
3719     for (unsigned II = 0; II <= MaxLevels; ++II)
3720       Constraints[II].setAny(SE);
3721     for (unsigned SI : Coupled.set_bits()) {
3722       LLVM_DEBUG(dbgs() << "testing subscript group " << SI << " { ");
3723       SmallBitVector Group(Pair[SI].Group);
3724       SmallBitVector Sivs(Pairs);
3725       SmallBitVector Mivs(Pairs);
3726       SmallBitVector ConstrainedLevels(MaxLevels + 1);
3727       SmallVector<Subscript *, 4> PairsInGroup;
3728       for (unsigned SJ : Group.set_bits()) {
3729         LLVM_DEBUG(dbgs() << SJ << " ");
3730         if (Pair[SJ].Classification == Subscript::SIV)
3731           Sivs.set(SJ);
3732         else
3733           Mivs.set(SJ);
3734         PairsInGroup.push_back(&Pair[SJ]);
3735       }
3736       unifySubscriptType(PairsInGroup);
3737       LLVM_DEBUG(dbgs() << "}\n");
3738       while (Sivs.any()) {
3739         bool Changed = false;
3740         for (unsigned SJ : Sivs.set_bits()) {
3741           LLVM_DEBUG(dbgs() << "testing subscript " << SJ << ", SIV\n");
3742           // SJ is an SIV subscript that's part of the current coupled group
3743           unsigned Level;
3744           const SCEV *SplitIter = nullptr;
3745           LLVM_DEBUG(dbgs() << "SIV\n");
3746           if (testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level, Result, NewConstraint,
3747                       SplitIter))
3748             return nullptr;
3749           ConstrainedLevels.set(Level);
3750           if (intersectConstraints(&Constraints[Level], &NewConstraint)) {
3751             if (Constraints[Level].isEmpty()) {
3752               ++DeltaIndependence;
3753               return nullptr;
3754             }
3755             Changed = true;
3756           }
3757           Sivs.reset(SJ);
3758         }
3759         if (Changed) {
3760           // propagate, possibly creating new SIVs and ZIVs
3761           LLVM_DEBUG(dbgs() << "    propagating\n");
3762           LLVM_DEBUG(dbgs() << "\tMivs = ");
3763           LLVM_DEBUG(dumpSmallBitVector(Mivs));
3764           for (unsigned SJ : Mivs.set_bits()) {
3765             // SJ is an MIV subscript that's part of the current coupled group
3766             LLVM_DEBUG(dbgs() << "\tSJ = " << SJ << "\n");
3767             if (propagate(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops,
3768                           Constraints, Result.Consistent)) {
3769               LLVM_DEBUG(dbgs() << "\t    Changed\n");
3770               ++DeltaPropagations;
3771               Pair[SJ].Classification =
3772                 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
3773                              Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
3774                              Pair[SJ].Loops);
3775               switch (Pair[SJ].Classification) {
3776               case Subscript::ZIV:
3777                 LLVM_DEBUG(dbgs() << "ZIV\n");
3778                 if (testZIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
3779                   return nullptr;
3780                 Mivs.reset(SJ);
3781                 break;
3782               case Subscript::SIV:
3783                 Sivs.set(SJ);
3784                 Mivs.reset(SJ);
3785                 break;
3786               case Subscript::RDIV:
3787               case Subscript::MIV:
3788                 break;
3789               default:
3790                 llvm_unreachable("bad subscript classification");
3791               }
3792             }
3793           }
3794         }
3795       }
3796 
3797       // test & propagate remaining RDIVs
3798       for (unsigned SJ : Mivs.set_bits()) {
3799         if (Pair[SJ].Classification == Subscript::RDIV) {
3800           LLVM_DEBUG(dbgs() << "RDIV test\n");
3801           if (testRDIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
3802             return nullptr;
3803           // I don't yet understand how to propagate RDIV results
3804           Mivs.reset(SJ);
3805         }
3806       }
3807 
3808       // test remaining MIVs
3809       // This code is temporary.
3810       // Better to somehow test all remaining subscripts simultaneously.
3811       for (unsigned SJ : Mivs.set_bits()) {
3812         if (Pair[SJ].Classification == Subscript::MIV) {
3813           LLVM_DEBUG(dbgs() << "MIV test\n");
3814           if (testMIV(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, Result))
3815             return nullptr;
3816         }
3817         else
3818           llvm_unreachable("expected only MIV subscripts at this point");
3819       }
3820 
3821       // update Result.DV from constraint vector
3822       LLVM_DEBUG(dbgs() << "    updating\n");
3823       for (unsigned SJ : ConstrainedLevels.set_bits()) {
3824         if (SJ > CommonLevels)
3825           break;
3826         updateDirection(Result.DV[SJ - 1], Constraints[SJ]);
3827         if (Result.DV[SJ - 1].Direction == Dependence::DVEntry::NONE)
3828           return nullptr;
3829       }
3830     }
3831   }
3832 
3833   // Make sure the Scalar flags are set correctly.
3834   SmallBitVector CompleteLoops(MaxLevels + 1);
3835   for (unsigned SI = 0; SI < Pairs; ++SI)
3836     CompleteLoops |= Pair[SI].Loops;
3837   for (unsigned II = 1; II <= CommonLevels; ++II)
3838     if (CompleteLoops[II])
3839       Result.DV[II - 1].Scalar = false;
3840 
3841   if (PossiblyLoopIndependent) {
3842     // Make sure the LoopIndependent flag is set correctly.
3843     // All directions must include equal, otherwise no
3844     // loop-independent dependence is possible.
3845     for (unsigned II = 1; II <= CommonLevels; ++II) {
3846       if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) {
3847         Result.LoopIndependent = false;
3848         break;
3849       }
3850     }
3851   }
3852   else {
3853     // On the other hand, if all directions are equal and there's no
3854     // loop-independent dependence possible, then no dependence exists.
3855     bool AllEqual = true;
3856     for (unsigned II = 1; II <= CommonLevels; ++II) {
3857       if (Result.getDirection(II) != Dependence::DVEntry::EQ) {
3858         AllEqual = false;
3859         break;
3860       }
3861     }
3862     if (AllEqual)
3863       return nullptr;
3864   }
3865 
3866   return std::make_unique<FullDependence>(std::move(Result));
3867 }
3868 
3869 //===----------------------------------------------------------------------===//
3870 // getSplitIteration -
3871 // Rather than spend rarely-used space recording the splitting iteration
3872 // during the Weak-Crossing SIV test, we re-compute it on demand.
3873 // The re-computation is basically a repeat of the entire dependence test,
3874 // though simplified since we know that the dependence exists.
3875 // It's tedious, since we must go through all propagations, etc.
3876 //
3877 // Care is required to keep this code up to date with respect to the routine
3878 // above, depends().
3879 //
3880 // Generally, the dependence analyzer will be used to build
3881 // a dependence graph for a function (basically a map from instructions
3882 // to dependences). Looking for cycles in the graph shows us loops
3883 // that cannot be trivially vectorized/parallelized.
3884 //
3885 // We can try to improve the situation by examining all the dependences
3886 // that make up the cycle, looking for ones we can break.
3887 // Sometimes, peeling the first or last iteration of a loop will break
3888 // dependences, and we've got flags for those possibilities.
3889 // Sometimes, splitting a loop at some other iteration will do the trick,
3890 // and we've got a flag for that case. Rather than waste the space to
3891 // record the exact iteration (since we rarely know), we provide
3892 // a method that calculates the iteration. It's a drag that it must work
3893 // from scratch, but wonderful in that it's possible.
3894 //
3895 // Here's an example:
3896 //
3897 //    for (i = 0; i < 10; i++)
3898 //        A[i] = ...
3899 //        ... = A[11 - i]
3900 //
3901 // There's a loop-carried flow dependence from the store to the load,
3902 // found by the weak-crossing SIV test. The dependence will have a flag,
3903 // indicating that the dependence can be broken by splitting the loop.
3904 // Calling getSplitIteration will return 5.
3905 // Splitting the loop breaks the dependence, like so:
3906 //
3907 //    for (i = 0; i <= 5; i++)
3908 //        A[i] = ...
3909 //        ... = A[11 - i]
3910 //    for (i = 6; i < 10; i++)
3911 //        A[i] = ...
3912 //        ... = A[11 - i]
3913 //
3914 // breaks the dependence and allows us to vectorize/parallelize
3915 // both loops.
3916 const SCEV *DependenceInfo::getSplitIteration(const Dependence &Dep,
3917                                               unsigned SplitLevel) {
3918   assert(Dep.isSplitable(SplitLevel) &&
3919          "Dep should be splitable at SplitLevel");
3920   Instruction *Src = Dep.getSrc();
3921   Instruction *Dst = Dep.getDst();
3922   assert(Src->mayReadFromMemory() || Src->mayWriteToMemory());
3923   assert(Dst->mayReadFromMemory() || Dst->mayWriteToMemory());
3924   assert(isLoadOrStore(Src));
3925   assert(isLoadOrStore(Dst));
3926   Value *SrcPtr = getLoadStorePointerOperand(Src);
3927   Value *DstPtr = getLoadStorePointerOperand(Dst);
3928   assert(underlyingObjectsAlias(AA, F->getParent()->getDataLayout(),
3929                                 MemoryLocation::get(Dst),
3930                                 MemoryLocation::get(Src)) == MustAlias);
3931 
3932   // establish loop nesting levels
3933   establishNestingLevels(Src, Dst);
3934 
3935   FullDependence Result(Src, Dst, false, CommonLevels);
3936 
3937   unsigned Pairs = 1;
3938   SmallVector<Subscript, 2> Pair(Pairs);
3939   const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3940   const SCEV *DstSCEV = SE->getSCEV(DstPtr);
3941   Pair[0].Src = SrcSCEV;
3942   Pair[0].Dst = DstSCEV;
3943 
3944   if (Delinearize) {
3945     if (tryDelinearize(Src, Dst, Pair)) {
3946       LLVM_DEBUG(dbgs() << "    delinearized\n");
3947       Pairs = Pair.size();
3948     }
3949   }
3950 
3951   for (unsigned P = 0; P < Pairs; ++P) {
3952     Pair[P].Loops.resize(MaxLevels + 1);
3953     Pair[P].GroupLoops.resize(MaxLevels + 1);
3954     Pair[P].Group.resize(Pairs);
3955     removeMatchingExtensions(&Pair[P]);
3956     Pair[P].Classification =
3957       classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3958                    Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
3959                    Pair[P].Loops);
3960     Pair[P].GroupLoops = Pair[P].Loops;
3961     Pair[P].Group.set(P);
3962   }
3963 
3964   SmallBitVector Separable(Pairs);
3965   SmallBitVector Coupled(Pairs);
3966 
3967   // partition subscripts into separable and minimally-coupled groups
3968   for (unsigned SI = 0; SI < Pairs; ++SI) {
3969     if (Pair[SI].Classification == Subscript::NonLinear) {
3970       // ignore these, but collect loops for later
3971       collectCommonLoops(Pair[SI].Src,
3972                          LI->getLoopFor(Src->getParent()),
3973                          Pair[SI].Loops);
3974       collectCommonLoops(Pair[SI].Dst,
3975                          LI->getLoopFor(Dst->getParent()),
3976                          Pair[SI].Loops);
3977       Result.Consistent = false;
3978     }
3979     else if (Pair[SI].Classification == Subscript::ZIV)
3980       Separable.set(SI);
3981     else {
3982       // SIV, RDIV, or MIV, so check for coupled group
3983       bool Done = true;
3984       for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
3985         SmallBitVector Intersection = Pair[SI].GroupLoops;
3986         Intersection &= Pair[SJ].GroupLoops;
3987         if (Intersection.any()) {
3988           // accumulate set of all the loops in group
3989           Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
3990           // accumulate set of all subscripts in group
3991           Pair[SJ].Group |= Pair[SI].Group;
3992           Done = false;
3993         }
3994       }
3995       if (Done) {
3996         if (Pair[SI].Group.count() == 1)
3997           Separable.set(SI);
3998         else
3999           Coupled.set(SI);
4000       }
4001     }
4002   }
4003 
4004   Constraint NewConstraint;
4005   NewConstraint.setAny(SE);
4006 
4007   // test separable subscripts
4008   for (unsigned SI : Separable.set_bits()) {
4009     switch (Pair[SI].Classification) {
4010     case Subscript::SIV: {
4011       unsigned Level;
4012       const SCEV *SplitIter = nullptr;
4013       (void) testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
4014                      Result, NewConstraint, SplitIter);
4015       if (Level == SplitLevel) {
4016         assert(SplitIter != nullptr);
4017         return SplitIter;
4018       }
4019       break;
4020     }
4021     case Subscript::ZIV:
4022     case Subscript::RDIV:
4023     case Subscript::MIV:
4024       break;
4025     default:
4026       llvm_unreachable("subscript has unexpected classification");
4027     }
4028   }
4029 
4030   if (Coupled.count()) {
4031     // test coupled subscript groups
4032     SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
4033     for (unsigned II = 0; II <= MaxLevels; ++II)
4034       Constraints[II].setAny(SE);
4035     for (unsigned SI : Coupled.set_bits()) {
4036       SmallBitVector Group(Pair[SI].Group);
4037       SmallBitVector Sivs(Pairs);
4038       SmallBitVector Mivs(Pairs);
4039       SmallBitVector ConstrainedLevels(MaxLevels + 1);
4040       for (unsigned SJ : Group.set_bits()) {
4041         if (Pair[SJ].Classification == Subscript::SIV)
4042           Sivs.set(SJ);
4043         else
4044           Mivs.set(SJ);
4045       }
4046       while (Sivs.any()) {
4047         bool Changed = false;
4048         for (unsigned SJ : Sivs.set_bits()) {
4049           // SJ is an SIV subscript that's part of the current coupled group
4050           unsigned Level;
4051           const SCEV *SplitIter = nullptr;
4052           (void) testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
4053                          Result, NewConstraint, SplitIter);
4054           if (Level == SplitLevel && SplitIter)
4055             return SplitIter;
4056           ConstrainedLevels.set(Level);
4057           if (intersectConstraints(&Constraints[Level], &NewConstraint))
4058             Changed = true;
4059           Sivs.reset(SJ);
4060         }
4061         if (Changed) {
4062           // propagate, possibly creating new SIVs and ZIVs
4063           for (unsigned SJ : Mivs.set_bits()) {
4064             // SJ is an MIV subscript that's part of the current coupled group
4065             if (propagate(Pair[SJ].Src, Pair[SJ].Dst,
4066                           Pair[SJ].Loops, Constraints, Result.Consistent)) {
4067               Pair[SJ].Classification =
4068                 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
4069                              Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
4070                              Pair[SJ].Loops);
4071               switch (Pair[SJ].Classification) {
4072               case Subscript::ZIV:
4073                 Mivs.reset(SJ);
4074                 break;
4075               case Subscript::SIV:
4076                 Sivs.set(SJ);
4077                 Mivs.reset(SJ);
4078                 break;
4079               case Subscript::RDIV:
4080               case Subscript::MIV:
4081                 break;
4082               default:
4083                 llvm_unreachable("bad subscript classification");
4084               }
4085             }
4086           }
4087         }
4088       }
4089     }
4090   }
4091   llvm_unreachable("somehow reached end of routine");
4092   return nullptr;
4093 }
4094