1035 Commits

Author SHA1 Message Date
Jakub Kuderski
eb78b9b42f
[mlir] Clean up prints with llvm::interleaved. NFC. (#136468) 2025-04-19 22:59:57 -04:00
Kazu Hirata
1cf188a1bc
[mlir] Use llvm::SmallVector::pop_back_val() (NFC) (#136452) 2025-04-19 13:21:29 -07:00
donald chen
ccbbb1722f
[mlir] [dataflow] : Improve the time and space footprint of data flow. (#135325)
MLIR's data flow analysis (especially dense data flow analysis)
constructs a lattice at every lattice anchor (which, for dense data
flow, means every program point). As the program grows larger, the time
and space complexity can become unmanageable.

However, in many programs, the lattice values at numerous lattice
anchors are actually identical. We can leverage this observation to
improve the complexity of data flow analysis. This patch introducing
equivalence lattice anchor to group lattice anchors that must contains
identical lattice on certain state to improve the time and space
footprint of data flow.
2025-04-15 16:20:37 +08:00
Kazu Hirata
eb7f51485e
[mlir] Use llvm::append_range (NFC) (#135722) 2025-04-14 22:22:04 -07:00
donald chen
d40bab359c
[mlir][liveness] fix bugs in liveness analysis (#133416)
This patch fixes the following bugs:
- In SparseBackwardAnalysis, the setToExitState function should
propagate changes if it modifies the lattice. Previously, this issue was
masked because multi-block scenarios were not tested, and the traversal
order of backward data flow analysis starts from the end of the program.
- The method in liveness analysis for determining whether the
non-forwarded operand in branch/region branch operations is live is
incorrect, which may cause originally live variables to be marked as not
live.
2025-04-02 11:56:13 +08:00
Han-Chung Wang
66b0b0466b
[MLIR][NFC] Fix incomplete boundary comments. (#133516)
I observed that we have the boundary comments in the codebase like:

```
//===----------------------------------------------------------------------===//
// ...
//===----------------------------------------------------------------------===//
```

I also observed that there are incomplete boundary comments. The
revision is generated by a script that completes the boundary comments.

```
//===----------------------------------------------------------------------===//
// ...

...
```

Signed-off-by: hanhanW <hanhan0912@gmail.com>
2025-03-31 09:29:54 -07:00
Kazu Hirata
1cc07a0865
[mlir] Use *Set::insert_range (NFC) (#133043)
We can use *Set::insert_range to collapse:

  for (auto Elem : Range)
    Set.insert(E);

down to:

  Set.insert_range(Range);

In some cases, we can further fold that into the set declaration.
2025-03-26 07:47:02 -07:00
Kazu Hirata
3041fa6c7a
[mlir] Use *Set::insert_range (NFC) (#132326)
DenseSet, SmallPtrSet, SmallSet, SetVector, and StringSet recently
gained C++23-style insert_range.  This patch replaces:

  Dest.insert(Src.begin(), Src.end());

with:

  Dest.insert_range(Src);

This patch does not touch custom begin like succ_begin for now.
2025-03-20 22:24:17 -07:00
Matthias Springer
6c867e27a7
[mlir] Use getSingleElement/hasSingleElement in various places (#131460)
This is a code cleanup. Update a few places in MLIR that should use
`hasSingleElement`/`getSingleElement`.

Note: `hasSingleElement` is faster than `.getSize() == 1` when it is
used with linked lists etc.

Depends on #131508.
2025-03-17 07:43:18 +01:00
Uday Bondhugula
ec54ec65e5
[MLIR][Affine] Improve memref region bounding size and shape computation (#129009)
Improve memref region utility (`getConstantBoundingSizeAndShape`) to get
its constant bounding size and shape using affine expressions/maps by
also considering local variables in the system. Leads to significantly
precise and tighter bounding size and shape in the presence of div/mod
expressions (as evident from the test cases). The approach is now more
robust, proper, and complete. For affine fusion, this leads to private
memrefs of accurate size in several cases. This also impacts other
affine analysis-based passes like data copy generation that use memref
regions.

With contributions from `Vinayaka Bandishti <vinayaka@polymagelabs.com>`
on `getConstantBoundingSizeAndShape` and getConstantBoundOnDimSize`.

Fixes: https://github.com/llvm/llvm-project/issues/46317

Co-authored-by: Vinayaka Bandishti <vinayaka@polymagelabs.com>
2025-03-04 16:44:14 +05:30
Uday Bondhugula
78de27aac6
[MLIR] NFC. Improve API signature + clang-tidy warning in IntegerRelation (#128993) 2025-03-01 08:14:03 +05:30
laichunfeng
35d7bf21b6
[mlir] Remove unused outer loop (NFC) (#127998)
The program will exit the outer loop directly if inner loop ends, so the
outer do {} while() is redundant.
2025-02-21 13:04:44 +08:00
Maksim Levental
ab7664c02c
[mlir][integer-range-analysis] expose helpers in header and fix ConstantIntRange print (#127888) 2025-02-19 21:01:45 -05:00
Uday Bondhugula
69f3e003bf
[MLIR] NFC. Refactor IntegerRelation getSliceBounds (#127308)
Refactor FlatLinearConstraints getSliceBounds. The method was too long
and nested. NFC.
2025-02-17 08:58:06 +05:30
Uday Bondhugula
61ad08792a
[MLIR][Affine] NFC. Fix/improve debug messages for affine analysis/fusion utils (#127164)
Fix/improve debug messages and API signatures for affine
analysis/fusion utils.

Move some warnings under LLVM_DEBUG. These weren't meant to be exposed
during compilation.

Add dump pretty methods for FlatLinearConstraints.

NFC.
2025-02-15 09:37:20 +05:30
Uday Bondhugula
9fddcea027
[MLIR][Affine] Fix getSliceBounds for missing handling of no lower/upper bound in certain cases (#127192)
Fix `FlatLinearValueConstraints::getSliceBounds` for missing checks on
no
lower/upper bound bound. Obvious bug.

Fixes: https://github.com/llvm/llvm-project/issues/119525
Fixes: https://github.com/llvm/llvm-project/issues/108374
2025-02-15 08:01:42 +05:30
donald chen
f15a6c99fa
[mlir] [DataFlow] Fix bug in int-range-analysis (#126708)
When querying the lower bound and upper bound of loop to update the
value range of a loop iteration variable, the program point to depend on
should be the block corresponding to the iteration variable rather than
the loop operation.
2025-02-12 09:58:56 +08:00
Hongren Zheng
3a439e2caf
[mlir][dataflow] disallow outside use of propagateIfChanged for DataFlowSolver (#120885)
Detailed writeup is in https://github.com/google/heir/issues/1153. See
also https://github.com/llvm/llvm-project/pull/120881. In short,
`propagateIfChanged` is used outside of the `DataFlowAnalysis` scope,
because it is public, but it does not propagate as expected as the
`DataFlowSolver` has stopped running.

To solve such misuse, `propagateIfChanged` should be made
protected/private.

For downstream users affected by this, to correctly propagate the
change, the Analysis should be re-run (check #120881) instead of just a
`propagateIfChanged`

The change to `IntegerRangeAnalysis` is just a expansion of the
`solver->propagateIfChanged`. The `Lattice` has already been updated by
the `join`. Propagation is done by `onUpdate`.

Cc @Mogball for review
2025-01-28 13:32:28 +08:00
Kazu Hirata
4f4e2abb1a
[mlir] Migrate away from PointerUnion::{is,get} (NFC) (#122591)
Note that PointerUnion::{is,get} have been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //        isa<T>, cast<T> and the llvm::dyn_cast<T>

I'm not touching PointerUnion::dyn_cast for now because it's a bit
complicated; we could blindly migrate it to dyn_cast_if_present, but
we should probably use dyn_cast when the operand is known to be
non-null.
2025-01-11 13:16:43 -08:00
Kazu Hirata
b5c5c2b26f
[DataFlow] Migrate away from PointerUnion::{is,get} (NFC) (#119950)
Note that PointerUnion::{is,get} have been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //        isa<T>, cast<T> and the llvm::dyn_cast<T>

I'm not touching PointerUnion::dyn_cast for now because it's a bit
complicated; we could blindly migrate it to dyn_cast_if_present, but
we should probably use dyn_cast when the operand is known to be
non-null.
2024-12-14 11:34:24 -08:00
Christopher Bate
832ccfe552
[mlir][presburger] NFC: Add missing definition for 'MultiAffineFunction::dump' (#118397) 2024-12-06 15:34:38 -07:00
Shlomi Regev
13317502da
[mlir] Add a null pointer check in symbol lookup (#115165)
Dead code analysis crashed because a symbol that is called/used didn't appear in the symbol
table. 
This patch fixes this by adding a nullptr check after symbol table lookup.
2024-11-12 23:31:25 +01:00
Ivan Butygin
f54cdc5d6e
[mlir] IntegerRangeAnalysis: add support for vector type (#112292)
Treat integer range for vector type as union of ranges of individual
elements. With this semantics, most arith ops on vectors will work out
of the box, the only special handling needed for constants and vector
elements manipulation ops.

The end goal of these changes is to be able to optimize vectorized index
calculations.
2024-11-01 23:58:16 +03:00
Ian Wood
d97bc388fd
Reapply "Extend getBackwardSlice to track values captured… (#114452)
This commit fixes the failure in the original PR when building with
shared libs. The problem is that `visitUsedValuesDefinedAbove` is
defined in `MLIRTransformUtils`, but that lib depends on this lib
(`MLIRAnalysis`). To fix, I dropped the use of
`visitUsedValuesDefinedAbove` and use `Region::walk` to traverse values
defined above.

Reapplies PR https://github.com/llvm/llvm-project/pull/113478
Reverts PR https://github.com/llvm/llvm-project/pull/114432

This reverts commit a9a8351.
2024-11-01 08:42:12 -07:00
Mehdi Amini
a9a8351ef1
Revert "Extend getBackwardSlice to track values captured from above" (#114432)
Reverts llvm/llvm-project#113478

Bot is broken when building with shared libs.
2024-10-31 18:29:05 +01:00
Ian Wood
1bc58a258e
Extend getBackwardSlice to track values captured from above (#113478)
This change modifies `getBackwardSlice` to track values captures by the
regions of each operation that it traverses. Ignoring values captured
from a parent region may lead to an incomplete program slice. However,
there seems to be logic that depends on not traversing captured values,
so this change preserves the default behavior by hiding this logic
behind the `omitUsesFromAbove` flag.
2024-10-31 07:47:48 -07:00
Alexander Pivovarov
a24c468782
[MLIR] Fix assert expressions (#112474)
I noticed that several assertions in MLIR codebase have issues with
operator precedence

The issue with operator precedence in these assertions is due to the way
logical operators are evaluated. The `&&` operator has higher precedence
than the `||` operator, which means the assertion is currently
evaluating incorrectly, like this:
```
assert((resType.getNumDynamicDims() == dynOutDims.size()) ||
       (dynOutDims.empty() && "Either none or all output dynamic dims must be specified!"));
```

We should add parentheses around the entire expression involving
`dynOutDims.empty()` to ensure that the logical conditions are grouped
correctly. Here’s the corrected version:
```
assert(((resType.getNumDynamicDims() == dynOutDims.size()) || dynOutDims.empty()) &&
       "Either none or all output dynamic dims must be specified!");

```
2024-10-16 15:22:29 -07:00
donald chen
4b3f251bad
[mlir] [dataflow] unify semantics of program point (#110344)
The concept of a 'program point' in the original data flow framework is
ambiguous. It can refer to either an operation or a block itself. This
representation has different interpretations in forward and backward
data-flow analysis. In forward data-flow analysis, the program point of
an operation represents the state after the operation, while in backward
data flow analysis, it represents the state before the operation. When
using forward or backward data-flow analysis, it is crucial to carefully
handle this distinction to ensure correctness.

This patch refactors the definition of program point, unifying the
interpretation of program points in both forward and backward data-flow
analysis.

How to integrate this patch?

For dense forward data-flow analysis and other analysis (except dense
backward data-flow analysis), the program point corresponding to the
original operation can be obtained by `getProgramPointAfter(op)`, and
the program point corresponding to the original block can be obtained by
`getProgramPointBefore(block)`.

For dense backward data-flow analysis, the program point corresponding
to the original operation can be obtained by
`getProgramPointBefore(op)`, and the program point corresponding to the
original block can be obtained by `getProgramPointAfter(block)`.

NOTE: If you need to get the lattice of other data-flow analyses in
dense backward data-flow analysis, you should still use the dense
forward data-flow approach. For example, to get the Executable state of
a block in dense backward data-flow analysis and add the dependency of
the current operation, you should write:

``getOrCreateFor<Executable>(getProgramPointBefore(op),
getProgramPointBefore(block))``

In case above, we use getProgramPointBefore(op) because the analysis we
rely on is dense backward data-flow, and we use
getProgramPointBefore(block) because the lattice we query is the result
of a non-dense backward data flow computation.

related dsscussion:
https://discourse.llvm.org/t/rfc-unify-the-semantics-of-program-points/80671/8
corresponding PSA:
https://discourse.llvm.org/t/psa-program-point-semantics-change/81479
2024-10-11 21:59:05 +08:00
Mehdi Amini
6c7a3f80e7
Fix LLVM_ENABLE_ABI_BREAKING_CHECKS macro check: use #if instead of #ifdef (#110938)
This macros is always defined: either 0 or 1. The correct pattern is to
use #if.

Re-apply #110185 with more fixes for debug build with the ABI breaking
checks disabled.
2024-10-03 01:24:14 +02:00
Amy Wang
2740273505
[MLIR][Presburger] Make printing aligned to assist in debugging (#107648)
Hello Arjun! Please allow me to contribute this patch as it helps me
debugging significantly! When the 1's and 0's don't line up when
debugging farkas lemma of numerous polyhedrons using simplex lexmin
solver, it is truly straining on the eyes. Hopefully this patch can help
others!

The unfortunate part is the lack of testcase as I'm not sure how to add
testcase for debug dumps. :) However, you can add this testcase to the
SimplexTest.cpp to witness the nice printing!

```c++
TEST(SimplexTest, DumpTest) {
  int COLUMNS = 2;
  int ROWS = 2;
  LexSimplex simplex(COLUMNS * 2);
  IntMatrix m1(ROWS, COLUMNS * 2 + 1);
  // Adding LHS columns.
  for (int i = 0; i < ROWS; i++) {
    // an arbitrary formula to test all kinds of integers
    for (int j = 0; j < COLUMNS; j++) 
      m1(i, j) = i + (2 << (i % 3)) * (-1 * ((i + j) % 2));
  }
  // Adding RHS columns.
  for (int i = 0; i < ROWS; i++) {
    for (int j = 0; j < COLUMNS; j++)
      m1(i, j + COLUMNS) = j - (3 << (j % 4)) * (-1 * ((i + j * 2) % 2));
  }
  for (int i = 0; i < m1.getNumRows(); i++) {
    ArrayRef<DynamicAPInt> curRow = m1.getRow(i);
    simplex.addInequality(curRow);
  }
  IntegerRelation rel =
      parseRelationFromSet("(x, y, z)[] : (z - x - 17 * y == 0, x - 11 * z >= 1)",2);
  simplex.dump();
  m1.dump();
  rel.dump();
}
```

```
rows = 2, columns = 7
var: c3, c4, c5, c6
con: r0 [>=0], r1 [>=0]
r0: -1, r1: -2
c0: denom, c1: const, c2: 2147483647, c3: 0, c4: 1, c5: 2, c6: 3
  1  0  1  0 -2  0  1
  1  0 -8 -3  1  3  7

  0 -2  0  1  0
 -3  1  3  7  0
Domain: 2, Range: 1, Symbols: 0, Locals: 0
2 constraints
 -1  -17  1   0   = 0
  1   0  -11 -1  >= 0

```
2024-09-11 23:22:54 -04:00
Henrich Lauko
d1cad2290c
Reland [MLIR] Make resolveCallable customizable in CallOpInterface (#107989)
Relands #100361 with fixed dependencies.
2024-09-10 15:33:13 +02:00
Matthias Springer
7574042e2a
Revert "[MLIR] Make resolveCallable customizable in CallOpInterface" (#107984)
Reverts llvm/llvm-project#100361

This commit caused some linker errors. (Missing `MLIRCallInterfaces`
dependency.)
2024-09-10 10:24:05 +02:00
Henrich Lauko
958f59d90f
[MLIR] Make resolveCallable customizable in CallOpInterface (#100361)
Allow customization of the `resolveCallable` method in the
`CallOpInterface`. This change allows for operations implementing this
interface to provide their own logic for resolving callables.

- Introduce the `resolveCallable` method, which does not include the
optional symbol table parameter. This method replaces the previously
existing extra class declaration `resolveCallable`.

- Introduce the `resolveCallableInTable` method, which incorporates the
symbol table parameter. This method replaces the previous extra class
declaration `resolveCallable` that used the optional symbol table
parameter.
2024-09-10 10:08:41 +02:00
Kazu Hirata
b2dbcf4dc1
[Presburger] Avoid repeated hash lookups (NFC) (#107426) 2024-09-05 11:43:19 -07:00
donald chen
b6603e1bf1
[mlir] [dataflow] Refactoring the definition of program points in data flow analysis (#105656)
This patch distinguishes between program points and lattice anchors in
data flow analysis, where lattice anchors represent locations where a
lattice can be attached, while program points denote points in program
execution.

Related discussions:
https://discourse.llvm.org/t/rfc-unify-the-semantics-of-program-points/80671/8
2024-08-25 19:21:47 +08:00
Ivan Butygin
15e915a44f
[mlir][dataflow] Propagate errors from visitOperation (#105448)
Base `DataFlowAnalysis::visit` returns `LogicalResult`, but wrappers's
Sparse/Dense/Forward/Backward `visitOperation` doesn't.

Sometimes it's needed to abort solver early if some unrecoverable
condition detected inside analysis.

Update `visitOperation` to return `LogicalResult` and propagate it to
`solver.initializeAndRun()`. Only `visitOperation` is updated for now,
it's possible to update other hooks like `visitNonControlFlowArguments`,
bit it's not needed immediately and let's keep this PR small.

Hijacked `UnderlyingValueAnalysis` test analysis to test it.
2024-08-22 12:16:03 +03:00
Christian Ulmann
bf68e9047f
[MLIR] Introduce a SelectLikeOpInterface (#104751)
This commit introduces a `SelectLikeOpInterface` that can be used to
handle select-like operations generically. Select operations are similar
to control flow operations, as they forward operands depending on
conditions. This is the reason why it was placed to the already existing
control flow interfaces.
2024-08-20 07:32:12 +02:00
Christian Ulmann
141536544f
[MLIR][LLVM]: Add an IR utility to perform slice walking (#103053)
This commit introduces a slicing utility that can be used to walk
arbitrary IR slices. It additionally ships logic to determine control
flow predecessors, which allows users to walk backward slices without
dealing with both `RegionBranchOpInterface` and `BranchOpInterface`.

This utility is used to improve the `noalias` propagation in the LLVM
dialect's inliner interface. Before this change, it broke down as soon
as pointer were passed through region control flow operations.
2024-08-15 10:30:44 +02:00
Kazu Hirata
165f45354a
[mlir] Use llvm::is_contained (NFC) (#102714) 2024-08-09 21:42:19 -07:00
Kazu Hirata
5262865aac
[mlir] Construct SmallVector with ArrayRef (NFC) (#101896) 2024-08-04 11:43:05 -07:00
Ramkumar Ramachandra
266a5a9cb9
mlir/Presburger: optimize to avoid creating copies (#97897)
Optimize the Presburger library to avoid unnecessarily creating copies.
While at it, fix some other minor issues in the codebase.
2024-07-15 19:42:27 +01:00
Ramkumar Ramachandra
64740edac8
mlir/Presburger: optimize normalizeDiv when gcd=1 (#97893) 2024-07-08 08:28:53 +01:00
Ramkumar Ramachandra
f819302a09
mlir/Presburger: reinstate use of LogicalResult (#97415)
Follow up on a desire post-landing d0fee98 (mlir/Presburger: strip
dependency on MLIRSupport) to reinstate the use of LogicalResult in
Presburger. Since db791b2 (mlir/LogicalResult: move into llvm),
LogicalResult is in LLVM, and fulfilling this desire is possible while
still maintaining the goal of stripping the Presburger library of mlir
dependencies.
2024-07-03 10:51:25 +01:00
Ramkumar Ramachandra
db791b278a
mlir/LogicalResult: move into llvm (#97309)
This patch is part of a project to move the Presburger library into
LLVM.
2024-07-02 10:42:33 +01:00
Ramkumar Ramachandra
d0fee98e0c
mlir/Presburger: strip dependency on MLIRSupport (#96517)
Strip the Presburger library's dependency on the MLIR Support library,
as well as the headers, in the interest of making it leaner.

This patch is part of a project to move the Presburger library into
LLVM.
2024-06-29 12:23:20 +01:00
Felix Schneider
b78883fc6d
[mlir][intrange] Fix inference of zero-trip loop bound (#96429)
When lower bound and exclusive upper bound of a loop are the same, and
the zero-trip loop is not canonicalized away before the analysis, this
leads to a meaningless range for the induction variable being inferred.
This patch adds a check to make sure that the inferred range for the IV
is meaningful before updating the analysis state.

Fix https://github.com/llvm/llvm-project/issues/94423
2024-06-24 08:05:04 +02:00
Jay Foad
d4a0154902
[llvm-project] Fix typo "seperate" (#95373) 2024-06-13 20:20:27 +01:00
Ramkumar Ramachandra
1a0e67d730
Reland "mlir/Presburger/MPInt: move into llvm/ADT" (#95254)
Change: remove guards on debug-printing, to allow Release builds without
LLVM_ENABLE_DUMP to pass.

MPInt is an arbitrary-precision integer library that builds on top of
APInt, and has a fast-path when the number fits within 64 bits. It was
originally written for the Presburger library in MLIR, but seems useful
to the LLVM project in general, independently of the Presburger library
or MLIR. Hence, move it into LLVM/ADT under the name DynamicAPInt.

This patch is part of a project to move the Presburger library into
LLVM.
2024-06-12 18:09:16 +01:00
Maksim Levental
cb5d1b52ad
Revert #95218 and #94953 (#95244) 2024-06-12 08:55:48 -05:00
Ramkumar Ramachandra
76030dc157
mlir/Presburger/MPInt: move into llvm/ADT (#94953)
MPInt is an arbitrary-precision integer library that builds on top of
APInt, and has a fast-path when the number fits within 64 bits. It was
originally written for the Presburger library in MLIR, but seems useful
to the LLVM project in general, independently of the Presburger library
or MLIR. Hence, move it into LLVM/ADT under the name DynamicAPInt.

This patch is part of a project to move the Presburger library into
LLVM.
2024-06-12 09:19:21 +01:00