Skip to content

Commit 6a252e4

Browse files
joker-ephtru
authored andcommitted
[MLIR] Introduce a OpWithState class to act as a stream modifier for Operations (NFC) (#151547)
On the model of OpWithFlags, this modifier allows to stream an operation using a custom AsmPrinter.
1 parent 3e22f22 commit 6a252e4

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

mlir/include/mlir/IR/Operation.h

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1102,6 +1102,49 @@ inline raw_ostream &operator<<(raw_ostream &os, const Operation &op) {
11021102
return os;
11031103
}
11041104

1105+
/// A wrapper class that allows for printing an operation with a set of flags,
1106+
/// useful to act as a "stream modifier" to customize printing an operation
1107+
/// with a stream using the operator<< overload, e.g.:
1108+
/// llvm::dbgs() << OpWithFlags(op, OpPrintingFlags().skipRegions());
1109+
class OpWithFlags {
1110+
public:
1111+
OpWithFlags(Operation *op, OpPrintingFlags flags = {})
1112+
: op(op), theFlags(flags) {}
1113+
OpPrintingFlags &flags() { return theFlags; }
1114+
const OpPrintingFlags &flags() const { return theFlags; }
1115+
1116+
private:
1117+
Operation *op;
1118+
OpPrintingFlags theFlags;
1119+
friend raw_ostream &operator<<(raw_ostream &os, const OpWithFlags &op);
1120+
};
1121+
1122+
inline raw_ostream &operator<<(raw_ostream &os,
1123+
const OpWithFlags &opWithFlags) {
1124+
opWithFlags.op->print(os, opWithFlags.flags());
1125+
return os;
1126+
}
1127+
1128+
/// A wrapper class that allows for printing an operation with a custom
1129+
/// AsmState, useful to act as a "stream modifier" to customize printing an
1130+
/// operation with a stream using the operator<< overload, e.g.:
1131+
/// llvm::dbgs() << OpWithState(op, OpPrintingFlags().skipRegions());
1132+
class OpWithState {
1133+
public:
1134+
OpWithState(Operation *op, AsmState &state) : op(op), theState(state) {}
1135+
1136+
private:
1137+
Operation *op;
1138+
AsmState &theState;
1139+
friend raw_ostream &operator<<(raw_ostream &os, const OpWithState &op);
1140+
};
1141+
1142+
inline raw_ostream &operator<<(raw_ostream &os,
1143+
const OpWithState &opWithState) {
1144+
opWithState.op->print(os, const_cast<OpWithState &>(opWithState).theState);
1145+
return os;
1146+
}
1147+
11051148
} // namespace mlir
11061149

11071150
namespace llvm {

mlir/lib/Tools/mlir-opt/MlirOptMain.cpp

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -508,8 +508,7 @@ performActions(raw_ostream &os,
508508
<< "bytecode version while not emitting bytecode";
509509
AsmState asmState(op.get(), OpPrintingFlags(), /*locationMap=*/nullptr,
510510
&fallbackResourceMap);
511-
op.get()->print(os, asmState);
512-
os << '\n';
511+
os << OpWithState(op.get(), asmState) << '\n';
513512
return success();
514513
}
515514

0 commit comments

Comments
 (0)