MLIR  21.0.0git
CodeGenHelpers.cpp
Go to the documentation of this file.
1 //===- CodeGenHelpers.cpp - MLIR op definitions generator ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // OpDefinitionsGen uses the description of operations to generate C++
10 // definitions for ops.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "mlir/TableGen/Operator.h"
16 #include "mlir/TableGen/Pattern.h"
17 #include "llvm/Support/FormatVariadic.h"
18 #include "llvm/Support/Path.h"
19 #include "llvm/TableGen/Record.h"
20 
21 using namespace llvm;
22 using namespace mlir;
23 using namespace mlir::tblgen;
24 
25 /// Generate a unique label based on the current file name to prevent name
26 /// collisions if multiple generated files are included at once.
27 static std::string getUniqueOutputLabel(const RecordKeeper &records,
28  StringRef tag) {
29  // Use the input file name when generating a unique name.
30  std::string inputFilename = records.getInputFilename();
31 
32  // Drop all but the base filename.
33  StringRef nameRef = sys::path::filename(inputFilename);
34  nameRef.consume_back(".td");
35 
36  // Sanitize any invalid characters.
37  std::string uniqueName(tag);
38  for (char c : nameRef) {
39  if (isAlnum(c) || c == '_')
40  uniqueName.push_back(c);
41  else
42  uniqueName.append(utohexstr((unsigned char)c));
43  }
44  return uniqueName;
45 }
46 
47 StaticVerifierFunctionEmitter::StaticVerifierFunctionEmitter(
48  raw_ostream &os, const RecordKeeper &records, StringRef tag)
49  : os(os), uniqueOutputLabel(getUniqueOutputLabel(records, tag)) {}
50 
52  ArrayRef<const Record *> opDefs) {
53  NamespaceEmitter namespaceEmitter(os, Operator(*opDefs[0]).getCppNamespace());
54  emitTypeConstraints();
55  emitAttrConstraints();
56  emitSuccessorConstraints();
57  emitRegionConstraints();
58 }
59 
60 void StaticVerifierFunctionEmitter::emitPatternConstraints(
61  const ArrayRef<DagLeaf> constraints) {
62  collectPatternConstraints(constraints);
64 }
65 
66 //===----------------------------------------------------------------------===//
67 // Constraint Getters
68 //===----------------------------------------------------------------------===//
69 
71  const Constraint &constraint) const {
72  const auto *it = typeConstraints.find(constraint);
73  assert(it != typeConstraints.end() && "expected to find a type constraint");
74  return it->second;
75 }
76 
77 // Find a uniqued attribute constraint. Since not all attribute constraints can
78 // be uniqued, return std::nullopt if one was not found.
80  const Constraint &constraint) const {
81  const auto *it = attrConstraints.find(constraint);
82  return it == attrConstraints.end() ? std::optional<StringRef>()
83  : StringRef(it->second);
84 }
85 
87  const Constraint &constraint) const {
88  const auto *it = successorConstraints.find(constraint);
89  assert(it != successorConstraints.end() &&
90  "expected to find a sucessor constraint");
91  return it->second;
92 }
93 
95  const Constraint &constraint) const {
96  const auto *it = regionConstraints.find(constraint);
97  assert(it != regionConstraints.end() &&
98  "expected to find a region constraint");
99  return it->second;
100 }
101 
102 //===----------------------------------------------------------------------===//
103 // Constraint Emission
104 //===----------------------------------------------------------------------===//
105 
106 /// Code templates for emitting type, attribute, successor, and region
107 /// constraints. Each of these templates require the following arguments:
108 ///
109 /// {0}: The unique constraint name.
110 /// {1}: The constraint code.
111 /// {2}: The constraint description.
112 
113 /// Code for a type constraint. These may be called on the type of either
114 /// operands or results.
115 static const char *const typeConstraintCode = R"(
116 static ::llvm::LogicalResult {0}(
117  ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind,
118  unsigned valueIndex) {
119  if (!({1})) {
120  return op->emitOpError(valueKind) << " #" << valueIndex
121  << " must be {2}, but got " << type;
122  }
123  return ::mlir::success();
124 }
125 )";
126 
127 /// Code for an attribute constraint. These may be called from ops only.
128 /// Attribute constraints cannot reference anything other than `$_self` and
129 /// `$_op`.
130 ///
131 /// TODO: Unique constraints for adaptors. However, most Adaptor::verify
132 /// functions are stripped anyways.
133 static const char *const attrConstraintCode = R"(
134 static ::llvm::LogicalResult {0}(
135  ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) {{
136  if (attr && !({1}))
137  return emitError() << "attribute '" << attrName
138  << "' failed to satisfy constraint: {2}";
139  return ::mlir::success();
140 }
141 static ::llvm::LogicalResult {0}(
142  ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) {{
143  return {0}(attr, attrName, [op]() {{
144  return op->emitOpError();
145  });
146 }
147 )";
148 
149 /// Code for a successor constraint.
150 static const char *const successorConstraintCode = R"(
151 static ::llvm::LogicalResult {0}(
152  ::mlir::Operation *op, ::mlir::Block *successor,
153  ::llvm::StringRef successorName, unsigned successorIndex) {
154  if (!({1})) {
155  return op->emitOpError("successor #") << successorIndex << " ('"
156  << successorName << ")' failed to verify constraint: {2}";
157  }
158  return ::mlir::success();
159 }
160 )";
161 
162 /// Code for a region constraint. Callers will need to pass in the region's name
163 /// for emitting an error message.
164 static const char *const regionConstraintCode = R"(
165 static ::llvm::LogicalResult {0}(
166  ::mlir::Operation *op, ::mlir::Region &region, ::llvm::StringRef regionName,
167  unsigned regionIndex) {
168  if (!({1})) {
169  return op->emitOpError("region #") << regionIndex
170  << (regionName.empty() ? " " : " ('" + regionName + "') ")
171  << "failed to verify constraint: {2}";
172  }
173  return ::mlir::success();
174 }
175 )";
176 
177 /// Code for a pattern type or attribute constraint.
178 ///
179 /// {3}: "Type type" or "Attribute attr".
180 static const char *const patternAttrOrTypeConstraintCode = R"(
181 static ::llvm::LogicalResult {0}(
182  ::mlir::PatternRewriter &rewriter, ::mlir::Operation *op, ::mlir::{3},
183  ::llvm::StringRef failureStr) {
184  if (!({1})) {
185  return rewriter.notifyMatchFailure(op, [&](::mlir::Diagnostic &diag) {
186  diag << failureStr << ": {2}";
187  });
188  }
189  return ::mlir::success();
190 }
191 )";
192 
193 void StaticVerifierFunctionEmitter::emitConstraints(
194  const ConstraintMap &constraints, StringRef selfName,
195  const char *const codeTemplate) {
196  FmtContext ctx;
197  ctx.addSubst("_op", "*op").withSelf(selfName);
198  for (auto &it : constraints) {
199  os << formatv(codeTemplate, it.second,
200  tgfmt(it.first.getConditionTemplate(), &ctx),
201  escapeString(it.first.getSummary()));
202  }
203 }
204 
205 void StaticVerifierFunctionEmitter::emitTypeConstraints() {
206  emitConstraints(typeConstraints, "type", typeConstraintCode);
207 }
208 
209 void StaticVerifierFunctionEmitter::emitAttrConstraints() {
210  emitConstraints(attrConstraints, "attr", attrConstraintCode);
211 }
212 
213 void StaticVerifierFunctionEmitter::emitSuccessorConstraints() {
214  emitConstraints(successorConstraints, "successor", successorConstraintCode);
215 }
216 
217 void StaticVerifierFunctionEmitter::emitRegionConstraints() {
218  emitConstraints(regionConstraints, "region", regionConstraintCode);
219 }
220 
221 void StaticVerifierFunctionEmitter::emitPatternConstraints() {
222  FmtContext ctx;
223  ctx.addSubst("_op", "*op").withBuilder("rewriter").withSelf("type");
224  for (auto &it : typeConstraints) {
225  os << formatv(patternAttrOrTypeConstraintCode, it.second,
226  tgfmt(it.first.getConditionTemplate(), &ctx),
227  escapeString(it.first.getSummary()), "Type type");
228  }
229  ctx.withSelf("attr");
230  for (auto &it : attrConstraints) {
231  os << formatv(patternAttrOrTypeConstraintCode, it.second,
232  tgfmt(it.first.getConditionTemplate(), &ctx),
233  escapeString(it.first.getSummary()), "Attribute attr");
234  }
235 }
236 
237 //===----------------------------------------------------------------------===//
238 // Constraint Uniquing
239 //===----------------------------------------------------------------------===//
240 
241 /// An attribute constraint that references anything other than itself and the
242 /// current op cannot be generically extracted into a function. Most
243 /// prohibitive are operands and results, which require calls to
244 /// `getODSOperands` or `getODSResults`. Attribute references are tricky too
245 /// because ops use cached identifiers.
247  FmtContext ctx;
248  auto test = tgfmt(attr.getConditionTemplate(),
249  &ctx.withSelf("attr").addSubst("_op", "*op"))
250  .str();
251  return !StringRef(test).contains("<no-subst-found>");
252 }
253 
254 std::string StaticVerifierFunctionEmitter::getUniqueName(StringRef kind,
255  unsigned index) {
256  return ("__mlir_ods_local_" + kind + "_constraint_" + uniqueOutputLabel +
257  Twine(index))
258  .str();
259 }
260 
261 void StaticVerifierFunctionEmitter::collectConstraint(ConstraintMap &map,
262  StringRef kind,
263  Constraint constraint) {
264  auto [it, inserted] = map.try_emplace(constraint);
265  if (inserted)
266  it->second = getUniqueName(kind, map.size());
267 }
268 
270  ArrayRef<const Record *> opDefs) {
271  const auto collectTypeConstraints = [&](Operator::const_value_range values) {
272  for (const NamedTypeConstraint &value : values)
273  if (value.hasPredicate())
274  collectConstraint(typeConstraints, "type", value.constraint);
275  };
276 
277  for (const Record *def : opDefs) {
278  Operator op(*def);
279  /// Collect type constraints.
280  collectTypeConstraints(op.getOperands());
281  collectTypeConstraints(op.getResults());
282  /// Collect attribute constraints.
283  for (const NamedAttribute &namedAttr : op.getAttributes()) {
284  if (!namedAttr.attr.getPredicate().isNull() &&
285  !namedAttr.attr.isDerivedAttr() &&
286  canUniqueAttrConstraint(namedAttr.attr))
287  collectConstraint(attrConstraints, "attr", namedAttr.attr);
288  }
289  /// Collect successor constraints.
290  for (const NamedSuccessor &successor : op.getSuccessors()) {
291  if (!successor.constraint.getPredicate().isNull()) {
292  collectConstraint(successorConstraints, "successor",
293  successor.constraint);
294  }
295  }
296  /// Collect region constraints.
297  for (const NamedRegion &region : op.getRegions())
298  if (!region.constraint.getPredicate().isNull())
299  collectConstraint(regionConstraints, "region", region.constraint);
300  }
301 }
302 
303 void StaticVerifierFunctionEmitter::collectPatternConstraints(
304  const ArrayRef<DagLeaf> constraints) {
305  for (auto &leaf : constraints) {
306  assert(leaf.isOperandMatcher() || leaf.isAttrMatcher());
307  collectConstraint(
308  leaf.isOperandMatcher() ? typeConstraints : attrConstraints,
309  leaf.isOperandMatcher() ? "type" : "attr", leaf.getAsConstraint());
310  }
311 }
312 
313 //===----------------------------------------------------------------------===//
314 // Public Utility Functions
315 //===----------------------------------------------------------------------===//
316 
317 std::string mlir::tblgen::escapeString(StringRef value) {
318  std::string ret;
319  raw_string_ostream os(ret);
320  os.write_escaped(value);
321  return ret;
322 }
static const char *const successorConstraintCode
Code for a successor constraint.
static const char *const regionConstraintCode
Code for a region constraint.
static const char *const typeConstraintCode
Code templates for emitting type, attribute, successor, and region constraints.
static std::string getUniqueOutputLabel(const RecordKeeper &records, StringRef tag)
Generate a unique label based on the current file name to prevent name collisions if multiple generat...
static const char *const patternAttrOrTypeConstraintCode
Code for a pattern type or attribute constraint.
static bool canUniqueAttrConstraint(Attribute attr)
An attribute constraint that references anything other than itself and the current op cannot be gener...
static const char *const attrConstraintCode
Code for an attribute constraint.
union mlir::linalg::@1197::ArityGroupAndKind::Kind kind
Attributes are known-constant values of operations.
Definition: Attributes.h:25
Format context containing substitutions for special placeholders.
Definition: Format.h:40
FmtContext & withBuilder(Twine subst)
Definition: Format.cpp:36
FmtContext & withSelf(Twine subst)
Definition: Format.cpp:41
FmtContext & addSubst(StringRef placeholder, const Twine &subst)
Definition: Format.cpp:31
Wrapper class that contains a MLIR op's information (e.g., operands, attributes) defined in TableGen ...
Definition: Operator.h:77
llvm::iterator_range< const_region_iterator > getRegions() const
Definition: Operator.cpp:281
const_value_range getResults() const
Definition: Operator.cpp:199
const_value_range getOperands() const
Definition: Operator.cpp:355
llvm::iterator_range< const_attribute_iterator > getAttributes() const
Definition: Operator.cpp:335
llvm::iterator_range< const_successor_iterator > getSuccessors() const
Definition: Operator.cpp:303
StringRef getRegionConstraintFn(const Constraint &constraint) const
Get the name of the static function used for the given region constraint.
void emitPatternConstraints(const ArrayRef< DagLeaf > constraints)
Unique all compatible type and attribute constraints from a pattern file and emit them at the top of ...
std::optional< StringRef > getAttrConstraintFn(const Constraint &constraint) const
Get the name of the static function used for the given attribute constraint.
void emitOpConstraints(ArrayRef< const llvm::Record * > opDefs)
Collect and unique all compatible type, attribute, successor, and region constraints from the operati...
void collectOpConstraints(ArrayRef< const llvm::Record * > opDefs)
Collect and unique all the constraints used by operations.
StringRef getTypeConstraintFn(const Constraint &constraint) const
Get the name of the static function used for the given type constraint.
StringRef getSuccessorConstraintFn(const Constraint &constraint) const
Get the name of the static function used for the given successor constraint.
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition: CallGraph.h:229
auto tgfmt(StringRef fmt, const FmtContext *ctx, Ts &&...vals) -> FmtObject< decltype(std::make_tuple(llvm::support::detail::build_format_adapter(std::forward< Ts >(vals))...))>
Formats text by substituting placeholders in format string with replacement parameters.
Definition: Format.h:262
std::string escapeString(StringRef value)
Escape a string using C++ encoding. E.g. foo"bar -> foo\x22bar.
Include the generated interface declarations.