MLIR  19.0.0git
ShapeToShapeLowering.cpp
Go to the documentation of this file.
1 //===- ShapeToShapeLowering.cpp - Prepare for lowering to Standard --------===//
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 
10 
14 #include "mlir/IR/Builders.h"
15 #include "mlir/IR/PatternMatch.h"
16 #include "mlir/Pass/Pass.h"
18 
19 namespace mlir {
20 #define GEN_PASS_DEF_SHAPETOSHAPELOWERING
21 #include "mlir/Dialect/Shape/Transforms/Passes.h.inc"
22 } // namespace mlir
23 
24 using namespace mlir;
25 using namespace mlir::shape;
26 
27 namespace {
28 /// Converts `shape.num_elements` to `shape.reduce`.
29 struct NumElementsOpConverter : public OpRewritePattern<NumElementsOp> {
30 public:
32 
33  LogicalResult matchAndRewrite(NumElementsOp op,
34  PatternRewriter &rewriter) const final;
35 };
36 } // namespace
37 
39 NumElementsOpConverter::matchAndRewrite(NumElementsOp op,
40  PatternRewriter &rewriter) const {
41  auto loc = op.getLoc();
42  Type valueType = op.getResult().getType();
43  Value init = op->getDialect()
44  ->materializeConstant(rewriter, rewriter.getIndexAttr(1),
45  valueType, loc)
46  ->getResult(0);
47  ReduceOp reduce = rewriter.create<ReduceOp>(loc, op.getShape(), init);
48 
49  // Generate reduce operator.
50  Block *body = reduce.getBody();
52  Value product = b.create<MulOp>(loc, valueType, body->getArgument(1),
53  body->getArgument(2));
54  b.create<shape::YieldOp>(loc, product);
55 
56  rewriter.replaceOp(op, reduce.getResult());
57  return success();
58 }
59 
60 namespace {
61 struct ShapeToShapeLowering
62  : public impl::ShapeToShapeLoweringBase<ShapeToShapeLowering> {
63  void runOnOperation() override;
64 };
65 } // namespace
66 
67 void ShapeToShapeLowering::runOnOperation() {
68  MLIRContext &ctx = getContext();
69 
70  RewritePatternSet patterns(&ctx);
72 
73  ConversionTarget target(getContext());
74  target.addLegalDialect<arith::ArithDialect, ShapeDialect>();
75  target.addIllegalOp<NumElementsOp>();
76  if (failed(mlir::applyPartialConversion(getOperation(), target,
77  std::move(patterns))))
78  signalPassFailure();
79 }
80 
82  patterns.add<NumElementsOpConverter>(patterns.getContext());
83 }
84 
85 std::unique_ptr<Pass> mlir::createShapeToShapeLowering() {
86  return std::make_unique<ShapeToShapeLowering>();
87 }
static int64_t product(ArrayRef< int64_t > vals)
static MLIRContext * getContext(OpFoldResult val)
static Value reduce(OpBuilder &builder, Location loc, Value input, Value output, int64_t dim)
Definition: LinalgOps.cpp:2515
Block represents an ordered list of Operations.
Definition: Block.h:30
IntegerAttr getIndexAttr(int64_t value)
Definition: Builders.cpp:124
This class describes a specific conversion target.
virtual Operation * materializeConstant(OpBuilder &builder, Attribute value, Type type, Location loc)
Registered hook to materialize a single constant operation from a given attribute value with the desi...
Definition: Dialect.h:86
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
This class helps build Operations.
Definition: Builders.h:209
static OpBuilder atBlockEnd(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to after the last operation in the block but still insid...
Definition: Builders.h:248
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:464
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Definition: Operation.h:220
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition: Operation.h:402
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:785
MLIRContext * getContext() const
Definition: PatternMatch.h:822
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
Definition: PatternMatch.h:846
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:129
Include the generated interface declarations.
std::unique_ptr< Pass > createShapeToShapeLowering()
Creates an instance of the ShapeToShapeLowering pass that legalizes Shape dialect to be convertible t...
void populateShapeRewritePatterns(RewritePatternSet &patterns)
Collects a set of patterns to rewrite ops within the Shape dialect.
LogicalResult success(bool isSuccess=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:56
LogicalResult applyPartialConversion(ArrayRef< Operation * > ops, const ConversionTarget &target, const FrozenRewritePatternSet &patterns, ConversionConfig config=ConversionConfig())
Below we define several entry points for operation conversion.
bool failed(LogicalResult result)
Utility function that returns true if the provided LogicalResult corresponds to a failure value.
Definition: LogicalResult.h:72
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
Definition: PatternMatch.h:358
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
Definition: PatternMatch.h:362