[llvm-branch-commits] [mlir] [mlir][tblgen] Check substitutions throughout code generation (PR #238152)
Mehdi Amini via llvm-branch-commits
llvm-branch-commits at lists.llvm.org
Mon Nov 2 15:50:52 PST 2026
https://github.com/joker-eph created https://github.com/llvm/llvm-project/pull/238152
Migrate generator and shared-verifier emission to eager fatal formatting with template-definition origins and operation use notes. Synthesized properties without a record fall back to the operation location. Speculative attribute and property uniquing now consumes checked errors and falls back to inline verification. Keep value-specific bindings local to their verifier.
Add checked summary-expression formatting that retains the escaped segment and propagates its owned error to the source diagnostic boundary. Expose reference-taking tgfmt and tgfmtv overloads returning Expected, retain transition aliases, and document formatting semantics and diagnostics in the existing ODS guide.
Escape literal dollars in a test builder comment, and keep the nested matcher error test focused on its intended invalid DAG. Add regression coverage for shared and inline constraints, summaries, attribute templates, interface templates, and the reference-taking API.
Assisted-by: Codex
>From 9db43d4cebaa6d55aa7f139d5a5ae92d603c684c Mon Sep 17 00:00:00 2001
From: Mehdi Amini <joker.eph at gmail.com>
Date: Sun, 1 Nov 2026 04:52:18 -0800
Subject: [PATCH] [mlir][tblgen] Check substitutions throughout code generation
Migrate generator and shared-verifier emission to eager fatal formatting
with template-definition origins and operation use notes. Synthesized
properties without a record fall back to the operation location.
Speculative attribute and property uniquing now consumes checked errors
and falls back to inline verification. Keep value-specific bindings
local to their verifier.
Add checked summary-expression formatting that retains the escaped
segment and propagates its owned error to the source diagnostic
boundary. Expose reference-taking tgfmt and tgfmtv overloads returning
Expected, retain transition aliases, and document formatting semantics
and diagnostics in the existing ODS guide.
Escape literal dollars in a test builder comment, and keep the nested
matcher error test focused on its intended invalid DAG. Add regression
coverage for shared and inline constraints, summaries, attribute
templates, interface templates, and the reference-taking API.
Validation: mlir-tblgen, MLIRTableGenTests, and mlir-opt rebuild; all 77
TableGen unit tests and all 70 mlir-tblgen lit tests pass.
Assisted-by: Codex
---
mlir/docs/DefiningDialects/Operations.md | 90 +++++++
mlir/include/mlir/TableGen/Class.h | 5 -
mlir/include/mlir/TableGen/CodeGenHelpers.h | 23 +-
mlir/include/mlir/TableGen/Format.h | 24 +-
mlir/include/mlir/TableGen/Property.h | 4 +
mlir/lib/TableGen/CodeGenHelpers.cpp | 137 +++++++---
mlir/test/lib/Dialect/Test/TestOps.td | 6 +-
.../mlir-tblgen/format-substitution-errors.td | 196 ++++++++++++++
mlir/test/mlir-tblgen/rewriter-errors.td | 10 +-
mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp | 38 ++-
.../tools/mlir-tblgen/AttrOrTypeFormatGen.cpp | 171 ++++++++-----
mlir/tools/mlir-tblgen/EnumsGen.cpp | 12 +-
mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp | 241 ++++++++++++------
mlir/tools/mlir-tblgen/OpFormatGen.cpp | 166 +++++++-----
mlir/tools/mlir-tblgen/OpInterfacesGen.cpp | 61 ++++-
mlir/tools/mlir-tblgen/RewriterGen.cpp | 63 +++--
mlir/tools/mlir-tblgen/SPIRVUtilsGen.cpp | 15 +-
mlir/unittests/TableGen/FormatTest.cpp | 49 ++++
18 files changed, 1014 insertions(+), 297 deletions(-)
create mode 100644 mlir/test/mlir-tblgen/format-substitution-errors.td
diff --git a/mlir/docs/DefiningDialects/Operations.md b/mlir/docs/DefiningDialects/Operations.md
index f991f5308c5ae4..27d4021be4cb4d 100644
--- a/mlir/docs/DefiningDialects/Operations.md
+++ b/mlir/docs/DefiningDialects/Operations.md
@@ -1468,6 +1468,10 @@ is used. They serve as "hooks" to the enclosing environment. This includes
replaced by the operand/result's type. E.g., for `F32` in `F32:$operand`,
its `$_self` will be expanded as `operand(...).getType()`.
+The available substitutions depend on the template's use. See
+[Diagnose template substitutions](#diagnose-template-substitutions) for error
+reporting and escaping literal dollars.
+
TODO: Reconsider the leading symbol for special placeholders. Eventually we want
to allow referencing operand/result `$-name`s; such `$-name`s can start with
underscore.
@@ -1863,6 +1867,92 @@ mlir-tblgen --gen-op-interface-defs -I /path/to/mlir/include /path/to/input/td/f
mlir-tblgen --gen-op-interface-doc -I /path/to/mlir/include /path/to/input/td/file
```
+### Diagnose template substitutions
+
+ODS C++ templates use named substitutions such as `$_self` and `$_op`. The
+available substitutions depend on where the template is expanded. For example,
+`$_self` denotes a value in an attribute or type constraint, but is unavailable
+in an operation trait predicate. Write `$$` to emit a literal dollar, including
+inside C++ strings and comments.
+
+A missing substitution produces a TableGen error identifying the template's
+source, with its use site as a note when available. The diagnostic includes the
+template, failed occurrences, and the names of the available substitutions.
+Byte offsets refer to the displayed template, not positions in the `.td` source.
+For example:
+
+```text
+BadTraits.td:12:5: error: cannot substitute '$_self' while formatting trait predicate: missing named binding
+note: template: ($_self)
+note: failed occurrence starts at template byte offset 1
+Ops.td:24:1: note: while expanding operation verifier
+note: available named substitutions: $_op
+note: no positional substitutions were supplied
+```
+
+### Format templates in a generator
+
+`mlir/TableGen/Format.h` provides `tgfmt(template, ctx, values...)` and its
+array form `tgfmtv(template, ctx, values)`. Both take a `const FmtContext &`,
+validate all placeholders before rendering positional values, and return an
+`llvm::Expected<std::string>` that owns its result or error. Use `FmtContext{}`
+for positional-only formatting. Check an inner result before passing its string
+to another formatting call:
+
+```cpp
+llvm::Expected<std::string> formatVerifier(StringRef predicate,
+ const FmtContext &ctx) {
+ auto condition = tgfmt(predicate, ctx);
+ if (!condition)
+ return condition.takeError();
+ return tgfmt("if (!($0)) return failure();", ctx, *condition);
+}
+```
+
+Register named substitutions without the leading `$`. Builtin setters such as
+`withSelf(value)` and `withBuilder(value)` register `_self` and `_builder` in the
+same map as `addSubst`; the last registration wins. Positional indices are decimal
+(`$010` denotes index 10). `$N...` expands the remaining positional arguments,
+with commas between them; `N` must be less than the argument count. Replacement
+text is emitted literally without recursive expansion.
+
+At a generator boundary that terminates on invalid input, use `tgfmtOrFatal` or
+`tgfmtvOrFatal` from `mlir/TableGen/CodeGenHelpers.h`. Supply the template's
+source and purpose with a `FmtOrigin`; attach the enclosing operation as a use
+site. For a synthesized template without a definition, use the enclosing
+operation's location:
+
+```cpp
+FmtContext ctx;
+ctx.addSubst("_op", "getOperation()");
+FmtOrigin origin = FmtOrigin::at(trait.getDef().getLoc(), "trait predicate")
+ .withUse(op.getLoc(), "operation verifier");
+os << tgfmtOrFatal(origin, trait.getPredTemplate(), ctx);
+```
+
+Recoverable helpers can attach source context with
+`addFmtOrigin(result.takeError(), origin)` and propagate the typed `FmtError`.
+The error owns the template, failed occurrences, and a sorted snapshot of named
+bindings. `getFmtDiagnostics` renders messages for a caller's diagnostic system.
+Source-manager buffers must remain alive until those messages are emitted.
+`FmtContext::printBindings` and `FmtError::printBindings` log names and escaped
+replacement values; the error prints its snapshot even if the context changes.
+
+A speculative probe can consume a formatting error and choose another emission
+path. Check the template with the full context when it is emitted:
+
+```cpp
+auto probe = tgfmt(predicate, restrictedCtx);
+if (!probe) {
+ llvm::consumeError(probe.takeError());
+ return false;
+}
+```
+
+Constraint summaries can contain `{{...}}` C++ expressions. These expressions
+are formatted after C++ string escaping. Their diagnostics identify the failing
+segment as an "escaped summary expression", with offsets within that segment.
+
## Appendix
### Reporting deprecation in TableGen
diff --git a/mlir/include/mlir/TableGen/Class.h b/mlir/include/mlir/TableGen/Class.h
index e6bedc7cc896d9..e6328615b17544 100644
--- a/mlir/include/mlir/TableGen/Class.h
+++ b/mlir/include/mlir/TableGen/Class.h
@@ -37,8 +37,6 @@
namespace mlir {
namespace tblgen {
-class FmtObjectBase;
-
/// This class contains a single method parameter for a C++ function.
class MethodParameter {
public:
@@ -480,7 +478,6 @@ class Constructor : public Method {
/// The list of member initializers.
SmallVector<MemberInitializer> initializers;
};
-
} // namespace tblgen
} // namespace mlir
@@ -502,7 +499,6 @@ operator|=(mlir::tblgen::Method::Properties &lhs,
namespace mlir {
namespace tblgen {
-
template <typename ParamT>
void Method::addTemplateParam(ParamT param) {
// Templates imply inline.
@@ -896,7 +892,6 @@ class Class {
/// An optional list of class template parameters.
SetVector<std::string, SmallVector<std::string>, StringSet<>> templateParams;
};
-
} // namespace tblgen
} // namespace mlir
diff --git a/mlir/include/mlir/TableGen/CodeGenHelpers.h b/mlir/include/mlir/TableGen/CodeGenHelpers.h
index 88cc565a69ddba..a604d101523a4d 100644
--- a/mlir/include/mlir/TableGen/CodeGenHelpers.h
+++ b/mlir/include/mlir/TableGen/CodeGenHelpers.h
@@ -32,6 +32,8 @@ namespace mlir {
namespace tblgen {
class Constraint;
class DagLeaf;
+class Operator;
+class Property;
/// Consume every error payload, print all messages, then terminate through
/// TableGen's fatal cleanup path. The caller origin is appended after any
@@ -39,6 +41,13 @@ class DagLeaf;
[[noreturn]] void reportFatalFmtError(llvm::Error error,
const FmtOrigin &callerOrigin);
+/// Anchor a constraint template at its definition and retain the operation use.
+/// Synthesized properties without a definition use the operation location.
+FmtOrigin getConstraintFmtOrigin(const Constraint &constraint,
+ const Operator &op, StringRef purpose);
+FmtOrigin getConstraintFmtOrigin(const Property &property, const Operator &op,
+ StringRef purpose);
+
/// Eager formatting at a TableGen diagnostic boundary. User-authored templates
/// should supply their definition origin and any known use-site context.
template <typename... Ts>
@@ -286,11 +295,21 @@ std::string stringify(T &&t) {
/// "failed to verify {{foo}}"
/// into:
/// "failed to verify " << bar
-/// where bar is the result of evaluating 'tgfmt("foo", &ctx)' at compile
-/// time.
+/// where bar is the result of formatting "foo" with ctx during code generation.
std::string buildErrorStreamingString(
StringRef message, const FmtContext &ctx,
ErrorStreamType errorStreamType = ErrorStreamType::InString);
+
+/// Checked summary formatting. Failed templates and offsets refer to the
+/// escaped expression segment, not the whole original summary.
+llvm::Expected<std::string> buildErrorStreamingStringChecked(
+ StringRef message, const FmtContext &ctx,
+ ErrorStreamType errorStreamType = ErrorStreamType::InString);
+
+/// Format a summary at a source-aware TableGen diagnostic boundary.
+std::string buildErrorStreamingStringOrFatal(
+ const FmtOrigin &origin, StringRef message, const FmtContext &ctx,
+ ErrorStreamType errorStreamType = ErrorStreamType::InString);
} // namespace tblgen
} // namespace mlir
diff --git a/mlir/include/mlir/TableGen/Format.h b/mlir/include/mlir/TableGen/Format.h
index 6d1b1c56d077c7..5ab0ef179ebcac 100644
--- a/mlir/include/mlir/TableGen/Format.h
+++ b/mlir/include/mlir/TableGen/Format.h
@@ -373,16 +373,36 @@ inline FmtStrVecObject tgfmtv(StringRef fmt, const FmtContext *ctx,
/// their text; neither result nor error borrows the input template, context, or
/// arguments.
template <typename... Ts>
+llvm::Expected<std::string> tgfmt(StringRef fmt, const FmtContext &ctx,
+ Ts &&...vals) {
+ using ParamTuple = decltype(std::make_tuple(
+ llvm::support::detail::FormatFunctor<Ts>(std::forward<Ts>(vals))...));
+ return FmtObject<ParamTuple>(
+ fmt, &ctx,
+ std::make_tuple(llvm::support::detail::FormatFunctor<Ts>(
+ std::forward<Ts>(vals))...))
+ .strChecked();
+}
+
+/// Checked array form, with the same validation and ownership as tgfmt.
+inline llvm::Expected<std::string> tgfmtv(StringRef fmt, const FmtContext &ctx,
+ ArrayRef<std::string> params) {
+ return FmtStrVecObject(fmt, &ctx, params).strChecked();
+}
+
+/// Alias for the reference-taking tgfmt overload, with the same placeholder
+/// validation and FmtError conditions documented above.
+template <typename... Ts>
llvm::Expected<std::string> tgfmtChecked(StringRef fmt, const FmtContext &ctx,
Ts &&...vals) {
- return tgfmt(fmt, &ctx, std::forward<Ts>(vals)...).strChecked();
+ return tgfmt(fmt, ctx, std::forward<Ts>(vals)...);
}
/// Array form of tgfmtChecked, with the same validation and ownership.
inline llvm::Expected<std::string> tgfmtvChecked(StringRef fmt,
const FmtContext &ctx,
ArrayRef<std::string> params) {
- return tgfmtv(fmt, &ctx, params).strChecked();
+ return tgfmtv(fmt, ctx, params);
}
} // namespace tblgen
} // namespace mlir
diff --git a/mlir/include/mlir/TableGen/Property.h b/mlir/include/mlir/TableGen/Property.h
index 5877b54147f99d..aac9b5f6f80145 100644
--- a/mlir/include/mlir/TableGen/Property.h
+++ b/mlir/include/mlir/TableGen/Property.h
@@ -57,6 +57,10 @@ class Property : public PropConstraint {
StringRef writeToMlirBytecodeCall, StringRef hashPropertyCall,
StringRef defaultValue, StringRef storageTypeValueOverride);
+ /// Whether this property has a TableGen definition. Builtin segment-size
+ /// properties may be synthesized without one.
+ bool hasDef() const { return def != nullptr; }
+
// Returns the summary (for error messages) of this property's type.
StringRef getSummary() const { return summary; }
diff --git a/mlir/lib/TableGen/CodeGenHelpers.cpp b/mlir/lib/TableGen/CodeGenHelpers.cpp
index 9f17892a3234ff..96ed992cc09c5d 100644
--- a/mlir/lib/TableGen/CodeGenHelpers.cpp
+++ b/mlir/lib/TableGen/CodeGenHelpers.cpp
@@ -168,11 +168,30 @@ StringRef StaticVerifierFunctionEmitter::getRegionConstraintFn(
// Constraint Emission
//===----------------------------------------------------------------------===//
+/// Point at the record that supplies the template and retain its operation use.
+FmtOrigin mlir::tblgen::getConstraintFmtOrigin(const Constraint &constraint,
+ const Operator &op,
+ StringRef purpose) {
+ return FmtOrigin::at(constraint.getDef().getLoc(), purpose)
+ .withUse(op.getLoc(), "operation '" + op.getOperationName() + "'");
+}
+
+// Builtin segment-size properties are synthesized without a TableGen record.
+FmtOrigin mlir::tblgen::getConstraintFmtOrigin(const Property &property,
+ const Operator &op,
+ StringRef purpose) {
+ if (!property.hasDef())
+ return FmtOrigin::at(op.getLoc(), purpose);
+ return getConstraintFmtOrigin(static_cast<const Constraint &>(property), op,
+ purpose);
+}
+
/// Helper to generate a C++ string expression from a given message.
/// Message can contain '{{...}}' placeholders that are substituted with
/// C-expressions via tgfmt.
-std::string mlir::tblgen::buildErrorStreamingString(
- StringRef message, const FmtContext &ctx, ErrorStreamType errorStreamType) {
+static llvm::Expected<std::string>
+buildErrorStreamingStringImpl(StringRef message, const FmtContext &ctx,
+ ErrorStreamType errorStreamType, bool checked) {
std::string result;
raw_string_ostream os(result);
@@ -197,7 +216,14 @@ std::string mlir::tblgen::buildErrorStreamingString(
StringRef var = split.first;
StringRef rest = split.second;
- os << " << " << tgfmt(var, &ctx);
+ auto expression =
+ checked
+ ? tgfmtChecked(var, ctx)
+ : llvm::Expected<std::string>(FmtStrVecObject(var, &ctx, {}).str());
+ if (!expression)
+ return addFmtOrigin(expression.takeError(),
+ FmtOrigin::describe("escaped summary expression"));
+ os << " << " << *expression;
if (errorStreamType == ErrorStreamType::InsideOpError) {
// To enable having part of string post, this adds a parenthesis before
@@ -215,6 +241,26 @@ std::string mlir::tblgen::buildErrorStreamingString(
return os.str();
}
+std::string mlir::tblgen::buildErrorStreamingString(
+ StringRef message, const FmtContext &ctx, ErrorStreamType errorStreamType) {
+ return llvm::cantFail(
+ buildErrorStreamingStringImpl(message, ctx, errorStreamType, false));
+}
+
+llvm::Expected<std::string> mlir::tblgen::buildErrorStreamingStringChecked(
+ StringRef message, const FmtContext &ctx, ErrorStreamType errorStreamType) {
+ return buildErrorStreamingStringImpl(message, ctx, errorStreamType, true);
+}
+
+std::string mlir::tblgen::buildErrorStreamingStringOrFatal(
+ const FmtOrigin &origin, StringRef message, const FmtContext &ctx,
+ ErrorStreamType errorStreamType) {
+ auto result = buildErrorStreamingStringChecked(message, ctx, errorStreamType);
+ if (!result)
+ reportFatalFmtError(result.takeError(), origin);
+ return std::move(*result);
+}
+
/// Code templates for emitting type, attribute, successor, and region
/// constraints. Each of these templates require the following arguments:
///
@@ -332,9 +378,12 @@ void StaticVerifierFunctionEmitter::emitConstraints(
ctx.addSubst("_op", "*op").withSelf(selfName);
for (auto &it : constraints) {
+ FmtOrigin origin = FmtOrigin::at(it.first.getDef().getLoc(),
+ "shared " + selfName + " constraint");
os << formatv(codeTemplate, it.second,
- tgfmt(it.first.getConditionTemplate(), &ctx),
- buildErrorStreamingString(it.first.getSummary(), ctx));
+ tgfmtOrFatal(origin, it.first.getConditionTemplate(), ctx),
+ buildErrorStreamingStringOrFatal(
+ origin, it.first.getSummary(), ctx, errorStreamType));
}
}
void StaticVerifierFunctionEmitter::emitTypeConstraints() {
@@ -353,11 +402,14 @@ void StaticVerifierFunctionEmitter::emitPropConstraints() {
FmtContext ctx;
ctx.addSubst("_op", "*op").withSelf("prop");
for (auto &it : propConstraints) {
+ FmtOrigin origin =
+ FmtOrigin::at(it.first.getDef().getLoc(), "shared property constraint");
auto propConstraint = cast<PropConstraint>(it.first);
- os << formatv(propConstraintCode, it.second,
- tgfmt(propConstraint.getConditionTemplate(), &ctx),
- buildErrorStreamingString(it.first.getSummary(), ctx),
- propConstraint.getInterfaceType());
+ os << formatv(
+ propConstraintCode, it.second,
+ tgfmtOrFatal(origin, propConstraint.getConditionTemplate(), ctx),
+ buildErrorStreamingStringOrFatal(origin, it.first.getSummary(), ctx),
+ propConstraint.getInterfaceType());
}
}
@@ -375,20 +427,28 @@ void StaticVerifierFunctionEmitter::emitPatternConstraints() {
FmtContext ctx;
ctx.addSubst("_op", "*op").withBuilder("rewriter").withSelf("type");
for (auto &it : typeConstraints) {
- os << formatv(patternConstraintCode, it.second,
- tgfmt(it.first.getConditionTemplate(), &ctx),
- buildErrorStreamingString(it.first.getSummary(), ctx),
- "::mlir::Type type");
+ FmtOrigin origin = FmtOrigin::at(it.first.getDef().getLoc(),
+ "shared pattern type constraint");
+ os << formatv(
+ patternConstraintCode, it.second,
+ tgfmtOrFatal(origin, it.first.getConditionTemplate(), ctx),
+ buildErrorStreamingStringOrFatal(origin, it.first.getSummary(), ctx),
+ "::mlir::Type type");
}
ctx.withSelf("attr");
for (auto &it : attrConstraints) {
- os << formatv(patternConstraintCode, it.second,
- tgfmt(it.first.getConditionTemplate(), &ctx),
- buildErrorStreamingString(it.first.getSummary(), ctx),
- "::mlir::Attribute attr");
+ FmtOrigin origin = FmtOrigin::at(it.first.getDef().getLoc(),
+ "shared pattern attribute constraint");
+ os << formatv(
+ patternConstraintCode, it.second,
+ tgfmtOrFatal(origin, it.first.getConditionTemplate(), ctx),
+ buildErrorStreamingStringOrFatal(origin, it.first.getSummary(), ctx),
+ "::mlir::Attribute attr");
}
ctx.withSelf("prop");
for (auto &it : propConstraints) {
+ FmtOrigin origin = FmtOrigin::at(it.first.getDef().getLoc(),
+ "shared pattern property constraint");
PropConstraint propConstraint = cast<PropConstraint>(it.first);
StringRef interfaceType = propConstraint.getInterfaceType();
// Constraints that are generic over multiple interface types are
@@ -397,10 +457,12 @@ void StaticVerifierFunctionEmitter::emitPatternConstraints() {
interfaceType = "T";
os << "template <typename T>";
}
- os << formatv(patternConstraintCode, it.second,
- tgfmt(propConstraint.getConditionTemplate(), &ctx),
- buildErrorStreamingString(propConstraint.getSummary(), ctx),
- Twine(interfaceType) + " prop");
+ os << formatv(
+ patternConstraintCode, it.second,
+ tgfmtOrFatal(origin, propConstraint.getConditionTemplate(), ctx),
+ buildErrorStreamingStringOrFatal(origin, propConstraint.getSummary(),
+ ctx),
+ Twine(interfaceType) + " prop");
}
}
@@ -415,10 +477,18 @@ void StaticVerifierFunctionEmitter::emitPatternConstraints() {
/// because ops use cached identifiers.
static bool canUniqueAttrConstraint(Attribute attr) {
FmtContext ctx;
- auto test = tgfmt(attr.getConditionTemplate(),
- &ctx.withSelf("attr").addSubst("_op", "*op"))
- .str();
- return !StringRef(test).contains("<no-subst-found>");
+ auto test = tgfmtChecked(attr.getConditionTemplate(),
+ ctx.withSelf("attr").addSubst("_op", "*op"));
+ if (!test) {
+ llvm::consumeError(test.takeError());
+ return false;
+ }
+ auto summary = buildErrorStreamingStringChecked(attr.getSummary(), ctx);
+ if (!summary) {
+ llvm::consumeError(summary.takeError());
+ return false;
+ }
+ return true;
}
/// A property constraint that references anything other than itself and the
@@ -428,11 +498,18 @@ static bool canUniqueAttrConstraint(Attribute attr) {
/// "true" shouldn't be constrained.
static bool canUniquePropConstraint(Property prop) {
FmtContext ctx;
- auto test = tgfmt(prop.getConditionTemplate(),
- &ctx.withSelf("prop").addSubst("_op", "*op"))
- .str();
- return !StringRef(test).contains("<no-subst-found>") && test != "true" &&
- !prop.getInterfaceType().empty();
+ auto test = tgfmtChecked(prop.getConditionTemplate(),
+ ctx.withSelf("prop").addSubst("_op", "*op"));
+ if (!test) {
+ llvm::consumeError(test.takeError());
+ return false;
+ }
+ auto summary = buildErrorStreamingStringChecked(prop.getSummary(), ctx);
+ if (!summary) {
+ llvm::consumeError(summary.takeError());
+ return false;
+ }
+ return *test != "true" && !prop.getInterfaceType().empty();
}
std::string StaticVerifierFunctionEmitter::getUniqueName(StringRef kind,
diff --git a/mlir/test/lib/Dialect/Test/TestOps.td b/mlir/test/lib/Dialect/Test/TestOps.td
index fc096a9e61d710..92f1507267238b 100644
--- a/mlir/test/lib/Dialect/Test/TestOps.td
+++ b/mlir/test/lib/Dialect/Test/TestOps.td
@@ -2088,10 +2088,10 @@ def MixedVResultOp3 : TEST_Op<"mixed_variadic_out3",
OpBuilder<(ins "::mlir::IntegerAttr":$count),
[{
auto i32Type = $_builder.getIntegerType(32);
- $_state.addTypes(i32Type); // $output1
+ $_state.addTypes(i32Type); // $$output1
SmallVector<Type, 4> types(count.getInt(), i32Type);
- $_state.addTypes(types); // $output2
- $_state.addTypes(types); // $output3
+ $_state.addTypes(types); // $$output2
+ $_state.addTypes(types); // $$output3
$_state.addAttribute("count", count);
}]>
];
diff --git a/mlir/test/mlir-tblgen/format-substitution-errors.td b/mlir/test/mlir-tblgen/format-substitution-errors.td
new file mode 100644
index 00000000000000..715f20c993ee56
--- /dev/null
+++ b/mlir/test/mlir-tblgen/format-substitution-errors.td
@@ -0,0 +1,196 @@
+// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DDEFAULT %s 2>&1 | FileCheck %s --check-prefix=DEFAULT
+// RUN: mlir-tblgen -gen-op-defs -I %S/../../include -DSUMMARYVALID %s | FileCheck %s --check-prefix=SUMMARYVALID
+// RUN: mlir-tblgen -gen-op-defs -I %S/../../include -DPROPVALID %s | FileCheck %s --check-prefix=PROPVALID
+// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DPROP %s 2>&1 | FileCheck %s --check-prefix=PROP
+// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DPROPSUM %s 2>&1 | FileCheck %s --check-prefix=PROPSUM
+// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DATTRSUM %s 2>&1 | FileCheck %s --check-prefix=ATTRSUM
+// RUN: not mlir-tblgen -gen-typedef-defs -I %S/../../include -DASSEMBLY %s 2>&1 | FileCheck %s --check-prefix=ASSEMBLY
+// RUN: not mlir-tblgen -gen-typedef-defs -I %S/../../include -DPARAM %s 2>&1 | FileCheck %s --check-prefix=PARAM
+// RUN: not mlir-tblgen -gen-enum-defs -I %S/../../include -DENUM %s 2>&1 | FileCheck %s --check-prefix=ENUM
+// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DSHARED %s 2>&1 | FileCheck %s --check-prefix=SHARED
+// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DSUMMARY %s 2>&1 | FileCheck %s --check-prefix=SUMMARY
+// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DINLINE %s 2>&1 | FileCheck %s --check-prefix=INLINE
+// RUN: not mlir-tblgen -gen-attrdef-defs -I %S/../../include -DATTR %s 2>&1 | FileCheck %s --check-prefix=ATTR
+// RUN: not mlir-tblgen -gen-op-interface-decls -I %S/../../include -DINTERFACE %s 2>&1 | FileCheck %s --check-prefix=INTERFACE
+
+include "mlir/IR/OpBase.td"
+include "mlir/IR/AttrTypeBase.td"
+include "mlir/IR/Properties.td"
+include "mlir/IR/EnumAttr.td"
+
+def TestDialect : Dialect {
+ let name = "test";
+ let cppNamespace = "::test";
+}
+
+#ifdef SHARED
+// SHARED: format-substitution-errors.td:[[#@LINE+5]]:5: error: cannot substitute '$_builder' while formatting shared type constraint
+// SHARED: note: template: ($_builder.getType())
+// SHARED: note: available named substitutions: $_op, $_self
+// SHARED-NOT: <no-subst-found>
+// A type constraint's shared verifier has no builder binding.
+def MissingBuilder : Type<CPred<"$_builder.getType()">, "bad type">;
+def SharedOp : Op<TestDialect, "shared"> {
+ let arguments = (ins MissingBuilder:$input);
+}
+#endif
+
+#ifdef SUMMARY
+// SUMMARY: format-substitution-errors.td:[[#@LINE+5]]:5: error: cannot substitute '$missing' while formatting escaped summary expression
+// SUMMARY: note: template: $missing
+// SUMMARY: note: while formatting shared type constraint
+// SUMMARY: note: available named substitutions: $_op, $_self
+// SUMMARY-NOT: <no-subst-found>
+def MissingSummary : Type<CPred<"true">, "bad {{$missing}} type">;
+def SummaryOp : Op<TestDialect, "summary"> {
+ let arguments = (ins MissingSummary:$input);
+}
+#endif
+
+#ifdef INLINE
+// A rejected speculative attribute probe is retried in the full inline context.
+// INLINE: format-substitution-errors.td:[[#@LINE+4]]:5: error: cannot substitute '$absent' while formatting attribute predicate
+// INLINE: format-substitution-errors.td:[[#@LINE+4]]:5: note: while expanding operation adaptor verifier
+// INLINE: note: available named substitutions: $_self, $input, $value
+// INLINE-NOT: <no-subst-found>
+def InlineAttr : Attr<CPred<"$_self && $input && $absent">, "inline attr">;
+def InlineOp : Op<TestDialect, "inline"> {
+ let arguments = (ins AnyType:$input, InlineAttr:$value);
+}
+#endif
+
+#ifdef ATTR
+// ATTR: format-substitution-errors.td:[[#@LINE+4]]:5: error: cannot substitute '$missing' while formatting attribute/type template
+// ATTR: note: template: $missing
+// ATTR: note: available named substitutions: $cppClass
+// ATTR-NOT: <no-subst-found>
+def BadAttr : AttrDef<TestDialect, "Bad"> {
+ let mnemonic = "bad";
+ let extraClassDefinition = [{$missing}];
+}
+#endif
+
+#ifdef INTERFACE
+// INTERFACE: format-substitution-errors.td:[[#@LINE+4]]:5: error: cannot substitute '$missing' while formatting interface template
+// INTERFACE: note: template: return $missing;
+// INTERFACE: note: available named substitutions: $_op
+// INTERFACE-NOT: <no-subst-found>
+def BadInterface : OpInterface<"BadInterface"> {
+ let methods = [InterfaceMethod<"bad default", "int", "test", (ins),
+ [{}], [{return $missing;}]>];
+}
+#endif
+
+#ifdef PROP
+// The property probe cannot extract an operand-dependent predicate.
+// PROP: format-substitution-errors.td:[[#@LINE+3]]:5: error: cannot substitute '$absent' while formatting property predicate
+// PROP: note: while expanding operation adaptor verifier
+// PROP: note: available named substitutions: $_self, $input
+def InlineProp : Property<"int"> {
+ let predicate = CPred<"$_self && $input && $absent">;
+}
+def PropOp : Op<TestDialect, "prop"> {
+ let arguments = (ins AnyType:$input, InlineProp:$value);
+}
+#endif
+
+#ifdef PROPSUM
+// PROPSUM: format-substitution-errors.td:[[#@LINE+4]]:5: error: cannot substitute '$missing' while formatting escaped summary expression
+// PROPSUM: note: template: $missing
+// PROPSUM: note: while formatting property summary
+// PROPSUM: note: while expanding operation adaptor verifier
+def SummaryProp : Property<"int", "bad {{$missing}} property"> {
+ let predicate = CPred<"$_self && $input">;
+}
+def PropSummaryOp : Op<TestDialect, "prop_summary"> {
+ let arguments = (ins AnyType:$input, SummaryProp:$value);
+}
+#endif
+
+#ifdef ATTRSUM
+// ATTRSUM: format-substitution-errors.td:[[#@LINE+3]]:5: error: cannot substitute '$missing' while formatting escaped summary expression
+// ATTRSUM: note: while formatting attribute summary
+// ATTRSUM: note: while expanding operation adaptor verifier
+def SummaryAttr : Attr<CPred<"$_self && $input">, "bad {{$missing}} attribute">;
+def AttrSummaryOp : Op<TestDialect, "attr_summary"> {
+ let arguments = (ins AnyType:$input, SummaryAttr:$value);
+}
+#endif
+
+#ifdef ASSEMBLY
+// ASSEMBLY: format-substitution-errors.td:[[#@LINE+6]]:5: error: cannot substitute '$missing' while formatting attribute/type assembly format
+// ASSEMBLY: note: template: $missing
+// ASSEMBLY: note: available named substitutions: $_builder, $_ctxt, $_loc, $_parser
+def AssemblyParam : AttrOrTypeParameter<"int", "bad parser"> {
+ let parser = "$missing";
+}
+def BadAssembly : TypeDef<TestDialect, "BadAssembly"> {
+ let mnemonic = "assembly";
+ let parameters = (ins AssemblyParam:$value);
+ let assemblyFormat = "$value";
+}
+#endif
+
+#ifdef PARAM
+// PARAM: format-substitution-errors.td:[[#@LINE+3]]:5: error: cannot substitute '$_builder' while formatting parameter constraint predicate
+// PARAM: format-substitution-errors.td:[[#@LINE+3]]:5: note: while expanding attribute/type verifier
+// PARAM: note: available named substitutions: $_self
+def ParamConstraint : Type<CPred<"$_builder.getType()">, "bad parameter">;
+def BadParam : TypeDef<TestDialect, "BadParam"> {
+ let mnemonic = "param";
+ let hasCustomAssemblyFormat = 1;
+ let parameters = (ins ParamConstraint:$value);
+}
+#endif
+
+#ifdef ENUM
+// ENUM: format-substitution-errors.td:[[#@LINE+2]]:5: error: cannot substitute '$missing' while formatting enum attribute predicate
+// ENUM: note: available named substitutions: $_self
+def EnumBase : Attr<CPred<"$missing">, "bad enum"> {
+ let storageType = "::mlir::IntegerAttr";
+ let returnType = "int";
+ let constBuilderCall = "build($0)";
+ let valueType = I32;
+}
+def BadEnum : I32EnumAttr<"BadEnum", "bad enum", [I32EnumAttrCase<"A", 0>]> {
+ let baseAttrClass = EnumBase;
+}
+#endif
+
+#ifdef PROPVALID
+// An operand-dependent property fails the restricted probe, then succeeds inline.
+// PROPVALID: if (!((tblgen_value && (*this->getODSOperands(0).begin()))))
+// PROPVALID-NOT: <no-subst-found>
+def ValidInlineProp : Property<"int"> {
+ let predicate = CPred<"$_self && $input">;
+}
+def ValidPropOp : Op<TestDialect, "valid_prop"> {
+ let arguments = (ins AnyType:$input, ValidInlineProp:$value);
+}
+#endif
+
+#ifdef SUMMARYVALID
+// Both predicates fit a shared verifier, but their summaries need an operand.
+// SUMMARYVALID: SummaryBindingsOpAdaptor::verify
+// SUMMARYVALID: property 'prop' failed to satisfy constraint: needs ") << (*this->getODSOperands(0).begin())
+// SUMMARYVALID: attribute 'attr' failed to satisfy constraint: needs ") << (*this->getODSOperands(0).begin())
+// SUMMARYVALID-NOT: <no-subst-found>
+def OperandSummaryProp : Property<"int", "needs {{$input}}"> {
+ let predicate = CPred<"$_self">;
+}
+def OperandSummaryAttr : Attr<CPred<"$_self">, "needs {{$input}}">;
+def SummaryBindingsOp : Op<TestDialect, "summary_bindings"> {
+ let arguments = (ins AnyType:$input, OperandSummaryProp:$prop,
+ OperandSummaryAttr:$attr);
+}
+#endif
+
+#ifdef DEFAULT
+// DEFAULT: format-substitution-errors.td:[[#@LINE+3]]:5: error: cannot substitute '$missing' while formatting default value
+// DEFAULT: note: template: $missing
+// DEFAULT: format-substitution-errors.td:[[#@LINE+2]]:5: note: while expanding operation 'test.default_value'
+def BadDefault : DefaultValuedAttr<I32Attr, "$missing">;
+def DefaultOp : Op<TestDialect, "default_value"> {
+ let arguments = (ins BadDefault:$value);
+}
+#endif
diff --git a/mlir/test/mlir-tblgen/rewriter-errors.td b/mlir/test/mlir-tblgen/rewriter-errors.td
index 0b6d8c3fec6134..6a3334fa91d579 100644
--- a/mlir/test/mlir-tblgen/rewriter-errors.td
+++ b/mlir/test/mlir-tblgen/rewriter-errors.td
@@ -1,3 +1,4 @@
+// RUN: not mlir-tblgen -gen-rewriters -I %S/../../include -DERROR9 %s 2>&1 | FileCheck --check-prefix=ERROR9 %s
// RUN: not mlir-tblgen -gen-rewriters -I %S/../../include -DERROR1 %s 2>&1 | FileCheck --check-prefix=ERROR1 %s
// RUN: not mlir-tblgen -gen-rewriters -I %S/../../include -DERROR2 %s 2>&1 | FileCheck --check-prefix=ERROR2 %s
// RUN: not mlir-tblgen -gen-rewriters -I %S/../../include -DERROR3 %s 2>&1 | FileCheck --check-prefix=ERROR3 %s
@@ -36,7 +37,7 @@ def : Pat<(OpA (NativeMatcher:$error $val), AnyI32Attr:$arg),
#endif
#ifdef ERROR3
-def NativeMatcher : NativeCodeCall<"success(nativeCall($_self, $0, $1))">;
+def NativeMatcher : NativeCodeCall<"success(nativeCall($_self, $0))">;
// ERROR3: [[@LINE+1]]:1: error: Matching nested tree in NativeCodecall not support for
def : Pat<(OpA (NativeMatcher (OpB $val, $unused)), AnyI32Attr:$arg),
(OpB $val, $arg)>;
@@ -79,3 +80,10 @@ def : Pat<(OpB:$opB $val, $attr), (OpD $val)>;
// ERROR8-SAME: op expects variadic operand `vargs`, while provided is non-variadic
def : Pat<(OpB:$opB $val, $attr), (OpD (OpC))>;
#endif
+
+#ifdef ERROR9
+def MissingPositional : NativeCodeCall<"foo($_self, $0, $1)">;
+// ERROR9: error: cannot substitute '$1' while formatting rewrite template: positional argument out of range
+// ERROR9: note: positional substitutions supplied: 1 (available indices: $0 through $0)
+def : Pat<(OpA (MissingPositional $val), AnyI32Attr:$arg), (OpB $val, $arg)>;
+#endif
diff --git a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
index 64f35e7fef6d34..9d819fd9e88f16 100644
--- a/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
+++ b/mlir/tools/mlir-tblgen/AttrOrTypeDefGen.cpp
@@ -10,6 +10,7 @@
#include "CppGenUtilities.h"
#include "mlir/TableGen/AttrOrTypeDef.h"
#include "mlir/TableGen/Class.h"
+#include "mlir/TableGen/CodeGenHelpers.h"
#include "mlir/TableGen/Format.h"
#include "mlir/TableGen/GenInfo.h"
#include "mlir/TableGen/Interfaces.h"
@@ -305,7 +306,8 @@ static std::string formatExtraDefinitions(const AttrOrTypeDef &def) {
extraDefinitions.push_back(*extraDef);
}
FmtContext ctx = FmtContext().addSubst("cppClass", def.getCppClassName());
- return tgfmt(llvm::join(extraDefinitions, "\n"), &ctx).str();
+ return tgfmtOrFatal(FmtOrigin::at(def.getLoc(), "attribute/type template"),
+ llvm::join(extraDefinitions, "\n"), ctx);
}
void DefGen::emitTopLevelDeclarations() {
@@ -385,7 +387,11 @@ void DefGen::emitInvariantsVerifierImpl() {
FmtContext ctx;
// Note: Skip over the first method parameter (`emitError`).
ctx.withSelf(builderParams[it.index() + 1].getName());
- std::string condition = tgfmt(constraint->getConditionTemplate(), &ctx);
+ std::string condition =
+ tgfmtOrFatal(FmtOrigin::at(constraint->getDef().getLoc(),
+ "parameter constraint predicate")
+ .withUse(def.getLoc(), "attribute/type verifier"),
+ constraint->getConditionTemplate(), ctx);
verifier->body() << formatv(patternParameterVerificationCode, condition,
param.getName(), constraint->getSummary())
<< "\n";
@@ -400,12 +406,17 @@ void DefGen::emitInvariantsVerifierImpl() {
}
for (const Trait &trait : def.getTraits()) {
if (auto *t = dyn_cast<PredTrait>(&trait)) {
- verifier->body() << tgfmt(
+ verifier->body() << tgfmtOrFatal(
+ FmtOrigin::at(def.getLoc(), "attribute/type template"),
"if (!($0)) {\n"
" emitError() << \"failed to verify that $1\";\n"
" return ::mlir::failure();\n"
"}\n",
- &traitCtx, tgfmt(t->getPredTemplate(), &traitCtx), t->getSummary());
+ traitCtx,
+ tgfmtOrFatal(FmtOrigin::at(t->getDef().getLoc(), "trait predicate")
+ .withUse(def.getLoc(), "attribute/type verifier"),
+ t->getPredTemplate(), traitCtx),
+ t->getSummary());
}
}
}
@@ -603,7 +614,9 @@ void DefGen::emitCustomBuilder(const AttrOrTypeBuilder &builder) {
ctx.addSubst("_get", "Base::get");
if (!builder.hasInferredContextParameter())
ctx.addSubst("_ctxt", "context");
- std::string bodyStr = tgfmt(*builder.getBody(), &ctx);
+ std::string bodyStr =
+ tgfmtOrFatal(FmtOrigin::at(def.getLoc(), "attribute/type template"),
+ *builder.getBody(), ctx);
m->body().indent().getStream().printReindented(bodyStr);
}
@@ -644,7 +657,8 @@ void DefGen::emitCheckedCustomBuilder(const AttrOrTypeBuilder &builder) {
ctx.addSubst("_ctxt", "context");
std::string bodyStr = replaceInStr(builder.getBody()->str(), "$_get(",
"Base::getChecked(emitError, ");
- bodyStr = tgfmt(bodyStr, &ctx);
+ bodyStr = tgfmtOrFatal(FmtOrigin::at(def.getLoc(), "attribute/type template"),
+ bodyStr, ctx);
m->body().indent().getStream().printReindented(bodyStr);
}
@@ -746,7 +760,8 @@ void DefGen::emitEquals() {
const auto eachFn = [&](auto it) {
FmtContext ctx({{"_lhs", it.value().getName()},
{"_rhs", strfmt("std::get<{0}>(tblgenKey)", it.index())}});
- body << tgfmt(it.value().getComparator(), &ctx);
+ body << tgfmtOrFatal(FmtOrigin::at(def.getLoc(), "attribute/type template"),
+ it.value().getComparator(), ctx);
};
llvm::interleave(llvm::enumerate(params), body, eachFn, ") && (");
}
@@ -781,7 +796,10 @@ void DefGen::emitConstruct() {
for (auto ¶m : params) {
if (std::optional<StringRef> allocCode = param.getAllocator()) {
ctx.withSelf(param.getName()).addSubst("_dst", param.getName());
- body << tgfmt(*allocCode, &ctx) << '\n';
+ body << tgfmtOrFatal(
+ FmtOrigin::at(def.getLoc(), "attribute/type template"),
+ *allocCode, ctx)
+ << '\n';
}
}
auto scope =
@@ -1293,7 +1311,9 @@ return ({3});
for (Constraint constr : constraints) {
FmtContext ctx;
ctx.withSelf(selfName);
- std::string condition = tgfmt(constr.getConditionTemplate(), &ctx);
+ std::string condition = tgfmtOrFatal(
+ FmtOrigin::at(constr.getDef().getLoc(), "constraint predicate"),
+ constr.getConditionTemplate(), ctx);
os << strfmt(constraintDef, *constr.getCppFunctionName(), parameterTypeName,
selfName, condition);
}
diff --git a/mlir/tools/mlir-tblgen/AttrOrTypeFormatGen.cpp b/mlir/tools/mlir-tblgen/AttrOrTypeFormatGen.cpp
index 853ba5b0d0c71d..eef4c3bda98077 100644
--- a/mlir/tools/mlir-tblgen/AttrOrTypeFormatGen.cpp
+++ b/mlir/tools/mlir-tblgen/AttrOrTypeFormatGen.cpp
@@ -10,6 +10,7 @@
#include "FormatGen.h"
#include "mlir/Support/LLVM.h"
#include "mlir/TableGen/AttrOrTypeDef.h"
+#include "mlir/TableGen/CodeGenHelpers.h"
#include "mlir/TableGen/EnumInfo.h"
#include "mlir/TableGen/Format.h"
#include "mlir/TableGen/GenInfo.h"
@@ -58,18 +59,22 @@ class ParameterElement
StringRef getName() const { return param.getName(); }
/// Return the code to check whether the parameter is present.
- auto genIsPresent(FmtContext &ctx, const Twine &self) const {
+ auto genIsPresent(const FmtOrigin &origin, const FmtContext &baseCtx,
+ const Twine &self) const {
+ // Comparator-only bindings must not escape into the next parameter.
+ FmtContext ctx(baseCtx);
assert(isOptional() && "cannot guard on a mandatory parameter");
- std::string valueStr = tgfmt(*param.getDefaultValue(), &ctx).str();
+ std::string valueStr = tgfmtOrFatal(origin, *param.getDefaultValue(), ctx);
ctx.addSubst("_lhs", self).addSubst("_rhs", valueStr);
- return tgfmt(getParam().getComparator(), &ctx);
+ return tgfmtOrFatal(origin, getParam().getComparator(), ctx);
}
/// Generate the code to check whether the parameter should be printed.
- MethodBody &genPrintGuard(FmtContext &ctx, MethodBody &os) const {
+ MethodBody &genPrintGuard(const FmtOrigin &origin, const FmtContext &ctx,
+ MethodBody &os) const {
assert(isOptional() && "cannot guard on a mandatory parameter");
std::string self = param.getAccessorName() + "()";
- return os << "!(" << genIsPresent(ctx, self) << ")";
+ return os << "!(" << genIsPresent(origin, ctx, self) << ")";
}
private:
@@ -181,7 +186,6 @@ class StructDirective
return llvm::any_of(getElements(), formatIsOptional);
}
};
-
} // namespace
//===----------------------------------------------------------------------===//
@@ -240,6 +244,10 @@ class DefFormat {
void genPrinter(MethodBody &os);
private:
+ FmtOrigin getFmtOrigin() const {
+ return FmtOrigin::at(def.getLoc(), "attribute/type assembly format");
+ }
+
/// Generate the parser code for a specific format element.
void genElementParser(FormatElement *el, FmtContext &ctx, MethodBody &os);
/// Generate the parser code for a literal.
@@ -314,7 +322,8 @@ class DefFormat {
/// Generate a special-case "parser" for an attribute's self type parameter. The
/// self type parameter has special handling in the assembly format in that it
/// is derived from the optional trailing colon type after the attribute.
-static void genAttrSelfTypeParser(MethodBody &os, const FmtContext &ctx,
+static void genAttrSelfTypeParser(const FmtOrigin &origin, MethodBody &os,
+ const FmtContext &ctx,
const AttributeSelfTypeParameter ¶m) {
// "Parser" for an attribute self type parameter that checks the
// optionally-parsed trailing colon type.
@@ -338,9 +347,10 @@ if ($_type) {
return {};
})";
- os << tgfmt(selfTypeParser, &ctx, param.getCppStorageType(), param.getName());
+ os << tgfmtOrFatal(origin, selfTypeParser, ctx, param.getCppStorageType(),
+ param.getName());
if (!param.isOptional())
- os << tgfmt(selfTypeRequired, &ctx);
+ os << tgfmtOrFatal(origin, selfTypeRequired, ctx);
os << "\n";
}
@@ -356,9 +366,10 @@ void DefFormat::genParser(MethodBody &os) {
// Store the initial location of the parser.
ctx.addSubst("_loc", "odsLoc");
- os << tgfmt("::llvm::SMLoc $_loc = $_parser.getCurrentLocation();\n"
- "(void) $_loc;\n",
- &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(),
+ "::llvm::SMLoc $_loc = $_parser.getCurrentLocation();\n"
+ "(void) $_loc;\n",
+ ctx);
// Declare variables to store all of the parameters. Allocated parameters
// such as `ArrayRef` and `StringRef` must provide a `storageType`. Store
@@ -369,7 +380,7 @@ void DefFormat::genParser(MethodBody &os) {
os << formatv("::mlir::FailureOr<{0}> _result_{1};\n",
param.getCppStorageType(), param.getName());
if (auto *selfTypeParam = dyn_cast<AttributeSelfTypeParameter>(¶m))
- genAttrSelfTypeParser(os, ctx, *selfTypeParam);
+ genAttrSelfTypeParser(getFmtOrigin(), os, ctx, *selfTypeParam);
}
// Generate call to each parameter parser.
@@ -387,11 +398,13 @@ void DefFormat::genParser(MethodBody &os) {
// Generate call to the attribute or type builder. Use the checked getter
// if one was generated.
if (def.genVerifyDecl() || def.genVerifyInvariantsImpl()) {
- os << tgfmt("return $_parser.getChecked<$0>($_loc, $_parser.getContext()",
- &ctx, def.getCppClassName());
+ os << tgfmtOrFatal(
+ getFmtOrigin(),
+ "return $_parser.getChecked<$0>($_loc, $_parser.getContext()", ctx,
+ def.getCppClassName());
} else {
- os << tgfmt("return $0::get($_parser.getContext()", &ctx,
- def.getCppClassName());
+ os << tgfmtOrFatal(getFmtOrigin(), "return $0::get($_parser.getContext()",
+ ctx, def.getCppClassName());
}
for (const AttrOrTypeParameter ¶m : params) {
os << ",\n ";
@@ -399,13 +412,14 @@ void DefFormat::genParser(MethodBody &os) {
llvm::raw_string_ostream selfOs(paramSelfStr);
if (std::optional<StringRef> defaultValue = param.getDefaultValue()) {
selfOs << formatv("(_result_{0}.value_or(", param.getName())
- << tgfmt(*defaultValue, &ctx) << "))";
+ << tgfmtOrFatal(getFmtOrigin(), *defaultValue, ctx) << "))";
} else {
selfOs << formatv("(*_result_{0})", param.getName());
}
ctx.addSubst(param.getName(), selfOs.str());
os << param.getCppType() << "("
- << tgfmt(param.getConvertFromStorage(), &ctx.withSelf(selfOs.str()))
+ << tgfmtOrFatal(getFmtOrigin(), param.getConvertFromStorage(),
+ ctx.withSelf(selfOs.str()))
<< ")";
}
os << ");";
@@ -434,7 +448,7 @@ void DefFormat::genElementParser(FormatElement *el, FmtContext &ctx,
void DefFormat::genLiteralParser(StringRef value, FmtContext &ctx,
MethodBody &os, bool isOptional) {
os << "// Parse literal '" << value << "'\n";
- os << tgfmt("if ($_parser.parse", &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(), "if ($_parser.parse", ctx);
if (isOptional)
os << "Optional";
if (value.front() == '_' || isalpha(value.front())) {
@@ -496,10 +510,11 @@ void DefFormat::genVariableParser(ParameterElement *el, FmtContext &ctx,
}
}
}
- os << formatv(variableParser, param.getName(),
- tgfmt(parser, &ctx, param.getCppStorageType()),
- tgfmt(parserErrorStr, &ctx), def.getName(), param.getCppType(),
- dialectLoading);
+ os << formatv(
+ variableParser, param.getName(),
+ tgfmtOrFatal(getFmtOrigin(), parser, ctx, param.getCppStorageType()),
+ tgfmtOrFatal(getFmtOrigin(), parserErrorStr, ctx), def.getName(),
+ param.getCppType(), dialectLoading);
}
void DefFormat::genStructParameterParser(ParameterElement *el, FmtContext &ctx,
@@ -517,10 +532,12 @@ void DefFormat::genStructParameterParser(ParameterElement *el, FmtContext &ctx,
llvm::raw_string_ostream parserOS(parser);
parserOS << "[&]() -> ::mlir::FailureOr<" << param.getCppStorageType()
<< "> {\n auto odsEnumValue = "
- << tgfmt(defaultParameterParser, &ctx, enumType)
+ << tgfmtOrFatal(getFmtOrigin(), defaultParameterParser, ctx,
+ enumType)
<< ";\n if (::mlir::failed(odsEnumValue))\n"
" return ::mlir::failure();\n return "
- << param.getCppStorageType() << "::get(" << tgfmt("$_ctxt", &ctx)
+ << param.getCppStorageType() << "::get("
+ << tgfmtOrFatal(getFmtOrigin(), "$_ctxt", ctx)
<< ", *odsEnumValue);\n}()";
genVariableParser(el, ctx, os, parserOS.str());
}
@@ -557,7 +574,8 @@ void DefFormat::genParamsParser(ParamsDirective *el, FmtContext &ctx,
if (el->isOptional()) {
os << formatv("if (::mlir::succeeded(_result_{0}) && !({1})) {{\n",
el->getName(),
- el->genIsPresent(ctx, "(*_result_" + el->getName() + ")"));
+ el->genIsPresent(getFmtOrigin(), ctx,
+ "(*_result_" + el->getName() + ")"));
os.indent();
}
if (it <= lastReqIt) {
@@ -681,7 +699,8 @@ void DefFormat::genStructParser(StructDirective *el, FmtContext &ctx,
os.unindent() << "} else ";
// Print the check for duplicate or unknown parameter.
}
- os.getStream().printReindented(strfmt(loopEnd, tgfmt(parserErrorStr, &ctx)));
+ os.getStream().printReindented(
+ strfmt(loopEnd, tgfmtOrFatal(getFmtOrigin(), parserErrorStr, ctx)));
os << "return true;\n";
os.unindent() << "};\n";
@@ -691,17 +710,18 @@ void DefFormat::genStructParser(StructDirective *el, FmtContext &ctx,
if (numOptional) {
// If the struct itself is optional, pull out the first iteration.
if (numOptional == el->getNumElements()) {
- os.getStream().printReindented(tgfmt(optionalStructFirst, &ctx).str());
+ os.getStream().printReindented(
+ tgfmtOrFatal(getFmtOrigin(), optionalStructFirst, ctx));
os.indent();
} else {
os << "do {\n";
}
} else {
os.getStream().printReindented(
- tgfmt(loopHeader, &ctx, el->getNumElements()).str());
+ tgfmtOrFatal(getFmtOrigin(), loopHeader, ctx, el->getNumElements()));
}
os.indent();
- os.getStream().printReindented(tgfmt(loopStart, &ctx).str());
+ os.getStream().printReindented(tgfmtOrFatal(getFmtOrigin(), loopStart, ctx));
os.unindent();
// Print the loop terminator. For optional parameters, we have to check that
@@ -712,13 +732,15 @@ void DefFormat::genStructParser(StructDirective *el, FmtContext &ctx,
os << "}\n";
os.unindent() << "}\n";
} else {
- os << tgfmt("} while(!$_parser.parseOptionalComma());\n", &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(),
+ "} while(!$_parser.parseOptionalComma());\n", ctx);
for (FormatElement *arg : el->getElements()) {
ParameterElement *param = getEncapsulatedParameterElement(arg);
if (param->isOptional())
continue;
os.getStream().printReindented(
- strfmt(checkParam, param->getName(), tgfmt(parserErrorStr, &ctx)));
+ strfmt(checkParam, param->getName(),
+ tgfmtOrFatal(getFmtOrigin(), parserErrorStr, ctx)));
}
}
} else {
@@ -740,9 +762,12 @@ void DefFormat::genCustomParser(CustomDirective *el, FmtContext &ctx,
// Bound variables are passed directly to the parser as `FailureOr<T> &`.
// Referenced variables are passed as `T`. The custom parser fails if it
// returns failure or if any of the required parameters failed.
- os << tgfmt("auto odsCustomLoc = $_parser.getCurrentLocation();\n", &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(),
+ "auto odsCustomLoc = $_parser.getCurrentLocation();\n",
+ ctx);
os << "(void)odsCustomLoc;\n";
- os << tgfmt("auto odsCustomResult = parse$0($_parser", &ctx, el->getName());
+ os << tgfmtOrFatal(getFmtOrigin(), "auto odsCustomResult = parse$0($_parser",
+ ctx, el->getName());
os.indent();
for (FormatElement *arg : el->getElements()) {
os << ",\n";
@@ -752,7 +777,8 @@ void DefFormat::genCustomParser(CustomDirective *el, FmtContext &ctx,
else if (auto *ref = dyn_cast<RefDirective>(arg))
os << "*_result_" << cast<ParameterElement>(ref->getArg())->getName();
else
- os << tgfmt(cast<StringElement>(arg)->getValue(), &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(), cast<StringElement>(arg)->getValue(),
+ ctx);
}
os.unindent() << ");\n";
if (isOptional) {
@@ -766,7 +792,8 @@ void DefFormat::genCustomParser(CustomDirective *el, FmtContext &ctx,
if (param->isOptional())
continue;
os << formatv("if (::mlir::failed(_result_{0})) {{\n", param->getName());
- os.indent() << tgfmt("$_parser.emitError(odsCustomLoc, ", &ctx)
+ os.indent() << tgfmtOrFatal(getFmtOrigin(),
+ "$_parser.emitError(odsCustomLoc, ", ctx)
<< "\"custom parser failed to parse parameter '"
<< param->getName() << "'\");\n";
os << "return " << (isOptional ? "::mlir::failure()" : "{}") << ";\n";
@@ -877,8 +904,8 @@ void DefFormat::genLiteralPrinter(StringRef value, FmtContext &ctx,
// Don't insert a space before certain punctuation.
bool needSpace =
shouldEmitSpace && shouldEmitSpaceBefore(value, lastWasPunctuation);
- os << tgfmt("$_printer$0 << \"$1\";\n", &ctx, needSpace ? " << ' '" : "",
- value);
+ os << tgfmtOrFatal(getFmtOrigin(), "$_printer$0 << \"$1\";\n", ctx,
+ needSpace ? " << ' '" : "", value);
// Update the flags.
shouldEmitSpace =
@@ -898,24 +925,24 @@ void DefFormat::genVariablePrinter(ParameterElement *el, FmtContext &ctx,
// Guard the printer on the presence of optional parameters and that they
// aren't equal to their default values (if they have one).
if (el->isOptional() && !skipGuard) {
- el->genPrintGuard(ctx, os << "if (") << ") {\n";
+ el->genPrintGuard(getFmtOrigin(), ctx, os << "if (") << ") {\n";
os.indent();
}
// Insert a space before the next parameter, if necessary.
if (shouldEmitSpace || !lastWasPunctuation)
- os << tgfmt("$_printer << ' ';\n", &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(), "$_printer << ' ';\n", ctx);
shouldEmitSpace = true;
lastWasPunctuation = false;
if (printerOverride)
- os << tgfmt(*printerOverride, &ctx) << ";\n";
+ os << tgfmtOrFatal(getFmtOrigin(), *printerOverride, ctx) << ";\n";
else if (el->shouldBeQualified())
- os << tgfmt(qualifiedParameterPrinter, &ctx) << ";\n";
+ os << tgfmtOrFatal(getFmtOrigin(), qualifiedParameterPrinter, ctx) << ";\n";
else if (auto printer = param.getPrinter())
- os << tgfmt(*printer, &ctx) << ";\n";
+ os << tgfmtOrFatal(getFmtOrigin(), *printer, ctx) << ";\n";
else
- os << tgfmt(defaultParameterPrinter, &ctx) << ";\n";
+ os << tgfmtOrFatal(getFmtOrigin(), defaultParameterPrinter, ctx) << ";\n";
if (el->isOptional() && !skipGuard)
os.unindent() << "}\n";
@@ -934,14 +961,15 @@ void DefFormat::genStructParameterPrinter(ParameterElement *el, FmtContext &ctx,
/// Generate code to guard printing on the presence of any optional parameters.
template <typename ParameterRange>
-static void guardOnAny(FmtContext &ctx, MethodBody &os, ParameterRange &¶ms,
- bool inverted = false) {
+static void guardOnAny(const FmtOrigin &origin, FmtContext &ctx, MethodBody &os,
+ ParameterRange &¶ms, bool inverted = false) {
os << "if (";
if (inverted)
os << "!(";
llvm::interleave(
params, os,
- [&](ParameterElement *param) { param->genPrintGuard(ctx, os); }, " || ");
+ [&](ParameterElement *param) { param->genPrintGuard(origin, ctx, os); },
+ " || ");
if (inverted)
os << ")";
os << ") {\n";
@@ -951,9 +979,10 @@ static void guardOnAny(FmtContext &ctx, MethodBody &os, ParameterRange &¶ms,
/// Generate code to guard printing on the presence of any optional format
/// elements.
template <typename FormatElemRange>
-static void guardOnAnyOptional(FmtContext &ctx, MethodBody &os,
- FormatElemRange &&args, bool inverted = false) {
- guardOnAny(ctx, os,
+static void guardOnAnyOptional(const FmtOrigin &origin, FmtContext &ctx,
+ MethodBody &os, FormatElemRange &&args,
+ bool inverted = false) {
+ guardOnAny(origin, ctx, os,
llvm::make_filter_range(
llvm::map_range(args, getEncapsulatedParameterElement),
[](ParameterElement *param) { return param->isOptional(); }),
@@ -968,8 +997,8 @@ void DefFormat::genCommaSeparatedPrinter(
if (shouldEmitSpace || !lastWasPunctuation) {
bool allOptional = llvm::all_of(args, formatIsOptional);
if (allOptional)
- guardOnAnyOptional(ctx, os, args);
- os << tgfmt("$_printer << ' ';\n", &ctx);
+ guardOnAnyOptional(getFmtOrigin(), ctx, os, args);
+ os << tgfmtOrFatal(getFmtOrigin(), "$_printer << ' ';\n", ctx);
if (allOptional)
os.unindent() << "}\n";
}
@@ -981,10 +1010,11 @@ void DefFormat::genCommaSeparatedPrinter(
for (FormatElement *arg : args) {
ParameterElement *param = getEncapsulatedParameterElement(arg);
if (param->isOptional()) {
- param->genPrintGuard(ctx, os << "if (") << ") {\n";
+ param->genPrintGuard(getFmtOrigin(), ctx, os << "if (") << ") {\n";
os.indent();
}
- os << tgfmt("if (!_firstPrinted) $_printer << \", \";\n", &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(),
+ "if (!_firstPrinted) $_printer << \", \";\n", ctx);
os << "_firstPrinted = false;\n";
extra(arg);
shouldEmitSpace = false;
@@ -1028,18 +1058,19 @@ void DefFormat::genStructPrinter(StructDirective *el, FmtContext &ctx,
elems, ctx, os,
[&](FormatElement *arg) {
ParameterElement *param = getEncapsulatedParameterElement(arg);
- os << tgfmt("$_printer << \"$0 = \";\n", &ctx, param->getName());
+ os << tgfmtOrFatal(getFmtOrigin(), "$_printer << \"$0 = \";\n", ctx,
+ param->getName());
auto *paramEl = dyn_cast<ParameterElement>(arg);
if (paramEl && needsStructBrackets(paramEl) &&
elemIdx + 1 < elems.size())
- os << tgfmt("$_printer << \"[\";\n", &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(), "$_printer << \"[\";\n", ctx);
},
/*stripEnumAttrs=*/true,
[&](FormatElement *arg) {
auto *paramEl = dyn_cast<ParameterElement>(arg);
if (paramEl && needsStructBrackets(paramEl) &&
elemIdx + 1 < elems.size())
- os << tgfmt("$_printer << \"]\";\n", &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(), "$_printer << \"]\";\n", ctx);
++elemIdx;
});
}
@@ -1048,11 +1079,11 @@ void DefFormat::genCustomPrinter(CustomDirective *el, FmtContext &ctx,
MethodBody &os) {
// Insert a space before the custom directive, if necessary.
if (shouldEmitSpace || !lastWasPunctuation)
- os << tgfmt("$_printer << ' ';\n", &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(), "$_printer << ' ';\n", ctx);
shouldEmitSpace = true;
lastWasPunctuation = false;
- os << tgfmt("print$0($_printer", &ctx, el->getName());
+ os << tgfmtOrFatal(getFmtOrigin(), "print$0($_printer", ctx, el->getName());
os.indent();
for (FormatElement *arg : el->getElements()) {
os << ",\n";
@@ -1062,7 +1093,8 @@ void DefFormat::genCustomPrinter(CustomDirective *el, FmtContext &ctx,
os << cast<ParameterElement>(ref->getArg())->getParam().getAccessorName()
<< "()";
} else {
- os << tgfmt(cast<StringElement>(arg)->getValue(), &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(), cast<StringElement>(arg)->getValue(),
+ ctx);
}
}
os.unindent() << ");\n";
@@ -1072,14 +1104,18 @@ void DefFormat::genOptionalGroupPrinter(OptionalElement *el, FmtContext &ctx,
MethodBody &os) {
FormatElement *anchor = el->getAnchor();
if (auto *param = dyn_cast<ParameterElement>(anchor)) {
- guardOnAny(ctx, os, llvm::ArrayRef(param), el->isInverted());
+ guardOnAny(getFmtOrigin(), ctx, os, llvm::ArrayRef(param),
+ el->isInverted());
} else if (auto *params = dyn_cast<ParamsDirective>(anchor)) {
- guardOnAny(ctx, os, params->getElements(), el->isInverted());
+ guardOnAny(getFmtOrigin(), ctx, os, params->getElements(),
+ el->isInverted());
} else if (auto *strct = dyn_cast<StructDirective>(anchor)) {
- guardOnAnyOptional(ctx, os, strct->getElements(), el->isInverted());
+ guardOnAnyOptional(getFmtOrigin(), ctx, os, strct->getElements(),
+ el->isInverted());
} else {
auto *custom = cast<CustomDirective>(anchor);
- guardOnAnyOptional(ctx, os, custom->getElements(), el->isInverted());
+ guardOnAnyOptional(getFmtOrigin(), ctx, os, custom->getElements(),
+ el->isInverted());
}
// Generate the printer for the contained elements.
{
@@ -1098,9 +1134,10 @@ void DefFormat::genOptionalGroupPrinter(OptionalElement *el, FmtContext &ctx,
void DefFormat::genWhitespacePrinter(WhitespaceElement *el, FmtContext &ctx,
MethodBody &os) {
if (el->getValue() == "\\n") {
- os << tgfmt("$_printer.printNewline();\n", &ctx);
+ os << tgfmtOrFatal(getFmtOrigin(), "$_printer.printNewline();\n", ctx);
} else if (!el->getValue().empty()) {
- os << tgfmt("$_printer << \"$0\";\n", &ctx, el->getValue());
+ os << tgfmtOrFatal(getFmtOrigin(), "$_printer << \"$0\";\n", ctx,
+ el->getValue());
} else {
lastWasPunctuation = true;
}
diff --git a/mlir/tools/mlir-tblgen/EnumsGen.cpp b/mlir/tools/mlir-tblgen/EnumsGen.cpp
index c83ed3cf42fcd7..ee7318648a3a02 100644
--- a/mlir/tools/mlir-tblgen/EnumsGen.cpp
+++ b/mlir/tools/mlir-tblgen/EnumsGen.cpp
@@ -12,6 +12,7 @@
#include "FormatGen.h"
#include "mlir/TableGen/Attribute.h"
+#include "mlir/TableGen/CodeGenHelpers.h"
#include "mlir/TableGen/EnumInfo.h"
#include "mlir/TableGen/Format.h"
#include "mlir/TableGen/GenInfo.h"
@@ -35,7 +36,8 @@ using mlir::tblgen::Attribute;
using mlir::tblgen::EnumCase;
using mlir::tblgen::EnumInfo;
using mlir::tblgen::FmtContext;
-using mlir::tblgen::tgfmt;
+using mlir::tblgen::FmtOrigin;
+using mlir::tblgen::tgfmtOrFatal;
static std::string makeIdentifier(StringRef str) {
if (!str.empty() && isDigit(static_cast<unsigned char>(str.front()))) {
@@ -652,7 +654,13 @@ static void emitSpecializedAttrDef(const Record &enumDef, raw_ostream &os) {
std::string condition = baseAttrPred.getCondition();
FmtContext verifyCtx;
verifyCtx.withSelf("attr");
- os << tgfmt(" return $0;\n", /*ctx=*/nullptr, tgfmt(condition, &verifyCtx));
+ os << tgfmtOrFatal(
+ FmtOrigin::at(enumDef.getLoc(), "enum attribute predicate"),
+ " return $0;\n", FmtContext{},
+ tgfmtOrFatal(
+ FmtOrigin::at(baseAttrDef->getLoc(), "enum attribute predicate")
+ .withUse(enumDef.getLoc(), "enum attribute"),
+ condition, verifyCtx));
os << "}\n";
diff --git a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
index a388e01f0dc379..40e900a8a2357c 100644
--- a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
+++ b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
@@ -279,7 +279,9 @@ static std::string constBuildAttrFromParam(const tblgen::Attribute &attr,
if (StringRef(builderTemplate).contains("\"$0\""))
builderTemplate = replaceAllSubstrs(builderTemplate, "\"$0\"", "$0");
- return tgfmt(builderTemplate, &fctx, paramName).str();
+ return tgfmtOrFatal(
+ FmtOrigin::at(attr.getDef().getLoc(), "attribute constant builder"),
+ builderTemplate, fctx, paramName);
}
namespace {
@@ -823,7 +825,8 @@ static bool canEmitAttrVerifier(Attribute attr, bool isEmittingForOp) {
// and operand or result getters.
// 3. Verify the constraints on all present attributes.
static void genAttributeVerifier(
- const OpOrAdaptorHelper &emitHelper, FmtContext &ctx, MethodBody &body,
+ const OpOrAdaptorHelper &emitHelper, const FmtContext &ctx,
+ MethodBody &body,
const StaticVerifierFunctionEmitter &staticVerifierEmitter) {
if (emitHelper.getAttrMetadata().empty())
return;
@@ -863,11 +866,25 @@ static void genAttributeVerifier(
(constraintFn = staticVerifierEmitter.getAttrConstraintFn(attr))) {
body << formatv(verifyAttrUnique, *constraintFn, varName, attrName);
} else {
+ FmtContext valueCtx(ctx);
+ valueCtx.withSelf(varName);
body << formatv(
- verifyAttrInline, varName, tgfmt(condition, &ctx.withSelf(varName)),
+ verifyAttrInline, varName,
+ tgfmtOrFatal(
+ FmtOrigin::at(attr.getDef().getLoc(), "attribute predicate")
+ .withUse(emitHelper.getOp().getLoc(),
+ emitHelper.isEmittingForOp()
+ ? "operation verifier"
+ : "operation adaptor verifier"),
+ condition, valueCtx),
emitHelper.emitErrorPrefix(), attrName,
- buildErrorStreamingString(attr.getSummary(), ctx.withSelf(varName),
- ErrorStreamType::InsideOpError));
+ buildErrorStreamingStringOrFatal(
+ FmtOrigin::at(attr.getDef().getLoc(), "attribute summary")
+ .withUse(emitHelper.getOp().getLoc(),
+ emitHelper.isEmittingForOp()
+ ? "operation verifier"
+ : "operation adaptor verifier"),
+ attr.getSummary(), valueCtx, ErrorStreamType::InsideOpError));
}
};
@@ -898,7 +915,8 @@ static void genAttributeVerifier(
}
static void genPropertyVerifier(
- const OpOrAdaptorHelper &emitHelper, FmtContext &ctx, MethodBody &body,
+ const OpOrAdaptorHelper &emitHelper, const FmtContext &ctx,
+ MethodBody &body,
const StaticVerifierFunctionEmitter &staticVerifierEmitter) {
// Code to get a reference to a property into a variable to avoid multiple
@@ -961,13 +979,28 @@ static void genPropertyVerifier(
auto uniquedFn = staticVerifierEmitter.getPropConstraintFn(prop.prop);
if (uniquedFn.has_value() && emitHelper.isEmittingForOp())
body << formatv(verifyPropertyUniqued, *uniquedFn, varName, prop.name);
- else
- body << formatv(verifyPropertyInline,
- tgfmt(rawCondition, &ctx.withSelf(varName)),
- emitHelper.emitErrorPrefix(), prop.name,
- buildErrorStreamingString(
- prop.prop.getSummary(), ctx.withSelf(varName),
- ErrorStreamType::InsideOpError));
+ else {
+ FmtContext valueCtx(ctx);
+ valueCtx.withSelf(varName);
+ body << formatv(
+ verifyPropertyInline,
+ tgfmtOrFatal(
+ FmtOrigin::at(prop.prop.getDef().getLoc(), "property predicate")
+ .withUse(emitHelper.getOp().getLoc(),
+ emitHelper.isEmittingForOp()
+ ? "operation verifier"
+ : "operation adaptor verifier"),
+ rawCondition, valueCtx),
+ emitHelper.emitErrorPrefix(), prop.name,
+ buildErrorStreamingStringOrFatal(
+ FmtOrigin::at(prop.prop.getDef().getLoc(), "property summary")
+ .withUse(emitHelper.getOp().getLoc(),
+ emitHelper.isEmittingForOp()
+ ? "operation verifier"
+ : "operation adaptor verifier"),
+ prop.prop.getSummary(), valueCtx,
+ ErrorStreamType::InsideOpError));
+ }
}
}
@@ -1003,7 +1036,8 @@ static std::string formatExtraDefinitions(const Operator &op) {
}
extraDefinitions.push_back(op.getExtraClassDefinition());
FmtContext ctx = FmtContext().addSubst("cppClass", op.getCppClassName());
- return tgfmt(llvm::join(extraDefinitions, "\n"), &ctx).str();
+ return tgfmtOrFatal(FmtOrigin::at(op.getLoc(), "operation template"),
+ llvm::join(extraDefinitions, "\n"), ctx);
}
OpEmitter::OpEmitter(const Operator &op,
@@ -1216,16 +1250,20 @@ static void emitAttrGetterWithReturnType(FmtContext &fctx,
PrintFatalError("DefaultValuedAttr of type " + attr.getAttrDefName() +
" must have a constBuilder");
}
- std::string defaultValue =
- std::string(tgfmt(attr.getConstBuilderTemplate(), &fctx,
- tgfmt(attr.getDefaultValue(), &fctx)));
+ std::string defaultValue = tgfmtOrFatal(
+ getConstraintFmtOrigin(attr, op, "attribute constant builder"),
+ attr.getConstBuilderTemplate(), fctx,
+ tgfmtOrFatal(getConstraintFmtOrigin(attr, op, "default value"),
+ attr.getDefaultValue(), fctx));
body << " if (!attr)\n return "
- << tgfmt(attr.getConvertFromStorageCall(),
- &fctx.withSelf(defaultValue))
+ << tgfmtOrFatal(getConstraintFmtOrigin(attr, op, "attribute template"),
+ attr.getConvertFromStorageCall(),
+ fctx.withSelf(defaultValue))
<< ";\n";
}
body << " return "
- << tgfmt(attr.getConvertFromStorageCall(), &fctx.withSelf("attr"))
+ << tgfmtOrFatal(getConstraintFmtOrigin(attr, op, "attribute template"),
+ attr.getConvertFromStorageCall(), fctx.withSelf("attr"))
<< ";\n";
}
@@ -1362,17 +1400,22 @@ void OpEmitter::genPropertiesSupport() {
fctx.withBuilder(odsBuilder);
setPropMethod << "{\n"
<< formatv(propFromAttrFmt,
- tgfmt(prop.getConvertFromAttributeCall(),
- &fctx.addSubst("_attr", propertyAttr)
- .addSubst("_storage", propertyStorage)
- .addSubst("_diag", propertyDiag)),
+ tgfmtOrFatal(
+ getConstraintFmtOrigin(prop, op,
+ "property template"),
+ prop.getConvertFromAttributeCall(),
+ fctx.addSubst("_attr", propertyAttr)
+ .addSubst("_storage", propertyStorage)
+ .addSubst("_diag", propertyDiag)),
getAttr);
if (prop.hasStorageTypeValueOverride()) {
setPropMethod << formatv(attrGetDefaultFmt, name,
prop.getStorageTypeValueOverride());
} else if (prop.hasDefaultValue()) {
- setPropMethod << formatv(attrGetDefaultFmt, name,
- tgfmt(prop.getDefaultValue(), &fctx));
+ setPropMethod << formatv(
+ attrGetDefaultFmt, name,
+ tgfmtOrFatal(getConstraintFmtOrigin(prop, op, "default value"),
+ prop.getDefaultValue(), fctx));
} else {
setPropMethod << formatv(attrGetNoDefaultFmt, name);
}
@@ -1429,9 +1472,10 @@ void OpEmitter::genPropertiesSupport() {
FmtContext fctx;
getPropMethod << formatv(
propToAttrFmt, name,
- tgfmt(prop.getConvertToAttributeCall(),
- &fctx.addSubst("_ctxt", "ctx")
- .addSubst("_storage", propertyStorage)));
+ tgfmtOrFatal(getConstraintFmtOrigin(prop, op, "property template"),
+ prop.getConvertToAttributeCall(),
+ fctx.addSubst("_ctxt", "ctx")
+ .addSubst("_storage", propertyStorage)));
continue;
}
const auto *namedAttr =
@@ -1465,8 +1509,9 @@ void OpEmitter::genPropertiesSupport() {
if (!prop.getHashPropertyCall().empty()) {
hashMethod << formatv(
propHashFmt, name,
- tgfmt(prop.getHashPropertyCall(),
- &fctx.addSubst("_storage", propertyStorage)));
+ tgfmtOrFatal(getConstraintFmtOrigin(prop, op, "property template"),
+ prop.getHashPropertyCall(),
+ fctx.addSubst("_storage", propertyStorage)));
}
}
}
@@ -1541,7 +1586,10 @@ void OpEmitter::genPropertiesSupport() {
legacyResultSegmentAttrName, resultSegmentAttrName);
}
getInherentAttrMethod << "[&]() -> ::mlir::Attribute { "
- << tgfmt(prop.getConvertToAttributeCall(), &fctx)
+ << tgfmtOrFatal(getConstraintFmtOrigin(
+ prop, op, "property template"),
+ prop.getConvertToAttributeCall(),
+ fctx)
<< " }();\n";
if (name == operandSegmentAttrName) {
@@ -1563,16 +1611,18 @@ void OpEmitter::genPropertiesSupport() {
}
)decl",
name);
- walkInherentAttrsMethod
- << formatv(" {{\n"
- " ::mlir::Attribute value = [&]() -> ::mlir::Attribute "
- "{ {1} }();\n"
- " ::mlir::Attribute originalValue = value;\n"
- " visitor(\"{0}\", value);\n"
- " if (value != originalValue)\n"
- " setInherentAttr(prop, \"{0}\", value);\n"
- " }\n",
- name, tgfmt(prop.getConvertToAttributeCall(), &fctx));
+ walkInherentAttrsMethod << formatv(
+ " {{\n"
+ " ::mlir::Attribute value = [&]() -> ::mlir::Attribute "
+ "{ {1} }();\n"
+ " ::mlir::Attribute originalValue = value;\n"
+ " visitor(\"{0}\", value);\n"
+ " if (value != originalValue)\n"
+ " setInherentAttr(prop, \"{0}\", value);\n"
+ " }\n",
+ name,
+ tgfmtOrFatal(getConstraintFmtOrigin(prop, op, "property template"),
+ prop.getConvertToAttributeCall(), fctx));
}
getInherentAttrMethod << " return std::nullopt;\n";
@@ -1658,15 +1708,23 @@ void OpEmitter::genPropertiesSupportForBytecode(
item.index() == emitHelper.getOperandSegmentSizesLegacyIndex()) {
FmtContext fmtCtxt(fctx);
fmtCtxt.addSubst("_propName", operandSegmentAttrName);
- readPropertiesMethod << tgfmt(readBytecodeSegmentSizeLegacy, &fmtCtxt);
- writePropertiesMethod << tgfmt(writeBytecodeSegmentSizeLegacy, &fmtCtxt);
+ readPropertiesMethod << tgfmtOrFatal(
+ FmtOrigin::at(op.getLoc(), "operation template"),
+ readBytecodeSegmentSizeLegacy, fmtCtxt);
+ writePropertiesMethod
+ << tgfmtOrFatal(FmtOrigin::at(op.getLoc(), "operation template"),
+ writeBytecodeSegmentSizeLegacy, fmtCtxt);
}
if (emitHelper.getResultSegmentsSize().has_value() &&
item.index() == emitHelper.getResultSegmentSizesLegacyIndex()) {
FmtContext fmtCtxt(fctx);
fmtCtxt.addSubst("_propName", resultSegmentAttrName);
- readPropertiesMethod << tgfmt(readBytecodeSegmentSizeLegacy, &fmtCtxt);
- writePropertiesMethod << tgfmt(writeBytecodeSegmentSizeLegacy, &fmtCtxt);
+ readPropertiesMethod << tgfmtOrFatal(
+ FmtOrigin::at(op.getLoc(), "operation template"),
+ readBytecodeSegmentSizeLegacy, fmtCtxt);
+ writePropertiesMethod
+ << tgfmtOrFatal(FmtOrigin::at(op.getLoc(), "operation template"),
+ writeBytecodeSegmentSizeLegacy, fmtCtxt);
}
if (const auto *namedProperty =
dyn_cast<const NamedProperty *>(attrOrProp)) {
@@ -1684,7 +1742,10 @@ void OpEmitter::genPropertiesSupportForBytecode(
}
)",
name,
- tgfmt(namedProperty->prop.getReadFromMlirBytecodeCall(), &fctx));
+ tgfmtOrFatal(getConstraintFmtOrigin(namedProperty->prop, op,
+ "property bytecode reader"),
+ namedProperty->prop.getReadFromMlirBytecodeCall(),
+ fctx));
writePropertiesMethod << formatv(
R"(
{{
@@ -1692,7 +1753,10 @@ void OpEmitter::genPropertiesSupportForBytecode(
{1};
}
)",
- name, tgfmt(namedProperty->prop.getWriteToMlirBytecodeCall(), &fctx));
+ name,
+ tgfmtOrFatal(getConstraintFmtOrigin(namedProperty->prop, op,
+ "property bytecode writer"),
+ namedProperty->prop.getWriteToMlirBytecodeCall(), fctx));
continue;
}
const auto *namedAttr = dyn_cast<const AttributeMetadata *>(attrOrProp);
@@ -1837,7 +1901,10 @@ void OpEmitter::genAttrGetters() {
auto tmpl = namedAttr.attr.getConvertFromStorageCall();
std::string name = op.getGetterName(namedAttr.name);
body << " {" << name << "AttrName(),\n"
- << tgfmt(tmpl, &fctx.withSelf(name + "()")
+ << tgfmtOrFatal(getConstraintFmtOrigin(namedAttr.attr, op,
+ "attribute conversion"),
+ tmpl,
+ fctx.withSelf(name + "()")
.withBuilder("odsBuilder")
.addSubst("_ctxt", "ctx")
.addSubst("_storage", "ctx"))
@@ -2714,8 +2781,11 @@ void OpEmitter::genPopulateDefaultAttributes() {
fctx.withBuilder(odsBuilder);
body << "if (!properties." << name << ")\n"
<< " properties." << name << " = "
- << std::string(tgfmt(attr.getConstBuilderTemplate(), &fctx,
- tgfmt(attr.getDefaultValue(), &fctx)))
+ << tgfmtOrFatal(
+ getConstraintFmtOrigin(attr, op, "attribute constant builder"),
+ attr.getConstBuilderTemplate(), fctx,
+ tgfmtOrFatal(getConstraintFmtOrigin(attr, op, "default value"),
+ attr.getDefaultValue(), fctx))
<< ";\n";
}
}
@@ -2900,10 +2970,10 @@ void OpEmitter::genUseAttrAsResultTypeCollectiveParamBuilder(
<< llvm::join(resultTypes, ", ") << "});\n";
}
-/// Returns a signature of the builder. Updates the context `fctx` to enable
-/// replacement of $_builder and $_state in the body.
+/// Return the builder signature, formatting parameter defaults with $_builder
+/// and $_state available.
static SmallVector<MethodParameter>
-getBuilderSignature(const Builder &builder) {
+getBuilderSignature(const Builder &builder, const FmtOrigin &origin) {
ArrayRef<Builder::Parameter> params(builder.getParameters());
// Inject builder and state arguments.
@@ -2927,7 +2997,7 @@ getBuilderSignature(const Builder &builder) {
defaultValue = *defaultParamValue;
arguments.emplace_back(params[i].getCppType(), std::move(name),
- tgfmt(defaultValue, &fctx));
+ tgfmtOrFatal(origin, defaultValue, fctx));
}
return arguments;
@@ -2936,7 +3006,8 @@ getBuilderSignature(const Builder &builder) {
void OpEmitter::genBuilder() {
// Handle custom builders if provided.
for (const Builder &builder : op.getBuilders()) {
- SmallVector<MethodParameter> arguments = getBuilderSignature(builder);
+ SmallVector<MethodParameter> arguments = getBuilderSignature(
+ builder, FmtOrigin::at(op.getLoc(), "builder parameter default"));
std::optional<StringRef> body = builder.getBody();
auto properties = body ? Method::Static : Method::StaticDeclaration;
@@ -2951,7 +3022,8 @@ void OpEmitter::genBuilder() {
fctx.withBuilder(odsBuilder);
fctx.addSubst("_state", builderOpState);
if (body)
- method->body() << tgfmt(*body, &fctx);
+ method->body() << tgfmtOrFatal(
+ FmtOrigin::at(op.getLoc(), "operation template"), *body, fctx);
genInlineCreateBody(arguments);
}
@@ -3209,7 +3281,9 @@ void OpEmitter::buildParamList(SmallVectorImpl<MethodParameter> ¶mList,
StringRef type = prop.getInterfaceType();
std::string defaultValue;
if (prop.hasDefaultValue() && i >= defaultValuedAttrLikeStartIndex) {
- defaultValue = tgfmt(prop.getDefaultValue(), &fctx);
+ defaultValue =
+ tgfmtOrFatal(getConstraintFmtOrigin(prop, op, "default value"),
+ prop.getDefaultValue(), fctx);
}
bool isOptional = prop.hasDefaultValue();
paramList.emplace_back(type, propArg->name, StringRef(defaultValue),
@@ -3241,7 +3315,9 @@ void OpEmitter::buildParamList(SmallVectorImpl<MethodParameter> ¶mList,
if (i >= defaultValuedAttrStartIndex) {
if (attrParamKind == AttrParamKind::UnwrappedValue &&
canUseUnwrappedRawValue(attr))
- defaultValue += tgfmt(attr.getDefaultValue(), &fctx);
+ defaultValue +=
+ tgfmtOrFatal(getConstraintFmtOrigin(attr, op, "default value"),
+ attr.getDefaultValue(), fctx);
else
defaultValue += "nullptr";
}
@@ -3715,7 +3791,8 @@ void OpEmitter::genTypeInterfaceMethods() {
} else if (std::optional<StringRef> builder =
op.getResult(infer.getResultIndex())
.constraint.getBuilderCall()) {
- typeStr = tgfmt(*builder, &fctx).str();
+ typeStr = tgfmtOrFatal(FmtOrigin::at(op.getLoc(), "operation template"),
+ *builder, fctx);
} else if (int index = constructedIndices[infer.getResultIndex()];
index >= 0) {
typeStr = ("odsInferredType" + Twine(index)).str();
@@ -3723,7 +3800,9 @@ void OpEmitter::genTypeInterfaceMethods() {
continue;
}
body << " ::mlir::Type odsInferredType" << inferredTypeIdx++ << " = "
- << tgfmt(infer.getTransformer(), &fctx.withSelf(typeStr)) << ";\n";
+ << tgfmtOrFatal(FmtOrigin::at(op.getLoc(), "operation template"),
+ infer.getTransformer(), fctx.withSelf(typeStr))
+ << ";\n";
constructedIndices[i] = inferredTypeIdx - 1;
}
}
@@ -3767,9 +3846,6 @@ void OpEmitter::genVerifier() {
ERROR_IF_PRUNED(implMethod, "verifyInvariantsImpl", op);
auto &implBody = implMethod->body();
populateSubstitutions(emitHelper, verifyCtx);
- // Value verifiers may add a temporary $_self binding. Traits refer to the
- // whole operation and must not inherit a binding to the last checked value.
- FmtContext traitCtx = verifyCtx;
genPropertyVerifier(emitHelper, verifyCtx, implBody, staticVerifierEmitter);
genAttributeVerifier(emitHelper, verifyCtx, implBody, staticVerifierEmitter);
genOperandResultVerifier(implBody, op.getOperands(), "operand");
@@ -3782,10 +3858,12 @@ void OpEmitter::genVerifier() {
.withUse(op.getLoc(),
"operation '" + op.getOperationName() + "'");
std::string predicate =
- tgfmtOrFatal(origin, t->getPredTemplate(), traitCtx);
- implBody << tgfmt(" if (!($0))\n "
- "return emitOpError(\"failed to verify that $1\");\n",
- &traitCtx, predicate, t->getSummary());
+ tgfmtOrFatal(origin, t->getPredTemplate(), verifyCtx);
+ implBody << tgfmtOrFatal(
+ FmtOrigin::at(op.getLoc(), "operation template"),
+ " if (!($0))\n "
+ "return emitOpError(\"failed to verify that $1\");\n",
+ verifyCtx, predicate, t->getSummary());
}
}
@@ -4229,7 +4307,9 @@ OpOperandAdaptorEmitter::OpOperandAdaptorEmitter(
if (prop.hasStorageTypeValueOverride())
os << " = " << prop.getStorageTypeValueOverride();
else if (prop.hasDefaultValue())
- os << " = " << tgfmt(prop.getDefaultValue(), &fctx);
+ os << " = "
+ << tgfmtOrFatal(getConstraintFmtOrigin(prop, op, "default value"),
+ prop.getDefaultValue(), fctx);
comparatorOs << " rhs." << name << " == this->" << name
<< " &&\n";
// Emit accessors using the interface type.
@@ -4244,12 +4324,15 @@ OpOperandAdaptorEmitter::OpOperandAdaptorEmitter(
}
)decl";
FmtContext fctx;
- os << formatv(accessorFmt, prop.getInterfaceType(), camelName, name,
- tgfmt(prop.getConvertFromStorageCall(),
- &fctx.addSubst("_storage", propertyStorage)),
- tgfmt(prop.getAssignToStorageCall(),
- &fctx.addSubst("_value", propertyValue)
- .addSubst("_storage", propertyStorage)));
+ os << formatv(
+ accessorFmt, prop.getInterfaceType(), camelName, name,
+ tgfmtOrFatal(getConstraintFmtOrigin(prop, op, "property template"),
+ prop.getConvertFromStorageCall(),
+ fctx.addSubst("_storage", propertyStorage)),
+ tgfmtOrFatal(getConstraintFmtOrigin(prop, op, "property template"),
+ prop.getAssignToStorageCall(),
+ fctx.addSubst("_value", propertyValue)
+ .addSubst("_storage", propertyStorage)));
continue;
}
const auto *namedAttr =
@@ -4467,9 +4550,11 @@ OpOperandAdaptorEmitter::OpOperandAdaptorEmitter(
// Use the default value if attribute is not set.
// TODO: this is inefficient, we are recreating the attribute for every
// call. This should be set instead.
- std::string defaultValue =
- std::string(tgfmt(attr.getConstBuilderTemplate(), &fctx,
- tgfmt(attr.getDefaultValue(), &fctx)));
+ std::string defaultValue = tgfmtOrFatal(
+ getConstraintFmtOrigin(attr, op, "attribute constant builder"),
+ attr.getConstBuilderTemplate(), fctx,
+ tgfmtOrFatal(getConstraintFmtOrigin(attr, op, "default value"),
+ attr.getDefaultValue(), fctx));
body << "if (!attr)\n attr = " << defaultValue << ";\n";
}
body << "return attr;\n";
diff --git a/mlir/tools/mlir-tblgen/OpFormatGen.cpp b/mlir/tools/mlir-tblgen/OpFormatGen.cpp
index 1fd993cc197a9a..d5a9ad0009a43a 100644
--- a/mlir/tools/mlir-tblgen/OpFormatGen.cpp
+++ b/mlir/tools/mlir-tblgen/OpFormatGen.cpp
@@ -11,15 +11,16 @@
#include "OpClass.h"
#include "mlir/Support/LLVM.h"
#include "mlir/TableGen/Class.h"
+#include "mlir/TableGen/CodeGenHelpers.h"
#include "mlir/TableGen/EnumInfo.h"
#include "mlir/TableGen/Format.h"
#include "mlir/TableGen/Operator.h"
#include "mlir/TableGen/Trait.h"
#include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallBitVector.h"
-#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/TypeSwitch.h"
@@ -306,7 +307,6 @@ class OIListElement : public DirectiveElementBase<DirectiveElement::OIList> {
//===----------------------------------------------------------------------===//
namespace {
-
using ConstArgument =
llvm::PointerUnion<const NamedAttribute *, const NamedTypeConstraint *>;
@@ -371,7 +371,8 @@ struct OperationFormat {
OperationFormat(const Operator &op)
: useStrictPropertiesInAssemblyFormat(
op.getDialect().useStrictPropertiesInAssemblyFormat()),
- opCppClassName(op.getCppClassName()) {
+ opCppClassName(op.getCppClassName()),
+ fmtOrigin(FmtOrigin::at(op.getLoc(), "operation assembly format")) {
operandTypes.resize(op.getNumOperands(), TypeResolution());
resultTypes.resize(op.getNumResults(), TypeResolution());
@@ -441,6 +442,7 @@ struct OperationFormat {
/// The Operation class name
StringRef opCppClassName;
+ FmtOrigin fmtOrigin;
/// The names of inherent attributes for this operation.
SmallVector<StringRef> inherentAttrNames;
@@ -1017,9 +1019,9 @@ static void genElementParserStorage(FormatElement *element, const Operator &op,
body << " auto &" << name << "Operands = odsOperandVectors[" << index
<< "];\n";
} else {
- body
- << " ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> "
- << name << "Operands;\n";
+ body << " ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, "
+ "4> "
+ << name << "Operands;\n";
}
if (operand->getVar()->isVariadicOfVariadic()) {
body << " llvm::SmallVector<int32_t> " << name
@@ -1079,7 +1081,8 @@ static void genElementParserStorage(FormatElement *element, const Operator &op,
}
/// Generate the parser for a parameter to a custom directive.
-static void genCustomParameterParser(FormatElement *param, MethodBody &body,
+static void genCustomParameterParser(const FmtOrigin &origin,
+ FormatElement *param, MethodBody &body,
StringRef opCppClassName) {
if (auto *attr = dyn_cast<AttributeVariable>(param)) {
body << attr->getVar()->name << "Attr";
@@ -1114,7 +1117,7 @@ static void genCustomParameterParser(FormatElement *param, MethodBody &body,
body << formatv("{0}Successor", name);
} else if (auto *dir = dyn_cast<RefDirective>(param)) {
- genCustomParameterParser(dir->getArg(), body, opCppClassName);
+ genCustomParameterParser(origin, dir->getArg(), body, opCppClassName);
} else if (auto *dir = dyn_cast<TypeDirective>(param)) {
ArgumentLengthKind lengthKind;
@@ -1132,7 +1135,7 @@ static void genCustomParameterParser(FormatElement *param, MethodBody &body,
FmtContext ctx;
ctx.withBuilder("parser.getBuilder()");
ctx.addSubst("_ctxt", "parser.getContext()");
- body << tgfmt(string->getValue(), &ctx);
+ body << tgfmtOrFatal(origin, string->getValue(), ctx);
} else if (auto *property = dyn_cast<PropertyVariable>(param)) {
body << formatv(getPropertiesCode, opCppClassName) << "."
@@ -1143,7 +1146,8 @@ static void genCustomParameterParser(FormatElement *param, MethodBody &body,
}
/// Generate the parser for a custom directive.
-static void genCustomDirectiveParser(CustomDirective *dir, MethodBody &body,
+static void genCustomDirectiveParser(const FmtOrigin &origin,
+ CustomDirective *dir, MethodBody &body,
StringRef opCppClassName,
bool isOptional = false) {
body << " {\n";
@@ -1206,7 +1210,7 @@ static void genCustomDirectiveParser(CustomDirective *dir, MethodBody &body,
body << " auto odsResult = parse" << dir->getName() << "(parser";
for (FormatElement *param : dir->getElements()) {
body << ", ";
- genCustomParameterParser(param, body, opCppClassName);
+ genCustomParameterParser(origin, param, body, opCppClassName);
}
body << ");\n";
@@ -1272,8 +1276,9 @@ static void genEnumAttrParser(const NamedAttribute *var, MethodBody &body,
std::string attrBuilderStr;
{
llvm::raw_string_ostream os(attrBuilderStr);
- os << tgfmt(baseAttr.getConstBuilderTemplate(), &attrTypeCtx,
- "*attrOptional");
+ os << tgfmtOrFatal(
+ FmtOrigin::at(baseAttr.getDef().getLoc(), "enum attribute builder"),
+ baseAttr.getConstBuilderTemplate(), attrTypeCtx, "*attrOptional");
}
// Build a string containing the cases that can be formatted as a keyword.
@@ -1346,12 +1351,16 @@ static void genPropertyParser(PropertyVariable *propVar, MethodBody &body,
std::string propAccess = formatv(getPropertiesCode, opCppClassName);
if (parseOptionally) {
- body << formatv(optionalPropertyParserCode, name, propAccess,
- tgfmt(prop.getOptionalParserCall(), &fmtContext));
+ body << formatv(
+ optionalPropertyParserCode, name, propAccess,
+ tgfmtOrFatal(FmtOrigin::at(prop.getDef().getLoc(), "property parser"),
+ prop.getOptionalParserCall(), fmtContext));
} else {
- body << formatv(propertyParserCode, name, propAccess,
- tgfmt(prop.getParserCall(), &fmtContext),
- prop.getSummary());
+ body << formatv(
+ propertyParserCode, name, propAccess,
+ tgfmtOrFatal(FmtOrigin::at(prop.getDef().getLoc(), "property parser"),
+ prop.getParserCall(), fmtContext),
+ prop.getSummary());
}
}
@@ -1378,7 +1387,9 @@ static void genAttrParser(AttributeVariable *attr, MethodBody &body,
std::string attrTypeStr;
if (std::optional<StringRef> typeBuilder = attr->getTypeBuilder()) {
llvm::raw_string_ostream os(attrTypeStr);
- os << tgfmt(*typeBuilder, &attrTypeCtx);
+ os << tgfmtOrFatal(FmtOrigin::at(attr->getVar()->attr.getDef().getLoc(),
+ "attribute type builder"),
+ *typeBuilder, attrTypeCtx);
} else {
attrTypeStr = "::mlir::Type{}";
}
@@ -1503,12 +1514,14 @@ if (attr && ::mlir::failed(setFromAttr(prop.{1}, attr, [&]() {{
const Property &prop = namedProperty.prop;
bool isRequired = !prop.hasDefaultValue();
FmtContext fctx;
- body << formatv(propFromAttrFmt,
- tgfmt(prop.getConvertFromAttributeCall(),
- &fctx.addSubst("_attr", "propAttr")
- .addSubst("_storage", "propStorage")
- .addSubst("_diag", "emitError")),
- name, isRequired);
+ body << formatv(
+ propFromAttrFmt,
+ tgfmtOrFatal(getConstraintFmtOrigin(prop, op, "property template"),
+ prop.getConvertFromAttributeCall(),
+ fctx.addSubst("_attr", "propAttr")
+ .addSubst("_storage", "propStorage")
+ .addSubst("_diag", "emitError")),
+ name, isRequired);
}
// Generate the setter for any attribute not parsed elsewhere.
@@ -1732,7 +1745,9 @@ auto parseResult = ::mlir::detail::parsePropertyWithFallback(
<< "invalid value for property " << key << ": ";
};
)decl";
- body << tgfmt(property.prop.getConvertFromAttributeCall(), &fctx)
+ body << tgfmtOrFatal(getConstraintFmtOrigin(property.prop, op,
+ "property template"),
+ property.prop.getConvertFromAttributeCall(), fctx)
<< ";\n";
body << "});\n"
<< "if (failed(parseResult))\n"
@@ -1851,8 +1866,8 @@ void OperationFormat::genParser(Operator &op, OpClass &opClass) {
// Generate variables to store the operands and type within the format. This
// allows for referencing these variables in the presence of optional
// groupings.
- unsigned numVariableLengthOperands = llvm::count_if(
- op.getOperands(), [](const NamedTypeConstraint &operand) {
+ unsigned numVariableLengthOperands =
+ llvm::count_if(op.getOperands(), [](const NamedTypeConstraint &operand) {
return operand.isVariableLength();
});
bool groupOperandStorage = !allOperands && numVariableLengthOperands > 1;
@@ -1959,7 +1974,7 @@ void OperationFormat::genElementParser(FormatElement *element, MethodBody &body,
}
} else if (auto *custom = dyn_cast<CustomDirective>(firstElement)) {
body << " if (auto optResult = [&]() -> ::mlir::OptionalParseResult {\n";
- genCustomDirectiveParser(custom, body, opCppClassName,
+ genCustomDirectiveParser(fmtOrigin, custom, body, opCppClassName,
/*isOptional=*/true);
body << " return ::mlir::success();\n"
<< " }(); optResult.has_value() && ::mlir::failed(*optResult)) {\n"
@@ -2134,7 +2149,7 @@ void OperationFormat::genElementParser(FormatElement *element, MethodBody &body,
body << " if (parseProperties(parser, result))\n"
<< " return ::mlir::failure();\n";
} else if (auto *customDir = dyn_cast<CustomDirective>(element)) {
- genCustomDirectiveParser(customDir, body, opCppClassName);
+ genCustomDirectiveParser(fmtOrigin, customDir, body, opCppClassName);
} else if (isa<OperandsDirective>(element)) {
body << " [[maybe_unused]] ::llvm::SMLoc allOperandLoc ="
<< " parser.getCurrentLocation();\n"
@@ -2202,8 +2217,10 @@ void OperationFormat::genParserTypeResolution(Operator &op, MethodBody &body) {
body << " for (::mlir::Type type : " << variable->name << "Types) {\n"
<< " (void)type;\n"
<< " if (!("
- << tgfmt(constraint.getConditionTemplate(),
- &verifierFCtx.withSelf("type"))
+ << tgfmtOrFatal(
+ getConstraintFmtOrigin(constraint, op, "constraint predicate"),
+ constraint.getConditionTemplate(),
+ verifierFCtx.withSelf("type"))
<< ")) {\n"
<< formatv(" return parser.emitError(parser.getNameLoc()) << "
"\"'{0}' must be {1}, but got \" << type;\n",
@@ -2218,7 +2235,10 @@ void OperationFormat::genParserTypeResolution(Operator &op, MethodBody &body) {
typeBuilderCtx.withBuilder("parser.getBuilder()");
for (auto &it : buildableTypes)
body << " ::mlir::Type odsBuildableType" << it.second << " = "
- << tgfmt(it.first, &typeBuilderCtx) << ";\n";
+ << tgfmtOrFatal(
+ FmtOrigin::at(op.getLoc(), "operation assembly format"),
+ it.first, typeBuilderCtx)
+ << ";\n";
}
// Emit the code necessary for a type resolver.
@@ -2233,7 +2253,9 @@ void OperationFormat::genParserTypeResolution(Operator &op, MethodBody &body) {
fmtContext.withSelf(var->name + "Types");
else
fmtContext.withSelf(var->name + "Types[0]");
- body << tgfmt(*tform, &fmtContext);
+ body << tgfmtOrFatal(
+ FmtOrigin::at(op.getLoc(), "operation assembly format"), *tform,
+ fmtContext);
} else {
body << var->name << "Types";
if (!var->isVariadic())
@@ -2241,8 +2263,9 @@ void OperationFormat::genParserTypeResolution(Operator &op, MethodBody &body) {
}
} else if (const NamedAttribute *attr = resolver.getAttribute()) {
if (std::optional<StringRef> tform = resolver.getVarTransformer())
- body << tgfmt(*tform,
- &FmtContext().withSelf(attr->name + "Attr.getType()"));
+ body << tgfmtOrFatal(
+ FmtOrigin::at(op.getLoc(), "operation assembly format"), *tform,
+ FmtContext().withSelf(attr->name + "Attr.getType()"));
else
body << attr->name << "Attr.getType()";
} else {
@@ -2503,8 +2526,11 @@ static void genNonDefaultValueCheck(MethodBody &body, const Operator &op,
FmtContext fctx;
fctx.withBuilder("::mlir::OpBuilder((*this)->getContext())");
body << getter << "Attr() != "
- << tgfmt(attr.getConstBuilderTemplate(), &fctx,
- tgfmt(attr.getDefaultValue(), &fctx));
+ << tgfmtOrFatal(
+ getConstraintFmtOrigin(attr, op, "attribute constant builder"),
+ attr.getConstBuilderTemplate(), fctx,
+ tgfmtOrFatal(getConstraintFmtOrigin(attr, op, "default value"),
+ attr.getDefaultValue(), fctx));
}
if (optionalAndDefault)
body << ")";
@@ -2515,7 +2541,9 @@ static void genNonDefaultValueCheck(MethodBody &body, const Operator &op,
FmtContext fctx;
fctx.withBuilder("::mlir::OpBuilder((*this)->getContext())");
body << op.getGetterName(propElement.getVar()->name) << "() != "
- << tgfmt(propElement.getVar()->prop.getDefaultValue(), &fctx);
+ << tgfmtOrFatal(getConstraintFmtOrigin(propElement.getVar()->prop, op,
+ "property default value"),
+ propElement.getVar()->prop.getDefaultValue(), fctx);
}
/// Elide the variadic segment size attributes if necessary.
@@ -2607,20 +2635,28 @@ auto shouldPrint = [&](::llvm::StringRef name) {
body << " if constexpr (::mlir::detail::HasKeyValueFieldParser<"
"std::remove_cv_t<std::remove_reference_t<decltype(prop."
<< namedProperty.name << ")>>>::value) {\n"
- << " " << tgfmt(property.getPrinterCall(), &printerContext)
+ << " "
+ << tgfmtOrFatal(
+ getConstraintFmtOrigin(property, op, "property template"),
+ property.getPrinterCall(), printerContext)
<< ";\n"
<< " } else {\n"
<< " auto propertyAttr = [&]() -> ::mlir::Attribute {\n";
FmtContext conversionContext;
conversionContext.addSubst("_ctxt", "_odsContext");
conversionContext.addSubst("_storage", "prop." + namedProperty.name);
- body << tgfmt(property.getConvertToAttributeCall(), &conversionContext)
+ body << tgfmtOrFatal(
+ getConstraintFmtOrigin(property, op, "property template"),
+ property.getConvertToAttributeCall(), conversionContext)
<< "\n"
<< " }();\n"
<< " _odsPrinter.printAttribute(propertyAttr);\n"
<< " }\n";
} else {
- body << " " << tgfmt(property.getPrinterCall(), &printerContext)
+ body << " "
+ << tgfmtOrFatal(
+ getConstraintFmtOrigin(property, op, "property template"),
+ property.getPrinterCall(), printerContext)
<< ";\n";
}
body << "}\n";
@@ -2648,8 +2684,9 @@ auto shouldPrint = [&](::llvm::StringRef name) {
body << " _odsPrinter << \"[\";\n";
FmtContext conversionContext;
conversionContext.withSelf("prop." + name);
- std::string valueExpression = std::string(tgfmt(
- namedAttr.attr.getConvertFromStorageCall(), &conversionContext));
+ std::string valueExpression = tgfmtOrFatal(
+ getConstraintFmtOrigin(namedAttr.attr, op, "attribute template"),
+ namedAttr.attr.getConvertFromStorageCall(), conversionContext);
genEnumAttrPrinter(&namedAttr, op, body, valueExpression,
/*formatAsEnumDirective=*/true,
/*formatBitEnumAsUnquoted=*/true);
@@ -2658,8 +2695,9 @@ auto shouldPrint = [&](::llvm::StringRef name) {
} else if (canFormatEnumAttr(&namedAttr)) {
FmtContext conversionContext;
conversionContext.withSelf("prop." + name);
- std::string valueExpression = std::string(tgfmt(
- namedAttr.attr.getConvertFromStorageCall(), &conversionContext));
+ std::string valueExpression = tgfmtOrFatal(
+ getConstraintFmtOrigin(namedAttr.attr, op, "attribute template"),
+ namedAttr.attr.getConvertFromStorageCall(), conversionContext);
genEnumAttrPrinter(&namedAttr, op, body, valueExpression);
} else if (shouldFormatSymbolNameAttr(&namedAttr)) {
body << " _odsPrinter.printSymbolName(prop." << name
@@ -2705,9 +2743,11 @@ static void genPropDictPrinter(OperationFormat &fmt, Operator &op,
const StringRef &name = namedAttr.name;
FmtContext fctx;
fctx.withBuilder("odsBuilder");
- std::string defaultValue =
- std::string(tgfmt(attr.getConstBuilderTemplate(), &fctx,
- tgfmt(attr.getDefaultValue(), &fctx)));
+ std::string defaultValue = tgfmtOrFatal(
+ getConstraintFmtOrigin(attr, op, "attribute constant builder"),
+ attr.getConstBuilderTemplate(), fctx,
+ tgfmtOrFatal(getConstraintFmtOrigin(attr, op, "default value"),
+ attr.getDefaultValue(), fctx));
body << " {\n";
body << " ::mlir::Builder odsBuilder((*this)->getContext());\n";
body << " ::mlir::Attribute attr = " << op.getGetterName(name)
@@ -2722,8 +2762,11 @@ static void genPropDictPrinter(OperationFormat &fmt, Operator &op,
if (prop.prop.hasDefaultValue()) {
FmtContext fctx;
fctx.withBuilder("odsBuilder");
- body << " if (" << op.getGetterName(prop.name)
- << "() == " << tgfmt(prop.prop.getDefaultValue(), &fctx) << ") {";
+ body << " if (" << op.getGetterName(prop.name) << "() == "
+ << tgfmtOrFatal(
+ getConstraintFmtOrigin(prop.prop, op, "default value"),
+ prop.prop.getDefaultValue(), fctx)
+ << ") {";
body << " elidedProps.push_back(\"" << prop.name << "\");\n";
body << " }\n";
}
@@ -2793,9 +2836,11 @@ static void genAttrDictPrinter(OperationFormat &fmt, Operator &op,
const StringRef &name = namedAttr.name;
FmtContext fctx;
fctx.withBuilder("odsBuilder");
- std::string defaultValue =
- std::string(tgfmt(attr.getConstBuilderTemplate(), &fctx,
- tgfmt(attr.getDefaultValue(), &fctx)));
+ std::string defaultValue = tgfmtOrFatal(
+ getConstraintFmtOrigin(attr, op, "attribute constant builder"),
+ attr.getConstBuilderTemplate(), fctx,
+ tgfmtOrFatal(getConstraintFmtOrigin(attr, op, "default value"),
+ attr.getDefaultValue(), fctx));
body << " {\n";
body << " ::mlir::Builder odsBuilder((*this)->getContext());\n";
body << " ::mlir::Attribute attr = " << op.getGetterName(name)
@@ -2902,13 +2947,17 @@ static void genCustomDirectiveParameterPrinter(FormatElement *element,
FmtContext ctx;
ctx.withBuilder("::mlir::Builder(getContext())");
ctx.addSubst("_ctxt", "getContext()");
- body << tgfmt(string->getValue(), &ctx);
+ body << tgfmtOrFatal(
+ FmtOrigin::at(op.getLoc(), "operation assembly format"),
+ string->getValue(), ctx);
} else if (auto *property = dyn_cast<PropertyVariable>(element)) {
FmtContext ctx;
const NamedProperty *namedProperty = property->getVar();
ctx.addSubst("_storage", "getProperties()." + namedProperty->name);
- body << tgfmt(namedProperty->prop.getConvertFromStorageCall(), &ctx);
+ body << tgfmtOrFatal(
+ getConstraintFmtOrigin(namedProperty->prop, op, "property template"),
+ namedProperty->prop.getConvertFromStorageCall(), ctx);
} else {
llvm_unreachable("unknown custom directive parameter");
}
@@ -3301,7 +3350,10 @@ void OperationFormat::genElementPrinter(FormatElement *element,
fmtContext.addSubst("_printer", "_odsPrinter");
fmtContext.addSubst("_ctxt", "getContext()");
fmtContext.addSubst("_storage", "getProperties()." + var->name);
- body << tgfmt(var->prop.getPrinterCall(), &fmtContext) << ";\n";
+ body << tgfmtOrFatal(
+ getConstraintFmtOrigin(var->prop, op, "property template"),
+ var->prop.getPrinterCall(), fmtContext)
+ << ";\n";
} else if (auto *operand = dyn_cast<OperandVariable>(element)) {
if (operand->getVar()->isVariadicOfVariadic()) {
body << " ::llvm::interleaveComma("
diff --git a/mlir/tools/mlir-tblgen/OpInterfacesGen.cpp b/mlir/tools/mlir-tblgen/OpInterfacesGen.cpp
index 3f62969312de82..7a6a4f9ea234f9 100644
--- a/mlir/tools/mlir-tblgen/OpInterfacesGen.cpp
+++ b/mlir/tools/mlir-tblgen/OpInterfacesGen.cpp
@@ -12,6 +12,7 @@
#include "CppGenUtilities.h"
#include "DocGenUtilities.h"
+#include "mlir/TableGen/CodeGenHelpers.h"
#include "mlir/TableGen/Format.h"
#include "mlir/TableGen/GenInfo.h"
#include "mlir/TableGen/Interfaces.h"
@@ -399,7 +400,11 @@ void InterfaceGenerator::emitModelMethodsDef(const Interface &interface) {
emitMethodNameAndArgs(method, ("shared_" + method.getUniqueName()).str(),
os, valueType, /*addThisArg=*/true,
/*addConst=*/false);
- os << " {\n " << tblgen::tgfmt(body.trim(), &sharedOpMethodFmt)
+ os << " {\n "
+ << tblgen::tgfmtOrFatal(
+ tblgen::FmtOrigin::at(interface.getDef().getLoc(),
+ "interface template"),
+ body.trim(), sharedOpMethodFmt)
<< "\n}\n";
continue;
}
@@ -417,7 +422,10 @@ void InterfaceGenerator::emitModelMethodsDef(const Interface &interface) {
if (method.isStatic())
os << body->trim();
else
- os << tblgen::tgfmt(body->trim(), &nonStaticMethodFmt);
+ os << tblgen::tgfmtOrFatal(
+ tblgen::FmtOrigin::at(interface.getDef().getLoc(),
+ "interface template"),
+ body->trim(), nonStaticMethodFmt);
os << "\n}\n";
continue;
}
@@ -426,7 +434,10 @@ void InterfaceGenerator::emitModelMethodsDef(const Interface &interface) {
if (method.isStatic())
os << "return " << valueTemplate << "::";
else
- os << tblgen::tgfmt("return $_self.", &nonStaticMethodFmt);
+ os << tblgen::tgfmtOrFatal(
+ tblgen::FmtOrigin::at(interface.getDef().getLoc(),
+ "interface template"),
+ "return $_self.", nonStaticMethodFmt);
// Add the arguments to the call.
os << method.getName() << '(';
@@ -496,8 +507,12 @@ void InterfaceGenerator::emitModelMethodsDef(const Interface &interface) {
// Use the empty context for static methods.
tblgen::FmtContext ctx;
- os << tblgen::tgfmt(method.getDefaultImplementation()->trim(),
- method.isStatic() ? &ctx : &nonStaticMethodFmt);
+ const tblgen::FmtContext &implCtx =
+ method.isStatic() ? ctx : nonStaticMethodFmt;
+ os << tblgen::tgfmtOrFatal(
+ tblgen::FmtOrigin::at(interface.getDef().getLoc(),
+ "interface template"),
+ method.getDefaultImplementation()->trim(), implCtx);
os << "\n}\n";
}
}
@@ -533,7 +548,11 @@ void InterfaceGenerator::emitInterfaceTraitDecl(const Interface &interface) {
emitMethodNameAndArgs(method, method.getName(), os, valueType,
/*addThisArg=*/false,
/*addConst=*/!isOpInterface && !method.isStatic());
- os << " {\n " << tblgen::tgfmt(defaultImpl->trim(), &traitMethodFmt)
+ os << " {\n "
+ << tblgen::tgfmtOrFatal(
+ tblgen::FmtOrigin::at(interface.getDef().getLoc(),
+ "interface template"),
+ defaultImpl->trim(), traitMethodFmt)
<< "\n }\n";
}
@@ -546,13 +565,25 @@ void InterfaceGenerator::emitInterfaceTraitDecl(const Interface &interface) {
" static ::llvm::LogicalResult {0}(::mlir::Operation *op) ",
(interface.verifyWithRegions() ? "verifyRegionTrait"
: "verifyTrait"))
- << "{\n " << tblgen::tgfmt(verify->trim(), &verifyCtx)
+ << "{\n "
+ << tblgen::tgfmtOrFatal(
+ tblgen::FmtOrigin::at(interface.getDef().getLoc(),
+ "interface template"),
+ verify->trim(), verifyCtx)
<< "\n }\n";
}
if (auto extraTraitDecls = interface.getExtraTraitClassDeclaration())
- os << tblgen::tgfmt(*extraTraitDecls, &traitMethodFmt) << "\n";
+ os << tblgen::tgfmtOrFatal(
+ tblgen::FmtOrigin::at(interface.getDef().getLoc(),
+ "interface template"),
+ *extraTraitDecls, traitMethodFmt)
+ << "\n";
if (auto extraTraitDecls = interface.getExtraSharedClassDeclaration())
- os << tblgen::tgfmt(*extraTraitDecls, &traitMethodFmt) << "\n";
+ os << tblgen::tgfmtOrFatal(
+ tblgen::FmtOrigin::at(interface.getDef().getLoc(),
+ "interface template"),
+ *extraTraitDecls, traitMethodFmt)
+ << "\n";
os << " };\n";
}
@@ -576,7 +607,11 @@ static void emitInterfaceDeclMethods(const Interface &interface,
os << extraDecls->rtrim() << "\n";
if (std::optional<StringRef> extraDecls =
interface.getExtraSharedClassDeclaration())
- os << tblgen::tgfmt(extraDecls->rtrim(), &extraDeclsFmt) << "\n";
+ os << tblgen::tgfmtOrFatal(
+ tblgen::FmtOrigin::at(interface.getDef().getLoc(),
+ "interface template"),
+ extraDecls->rtrim(), extraDeclsFmt)
+ << "\n";
}
void InterfaceGenerator::forwardDeclareInterface(const Interface &interface) {
@@ -664,7 +699,11 @@ void InterfaceGenerator::emitInterfaceDecl(const Interface &interface) {
" return false;\n"
" "
<< interfaceName << " odsInterfaceInstance(base, interface);\n"
- << " " << tblgen::tgfmt(extraClassOf->trim(), &extraClassOfFmt)
+ << " "
+ << tblgen::tgfmtOrFatal(
+ tblgen::FmtOrigin::at(interface.getDef().getLoc(),
+ "interface template"),
+ extraClassOf->trim(), extraClassOfFmt)
<< "\n }\n";
}
diff --git a/mlir/tools/mlir-tblgen/RewriterGen.cpp b/mlir/tools/mlir-tblgen/RewriterGen.cpp
index a53ced0e394cb0..a9a7f14cafc3eb 100644
--- a/mlir/tools/mlir-tblgen/RewriterGen.cpp
+++ b/mlir/tools/mlir-tblgen/RewriterGen.cpp
@@ -59,7 +59,6 @@ struct format_provider<mlir::tblgen::Pattern::IdentifierLine> {
//===----------------------------------------------------------------------===//
namespace {
-
class StaticMatcherHelper;
class PatternEmitter {
@@ -132,7 +131,7 @@ class PatternEmitter {
// Emits C++ for checking a match with a corresponding match failure
// diagnostic.
- void emitMatchCheck(StringRef opName, const FmtObjectBase &matchFmt,
+ void emitMatchCheck(StringRef opName, const std::string &matchFmt,
const llvm::formatv_object_base &failureFmt);
// Emits C++ for checking a match with a corresponding match failure
@@ -349,7 +348,6 @@ class StaticMatcherHelper {
// Static type/attribute verification function emitter.
StaticVerifierFunctionEmitter staticVerifierEmitter;
};
-
} // namespace
PatternEmitter::PatternEmitter(const Record *pat, RecordOperatorMap *mapper,
@@ -366,7 +364,8 @@ std::string PatternEmitter::handleConstantAttr(Attribute attr,
" does not have the 'constBuilderCall' field");
// TODO: Verify the constants here
- return std::string(tgfmt(attr.getConstBuilderTemplate(), &fmtCtx, value));
+ return tgfmtOrFatal(FmtOrigin::at(loc, "rewrite template"),
+ attr.getConstBuilderTemplate(), fmtCtx, value);
}
void PatternEmitter::emitStaticMatcher(DagNode tree, std::string funcName) {
@@ -521,9 +520,10 @@ void PatternEmitter::emitNativeCodeMatch(DagNode tree, StringRef opName,
PrintFatalError(loc, "NativeCodeCall must have $_self as argument for "
"passing the defining Operation");
- auto nativeCodeCall = std::string(
- tgfmtv(fmt, &fmtCtx.addSubst("_loc", locToUse).withSelf(opName.str()),
- static_cast<ArrayRef<std::string>>(capture)));
+ auto nativeCodeCall =
+ tgfmtvOrFatal(FmtOrigin::at(loc, "rewrite template"), fmt,
+ fmtCtx.addSubst("_loc", locToUse).withSelf(opName.str()),
+ static_cast<ArrayRef<std::string>>(capture));
emitMatchCheck(opName, formatv("!::mlir::failed({0})", nativeCodeCall),
formatv("\"{0} return ::mlir::failure\"", nativeCodeCall));
@@ -897,8 +897,10 @@ void PatternEmitter::emitAttributeMatch(DagNode tree, StringRef castedName,
// TODO: This should use getter method to avoid duplication.
if (attr.hasDefaultValue()) {
os << "if (!tblgen_attr) tblgen_attr = "
- << std::string(tgfmt(attr.getConstBuilderTemplate(), &fmtCtx,
- tgfmt(attr.getDefaultValue(), &fmtCtx)))
+ << tgfmtOrFatal(FmtOrigin::at(loc, "rewrite template"),
+ attr.getConstBuilderTemplate(), fmtCtx,
+ tgfmtOrFatal(FmtOrigin::at(loc, "rewrite template"),
+ attr.getDefaultValue(), fmtCtx))
<< ";\n";
} else if (attr.isOptional()) {
// For a missing attribute that is optional according to definition, we
@@ -906,7 +908,9 @@ void PatternEmitter::emitAttributeMatch(DagNode tree, StringRef castedName,
// That is precisely what getDiscardableAttr() returns on missing
// attributes.
} else {
- emitMatchCheck(castedName, tgfmt("tblgen_attr", &fmtCtx),
+ emitMatchCheck(castedName,
+ tgfmtOrFatal(FmtOrigin::at(loc, "rewrite template"),
+ "tblgen_attr", fmtCtx),
formatv("\"expected op '{0}' to have attribute '{1}' "
"of type '{2}'\"",
op.getOperationName(), namedAttr->name,
@@ -996,9 +1000,9 @@ void PatternEmitter::emitPropertyMatch(DagNode tree, StringRef castedName,
}
void PatternEmitter::emitMatchCheck(
- StringRef opName, const FmtObjectBase &matchFmt,
+ StringRef opName, const std::string &matchFmt,
const llvm::formatv_object_base &failureFmt) {
- emitMatchCheck(opName, matchFmt.str(), failureFmt.str());
+ emitMatchCheck(opName, matchFmt, failureFmt.str());
}
void PatternEmitter::emitMatchCheck(StringRef opName,
@@ -1054,7 +1058,9 @@ void PatternEmitter::emitMatchLogic(DagNode tree, StringRef opName) {
auto self = formatv("({0}.getType())",
symbolInfoMap.getValueAndRangeUse(entities.front()));
emitMatchCheck(
- opName, tgfmt(condition, &fmtCtx.withSelf(self.str())),
+ opName,
+ tgfmtOrFatal(FmtOrigin::at(loc, "rewrite template"), condition,
+ fmtCtx.withSelf(self.str())),
formatv("\"value entity '{0}' failed to satisfy constraint: '{1}'\"",
entities.front(), escapeString(constraint.getSummary())));
@@ -1077,8 +1083,9 @@ void PatternEmitter::emitMatchLogic(DagNode tree, StringRef opName) {
for (; i < 4; ++i)
names.push_back("<unused>");
emitMatchCheck(opName,
- tgfmt(condition, &fmtCtx.withSelf(self), names[0],
- names[1], names[2], names[3]),
+ tgfmtOrFatal(FmtOrigin::at(loc, "rewrite template"),
+ condition, fmtCtx.withSelf(self), names[0],
+ names[1], names[2], names[3]),
formatv("\"entities '{0}' failed to satisfy constraint: "
"'{1}'\"",
llvm::join(entities, ", "),
@@ -1418,9 +1425,10 @@ std::string PatternEmitter::handleReturnTypeArg(DagNode returnType, int i,
// String literal.
auto dagLeaf = returnType.getArgAsLeaf(i);
if (dagLeaf.isStringAttr())
- return tgfmt(dagLeaf.getStringAttr(), &fmtCtx);
- return tgfmt(
- "$0.getType()", &fmtCtx,
+ return tgfmtOrFatal(FmtOrigin::at(loc, "rewrite template"),
+ dagLeaf.getStringAttr(), fmtCtx);
+ return tgfmtOrFatal(
+ FmtOrigin::at(loc, "rewrite template"), "$0.getType()", fmtCtx,
handleOpArgument(returnType.getArgAsLeaf(i), returnType.getArgName(i)));
}
@@ -1453,7 +1461,9 @@ std::string PatternEmitter::handleOpArgument(DagLeaf leaf,
return argName;
}
if (leaf.isNativeCodeCall()) {
- auto repl = tgfmt(leaf.getNativeCodeTemplate(), &fmtCtx.withSelf(argName));
+ auto repl =
+ tgfmtOrFatal(FmtOrigin::at(loc, "rewrite template"),
+ leaf.getNativeCodeTemplate(), fmtCtx.withSelf(argName));
LLVM_DEBUG(llvm::dbgs() << "replace " << patArgName << " with '" << repl
<< "' (via NativeCodeCall)\n");
return std::string(repl);
@@ -1488,8 +1498,9 @@ std::string PatternEmitter::handleReplaceWithNativeCodeCall(DagNode tree,
<< " replacement: " << attrs[i] << "\n");
}
- std::string symbol = tgfmtv(fmt, &fmtCtx.addSubst("_loc", locToUse),
- static_cast<ArrayRef<std::string>>(attrs));
+ std::string symbol = tgfmtvOrFatal(FmtOrigin::at(loc, "rewrite template"),
+ fmt, fmtCtx.addSubst("_loc", locToUse),
+ static_cast<ArrayRef<std::string>>(attrs));
// In general, NativeCodeCall without naming binding don't need this. To
// ensure void helper function has been correctly labeled, i.e., use
@@ -1798,8 +1809,9 @@ void PatternEmitter::createSeparateLocalVarsForOpArgs(
auto symbol =
symbolInfoMap.getValueAndRangeUse(node.getArgName(argIndex));
if (leaf.isNativeCodeCall()) {
- os << std::string(
- tgfmt(leaf.getNativeCodeTemplate(), &fmtCtx.withSelf(symbol)));
+ os << tgfmtOrFatal(FmtOrigin::at(loc, "rewrite template"),
+ leaf.getNativeCodeTemplate(),
+ fmtCtx.withSelf(symbol));
} else {
os << symbol;
}
@@ -1956,8 +1968,9 @@ void PatternEmitter::createAggregateLocalVarsForOpArgs(
auto symbol =
symbolInfoMap.getValueAndRangeUse(node.getArgName(argIndex));
if (leaf.isNativeCodeCall()) {
- os << std::string(
- tgfmt(leaf.getNativeCodeTemplate(), &fmtCtx.withSelf(symbol)));
+ os << tgfmtOrFatal(FmtOrigin::at(loc, "rewrite template"),
+ leaf.getNativeCodeTemplate(),
+ fmtCtx.withSelf(symbol));
} else {
os << symbol;
}
diff --git a/mlir/tools/mlir-tblgen/SPIRVUtilsGen.cpp b/mlir/tools/mlir-tblgen/SPIRVUtilsGen.cpp
index 732005f8827964..7df7a4c2d52446 100644
--- a/mlir/tools/mlir-tblgen/SPIRVUtilsGen.cpp
+++ b/mlir/tools/mlir-tblgen/SPIRVUtilsGen.cpp
@@ -48,9 +48,11 @@ using llvm::StringRef;
using mlir::tblgen::Attribute;
using mlir::tblgen::EnumCase;
using mlir::tblgen::EnumInfo;
+using mlir::tblgen::FmtOrigin;
using mlir::tblgen::NamedAttribute;
using mlir::tblgen::NamedTypeConstraint;
using mlir::tblgen::Operator;
+using mlir::tblgen::tgfmtOrFatal;
//===----------------------------------------------------------------------===//
// Availability Wrapper Class
@@ -1395,9 +1397,10 @@ static void emitAvailabilityImpl(const Operator &srcOp, raw_ostream &os) {
<< avail.getMergeInstancePreparation()
<< "\n "
// Merge this instance.
- << std::string(
- tgfmt(avail.getMergeActionCode(),
- &fctx.addSubst("instance", avail.getMergeInstance())))
+ << tgfmtOrFatal(
+ FmtOrigin::at(srcOp.getLoc(), "SPIR-V availability template"),
+ avail.getMergeActionCode(),
+ fctx.addSubst("instance", avail.getMergeInstance()))
<< ";\n }\n";
}
@@ -1449,8 +1452,10 @@ static void emitAvailabilityImpl(const Operator &srcOp, raw_ostream &os) {
// TODO` here once ODS supports
// dialect-specific contents so that we can use not implementing the
// availability interface as indication of no requirements.
- << std::string(tgfmt(caseSpecs.front().second.getMergeActionCode(),
- &fctx.addSubst("instance", "*tblgen_instance")))
+ << tgfmtOrFatal(
+ FmtOrigin::at(srcOp.getLoc(), "SPIR-V availability template"),
+ caseSpecs.front().second.getMergeActionCode(),
+ fctx.addSubst("instance", "*tblgen_instance"))
<< ";\n";
os << " }\n";
}
diff --git a/mlir/unittests/TableGen/FormatTest.cpp b/mlir/unittests/TableGen/FormatTest.cpp
index fe8e4028bae3b6..fb474bf10b2561 100644
--- a/mlir/unittests/TableGen/FormatTest.cpp
+++ b/mlir/unittests/TableGen/FormatTest.cpp
@@ -500,3 +500,52 @@ TEST(FormatTest, FatalFormattingPreservesUnrelatedErrors) {
::testing::ExitedWithCode(1), "unrelated failure");
}
#endif
+
+TEST(FormatTest, ReferenceOverloadsReturnCheckedOwnedResults) {
+ FmtContext ctx({{"name", "value"}});
+ auto result = tgfmt("$name $0", ctx, 42);
+ ASSERT_TRUE(static_cast<bool>(result));
+ ctx.addSubst("name", "changed");
+ EXPECT_EQ(*result, "value 42");
+ std::string values[] = {"zero", "one"};
+ auto arrayResult = tgfmtv("$1 $name", ctx, values);
+ ASSERT_TRUE(static_cast<bool>(arrayResult));
+ EXPECT_EQ(*arrayResult, "one changed");
+ auto error = takeFormatError(tgfmt("$absent", ctx));
+ ASSERT_TRUE(error);
+ EXPECT_EQ(error->getIssues()[0].placeholder, "$absent");
+ error = takeFormatError(tgfmtv("$2", ctx, values));
+ ASSERT_TRUE(error);
+ EXPECT_EQ(error->getIssues()[0].kind, FmtIssueKind::PositionalOutOfRange);
+}
+
+TEST(FormatTest, CheckedSummaryPreservesStreamingAndLiteralDollars) {
+ FmtContext ctx({{"_self", "value"}});
+ auto plain = buildErrorStreamingStringChecked("literal $text", ctx);
+ ASSERT_TRUE(static_cast<bool>(plain));
+ EXPECT_EQ(*plain, "literal $text");
+ for (ErrorStreamType type :
+ {ErrorStreamType::InString, ErrorStreamType::InsideOpError}) {
+ auto result =
+ buildErrorStreamingStringChecked("before {{$_self}} after", ctx, type);
+ ASSERT_TRUE(static_cast<bool>(result));
+ EXPECT_EQ(*result, type == ErrorStreamType::InString
+ ? "before \" << value << \" after"
+ : "before \") << value << (\" after");
+ }
+}
+
+TEST(FormatTest, SummaryErrorRetainsEscapedSegmentAndBindingSnapshot) {
+ FmtContext ctx({{"_self", "value"}});
+ auto error = takeFormatError(buildErrorStreamingStringChecked(
+ R"(before {{"quoted" + \path + $missing}} after)", ctx));
+ ASSERT_TRUE(error);
+ EXPECT_EQ(error->getTemplate(), R"(\"quoted\" + \\path + $missing)");
+ EXPECT_EQ(error->getIssues()[0].offset,
+ error->getTemplate().find("$missing"));
+ ASSERT_EQ(error->getOrigins().size(), 1u);
+ EXPECT_EQ(error->getOrigins()[0].getDefinition().description,
+ "escaped summary expression");
+ ctx.withSelf("changed");
+ EXPECT_EQ(error->getBindings()[0].replacement, "value");
+}
More information about the llvm-branch-commits
mailing list