1 //===- Operator.cpp - Operator class --------------------------------------===//
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 // Operator wrapper to simplify using TableGen Record defining a MLIR Op.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/TableGen/Operator.h"
14 #include "mlir/TableGen/OpTrait.h"
15 #include "mlir/TableGen/Predicate.h"
16 #include "mlir/TableGen/Type.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Support/FormatVariadic.h"
19 #include "llvm/TableGen/Error.h"
20 #include "llvm/TableGen/Record.h"
21 
22 #define DEBUG_TYPE "mlir-tblgen-operator"
23 
24 using namespace mlir;
25 
26 using llvm::DagInit;
27 using llvm::DefInit;
28 using llvm::Record;
29 
30 tblgen::Operator::Operator(const llvm::Record &def)
31     : dialect(def.getValueAsDef("opDialect")), def(def) {
32   // The first `_` in the op's TableGen def name is treated as separating the
33   // dialect prefix and the op class name. The dialect prefix will be ignored if
34   // not empty. Otherwise, if def name starts with a `_`, the `_` is considered
35   // as part of the class name.
36   StringRef prefix;
37   std::tie(prefix, cppClassName) = def.getName().split('_');
38   if (prefix.empty()) {
39     // Class name with a leading underscore and without dialect prefix
40     cppClassName = def.getName();
41   } else if (cppClassName.empty()) {
42     // Class name without dialect prefix
43     cppClassName = prefix;
44   }
45 
46   populateOpStructure();
47 }
48 
49 std::string tblgen::Operator::getOperationName() const {
50   auto prefix = dialect.getName();
51   auto opName = def.getValueAsString("opName");
52   if (prefix.empty())
53     return std::string(opName);
54   return std::string(llvm::formatv("{0}.{1}", prefix, opName));
55 }
56 
57 StringRef tblgen::Operator::getDialectName() const { return dialect.getName(); }
58 
59 StringRef tblgen::Operator::getCppClassName() const { return cppClassName; }
60 
61 std::string tblgen::Operator::getQualCppClassName() const {
62   auto prefix = dialect.getCppNamespace();
63   if (prefix.empty())
64     return std::string(cppClassName);
65   return std::string(llvm::formatv("{0}::{1}", prefix, cppClassName));
66 }
67 
68 int tblgen::Operator::getNumResults() const {
69   DagInit *results = def.getValueAsDag("results");
70   return results->getNumArgs();
71 }
72 
73 StringRef tblgen::Operator::getExtraClassDeclaration() const {
74   constexpr auto attr = "extraClassDeclaration";
75   if (def.isValueUnset(attr))
76     return {};
77   return def.getValueAsString(attr);
78 }
79 
80 const llvm::Record &tblgen::Operator::getDef() const { return def; }
81 
82 bool tblgen::Operator::isVariadic() const {
83   return getNumVariadicOperands() != 0 || getNumVariadicResults() != 0;
84 }
85 
86 bool tblgen::Operator::skipDefaultBuilders() const {
87   return def.getValueAsBit("skipDefaultBuilders");
88 }
89 
90 auto tblgen::Operator::result_begin() -> value_iterator {
91   return results.begin();
92 }
93 
94 auto tblgen::Operator::result_end() -> value_iterator { return results.end(); }
95 
96 auto tblgen::Operator::getResults() -> value_range {
97   return {result_begin(), result_end()};
98 }
99 
100 tblgen::TypeConstraint
101 tblgen::Operator::getResultTypeConstraint(int index) const {
102   DagInit *results = def.getValueAsDag("results");
103   return TypeConstraint(cast<DefInit>(results->getArg(index)));
104 }
105 
106 StringRef tblgen::Operator::getResultName(int index) const {
107   DagInit *results = def.getValueAsDag("results");
108   return results->getArgNameStr(index);
109 }
110 
111 unsigned tblgen::Operator::getNumVariadicResults() const {
112   return std::count_if(
113       results.begin(), results.end(),
114       [](const NamedTypeConstraint &c) { return c.constraint.isVariadic(); });
115 }
116 
117 unsigned tblgen::Operator::getNumVariadicOperands() const {
118   return std::count_if(
119       operands.begin(), operands.end(),
120       [](const NamedTypeConstraint &c) { return c.constraint.isVariadic(); });
121 }
122 
123 tblgen::Operator::arg_iterator tblgen::Operator::arg_begin() const {
124   return arguments.begin();
125 }
126 
127 tblgen::Operator::arg_iterator tblgen::Operator::arg_end() const {
128   return arguments.end();
129 }
130 
131 tblgen::Operator::arg_range tblgen::Operator::getArgs() const {
132   return {arg_begin(), arg_end()};
133 }
134 
135 StringRef tblgen::Operator::getArgName(int index) const {
136   DagInit *argumentValues = def.getValueAsDag("arguments");
137   return argumentValues->getArgName(index)->getValue();
138 }
139 
140 const tblgen::OpTrait *tblgen::Operator::getTrait(StringRef trait) const {
141   for (const auto &t : traits) {
142     if (auto opTrait = dyn_cast<tblgen::NativeOpTrait>(&t)) {
143       if (opTrait->getTrait() == trait)
144         return opTrait;
145     } else if (auto opTrait = dyn_cast<tblgen::InternalOpTrait>(&t)) {
146       if (opTrait->getTrait() == trait)
147         return opTrait;
148     } else if (auto opTrait = dyn_cast<tblgen::InterfaceOpTrait>(&t)) {
149       if (opTrait->getTrait() == trait)
150         return opTrait;
151     }
152   }
153   return nullptr;
154 }
155 
156 unsigned tblgen::Operator::getNumRegions() const { return regions.size(); }
157 
158 const tblgen::NamedRegion &tblgen::Operator::getRegion(unsigned index) const {
159   return regions[index];
160 }
161 
162 auto tblgen::Operator::successor_begin() const -> const_successor_iterator {
163   return successors.begin();
164 }
165 auto tblgen::Operator::successor_end() const -> const_successor_iterator {
166   return successors.end();
167 }
168 auto tblgen::Operator::getSuccessors() const
169     -> llvm::iterator_range<const_successor_iterator> {
170   return {successor_begin(), successor_end()};
171 }
172 
173 unsigned tblgen::Operator::getNumSuccessors() const {
174   return successors.size();
175 }
176 
177 const tblgen::NamedSuccessor &
178 tblgen::Operator::getSuccessor(unsigned index) const {
179   return successors[index];
180 }
181 
182 unsigned tblgen::Operator::getNumVariadicSuccessors() const {
183   return llvm::count_if(successors,
184                         [](const NamedSuccessor &c) { return c.isVariadic(); });
185 }
186 
187 auto tblgen::Operator::trait_begin() const -> const_trait_iterator {
188   return traits.begin();
189 }
190 auto tblgen::Operator::trait_end() const -> const_trait_iterator {
191   return traits.end();
192 }
193 auto tblgen::Operator::getTraits() const
194     -> llvm::iterator_range<const_trait_iterator> {
195   return {trait_begin(), trait_end()};
196 }
197 
198 auto tblgen::Operator::attribute_begin() const -> attribute_iterator {
199   return attributes.begin();
200 }
201 auto tblgen::Operator::attribute_end() const -> attribute_iterator {
202   return attributes.end();
203 }
204 auto tblgen::Operator::getAttributes() const
205     -> llvm::iterator_range<attribute_iterator> {
206   return {attribute_begin(), attribute_end()};
207 }
208 
209 auto tblgen::Operator::operand_begin() -> value_iterator {
210   return operands.begin();
211 }
212 auto tblgen::Operator::operand_end() -> value_iterator {
213   return operands.end();
214 }
215 auto tblgen::Operator::getOperands() -> value_range {
216   return {operand_begin(), operand_end()};
217 }
218 
219 auto tblgen::Operator::getArg(int index) const -> Argument {
220   return arguments[index];
221 }
222 
223 void tblgen::Operator::populateOpStructure() {
224   auto &recordKeeper = def.getRecords();
225   auto typeConstraintClass = recordKeeper.getClass("TypeConstraint");
226   auto attrClass = recordKeeper.getClass("Attr");
227   auto derivedAttrClass = recordKeeper.getClass("DerivedAttr");
228   numNativeAttributes = 0;
229 
230   DagInit *argumentValues = def.getValueAsDag("arguments");
231   unsigned numArgs = argumentValues->getNumArgs();
232 
233   // Handle operands and native attributes.
234   for (unsigned i = 0; i != numArgs; ++i) {
235     auto arg = argumentValues->getArg(i);
236     auto givenName = argumentValues->getArgNameStr(i);
237     auto argDefInit = dyn_cast<DefInit>(arg);
238     if (!argDefInit)
239       PrintFatalError(def.getLoc(),
240                       Twine("undefined type for argument #") + Twine(i));
241     Record *argDef = argDefInit->getDef();
242 
243     if (argDef->isSubClassOf(typeConstraintClass)) {
244       operands.push_back(
245           NamedTypeConstraint{givenName, TypeConstraint(argDefInit)});
246     } else if (argDef->isSubClassOf(attrClass)) {
247       if (givenName.empty())
248         PrintFatalError(argDef->getLoc(), "attributes must be named");
249       if (argDef->isSubClassOf(derivedAttrClass))
250         PrintFatalError(argDef->getLoc(),
251                         "derived attributes not allowed in argument list");
252       attributes.push_back({givenName, Attribute(argDef)});
253       ++numNativeAttributes;
254     } else {
255       PrintFatalError(def.getLoc(), "unexpected def type; only defs deriving "
256                                     "from TypeConstraint or Attr are allowed");
257     }
258   }
259 
260   // Handle derived attributes.
261   for (const auto &val : def.getValues()) {
262     if (auto *record = dyn_cast<llvm::RecordRecTy>(val.getType())) {
263       if (!record->isSubClassOf(attrClass))
264         continue;
265       if (!record->isSubClassOf(derivedAttrClass))
266         PrintFatalError(def.getLoc(),
267                         "unexpected Attr where only DerivedAttr is allowed");
268 
269       if (record->getClasses().size() != 1) {
270         PrintFatalError(
271             def.getLoc(),
272             "unsupported attribute modelling, only single class expected");
273       }
274       attributes.push_back(
275           {cast<llvm::StringInit>(val.getNameInit())->getValue(),
276            Attribute(cast<DefInit>(val.getValue()))});
277     }
278   }
279 
280   // Populate `arguments`. This must happen after we've finalized `operands` and
281   // `attributes` because we will put their elements' pointers in `arguments`.
282   // SmallVector may perform re-allocation under the hood when adding new
283   // elements.
284   int operandIndex = 0, attrIndex = 0;
285   for (unsigned i = 0; i != numArgs; ++i) {
286     Record *argDef = dyn_cast<DefInit>(argumentValues->getArg(i))->getDef();
287 
288     if (argDef->isSubClassOf(typeConstraintClass)) {
289       arguments.emplace_back(&operands[operandIndex++]);
290     } else {
291       assert(argDef->isSubClassOf(attrClass));
292       arguments.emplace_back(&attributes[attrIndex++]);
293     }
294   }
295 
296   auto *resultsDag = def.getValueAsDag("results");
297   auto *outsOp = dyn_cast<DefInit>(resultsDag->getOperator());
298   if (!outsOp || outsOp->getDef()->getName() != "outs") {
299     PrintFatalError(def.getLoc(), "'results' must have 'outs' directive");
300   }
301 
302   // Handle results.
303   for (unsigned i = 0, e = resultsDag->getNumArgs(); i < e; ++i) {
304     auto name = resultsDag->getArgNameStr(i);
305     auto *resultDef = dyn_cast<DefInit>(resultsDag->getArg(i));
306     if (!resultDef) {
307       PrintFatalError(def.getLoc(),
308                       Twine("undefined type for result #") + Twine(i));
309     }
310     results.push_back({name, TypeConstraint(resultDef)});
311   }
312 
313   // Handle successors
314   auto *successorsDag = def.getValueAsDag("successors");
315   auto *successorsOp = dyn_cast<DefInit>(successorsDag->getOperator());
316   if (!successorsOp || successorsOp->getDef()->getName() != "successor") {
317     PrintFatalError(def.getLoc(),
318                     "'successors' must have 'successor' directive");
319   }
320 
321   for (unsigned i = 0, e = successorsDag->getNumArgs(); i < e; ++i) {
322     auto name = successorsDag->getArgNameStr(i);
323     auto *successorInit = dyn_cast<DefInit>(successorsDag->getArg(i));
324     if (!successorInit) {
325       PrintFatalError(def.getLoc(),
326                       Twine("undefined kind for successor #") + Twine(i));
327     }
328     Successor successor(successorInit->getDef());
329 
330     // Only support variadic successors if it is the last one for now.
331     if (i != e - 1 && successor.isVariadic())
332       PrintFatalError(def.getLoc(), "only the last successor can be variadic");
333     successors.push_back({name, successor});
334   }
335 
336   // Create list of traits, skipping over duplicates: appending to lists in
337   // tablegen is easy, making them unique less so, so dedupe here.
338   if (auto traitList = def.getValueAsListInit("traits")) {
339     // This is uniquing based on pointers of the trait.
340     SmallPtrSet<const llvm::Init *, 32> traitSet;
341     traits.reserve(traitSet.size());
342     for (auto traitInit : *traitList) {
343       // Keep traits in the same order while skipping over duplicates.
344       if (traitSet.insert(traitInit).second)
345         traits.push_back(OpTrait::create(traitInit));
346     }
347   }
348 
349   // Handle regions
350   auto *regionsDag = def.getValueAsDag("regions");
351   auto *regionsOp = dyn_cast<DefInit>(regionsDag->getOperator());
352   if (!regionsOp || regionsOp->getDef()->getName() != "region") {
353     PrintFatalError(def.getLoc(), "'regions' must have 'region' directive");
354   }
355 
356   for (unsigned i = 0, e = regionsDag->getNumArgs(); i < e; ++i) {
357     auto name = regionsDag->getArgNameStr(i);
358     auto *regionInit = dyn_cast<DefInit>(regionsDag->getArg(i));
359     if (!regionInit) {
360       PrintFatalError(def.getLoc(),
361                       Twine("undefined kind for region #") + Twine(i));
362     }
363     regions.push_back({name, Region(regionInit->getDef())});
364   }
365 
366   LLVM_DEBUG(print(llvm::dbgs()));
367 }
368 
369 ArrayRef<llvm::SMLoc> tblgen::Operator::getLoc() const { return def.getLoc(); }
370 
371 bool tblgen::Operator::hasDescription() const {
372   return def.getValue("description") != nullptr;
373 }
374 
375 StringRef tblgen::Operator::getDescription() const {
376   return def.getValueAsString("description");
377 }
378 
379 bool tblgen::Operator::hasSummary() const {
380   return def.getValue("summary") != nullptr;
381 }
382 
383 StringRef tblgen::Operator::getSummary() const {
384   return def.getValueAsString("summary");
385 }
386 
387 void tblgen::Operator::print(llvm::raw_ostream &os) const {
388   os << "op '" << getOperationName() << "'\n";
389   for (Argument arg : arguments) {
390     if (auto *attr = arg.dyn_cast<NamedAttribute *>())
391       os << "[attribute] " << attr->name << '\n';
392     else
393       os << "[operand] " << arg.get<NamedTypeConstraint *>()->name << '\n';
394   }
395 }
396