Skip to content

Commit

Permalink
[flang] Simple folding for hlfir.shape_of. (#119649)
Browse files Browse the repository at this point in the history
This folding makes sure there are no hlfir.shape_of users
of hlfir.elemental - this may enable more InlineElementals matches,
because it is looking for exactly two uses of an hlfir.elemental.
  • Loading branch information
vzakhari authored Dec 12, 2024
1 parent 2546ae4 commit 139e69b
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions flang/include/flang/Optimizer/HLFIR/HLFIROps.td
Original file line number Diff line number Diff line change
Expand Up @@ -1205,6 +1205,7 @@ def hlfir_ShapeOfOp : hlfir_Op<"shape_of", [Pure]> {
}];

let builders = [OpBuilder<(ins "mlir::Value":$expr)>];
let hasFolder = 1;
}

def hlfir_GetExtentOp : hlfir_Op<"get_extent", [Pure]> {
Expand Down
9 changes: 9 additions & 0 deletions flang/lib/Optimizer/HLFIR/IR/HLFIROps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1704,6 +1704,15 @@ hlfir::ShapeOfOp::canonicalize(ShapeOfOp shapeOf,
return llvm::LogicalResult::success();
}

mlir::OpFoldResult hlfir::ShapeOfOp::fold(FoldAdaptor adaptor) {
if (matchPattern(getExpr(), mlir::m_Op<hlfir::ElementalOp>())) {
auto elementalOp =
mlir::cast<hlfir::ElementalOp>(getExpr().getDefiningOp());
return elementalOp.getShape();
}
return {};
}

//===----------------------------------------------------------------------===//
// GetExtent
//===----------------------------------------------------------------------===//
Expand Down
18 changes: 18 additions & 0 deletions flang/test/HLFIR/shapeof.fir
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,21 @@ func.func @shapeof2(%arg0: !hlfir.expr<?x2xi32>) -> !fir.shape<2> {
// CHECK-ALL: %[[EXPR:.*]]: !hlfir.expr<?x2xi32>
// CHECK-ALL-NEXT: %[[SHAPE:.*]] = hlfir.shape_of %[[EXPR]] : (!hlfir.expr<?x2xi32>) -> !fir.shape<2>
// CHECK-ALL-NEXT: return %[[SHAPE]]

// Checks hlfir.elemental -> hlfir.shape_of folding
func.func @shapeof_fold1(%extent: index) -> !fir.shape<1> {
%shape1 = fir.shape %extent : (index) -> !fir.shape<1>
%elem = hlfir.elemental %shape1 : (!fir.shape<1>) -> !hlfir.expr<?xindex> {
hlfir.yield_element %extent : index
}
%shape2 = hlfir.shape_of %elem : (!hlfir.expr<?xindex>) -> !fir.shape<1>
return %shape2 : !fir.shape<1>
}
// CHECK-ALL-LABEL: func.func @shapeof_fold1(
// CHECK-ALL-SAME: %[[VAL_0:.*]]: index) -> !fir.shape<1> {
// CHECK-CANON-NEXT: %[[VAL_1:.*]] = fir.shape %[[VAL_0]] : (index) -> !fir.shape<1>
// CHECK-CANON-NEXT: %[[VAL_2:.*]] = hlfir.elemental %[[VAL_1]] : (!fir.shape<1>) -> !hlfir.expr<?xindex> {
// CHECK-CANON-NEXT: hlfir.yield_element %[[VAL_0]] : index
// CHECK-CANON-NEXT: }
// CHECK-CANON-NEXT: return %[[VAL_1]] : !fir.shape<1>
// CHECK-CANON-NEXT: }

0 comments on commit 139e69b

Please sign in to comment.