Files
clang-p2996/mlir/lib/Dialect/Arith/Transforms/ReifyValueBounds.cpp
Tres Popp 5550c82189 [mlir] Move casting calls from methods to function calls
The MLIR classes Type/Attribute/Operation/Op/Value support
cast/dyn_cast/isa/dyn_cast_or_null functionality through llvm's doCast
functionality in addition to defining methods with the same name.
This change begins the migration of uses of the method to the
corresponding function call as has been decided as more consistent.

Note that there still exist classes that only define methods directly,
such as AffineExpr, and this does not include work currently to support
a functional cast/isa call.

Caveats include:
- This clang-tidy script probably has more problems.
- This only touches C++ code, so nothing that is being generated.

Context:
- https://mlir.llvm.org/deprecation/ at "Use the free function variants
  for dyn_cast/cast/isa/…"
- Original discussion at https://discourse.llvm.org/t/preferred-casting-style-going-forward/68443

Implementation:
This first patch was created with the following steps. The intention is
to only do automated changes at first, so I waste less time if it's
reverted, and so the first mass change is more clear as an example to
other teams that will need to follow similar steps.

Steps are described per line, as comments are removed by git:
0. Retrieve the change from the following to build clang-tidy with an
   additional check:
   https://github.com/llvm/llvm-project/compare/main...tpopp:llvm-project:tidy-cast-check
1. Build clang-tidy
2. Run clang-tidy over your entire codebase while disabling all checks
   and enabling the one relevant one. Run on all header files also.
3. Delete .inc files that were also modified, so the next build rebuilds
   them to a pure state.
4. Some changes have been deleted for the following reasons:
   - Some files had a variable also named cast
   - Some files had not included a header file that defines the cast
     functions
   - Some files are definitions of the classes that have the casting
     methods, so the code still refers to the method instead of the
     function without adding a prefix or removing the method declaration
     at the same time.

```
ninja -C $BUILD_DIR clang-tidy

run-clang-tidy -clang-tidy-binary=$BUILD_DIR/bin/clang-tidy -checks='-*,misc-cast-functions'\
               -header-filter=mlir/ mlir/* -fix

rm -rf $BUILD_DIR/tools/mlir/**/*.inc

git restore mlir/lib/IR mlir/lib/Dialect/DLTI/DLTI.cpp\
            mlir/lib/Dialect/Complex/IR/ComplexDialect.cpp\
            mlir/lib/**/IR/\
            mlir/lib/Dialect/SparseTensor/Transforms/SparseVectorization.cpp\
            mlir/lib/Dialect/Vector/Transforms/LowerVectorMultiReduction.cpp\
            mlir/test/lib/Dialect/Test/TestTypes.cpp\
            mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp\
            mlir/test/lib/Dialect/Test/TestAttributes.cpp\
            mlir/unittests/TableGen/EnumsGenTest.cpp\
            mlir/test/python/lib/PythonTestCAPI.cpp\
            mlir/include/mlir/IR/
```

Differential Revision: https://reviews.llvm.org/D150123
2023-05-12 11:21:25 +02:00

145 lines
6.0 KiB
C++

