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 unsigned tblgen::Operator::getNumVariadicResults() const {
113   return std::count_if(
114       results.begin(), results.end(),
115       [](const NamedTypeConstraint &c) { return c.constraint.isVariadic(); });
116 }
117 
118 unsigned tblgen::Operator::getNumVariadicOperands() const {
119   return std::count_if(
120       operands.begin(), operands.end(),
121       [](const NamedTypeConstraint &c) { return c.constraint.isVariadic(); });
122 }
123 
124 tblgen::Operator::arg_iterator tblgen::Operator::arg_begin() const {
125   return arguments.begin();
126 }
127 
128 tblgen::Operator::arg_iterator tblgen::Operator::arg_end() const {
129   return arguments.end();
130 }
131 
132 tblgen::Operator::arg_range tblgen::Operator::getArgs() const {
133   return {arg_begin(), arg_end()};
134 }
135 
136 StringRef tblgen::Operator::getArgName(int index) const {
137   DagInit *argumentValues = def.getValueAsDag("arguments");
138   return argumentValues->getArgName(index)->getValue();
139 }
140 
141 const tblgen::OpTrait *tblgen::Operator::getTrait(StringRef trait) const {
142   for (const auto &t : traits) {
143     if (auto opTrait = dyn_cast<tblgen::NativeOpTrait>(&t)) {
144       if (opTrait->getTrait() == trait)
145         return opTrait;
146     } else if (auto opTrait = dyn_cast<tblgen::InternalOpTrait>(&t)) {
147       if (opTrait->getTrait() == trait)
148         return opTrait;
149     } else if (auto opTrait = dyn_cast<tblgen::InterfaceOpTrait>(&t)) {
150       if (opTrait->getTrait() == trait)
151         return opTrait;
152     }
153   }
154   return nullptr;
155 }
156 
157 unsigned tblgen::Operator::getNumRegions() const { return regions.size(); }
158 
159 const tblgen::NamedRegion &tblgen::Operator::getRegion(unsigned index) const {
160   return regions[index];
161 }
162 
163 auto tblgen::Operator::successor_begin() const -> const_successor_iterator {
164   return successors.begin();
165 }
166 auto tblgen::Operator::successor_end() const -> const_successor_iterator {
167   return successors.end();
168 }
169 auto tblgen::Operator::getSuccessors() const
170     -> llvm::iterator_range<const_successor_iterator> {
171   return {successor_begin(), successor_end()};
172 }
173 
174 unsigned tblgen::Operator::getNumSuccessors() const {
175   return successors.size();
176 }
177 
178 const tblgen::NamedSuccessor &
179 tblgen::Operator::getSuccessor(unsigned index) const {
180   return successors[index];
181 }
182 
183 unsigned tblgen::Operator::getNumVariadicSuccessors() const {
184   return llvm::count_if(successors,
185                         [](const NamedSuccessor &c) { return c.isVariadic(); });
186 }
187 
188 auto tblgen::Operator::trait_begin() const -> const_trait_iterator {
189   return traits.begin();
190 }
191 auto tblgen::Operator::trait_end() const -> const_trait_iterator {
192   return traits.end();
193 }
194 auto tblgen::Operator::getTraits() const
195     -> llvm::iterator_range<const_trait_iterator> {
196   return {trait_begin(), trait_end()};
197 }
198 
199 auto tblgen::Operator::attribute_begin() const -> attribute_iterator {
200   return attributes.begin();
201 }
202 auto tblgen::Operator::attribute_end() const -> attribute_iterator {
203   return attributes.end();
204 }
205 auto tblgen::Operator::getAttributes() const
206     -> llvm::iterator_range<attribute_iterator> {
207   return {attribute_begin(), attribute_end()};
208 }
209 
210 auto tblgen::Operator::operand_begin() -> value_iterator {
211   return operands.begin();
212 }
213 auto tblgen::Operator::operand_end() -> value_iterator {
214   return operands.end();
215 }
216 auto tblgen::Operator::getOperands() -> value_range {
217   return {operand_begin(), operand_end()};
218 }
219 
220 auto tblgen::Operator::getArg(int index) const -> Argument {
221   return arguments[index];
222 }
223 
224 void tblgen::Operator::populateOpStructure() {
225   auto &recordKeeper = def.getRecords();
226   auto typeConstraintClass = recordKeeper.getClass("TypeConstraint");
227   auto attrClass = recordKeeper.getClass("Attr");
228   auto derivedAttrClass = recordKeeper.getClass("DerivedAttr");
229   numNativeAttributes = 0;
230 
231   DagInit *argumentValues = def.getValueAsDag("arguments");
232   unsigned numArgs = argumentValues->getNumArgs();
233 
234   // Handle operands and native attributes.
235   for (unsigned i = 0; i != numArgs; ++i) {
236     auto arg = argumentValues->getArg(i);
237     auto givenName = argumentValues->getArgNameStr(i);
238     auto argDefInit = dyn_cast<DefInit>(arg);
239     if (!argDefInit)
240       PrintFatalError(def.getLoc(),
241                       Twine("undefined type for argument #") + Twine(i));
242     Record *argDef = argDefInit->getDef();
243 
244     if (argDef->isSubClassOf(typeConstraintClass)) {
245       operands.push_back(
246           NamedTypeConstraint{givenName, TypeConstraint(argDefInit)});
247     } else if (argDef->isSubClassOf(attrClass)) {
248       if (givenName.empty())
249         PrintFatalError(argDef->getLoc(), "attributes must be named");
250       if (argDef->isSubClassOf(derivedAttrClass))
251         PrintFatalError(argDef->getLoc(),
252                         "derived attributes not allowed in argument list");
253       attributes.push_back({givenName, Attribute(argDef)});
254       ++numNativeAttributes;
255     } else {
256       PrintFatalError(def.getLoc(), "unexpected def type; only defs deriving "
257                                     "from TypeConstraint or Attr are allowed");
258     }
259   }
260 
261   // Handle derived attributes.
262   for (const auto &val : def.getValues()) {
263     if (auto *record = dyn_cast<llvm::RecordRecTy>(val.getType())) {
264       if (!record->isSubClassOf(attrClass))
265         continue;
266       if (!record->isSubClassOf(derivedAttrClass))
267         PrintFatalError(def.getLoc(),
268                         "unexpected Attr where only DerivedAttr is allowed");
269 
270       if (record->getClasses().size() != 1) {
271         PrintFatalError(
272             def.getLoc(),
273             "unsupported attribute modelling, only single class expected");
274       }
275       attributes.push_back(
276           {cast<llvm::StringInit>(val.getNameInit())->getValue(),
277            Attribute(cast<DefInit>(val.getValue()))});
278     }
279   }
280 
281   // Populate `arguments`. This must happen after we've finalized `operands` and
282   // `attributes` because we will put their elements' pointers in `arguments`.
283   // SmallVector may perform re-allocation under the hood when adding new
284   // elements.
285   int operandIndex = 0, attrIndex = 0;
286   for (unsigned i = 0; i != numArgs; ++i) {
287     Record *argDef = dyn_cast<DefInit>(argumentValues->getArg(i))->getDef();
288 
289     if (argDef->isSubClassOf(typeConstraintClass)) {
290       arguments.emplace_back(&operands[operandIndex++]);
291     } else {
292       assert(argDef->isSubClassOf(attrClass));
293       arguments.emplace_back(&attributes[attrIndex++]);
294     }
295   }
296 
297   auto *resultsDag = def.getValueAsDag("results");
298   auto *outsOp = dyn_cast<DefInit>(resultsDag->getOperator());
299   if (!outsOp || outsOp->getDef()->getName() != "outs") {
300     PrintFatalError(def.getLoc(), "'results' must have 'outs' directive");
301   }
302 
303   // Handle results.
304   for (unsigned i = 0, e = resultsDag->getNumArgs(); i < e; ++i) {
305     auto name = resultsDag->getArgNameStr(i);
306     auto *resultDef = dyn_cast<DefInit>(resultsDag->getArg(i));
307     if (!resultDef) {
308       PrintFatalError(def.getLoc(),
309                       Twine("undefined type for result #") + Twine(i));
310     }
311     results.push_back({name, TypeConstraint(resultDef)});
312   }
313 
314   // Handle successors
315   auto *successorsDag = def.getValueAsDag("successors");
316   auto *successorsOp = dyn_cast<DefInit>(successorsDag->getOperator());
317   if (!successorsOp || successorsOp->getDef()->getName() != "successor") {
318     PrintFatalError(def.getLoc(),
319                     "'successors' must have 'successor' directive");
320   }
321 
322   for (unsigned i = 0, e = successorsDag->getNumArgs(); i < e; ++i) {
323     auto name = successorsDag->getArgNameStr(i);
324     auto *successorInit = dyn_cast<DefInit>(successorsDag->getArg(i));
325     if (!successorInit) {
326       PrintFatalError(def.getLoc(),
327                       Twine("undefined kind for successor #") + Twine(i));
328     }
329     Successor successor(successorInit->getDef());
330 
331     // Only support variadic successors if it is the last one for now.
332     if (i != e - 1 && successor.isVariadic())
333       PrintFatalError(def.getLoc(), "only the last successor can be variadic");
334     successors.push_back({name, successor});
335   }
336 
337   // Create list of traits, skipping over duplicates: appending to lists in
338   // tablegen is easy, making them unique less so, so dedupe here.
339   if (auto traitList = def.getValueAsListInit("traits")) {
340     // This is uniquing based on pointers of the trait.
341     SmallPtrSet<const llvm::Init *, 32> traitSet;
342     traits.reserve(traitSet.size());
343     for (auto traitInit : *traitList) {
344       // Keep traits in the same order while skipping over duplicates.
345       if (traitSet.insert(traitInit).second)
346         traits.push_back(OpTrait::create(traitInit));
347     }
348   }
349 
350   // Handle regions
351   auto *regionsDag = def.getValueAsDag("regions");
352   auto *regionsOp = dyn_cast<DefInit>(regionsDag->getOperator());
353   if (!regionsOp || regionsOp->getDef()->getName() != "region") {
354     PrintFatalError(def.getLoc(), "'regions' must have 'region' directive");
355   }
356 
357   for (unsigned i = 0, e = regionsDag->getNumArgs(); i < e; ++i) {
358     auto name = regionsDag->getArgNameStr(i);
359     auto *regionInit = dyn_cast<DefInit>(regionsDag->getArg(i));
360     if (!regionInit) {
361       PrintFatalError(def.getLoc(),
362                       Twine("undefined kind for region #") + Twine(i));
363     }
364     regions.push_back({name, Region(regionInit->getDef())});
365   }
366 
367   LLVM_DEBUG(print(llvm::dbgs()));
368 }
369 
370 ArrayRef<llvm::SMLoc> tblgen::Operator::getLoc() const { return def.getLoc(); }
371 
372 bool tblgen::Operator::hasDescription() const {
373   return def.getValue("description") != nullptr;
374 }
375 
376 StringRef tblgen::Operator::getDescription() const {
377   return def.getValueAsString("description");
378 }
379 
380 bool tblgen::Operator::hasSummary() const {
381   return def.getValue("summary") != nullptr;
382 }
383 
384 StringRef tblgen::Operator::getSummary() const {
385   return def.getValueAsString("summary");
386 }
387 
388 void tblgen::Operator::print(llvm::raw_ostream &os) const {
389   os << "op '" << getOperationName() << "'\n";
390   for (Argument arg : arguments) {
391     if (auto *attr = arg.dyn_cast<NamedAttribute *>())
392       os << "[attribute] " << attr->name << '\n';
393     else
394       os << "[operand] " << arg.get<NamedTypeConstraint *>()->name << '\n';
395   }
396 }
397