OSDN Git Service

Update aosp/master LLVM for rebase to r239765
[android-x86/external-llvm.git] / include / llvm / Analysis / DependenceAnalysis.h
1 //===-- llvm/Analysis/DependenceAnalysis.h -------------------- -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // DependenceAnalysis is an LLVM pass that analyses dependences between memory
11 // accesses. Currently, it is an implementation of the approach 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 // This pass exists to support the DependenceGraph pass. There are two separate
22 // passes because there's a useful separation of concerns. A dependence exists
23 // if two conditions are met:
24 //
25 //    1) Two instructions reference the same memory location, and
26 //    2) There is a flow of control leading from one instruction to the other.
27 //
28 // DependenceAnalysis attacks the first condition; DependenceGraph will attack
29 // the second (it's not yet ready).
30 //
31 // Please note that this is work in progress and the interface is subject to
32 // change.
33 //
34 // Plausible changes:
35 //    Return a set of more precise dependences instead of just one dependence
36 //    summarizing all.
37 //
38 //===----------------------------------------------------------------------===//
39
40 #ifndef LLVM_ANALYSIS_DEPENDENCEANALYSIS_H
41 #define LLVM_ANALYSIS_DEPENDENCEANALYSIS_H
42
43 #include "llvm/ADT/SmallBitVector.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/Pass.h"
47
48 namespace llvm {
49   class AliasAnalysis;
50   class Loop;
51   class LoopInfo;
52   class ScalarEvolution;
53   class SCEV;
54   class SCEVConstant;
55   class raw_ostream;
56
57   /// Dependence - This class represents a dependence between two memory
58   /// memory references in a function. It contains minimal information and
59   /// is used in the very common situation where the compiler is unable to
60   /// determine anything beyond the existence of a dependence; that is, it
61   /// represents a confused dependence (see also FullDependence). In most
62   /// cases (for output, flow, and anti dependences), the dependence implies
63   /// an ordering, where the source must precede the destination; in contrast,
64   /// input dependences are unordered.
65   ///
66   /// When a dependence graph is built, each Dependence will be a member of
67   /// the set of predecessor edges for its destination instruction and a set
68   /// if successor edges for its source instruction. These sets are represented
69   /// as singly-linked lists, with the "next" fields stored in the dependence
70   /// itelf.
71   class Dependence {
72   public:
73     Dependence(Instruction *Source,
74                Instruction *Destination) :
75       Src(Source),
76       Dst(Destination),
77       NextPredecessor(nullptr),
78       NextSuccessor(nullptr) {}
79     virtual ~Dependence() {}
80
81     /// Dependence::DVEntry - Each level in the distance/direction vector
82     /// has a direction (or perhaps a union of several directions), and
83     /// perhaps a distance.
84     struct DVEntry {
85       enum { NONE = 0,
86              LT = 1,
87              EQ = 2,
88              LE = 3,
89              GT = 4,
90              NE = 5,
91              GE = 6,
92              ALL = 7 };
93       unsigned char Direction : 3; // Init to ALL, then refine.
94       bool Scalar    : 1; // Init to true.
95       bool PeelFirst : 1; // Peeling the first iteration will break dependence.
96       bool PeelLast  : 1; // Peeling the last iteration will break the dependence.
97       bool Splitable : 1; // Splitting the loop will break dependence.
98       const SCEV *Distance; // NULL implies no distance available.
99       DVEntry() : Direction(ALL), Scalar(true), PeelFirst(false),
100                   PeelLast(false), Splitable(false), Distance(nullptr) { }
101     };
102
103     /// getSrc - Returns the source instruction for this dependence.
104     ///
105     Instruction *getSrc() const { return Src; }
106
107     /// getDst - Returns the destination instruction for this dependence.
108     ///
109     Instruction *getDst() const { return Dst; }
110
111     /// isInput - Returns true if this is an input dependence.
112     ///
113     bool isInput() const;
114
115     /// isOutput - Returns true if this is an output dependence.
116     ///
117     bool isOutput() const;
118
119     /// isFlow - Returns true if this is a flow (aka true) dependence.
120     ///
121     bool isFlow() const;
122
123     /// isAnti - Returns true if this is an anti dependence.
124     ///
125     bool isAnti() const;
126
127     /// isOrdered - Returns true if dependence is Output, Flow, or Anti
128     ///
129     bool isOrdered() const { return isOutput() || isFlow() || isAnti(); }
130
131     /// isUnordered - Returns true if dependence is Input
132     ///
133     bool isUnordered() const { return isInput(); }
134
135     /// isLoopIndependent - Returns true if this is a loop-independent
136     /// dependence.
137     virtual bool isLoopIndependent() const { return true; }
138
139     /// isConfused - Returns true if this dependence is confused
140     /// (the compiler understands nothing and makes worst-case
141     /// assumptions).
142     virtual bool isConfused() const { return true; }
143
144     /// isConsistent - Returns true if this dependence is consistent
145     /// (occurs every time the source and destination are executed).
146     virtual bool isConsistent() const { return false; }
147
148     /// getLevels - Returns the number of common loops surrounding the
149     /// source and destination of the dependence.
150     virtual unsigned getLevels() const { return 0; }
151
152     /// getDirection - Returns the direction associated with a particular
153     /// level.
154     virtual unsigned getDirection(unsigned Level) const { return DVEntry::ALL; }
155
156     /// getDistance - Returns the distance (or NULL) associated with a
157     /// particular level.
158     virtual const SCEV *getDistance(unsigned Level) const { return nullptr; }
159
160     /// isPeelFirst - Returns true if peeling the first iteration from
161     /// this loop will break this dependence.
162     virtual bool isPeelFirst(unsigned Level) const { return false; }
163
164     /// isPeelLast - Returns true if peeling the last iteration from
165     /// this loop will break this dependence.
166     virtual bool isPeelLast(unsigned Level) const { return false; }
167
168     /// isSplitable - Returns true if splitting this loop will break
169     /// the dependence.
170     virtual bool isSplitable(unsigned Level) const { return false; }
171
172     /// isScalar - Returns true if a particular level is scalar; that is,
173     /// if no subscript in the source or destination mention the induction
174     /// variable associated with the loop at this level.
175     virtual bool isScalar(unsigned Level) const;
176
177     /// getNextPredecessor - Returns the value of the NextPredecessor
178     /// field.
179     const Dependence *getNextPredecessor() const {
180       return NextPredecessor;
181     }
182     
183     /// getNextSuccessor - Returns the value of the NextSuccessor
184     /// field.
185     const Dependence *getNextSuccessor() const {
186       return NextSuccessor;
187     }
188     
189     /// setNextPredecessor - Sets the value of the NextPredecessor
190     /// field.
191     void setNextPredecessor(const Dependence *pred) {
192       NextPredecessor = pred;
193     }
194     
195     /// setNextSuccessor - Sets the value of the NextSuccessor
196     /// field.
197     void setNextSuccessor(const Dependence *succ) {
198       NextSuccessor = succ;
199     }
200     
201     /// dump - For debugging purposes, dumps a dependence to OS.
202     ///
203     void dump(raw_ostream &OS) const;
204   private:
205     Instruction *Src, *Dst;
206     const Dependence *NextPredecessor, *NextSuccessor;
207     friend class DependenceAnalysis;
208   };
209
210
211   /// FullDependence - This class represents a dependence between two memory
212   /// references in a function. It contains detailed information about the
213   /// dependence (direction vectors, etc.) and is used when the compiler is
214   /// able to accurately analyze the interaction of the references; that is,
215   /// it is not a confused dependence (see Dependence). In most cases
216   /// (for output, flow, and anti dependences), the dependence implies an
217   /// ordering, where the source must precede the destination; in contrast,
218   /// input dependences are unordered.
219   class FullDependence : public Dependence {
220   public:
221     FullDependence(Instruction *Src, Instruction *Dst, bool LoopIndependent,
222                    unsigned Levels);
223     ~FullDependence() override { delete[] DV; }
224
225     /// isLoopIndependent - Returns true if this is a loop-independent
226     /// dependence.
227     bool isLoopIndependent() const override { return LoopIndependent; }
228
229     /// isConfused - Returns true if this dependence is confused
230     /// (the compiler understands nothing and makes worst-case
231     /// assumptions).
232     bool isConfused() const override { return false; }
233
234     /// isConsistent - Returns true if this dependence is consistent
235     /// (occurs every time the source and destination are executed).
236     bool isConsistent() const override { return Consistent; }
237
238     /// getLevels - Returns the number of common loops surrounding the
239     /// source and destination of the dependence.
240     unsigned getLevels() const override { return Levels; }
241
242     /// getDirection - Returns the direction associated with a particular
243     /// level.
244     unsigned getDirection(unsigned Level) const override;
245
246     /// getDistance - Returns the distance (or NULL) associated with a
247     /// particular level.
248     const SCEV *getDistance(unsigned Level) const override;
249
250     /// isPeelFirst - Returns true if peeling the first iteration from
251     /// this loop will break this dependence.
252     bool isPeelFirst(unsigned Level) const override;
253
254     /// isPeelLast - Returns true if peeling the last iteration from
255     /// this loop will break this dependence.
256     bool isPeelLast(unsigned Level) const override;
257
258     /// isSplitable - Returns true if splitting the loop will break
259     /// the dependence.
260     bool isSplitable(unsigned Level) const override;
261
262     /// isScalar - Returns true if a particular level is scalar; that is,
263     /// if no subscript in the source or destination mention the induction
264     /// variable associated with the loop at this level.
265     bool isScalar(unsigned Level) const override;
266
267   private:
268     unsigned short Levels;
269     bool LoopIndependent;
270     bool Consistent; // Init to true, then refine.
271     DVEntry *DV;
272     friend class DependenceAnalysis;
273   };
274
275
276   /// DependenceAnalysis - This class is the main dependence-analysis driver.
277   ///
278   class DependenceAnalysis : public FunctionPass {
279     void operator=(const DependenceAnalysis &) = delete;
280     DependenceAnalysis(const DependenceAnalysis &) = delete;
281   public:
282     /// depends - Tests for a dependence between the Src and Dst instructions.
283     /// Returns NULL if no dependence; otherwise, returns a Dependence (or a
284     /// FullDependence) with as much information as can be gleaned.
285     /// The flag PossiblyLoopIndependent should be set by the caller
286     /// if it appears that control flow can reach from Src to Dst
287     /// without traversing a loop back edge.
288     std::unique_ptr<Dependence> depends(Instruction *Src,
289                                         Instruction *Dst,
290                                         bool PossiblyLoopIndependent);
291
292     /// getSplitIteration - Give a dependence that's splittable at some
293     /// particular level, return the iteration that should be used to split
294     /// the loop.
295     ///
296     /// Generally, the dependence analyzer will be used to build
297     /// a dependence graph for a function (basically a map from instructions
298     /// to dependences). Looking for cycles in the graph shows us loops
299     /// that cannot be trivially vectorized/parallelized.
300     ///
301     /// We can try to improve the situation by examining all the dependences
302     /// that make up the cycle, looking for ones we can break.
303     /// Sometimes, peeling the first or last iteration of a loop will break
304     /// dependences, and there are flags for those possibilities.
305     /// Sometimes, splitting a loop at some other iteration will do the trick,
306     /// and we've got a flag for that case. Rather than waste the space to
307     /// record the exact iteration (since we rarely know), we provide
308     /// a method that calculates the iteration. It's a drag that it must work
309     /// from scratch, but wonderful in that it's possible.
310     ///
311     /// Here's an example:
312     ///
313     ///    for (i = 0; i < 10; i++)
314     ///        A[i] = ...
315     ///        ... = A[11 - i]
316     ///
317     /// There's a loop-carried flow dependence from the store to the load,
318     /// found by the weak-crossing SIV test. The dependence will have a flag,
319     /// indicating that the dependence can be broken by splitting the loop.
320     /// Calling getSplitIteration will return 5.
321     /// Splitting the loop breaks the dependence, like so:
322     ///
323     ///    for (i = 0; i <= 5; i++)
324     ///        A[i] = ...
325     ///        ... = A[11 - i]
326     ///    for (i = 6; i < 10; i++)
327     ///        A[i] = ...
328     ///        ... = A[11 - i]
329     ///
330     /// breaks the dependence and allows us to vectorize/parallelize
331     /// both loops.
332     const SCEV *getSplitIteration(const Dependence &Dep, unsigned Level);
333
334   private:
335     AliasAnalysis *AA;
336     ScalarEvolution *SE;
337     LoopInfo *LI;
338     Function *F;
339
340     /// Subscript - This private struct represents a pair of subscripts from
341     /// a pair of potentially multi-dimensional array references. We use a
342     /// vector of them to guide subscript partitioning.
343     struct Subscript {
344       const SCEV *Src;
345       const SCEV *Dst;
346       enum ClassificationKind { ZIV, SIV, RDIV, MIV, NonLinear } Classification;
347       SmallBitVector Loops;
348       SmallBitVector GroupLoops;
349       SmallBitVector Group;
350     };
351
352     struct CoefficientInfo {
353       const SCEV *Coeff;
354       const SCEV *PosPart;
355       const SCEV *NegPart;
356       const SCEV *Iterations;
357     };
358
359     struct BoundInfo {
360       const SCEV *Iterations;
361       const SCEV *Upper[8];
362       const SCEV *Lower[8];
363       unsigned char Direction;
364       unsigned char DirSet;
365     };
366
367     /// Constraint - This private class represents a constraint, as defined
368     /// in the paper
369     ///
370     ///           Practical Dependence Testing
371     ///           Goff, Kennedy, Tseng
372     ///           PLDI 1991
373     ///
374     /// There are 5 kinds of constraint, in a hierarchy.
375     ///   1) Any - indicates no constraint, any dependence is possible.
376     ///   2) Line - A line ax + by = c, where a, b, and c are parameters,
377     ///             representing the dependence equation.
378     ///   3) Distance - The value d of the dependence distance;
379     ///   4) Point - A point <x, y> representing the dependence from
380     ///              iteration x to iteration y.
381     ///   5) Empty - No dependence is possible.
382     class Constraint {
383     private:
384       enum ConstraintKind { Empty, Point, Distance, Line, Any } Kind;
385       ScalarEvolution *SE;
386       const SCEV *A;
387       const SCEV *B;
388       const SCEV *C;
389       const Loop *AssociatedLoop;
390     public:
391       /// isEmpty - Return true if the constraint is of kind Empty.
392       bool isEmpty() const { return Kind == Empty; }
393
394       /// isPoint - Return true if the constraint is of kind Point.
395       bool isPoint() const { return Kind == Point; }
396
397       /// isDistance - Return true if the constraint is of kind Distance.
398       bool isDistance() const { return Kind == Distance; }
399
400       /// isLine - Return true if the constraint is of kind Line.
401       /// Since Distance's can also be represented as Lines, we also return
402       /// true if the constraint is of kind Distance.
403       bool isLine() const { return Kind == Line || Kind == Distance; }
404
405       /// isAny - Return true if the constraint is of kind Any;
406       bool isAny() const { return Kind == Any; }
407
408       /// getX - If constraint is a point <X, Y>, returns X.
409       /// Otherwise assert.
410       const SCEV *getX() const;
411
412       /// getY - If constraint is a point <X, Y>, returns Y.
413       /// Otherwise assert.
414       const SCEV *getY() const;
415
416       /// getA - If constraint is a line AX + BY = C, returns A.
417       /// Otherwise assert.
418       const SCEV *getA() const;
419
420       /// getB - If constraint is a line AX + BY = C, returns B.
421       /// Otherwise assert.
422       const SCEV *getB() const;
423
424       /// getC - If constraint is a line AX + BY = C, returns C.
425       /// Otherwise assert.
426       const SCEV *getC() const;
427
428       /// getD - If constraint is a distance, returns D.
429       /// Otherwise assert.
430       const SCEV *getD() const;
431
432       /// getAssociatedLoop - Returns the loop associated with this constraint.
433       const Loop *getAssociatedLoop() const;
434
435       /// setPoint - Change a constraint to Point.
436       void setPoint(const SCEV *X, const SCEV *Y, const Loop *CurrentLoop);
437
438       /// setLine - Change a constraint to Line.
439       void setLine(const SCEV *A, const SCEV *B,
440                    const SCEV *C, const Loop *CurrentLoop);
441
442       /// setDistance - Change a constraint to Distance.
443       void setDistance(const SCEV *D, const Loop *CurrentLoop);
444
445       /// setEmpty - Change a constraint to Empty.
446       void setEmpty();
447
448       /// setAny - Change a constraint to Any.
449       void setAny(ScalarEvolution *SE);
450
451       /// dump - For debugging purposes. Dumps the constraint
452       /// out to OS.
453       void dump(raw_ostream &OS) const;
454     };
455
456
457     /// establishNestingLevels - Examines the loop nesting of the Src and Dst
458     /// instructions and establishes their shared loops. Sets the variables
459     /// CommonLevels, SrcLevels, and MaxLevels.
460     /// The source and destination instructions needn't be contained in the same
461     /// loop. The routine establishNestingLevels finds the level of most deeply
462     /// nested loop that contains them both, CommonLevels. An instruction that's
463     /// not contained in a loop is at level = 0. MaxLevels is equal to the level
464     /// of the source plus the level of the destination, minus CommonLevels.
465     /// This lets us allocate vectors MaxLevels in length, with room for every
466     /// distinct loop referenced in both the source and destination subscripts.
467     /// The variable SrcLevels is the nesting depth of the source instruction.
468     /// It's used to help calculate distinct loops referenced by the destination.
469     /// Here's the map from loops to levels:
470     ///            0 - unused
471     ///            1 - outermost common loop
472     ///          ... - other common loops
473     /// CommonLevels - innermost common loop
474     ///          ... - loops containing Src but not Dst
475     ///    SrcLevels - innermost loop containing Src but not Dst
476     ///          ... - loops containing Dst but not Src
477     ///    MaxLevels - innermost loop containing Dst but not Src
478     /// Consider the follow code fragment:
479     ///    for (a = ...) {
480     ///      for (b = ...) {
481     ///        for (c = ...) {
482     ///          for (d = ...) {
483     ///            A[] = ...;
484     ///          }
485     ///        }
486     ///        for (e = ...) {
487     ///          for (f = ...) {
488     ///            for (g = ...) {
489     ///              ... = A[];
490     ///            }
491     ///          }
492     ///        }
493     ///      }
494     ///    }
495     /// If we're looking at the possibility of a dependence between the store
496     /// to A (the Src) and the load from A (the Dst), we'll note that they
497     /// have 2 loops in common, so CommonLevels will equal 2 and the direction
498     /// vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
499     /// A map from loop names to level indices would look like
500     ///     a - 1
501     ///     b - 2 = CommonLevels
502     ///     c - 3
503     ///     d - 4 = SrcLevels
504     ///     e - 5
505     ///     f - 6
506     ///     g - 7 = MaxLevels
507     void establishNestingLevels(const Instruction *Src,
508                                 const Instruction *Dst);
509
510     unsigned CommonLevels, SrcLevels, MaxLevels;
511
512     /// mapSrcLoop - Given one of the loops containing the source, return
513     /// its level index in our numbering scheme.
514     unsigned mapSrcLoop(const Loop *SrcLoop) const;
515
516     /// mapDstLoop - Given one of the loops containing the destination,
517     /// return its level index in our numbering scheme.
518     unsigned mapDstLoop(const Loop *DstLoop) const;
519
520     /// isLoopInvariant - Returns true if Expression is loop invariant
521     /// in LoopNest.
522     bool isLoopInvariant(const SCEV *Expression, const Loop *LoopNest) const;
523
524     /// Makes sure all subscript pairs share the same integer type by 
525     /// sign-extending as necessary.
526     /// Sign-extending a subscript is safe because getelementptr assumes the
527     /// array subscripts are signed. 
528     void unifySubscriptType(ArrayRef<Subscript *> Pairs);
529
530     /// removeMatchingExtensions - Examines a subscript pair.
531     /// If the source and destination are identically sign (or zero)
532     /// extended, it strips off the extension in an effort to
533     /// simplify the actual analysis.
534     void removeMatchingExtensions(Subscript *Pair);
535
536     /// collectCommonLoops - Finds the set of loops from the LoopNest that
537     /// have a level <= CommonLevels and are referred to by the SCEV Expression.
538     void collectCommonLoops(const SCEV *Expression,
539                             const Loop *LoopNest,
540                             SmallBitVector &Loops) const;
541
542     /// checkSrcSubscript - Examines the SCEV Src, returning true iff it's
543     /// linear. Collect the set of loops mentioned by Src.
544     bool checkSrcSubscript(const SCEV *Src,
545                            const Loop *LoopNest,
546                            SmallBitVector &Loops);
547
548     /// checkDstSubscript - Examines the SCEV Dst, returning true iff it's
549     /// linear. Collect the set of loops mentioned by Dst.
550     bool checkDstSubscript(const SCEV *Dst,
551                            const Loop *LoopNest,
552                            SmallBitVector &Loops);
553
554     /// isKnownPredicate - Compare X and Y using the predicate Pred.
555     /// Basically a wrapper for SCEV::isKnownPredicate,
556     /// but tries harder, especially in the presence of sign and zero
557     /// extensions and symbolics.
558     bool isKnownPredicate(ICmpInst::Predicate Pred,
559                           const SCEV *X,
560                           const SCEV *Y) const;
561
562     /// collectUpperBound - All subscripts are the same type (on my machine,
563     /// an i64). The loop bound may be a smaller type. collectUpperBound
564     /// find the bound, if available, and zero extends it to the Type T.
565     /// (I zero extend since the bound should always be >= 0.)
566     /// If no upper bound is available, return NULL.
567     const SCEV *collectUpperBound(const Loop *l, Type *T) const;
568
569     /// collectConstantUpperBound - Calls collectUpperBound(), then
570     /// attempts to cast it to SCEVConstant. If the cast fails,
571     /// returns NULL.
572     const SCEVConstant *collectConstantUpperBound(const Loop *l, Type *T) const;
573
574     /// classifyPair - Examines the subscript pair (the Src and Dst SCEVs)
575     /// and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
576     /// Collects the associated loops in a set.
577     Subscript::ClassificationKind classifyPair(const SCEV *Src,
578                                            const Loop *SrcLoopNest,
579                                            const SCEV *Dst,
580                                            const Loop *DstLoopNest,
581                                            SmallBitVector &Loops);
582
583     /// testZIV - Tests the ZIV subscript pair (Src and Dst) for dependence.
584     /// Returns true if any possible dependence is disproved.
585     /// If there might be a dependence, returns false.
586     /// If the dependence isn't proven to exist,
587     /// marks the Result as inconsistent.
588     bool testZIV(const SCEV *Src,
589                  const SCEV *Dst,
590                  FullDependence &Result) const;
591
592     /// testSIV - Tests the SIV subscript pair (Src and Dst) for dependence.
593     /// Things of the form [c1 + a1*i] and [c2 + a2*j], where
594     /// i and j are induction variables, c1 and c2 are loop invariant,
595     /// and a1 and a2 are constant.
596     /// Returns true if any possible dependence is disproved.
597     /// If there might be a dependence, returns false.
598     /// Sets appropriate direction vector entry and, when possible,
599     /// the distance vector entry.
600     /// If the dependence isn't proven to exist,
601     /// marks the Result as inconsistent.
602     bool testSIV(const SCEV *Src,
603                  const SCEV *Dst,
604                  unsigned &Level,
605                  FullDependence &Result,
606                  Constraint &NewConstraint,
607                  const SCEV *&SplitIter) const;
608
609     /// testRDIV - Tests the RDIV subscript pair (Src and Dst) for dependence.
610     /// Things of the form [c1 + a1*i] and [c2 + a2*j]
611     /// where i and j are induction variables, c1 and c2 are loop invariant,
612     /// and a1 and a2 are constant.
613     /// With minor algebra, this test can also be used for things like
614     /// [c1 + a1*i + a2*j][c2].
615     /// Returns true if any possible dependence is disproved.
616     /// If there might be a dependence, returns false.
617     /// Marks the Result as inconsistent.
618     bool testRDIV(const SCEV *Src,
619                   const SCEV *Dst,
620                   FullDependence &Result) const;
621
622     /// testMIV - Tests the MIV subscript pair (Src and Dst) for dependence.
623     /// Returns true if dependence disproved.
624     /// Can sometimes refine direction vectors.
625     bool testMIV(const SCEV *Src,
626                  const SCEV *Dst,
627                  const SmallBitVector &Loops,
628                  FullDependence &Result) const;
629
630     /// strongSIVtest - Tests the strong SIV subscript pair (Src and Dst)
631     /// for dependence.
632     /// Things of the form [c1 + a*i] and [c2 + a*i],
633     /// where i is an induction variable, c1 and c2 are loop invariant,
634     /// and a is a constant
635     /// Returns true if any possible dependence is disproved.
636     /// If there might be a dependence, returns false.
637     /// Sets appropriate direction and distance.
638     bool strongSIVtest(const SCEV *Coeff,
639                        const SCEV *SrcConst,
640                        const SCEV *DstConst,
641                        const Loop *CurrentLoop,
642                        unsigned Level,
643                        FullDependence &Result,
644                        Constraint &NewConstraint) const;
645
646     /// weakCrossingSIVtest - Tests the weak-crossing SIV subscript pair
647     /// (Src and Dst) for dependence.
648     /// Things of the form [c1 + a*i] and [c2 - a*i],
649     /// where i is an induction variable, c1 and c2 are loop invariant,
650     /// and a is a constant.
651     /// Returns true if any possible dependence is disproved.
652     /// If there might be a dependence, returns false.
653     /// Sets appropriate direction entry.
654     /// Set consistent to false.
655     /// Marks the dependence as splitable.
656     bool weakCrossingSIVtest(const SCEV *SrcCoeff,
657                              const SCEV *SrcConst,
658                              const SCEV *DstConst,
659                              const Loop *CurrentLoop,
660                              unsigned Level,
661                              FullDependence &Result,
662                              Constraint &NewConstraint,
663                              const SCEV *&SplitIter) const;
664
665     /// ExactSIVtest - Tests the SIV subscript pair
666     /// (Src and Dst) for dependence.
667     /// Things of the form [c1 + a1*i] and [c2 + a2*i],
668     /// where i is an induction variable, c1 and c2 are loop invariant,
669     /// and a1 and a2 are constant.
670     /// Returns true if any possible dependence is disproved.
671     /// If there might be a dependence, returns false.
672     /// Sets appropriate direction entry.
673     /// Set consistent to false.
674     bool exactSIVtest(const SCEV *SrcCoeff,
675                       const SCEV *DstCoeff,
676                       const SCEV *SrcConst,
677                       const SCEV *DstConst,
678                       const Loop *CurrentLoop,
679                       unsigned Level,
680                       FullDependence &Result,
681                       Constraint &NewConstraint) const;
682
683     /// weakZeroSrcSIVtest - Tests the weak-zero SIV subscript pair
684     /// (Src and Dst) for dependence.
685     /// Things of the form [c1] and [c2 + a*i],
686     /// where i is an induction variable, c1 and c2 are loop invariant,
687     /// and a is a constant. See also weakZeroDstSIVtest.
688     /// Returns true if any possible dependence is disproved.
689     /// If there might be a dependence, returns false.
690     /// Sets appropriate direction entry.
691     /// Set consistent to false.
692     /// If loop peeling will break the dependence, mark appropriately.
693     bool weakZeroSrcSIVtest(const SCEV *DstCoeff,
694                             const SCEV *SrcConst,
695                             const SCEV *DstConst,
696                             const Loop *CurrentLoop,
697                             unsigned Level,
698                             FullDependence &Result,
699                             Constraint &NewConstraint) const;
700
701     /// weakZeroDstSIVtest - Tests the weak-zero SIV subscript pair
702     /// (Src and Dst) for dependence.
703     /// Things of the form [c1 + a*i] and [c2],
704     /// where i is an induction variable, c1 and c2 are loop invariant,
705     /// and a is a constant. See also weakZeroSrcSIVtest.
706     /// Returns true if any possible dependence is disproved.
707     /// If there might be a dependence, returns false.
708     /// Sets appropriate direction entry.
709     /// Set consistent to false.
710     /// If loop peeling will break the dependence, mark appropriately.
711     bool weakZeroDstSIVtest(const SCEV *SrcCoeff,
712                             const SCEV *SrcConst,
713                             const SCEV *DstConst,
714                             const Loop *CurrentLoop,
715                             unsigned Level,
716                             FullDependence &Result,
717                             Constraint &NewConstraint) const;
718
719     /// exactRDIVtest - Tests the RDIV subscript pair for dependence.
720     /// Things of the form [c1 + a*i] and [c2 + b*j],
721     /// where i and j are induction variable, c1 and c2 are loop invariant,
722     /// and a and b are constants.
723     /// Returns true if any possible dependence is disproved.
724     /// Marks the result as inconsistent.
725     /// Works in some cases that symbolicRDIVtest doesn't,
726     /// and vice versa.
727     bool exactRDIVtest(const SCEV *SrcCoeff,
728                        const SCEV *DstCoeff,
729                        const SCEV *SrcConst,
730                        const SCEV *DstConst,
731                        const Loop *SrcLoop,
732                        const Loop *DstLoop,
733                        FullDependence &Result) const;
734
735     /// symbolicRDIVtest - Tests the RDIV subscript pair for dependence.
736     /// Things of the form [c1 + a*i] and [c2 + b*j],
737     /// where i and j are induction variable, c1 and c2 are loop invariant,
738     /// and a and b are constants.
739     /// Returns true if any possible dependence is disproved.
740     /// Marks the result as inconsistent.
741     /// Works in some cases that exactRDIVtest doesn't,
742     /// and vice versa. Can also be used as a backup for
743     /// ordinary SIV tests.
744     bool symbolicRDIVtest(const SCEV *SrcCoeff,
745                           const SCEV *DstCoeff,
746                           const SCEV *SrcConst,
747                           const SCEV *DstConst,
748                           const Loop *SrcLoop,
749                           const Loop *DstLoop) const;
750
751     /// gcdMIVtest - Tests an MIV subscript pair for dependence.
752     /// Returns true if any possible dependence is disproved.
753     /// Marks the result as inconsistent.
754     /// Can sometimes disprove the equal direction for 1 or more loops.
755     //  Can handle some symbolics that even the SIV tests don't get,
756     /// so we use it as a backup for everything.
757     bool gcdMIVtest(const SCEV *Src,
758                     const SCEV *Dst,
759                     FullDependence &Result) const;
760
761     /// banerjeeMIVtest - Tests an MIV subscript pair for dependence.
762     /// Returns true if any possible dependence is disproved.
763     /// Marks the result as inconsistent.
764     /// Computes directions.
765     bool banerjeeMIVtest(const SCEV *Src,
766                          const SCEV *Dst,
767                          const SmallBitVector &Loops,
768                          FullDependence &Result) const;
769
770     /// collectCoefficientInfo - Walks through the subscript,
771     /// collecting each coefficient, the associated loop bounds,
772     /// and recording its positive and negative parts for later use.
773     CoefficientInfo *collectCoeffInfo(const SCEV *Subscript,
774                                       bool SrcFlag,
775                                       const SCEV *&Constant) const;
776
777     /// getPositivePart - X^+ = max(X, 0).
778     ///
779     const SCEV *getPositivePart(const SCEV *X) const;
780
781     /// getNegativePart - X^- = min(X, 0).
782     ///
783     const SCEV *getNegativePart(const SCEV *X) const;
784
785     /// getLowerBound - Looks through all the bounds info and
786     /// computes the lower bound given the current direction settings
787     /// at each level.
788     const SCEV *getLowerBound(BoundInfo *Bound) const;
789
790     /// getUpperBound - Looks through all the bounds info and
791     /// computes the upper bound given the current direction settings
792     /// at each level.
793     const SCEV *getUpperBound(BoundInfo *Bound) const;
794
795     /// exploreDirections - Hierarchically expands the direction vector
796     /// search space, combining the directions of discovered dependences
797     /// in the DirSet field of Bound. Returns the number of distinct
798     /// dependences discovered. If the dependence is disproved,
799     /// it will return 0.
800     unsigned exploreDirections(unsigned Level,
801                                CoefficientInfo *A,
802                                CoefficientInfo *B,
803                                BoundInfo *Bound,
804                                const SmallBitVector &Loops,
805                                unsigned &DepthExpanded,
806                                const SCEV *Delta) const;
807
808     /// testBounds - Returns true iff the current bounds are plausible.
809     ///
810     bool testBounds(unsigned char DirKind,
811                     unsigned Level,
812                     BoundInfo *Bound,
813                     const SCEV *Delta) const;
814
815     /// findBoundsALL - Computes the upper and lower bounds for level K
816     /// using the * direction. Records them in Bound.
817     void findBoundsALL(CoefficientInfo *A,
818                        CoefficientInfo *B,
819                        BoundInfo *Bound,
820                        unsigned K) const;
821
822     /// findBoundsLT - Computes the upper and lower bounds for level K
823     /// using the < direction. Records them in Bound.
824     void findBoundsLT(CoefficientInfo *A,
825                       CoefficientInfo *B,
826                       BoundInfo *Bound,
827                       unsigned K) const;
828
829     /// findBoundsGT - Computes the upper and lower bounds for level K
830     /// using the > direction. Records them in Bound.
831     void findBoundsGT(CoefficientInfo *A,
832                       CoefficientInfo *B,
833                       BoundInfo *Bound,
834                       unsigned K) const;
835
836     /// findBoundsEQ - Computes the upper and lower bounds for level K
837     /// using the = direction. Records them in Bound.
838     void findBoundsEQ(CoefficientInfo *A,
839                       CoefficientInfo *B,
840                       BoundInfo *Bound,
841                       unsigned K) const;
842
843     /// intersectConstraints - Updates X with the intersection
844     /// of the Constraints X and Y. Returns true if X has changed.
845     bool intersectConstraints(Constraint *X,
846                               const Constraint *Y);
847
848     /// propagate - Review the constraints, looking for opportunities
849     /// to simplify a subscript pair (Src and Dst).
850     /// Return true if some simplification occurs.
851     /// If the simplification isn't exact (that is, if it is conservative
852     /// in terms of dependence), set consistent to false.
853     bool propagate(const SCEV *&Src,
854                    const SCEV *&Dst,
855                    SmallBitVector &Loops,
856                    SmallVectorImpl<Constraint> &Constraints,
857                    bool &Consistent);
858
859     /// propagateDistance - Attempt to propagate a distance
860     /// constraint into a subscript pair (Src and Dst).
861     /// Return true if some simplification occurs.
862     /// If the simplification isn't exact (that is, if it is conservative
863     /// in terms of dependence), set consistent to false.
864     bool propagateDistance(const SCEV *&Src,
865                            const SCEV *&Dst,
866                            Constraint &CurConstraint,
867                            bool &Consistent);
868
869     /// propagatePoint - Attempt to propagate a point
870     /// constraint into a subscript pair (Src and Dst).
871     /// Return true if some simplification occurs.
872     bool propagatePoint(const SCEV *&Src,
873                         const SCEV *&Dst,
874                         Constraint &CurConstraint);
875
876     /// propagateLine - Attempt to propagate a line
877     /// constraint into a subscript pair (Src and Dst).
878     /// Return true if some simplification occurs.
879     /// If the simplification isn't exact (that is, if it is conservative
880     /// in terms of dependence), set consistent to false.
881     bool propagateLine(const SCEV *&Src,
882                        const SCEV *&Dst,
883                        Constraint &CurConstraint,
884                        bool &Consistent);
885
886     /// findCoefficient - Given a linear SCEV,
887     /// return the coefficient corresponding to specified loop.
888     /// If there isn't one, return the SCEV constant 0.
889     /// For example, given a*i + b*j + c*k, returning the coefficient
890     /// corresponding to the j loop would yield b.
891     const SCEV *findCoefficient(const SCEV *Expr,
892                                 const Loop *TargetLoop) const;
893
894     /// zeroCoefficient - Given a linear SCEV,
895     /// return the SCEV given by zeroing out the coefficient
896     /// corresponding to the specified loop.
897     /// For example, given a*i + b*j + c*k, zeroing the coefficient
898     /// corresponding to the j loop would yield a*i + c*k.
899     const SCEV *zeroCoefficient(const SCEV *Expr,
900                                 const Loop *TargetLoop) const;
901
902     /// addToCoefficient - Given a linear SCEV Expr,
903     /// return the SCEV given by adding some Value to the
904     /// coefficient corresponding to the specified TargetLoop.
905     /// For example, given a*i + b*j + c*k, adding 1 to the coefficient
906     /// corresponding to the j loop would yield a*i + (b+1)*j + c*k.
907     const SCEV *addToCoefficient(const SCEV *Expr,
908                                  const Loop *TargetLoop,
909                                  const SCEV *Value)  const;
910
911     /// updateDirection - Update direction vector entry
912     /// based on the current constraint.
913     void updateDirection(Dependence::DVEntry &Level,
914                          const Constraint &CurConstraint) const;
915
916     bool tryDelinearize(const SCEV *SrcSCEV, const SCEV *DstSCEV,
917                         SmallVectorImpl<Subscript> &Pair,
918                         const SCEV *ElementSize);
919
920   public:
921     static char ID; // Class identification, replacement for typeinfo
922     DependenceAnalysis() : FunctionPass(ID) {
923       initializeDependenceAnalysisPass(*PassRegistry::getPassRegistry());
924     }
925
926     bool runOnFunction(Function &F) override;
927     void releaseMemory() override;
928     void getAnalysisUsage(AnalysisUsage &) const override;
929     void print(raw_ostream &, const Module * = nullptr) const override;
930   }; // class DependenceAnalysis
931
932   /// createDependenceAnalysisPass - This creates an instance of the
933   /// DependenceAnalysis pass.
934   FunctionPass *createDependenceAnalysisPass();
935
936 } // namespace llvm
937
938 #endif