//===- ReifyValueBounds.cpp --- Reify value bounds with arith ops -------*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Arith/Transforms/Transforms.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/Interfaces/ValueBoundsOpInterface.h"
using namespace mlir;
using namespace mlir::arith;
/// Build Arith IR for the given affine map and its operands.
static Value buildArithValue(OpBuilder &b, Location loc, AffineMap map,
ValueRange operands) {
assert(map.getNumResults() == 1 && "multiple results not supported yet");
std::function<Value(AffineExpr)> buildExpr = [&](AffineExpr e) -> Value {
switch (e.getKind()) {
case AffineExprKind::Constant:
return b.create<ConstantIndexOp>(loc,
e.cast<AffineConstantExpr>().getValue());
case AffineExprKind::DimId:
return operands[e.cast<AffineDimExpr>().getPosition()];
case AffineExprKind::SymbolId:
return operands[e.cast<AffineSymbolExpr>().getPosition() +
map.getNumDims()];
case AffineExprKind::Add: {
auto binaryExpr = e.cast<AffineBinaryOpExpr>();
return b.create<AddIOp>(loc, buildExpr(binaryExpr.getLHS()),
buildExpr(binaryExpr.getRHS()));
}
case AffineExprKind::Mul: {
auto binaryExpr = e.cast<AffineBinaryOpExpr>();
return b.create<MulIOp>(loc, buildExpr(binaryExpr.getLHS()),
buildExpr(binaryExpr.getRHS()));
}
case AffineExprKind::FloorDiv: {
auto binaryExpr = e.cast<AffineBinaryOpExpr>();
return b.create<DivSIOp>(loc, buildExpr(binaryExpr.getLHS()),
buildExpr(binaryExpr.getRHS()));
}
case AffineExprKind::CeilDiv: {
auto binaryExpr = e.cast<AffineBinaryOpExpr>();
return b.create<CeilDivSIOp>(loc, buildExpr(binaryExpr.getLHS()),
buildExpr(binaryExpr.getRHS()));
}
case AffineExprKind::Mod: {
auto binaryExpr = e.cast<AffineBinaryOpExpr>();
return b.create<RemSIOp>(loc, buildExpr(binaryExpr.getLHS()),
buildExpr(binaryExpr.getRHS()));
}
}
llvm_unreachable("unsupported AffineExpr kind");
};
return buildExpr(map.getResult(0));
}
static FailureOr<OpFoldResult>
reifyValueBound(OpBuilder &b, Location loc, presburger::BoundType type,
Value value, std::optional<int64_t> dim,
ValueBoundsConstraintSet::StopConditionFn stopCondition,
bool closedUB) {
// Compute bound.
AffineMap boundMap;
ValueDimList mapOperands;
if (failed(ValueBoundsConstraintSet::computeBound(
boundMap, mapOperands, type, value, dim, stopCondition, closedUB)))
return failure();
// Materialize tensor.dim/memref.dim ops.
SmallVector<Value> operands;
for (auto valueDim : mapOperands) {
Value value = valueDim.first;
std::optional<int64_t> dim = valueDim.second;
if (!dim.has_value()) {
// This is an index-typed value.
assert(value.getType().isIndex() && "expected index type");
operands.push_back(value);
continue;
}
assert(cast<ShapedType>(value.getType()).isDynamicDim(*dim) &&
"expected dynamic dim");
if (isa<RankedTensorType>(value.getType())) {
// A tensor dimension is used: generate a tensor.dim.
operands.push_back(b.create<tensor::DimOp>(loc, value, *dim));
} else if (isa<MemRefType>(value.getType())) {
// A memref dimension is used: generate a memref.dim.
operands.push_back(b.create<memref::DimOp>(loc, value, *dim));
} else {
llvm_unreachable("cannot generate DimOp for unsupported shaped type");
}
}
// Check for special cases where no arith ops are needed.
if (boundMap.isSingleConstant()) {
// Bound is a constant: return an IntegerAttr.
return static_cast<OpFoldResult>(
b.getIndexAttr(boundMap.getSingleConstantResult()));
}
// No arith ops are needed if the bound is a single SSA value.
if (auto expr = boundMap.getResult(0).dyn_cast<AffineDimExpr>())
return static_cast<OpFoldResult>(operands[expr.getPosition()]);
if (auto expr = boundMap.getResult(0).dyn_cast<AffineSymbolExpr>())
return static_cast<OpFoldResult>(
operands[expr.getPosition() + boundMap.getNumDims()]);
// General case: build Arith ops.
return static_cast<OpFoldResult>(buildArithValue(b, loc, boundMap, operands));
}
FailureOr<OpFoldResult> mlir::arith::reifyShapedValueDimBound(
OpBuilder &b, Location loc, presburger::BoundType type, Value value,
int64_t dim, ValueBoundsConstraintSet::StopConditionFn stopCondition,
bool closedUB) {
auto reifyToOperands = [&](Value v, std::optional<int64_t> d) {
// We are trying to reify a bound for `value` in terms of the owning op's
// operands. Construct a stop condition that evaluates to "true" for any SSA
// value expect for `value`. I.e., the bound will be computed in terms of
// any SSA values expect for `value`. The first such values are operands of
// the owner of `value`.
return v != value;
};
return reifyValueBound(b, loc, type, value, dim,
stopCondition ? stopCondition : reifyToOperands,
closedUB);
}
FailureOr<OpFoldResult> mlir::arith::reifyIndexValueBound(
OpBuilder &b, Location loc, presburger::BoundType type, Value value,
ValueBoundsConstraintSet::StopConditionFn stopCondition, bool closedUB) {
auto reifyToOperands = [&](Value v, std::optional<int64_t> d) {
return v != value;
};
return reifyValueBound(b, loc, type, value, /*dim=*/std::nullopt,
stopCondition ? stopCondition : reifyToOperands,
closedUB);
}