daphne-project/daphne

Elimination of redundant `ReshapeOp`

Aperta

#964 aperta il 9 mag 2025

 (0 commenti) (0 reazioni) (0 assegnatari)C++ (84 fork)auto 404
good first issue

Metriche repository

Star
 (80 stelle)
Metriche merge PR
 (Metriche PR in attesa)

Descrizione

Background: DaphneIR's ReshapeOp changes the shape (#rows and #cols) of a matrix. This operation is created through DaphneDSL's reshape() built-in function and implicitly in some situations, e.g., in shaped matrix literals like [1, 2, 3, 4](2, 2). Whenever the shape of the result is the same as that of the input, the ReshapeOp could be eliminated to simplify the IR.

Task: Add a canonicalization for ReshapeOp which replaces an instance of ReshapeOp by its input matrix if the input shape and result shape are known at compile-time and are the same.

Example: The following little DaphneDSL script implicitly reshapes a 1x1 matrix to a 1x1 matrix, which is redundant. You can see that by running bin/daphne --explain parsing_simplified example.daphne (see the IR below). When this task is solved, the reshape should automatically disappear.

#example.daphne
print([1]);
IR after parsing and some simplifications:
module {
  func.func @main() {
    %0 = "daphne.constant"() {value = 1 : index} : () -> index
    %1 = "daphne.constant"() {value = false} : () -> i1
    %2 = "daphne.constant"() {value = true} : () -> i1
    %3 = "daphne.constant"() {value = 104749040830256 : ui64} : () -> ui64
    %4 = "daphne.matrixConstant"(%3) : (ui64) -> !daphne.Matrix<?x?xsi64>
    %5 = "daphne.reshape"(%4, %0, %0) : (!daphne.Matrix<?x?xsi64>, index, index) -> !daphne.Matrix<?x?xsi64>
    "daphne.print"(%5, %2, %1) : (!daphne.Matrix<?x?xsi64>, i1, i1) -> ()
    "daphne.return"() : () -> ()
  }
}

Hints:

  • All canonicalizations of DaphneIR ops are implemented in src/ir/daphneir/Canonicalize.cpp.
  • CompilerUtils::isConstant() can be used to determine if an mlir::Value is a compile-time constant.
  • The shape of a matrix can be retrieved from its type.

Guida contributor