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