DependenceAnalysis.h 42 KB

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