How to getParentOperation of a SSA mlir::Value?

Given an SSA value in the MLIR function, how to get the parent operation? the operation is a node of the graph.

mlir graph function is as follow:

module  {
  func @main(%arg0: tensor<2x3x3x3xf32>, %arg1: tensor<4x3x28x28xf32>) -> tuple<tensor<4x2x30x30xf32>> {
    %0 = mhlo.convolution(%arg1, %arg0) dim_numbers = [b, f, 0, 1]x[o, i, 0, 1]->[b, f, 0, 1], window = {stride = [1, 1], pad = [[2, 2], [2, 2]], lhs_dilate = [1, 1], rhs_dilate = [1, 1]} {batch_group_count = 1 : i64, feature_group_count = 1 : i64, precision_config = ["DEFAULT", "DEFAULT"]} : (tensor<4x3x28x28xf32>, tensor<2x3x3x3xf32>) -> tensor<4x2x30x30xf32>
    %1 = "mhlo.tuple"(%0) : (tensor<4x2x30x30xf32>) -> tuple<tensor<4x2x30x30xf32>>
    return %1 : tuple<tensor<4x2x30x30xf32>>
  }
}

As above, the SSA value is %0 which is a input of the tuple. and the parent operation (a node of the graph) is mhlo.convolution. how can i get the mhlo.convolution?

the definition of mlir::value is found here, there are functions like these:

  /// Return the Region in which this Value is defined.
  Region *getParentRegion();

  /// Return the Block in which this Value is defined.
  Block *getParentBlock();

but without a function like this:

   Operation *getParentOperation();

Is there any function available to get the parent opetarion of the SSA value?

is this the correct function?

  /// If this value is the result of an operation of type OpTy, return the
  /// operation that defines it.
  template <typename OpTy>
  OpTy getDefiningOp() const {
    return llvm::dyn_cast_or_null<OpTy>(getDefiningOp());
  }

Yes, you can call getDefiningOp for your purposes. The templated version also attempts to cast the defining operation to the specific type. Note that it can return null, and always does so if the value is a block argument.

In MLIR terminology, the parent operation is the operation that contains the definition of the value (either the block for block arguments or the defining operation for op results). In your example, it would be func, not mhlo.convolution. What you are looking for is the defining operation as the function name indicates.

1 Like

it works. thanks a lot!