Skip to content

Commit

Permalink
[flang][HLFIR] Fix use-after-free when rewriting users in `canonicali…
Browse files Browse the repository at this point in the history
…ze` (#84371)

Rewriting an op can invalidate the operator range being iterated on.
Store the users in a separate list, and iterate over the list instead.

This was detected by address sanitizer.
  • Loading branch information
kparzysz committed Mar 8, 2024
1 parent 912ea6e commit 10b0156
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions flang/lib/Optimizer/HLFIR/IR/HLFIROps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
//===----------------------------------------------------------------------===//

#include "flang/Optimizer/HLFIR/HLFIROps.h"

#include "flang/Optimizer/Dialect/FIROpsSupport.h"
#include "flang/Optimizer/Dialect/FIRType.h"
#include "flang/Optimizer/Dialect/Support/FIRContext.h"
Expand Down Expand Up @@ -1152,7 +1153,9 @@ hlfir::MatmulOp::canonicalize(MatmulOp matmulOp,

// but we do need to get rid of the hlfir.destroy for the hlfir.transpose
// result (which is entirely removed)
for (mlir::Operation *user : transposeOp->getResult(0).getUsers())
llvm::SmallVector<mlir::Operation *> users(
transposeOp->getResult(0).getUsers());
for (mlir::Operation *user : users)
if (auto destroyOp = mlir::dyn_cast_or_null<hlfir::DestroyOp>(user))
rewriter.eraseOp(destroyOp);
rewriter.eraseOp(transposeOp);
Expand Down Expand Up @@ -1864,7 +1867,8 @@ hlfir::ForallIndexOp::canonicalize(hlfir::ForallIndexOp indexOp,
return mlir::failure();

auto insertPt = rewriter.saveInsertionPoint();
for (mlir::Operation *user : indexOp->getResult(0).getUsers())
llvm::SmallVector<mlir::Operation *> users(indexOp->getResult(0).getUsers());
for (mlir::Operation *user : users)
if (auto loadOp = mlir::dyn_cast<fir::LoadOp>(user)) {
rewriter.setInsertionPoint(loadOp);
rewriter.replaceOpWithNewOp<fir::ConvertOp>(
Expand Down

0 comments on commit 10b0156

Please sign in to comment.