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/EquivalenceClasses.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/Sequence.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/TypeSwitch.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/FormatVariadic.h"
24 #include "llvm/TableGen/Error.h"
25 #include "llvm/TableGen/Record.h"
26 
27 #define DEBUG_TYPE "mlir-tblgen-operator"
28 
29 using namespace mlir;
30 using namespace mlir::tblgen;
31 
32 using llvm::DagInit;
33 using llvm::DefInit;
34 using llvm::Record;
35 
36 Operator::Operator(const llvm::Record &def)
37     : dialect(def.getValueAsDef("opDialect")), def(def) {
38   // The first `_` in the op's TableGen def name is treated as separating the
39   // dialect prefix and the op class name. The dialect prefix will be ignored if
40   // not empty. Otherwise, if def name starts with a `_`, the `_` is considered
41   // as part of the class name.
42   StringRef prefix;
43   std::tie(prefix, cppClassName) = def.getName().split('_');
44   if (prefix.empty()) {
45     // Class name with a leading underscore and without dialect prefix
46     cppClassName = def.getName();
47   } else if (cppClassName.empty()) {
48     // Class name without dialect prefix
49     cppClassName = prefix;
50   }
51 
52   populateOpStructure();
53 }
54 
55 std::string Operator::getOperationName() const {
56   auto prefix = dialect.getName();
57   auto opName = def.getValueAsString("opName");
58   if (prefix.empty())
59     return std::string(opName);
60   return std::string(llvm::formatv("{0}.{1}", prefix, opName));
61 }
62 
63 std::string Operator::getAdaptorName() const {
64   return std::string(llvm::formatv("{0}Adaptor", getCppClassName()));
65 }
66 
67 StringRef Operator::getDialectName() const { return dialect.getName(); }
68 
69 StringRef Operator::getCppClassName() const { return cppClassName; }
70 
71 std::string Operator::getQualCppClassName() const {
72   auto prefix = dialect.getCppNamespace();
73   if (prefix.empty())
74     return std::string(cppClassName);
75   return std::string(llvm::formatv("{0}::{1}", prefix, cppClassName));
76 }
77 
78 int Operator::getNumResults() const {
79   DagInit *results = def.getValueAsDag("results");
80   return results->getNumArgs();
81 }
82 
83 StringRef Operator::getExtraClassDeclaration() const {
84   constexpr auto attr = "extraClassDeclaration";
85   if (def.isValueUnset(attr))
86     return {};
87   return def.getValueAsString(attr);
88 }
89 
90 const llvm::Record &Operator::getDef() const { return def; }
91 
92 bool Operator::skipDefaultBuilders() const {
93   return def.getValueAsBit("skipDefaultBuilders");
94 }
95 
96 auto Operator::result_begin() -> value_iterator { return results.begin(); }
97 
98 auto Operator::result_end() -> value_iterator { return results.end(); }
99 
100 auto Operator::getResults() -> value_range {
101   return {result_begin(), result_end()};
102 }
103 
104 TypeConstraint Operator::getResultTypeConstraint(int index) const {
105   DagInit *results = def.getValueAsDag("results");
106   return TypeConstraint(cast<DefInit>(results->getArg(index)));
107 }
108 
109 StringRef Operator::getResultName(int index) const {
110   DagInit *results = def.getValueAsDag("results");
111   return results->getArgNameStr(index);
112 }
113 
114 auto Operator::getResultDecorators(int index) const -> var_decorator_range {
115   Record *result =
116       cast<DefInit>(def.getValueAsDag("results")->getArg(index))->getDef();
117   if (!result->isSubClassOf("OpVariable"))
118     return var_decorator_range(nullptr, nullptr);
119   return *result->getValueAsListInit("decorators");
120 }
121 
122 unsigned Operator::getNumVariableLengthResults() const {
123   return llvm::count_if(results, [](const NamedTypeConstraint &c) {
124     return c.constraint.isVariableLength();
125   });
126 }
127 
128 unsigned Operator::getNumVariableLengthOperands() const {
129   return llvm::count_if(operands, [](const NamedTypeConstraint &c) {
130     return c.constraint.isVariableLength();
131   });
132 }
133 
134 bool Operator::hasSingleVariadicArg() const {
135   return getNumArgs() == 1 && getArg(0).is<NamedTypeConstraint *>() &&
136          getOperand(0).isVariadic();
137 }
138 
139 Operator::arg_iterator Operator::arg_begin() const { return arguments.begin(); }
140 
141 Operator::arg_iterator Operator::arg_end() const { return arguments.end(); }
142 
143 Operator::arg_range Operator::getArgs() const {
144   return {arg_begin(), arg_end()};
145 }
146 
147 StringRef Operator::getArgName(int index) const {
148   DagInit *argumentValues = def.getValueAsDag("arguments");
149   return argumentValues->getArgName(index)->getValue();
150 }
151 
152 auto Operator::getArgDecorators(int index) const -> var_decorator_range {
153   Record *arg =
154       cast<DefInit>(def.getValueAsDag("arguments")->getArg(index))->getDef();
155   if (!arg->isSubClassOf("OpVariable"))
156     return var_decorator_range(nullptr, nullptr);
157   return *arg->getValueAsListInit("decorators");
158 }
159 
160 const OpTrait *Operator::getTrait(StringRef trait) const {
161   for (const auto &t : traits) {
162     if (const auto *opTrait = dyn_cast<NativeOpTrait>(&t)) {
163       if (opTrait->getTrait() == trait)
164         return opTrait;
165     } else if (const auto *opTrait = dyn_cast<InternalOpTrait>(&t)) {
166       if (opTrait->getTrait() == trait)
167         return opTrait;
168     } else if (const auto *opTrait = dyn_cast<InterfaceOpTrait>(&t)) {
169       if (opTrait->getTrait() == trait)
170         return opTrait;
171     }
172   }
173   return nullptr;
174 }
175 
176 auto Operator::region_begin() const -> const_region_iterator {
177   return regions.begin();
178 }
179 auto Operator::region_end() const -> const_region_iterator {
180   return regions.end();
181 }
182 auto Operator::getRegions() const
183     -> llvm::iterator_range<const_region_iterator> {
184   return {region_begin(), region_end()};
185 }
186 
187 unsigned Operator::getNumRegions() const { return regions.size(); }
188 
189 const NamedRegion &Operator::getRegion(unsigned index) const {
190   return regions[index];
191 }
192 
193 unsigned Operator::getNumVariadicRegions() const {
194   return llvm::count_if(regions,
195                         [](const NamedRegion &c) { return c.isVariadic(); });
196 }
197 
198 auto Operator::successor_begin() const -> const_successor_iterator {
199   return successors.begin();
200 }
201 auto Operator::successor_end() const -> const_successor_iterator {
202   return successors.end();
203 }
204 auto Operator::getSuccessors() const
205     -> llvm::iterator_range<const_successor_iterator> {
206   return {successor_begin(), successor_end()};
207 }
208 
209 unsigned Operator::getNumSuccessors() const { return successors.size(); }
210 
211 const NamedSuccessor &Operator::getSuccessor(unsigned index) const {
212   return successors[index];
213 }
214 
215 unsigned Operator::getNumVariadicSuccessors() const {
216   return llvm::count_if(successors,
217                         [](const NamedSuccessor &c) { return c.isVariadic(); });
218 }
219 
220 auto Operator::trait_begin() const -> const_trait_iterator {
221   return traits.begin();
222 }
223 auto Operator::trait_end() const -> const_trait_iterator {
224   return traits.end();
225 }
226 auto Operator::getTraits() const -> llvm::iterator_range<const_trait_iterator> {
227   return {trait_begin(), trait_end()};
228 }
229 
230 auto Operator::attribute_begin() const -> attribute_iterator {
231   return attributes.begin();
232 }
233 auto Operator::attribute_end() const -> attribute_iterator {
234   return attributes.end();
235 }
236 auto Operator::getAttributes() const
237     -> llvm::iterator_range<attribute_iterator> {
238   return {attribute_begin(), attribute_end()};
239 }
240 
241 auto Operator::operand_begin() -> value_iterator { return operands.begin(); }
242 auto Operator::operand_end() -> value_iterator { return operands.end(); }
243 auto Operator::getOperands() -> value_range {
244   return {operand_begin(), operand_end()};
245 }
246 
247 auto Operator::getArg(int index) const -> Argument { return arguments[index]; }
248 
249 // Mapping from result index to combined argument and result index. Arguments
250 // are indexed to match getArg index, while the result indexes are mapped to
251 // avoid overlap.
252 static int resultIndex(int i) { return -1 - i; }
253 
254 bool Operator::isVariadic() const {
255   return any_of(llvm::concat<const NamedTypeConstraint>(operands, results),
256                 [](const NamedTypeConstraint &op) { return op.isVariadic(); });
257 }
258 
259 void Operator::populateTypeInferenceInfo(
260     const llvm::StringMap<int> &argumentsAndResultsIndex) {
261   // If the type inference op interface is not registered, then do not attempt
262   // to determine if the result types an be inferred.
263   auto &recordKeeper = def.getRecords();
264   auto *inferTrait = recordKeeper.getDef(inferTypeOpInterface);
265   allResultsHaveKnownTypes = false;
266   if (!inferTrait)
267     return;
268 
269   // If there are no results, the skip this else the build method generated
270   // overlaps with another autogenerated builder.
271   if (getNumResults() == 0)
272     return;
273 
274   // Skip for ops with variadic operands/results.
275   // TODO: This can be relaxed.
276   if (isVariadic())
277     return;
278 
279   // Skip cases currently being custom generated.
280   // TODO: Remove special cases.
281   if (getTrait("OpTrait::SameOperandsAndResultType"))
282     return;
283 
284   // We create equivalence classes of argument/result types where arguments
285   // and results are mapped into the same index space and indices corresponding
286   // to the same type are in the same equivalence class.
287   llvm::EquivalenceClasses<int> ecs;
288   resultTypeMapping.resize(getNumResults());
289   // Captures the argument whose type matches a given result type. Preference
290   // towards capturing operands first before attributes.
291   auto captureMapping = [&](int i) {
292     bool found = false;
293     ecs.insert(resultIndex(i));
294     auto mi = ecs.findLeader(resultIndex(i));
295     for (auto me = ecs.member_end(); mi != me; ++mi) {
296       if (*mi < 0) {
297         auto tc = getResultTypeConstraint(i);
298         if (tc.getBuilderCall().hasValue()) {
299           resultTypeMapping[i].emplace_back(tc);
300           found = true;
301         }
302         continue;
303       }
304 
305       if (getArg(*mi).is<NamedAttribute *>()) {
306         // TODO: Handle attributes.
307         continue;
308       } else {
309         resultTypeMapping[i].emplace_back(*mi);
310         found = true;
311       }
312     }
313     return found;
314   };
315 
316   for (const OpTrait &trait : traits) {
317     const llvm::Record &def = trait.getDef();
318     // If the infer type op interface was manually added, then treat it as
319     // intention that the op needs special handling.
320     // TODO: Reconsider whether to always generate, this is more conservative
321     // and keeps existing behavior so starting that way for now.
322     if (def.isSubClassOf(
323             llvm::formatv("{0}::Trait", inferTypeOpInterface).str()))
324       return;
325     if (const auto *opTrait = dyn_cast<InterfaceOpTrait>(&trait))
326       if (&opTrait->getDef() == inferTrait)
327         return;
328 
329     if (!def.isSubClassOf("AllTypesMatch"))
330       continue;
331 
332     auto values = def.getValueAsListOfStrings("values");
333     auto root = argumentsAndResultsIndex.lookup(values.front());
334     for (StringRef str : values)
335       ecs.unionSets(argumentsAndResultsIndex.lookup(str), root);
336   }
337 
338   // Verifies that all output types have a corresponding known input type
339   // and chooses matching operand or attribute (in that order) that
340   // matches it.
341   allResultsHaveKnownTypes =
342       all_of(llvm::seq<int>(0, getNumResults()), captureMapping);
343 
344   // If the types could be computed, then add type inference trait.
345   if (allResultsHaveKnownTypes)
346     traits.push_back(OpTrait::create(inferTrait->getDefInit()));
347 }
348 
349 void Operator::populateOpStructure() {
350   auto &recordKeeper = def.getRecords();
351   auto *typeConstraintClass = recordKeeper.getClass("TypeConstraint");
352   auto *attrClass = recordKeeper.getClass("Attr");
353   auto *derivedAttrClass = recordKeeper.getClass("DerivedAttr");
354   auto *opVarClass = recordKeeper.getClass("OpVariable");
355   numNativeAttributes = 0;
356 
357   DagInit *argumentValues = def.getValueAsDag("arguments");
358   unsigned numArgs = argumentValues->getNumArgs();
359 
360   // Mapping from name of to argument or result index. Arguments are indexed
361   // to match getArg index, while the results are negatively indexed.
362   llvm::StringMap<int> argumentsAndResultsIndex;
363 
364   // Handle operands and native attributes.
365   for (unsigned i = 0; i != numArgs; ++i) {
366     auto *arg = argumentValues->getArg(i);
367     auto givenName = argumentValues->getArgNameStr(i);
368     auto *argDefInit = dyn_cast<DefInit>(arg);
369     if (!argDefInit)
370       PrintFatalError(def.getLoc(),
371                       Twine("undefined type for argument #") + Twine(i));
372     Record *argDef = argDefInit->getDef();
373     if (argDef->isSubClassOf(opVarClass))
374       argDef = argDef->getValueAsDef("constraint");
375 
376     if (argDef->isSubClassOf(typeConstraintClass)) {
377       operands.push_back(
378           NamedTypeConstraint{givenName, TypeConstraint(argDef)});
379     } else if (argDef->isSubClassOf(attrClass)) {
380       if (givenName.empty())
381         PrintFatalError(argDef->getLoc(), "attributes must be named");
382       if (argDef->isSubClassOf(derivedAttrClass))
383         PrintFatalError(argDef->getLoc(),
384                         "derived attributes not allowed in argument list");
385       attributes.push_back({givenName, Attribute(argDef)});
386       ++numNativeAttributes;
387     } else {
388       PrintFatalError(def.getLoc(), "unexpected def type; only defs deriving "
389                                     "from TypeConstraint or Attr are allowed");
390     }
391     if (!givenName.empty())
392       argumentsAndResultsIndex[givenName] = i;
393   }
394 
395   // Handle derived attributes.
396   for (const auto &val : def.getValues()) {
397     if (auto *record = dyn_cast<llvm::RecordRecTy>(val.getType())) {
398       if (!record->isSubClassOf(attrClass))
399         continue;
400       if (!record->isSubClassOf(derivedAttrClass))
401         PrintFatalError(def.getLoc(),
402                         "unexpected Attr where only DerivedAttr is allowed");
403 
404       if (record->getClasses().size() != 1) {
405         PrintFatalError(
406             def.getLoc(),
407             "unsupported attribute modelling, only single class expected");
408       }
409       attributes.push_back(
410           {cast<llvm::StringInit>(val.getNameInit())->getValue(),
411            Attribute(cast<DefInit>(val.getValue()))});
412     }
413   }
414 
415   // Populate `arguments`. This must happen after we've finalized `operands` and
416   // `attributes` because we will put their elements' pointers in `arguments`.
417   // SmallVector may perform re-allocation under the hood when adding new
418   // elements.
419   int operandIndex = 0, attrIndex = 0;
420   for (unsigned i = 0; i != numArgs; ++i) {
421     Record *argDef = dyn_cast<DefInit>(argumentValues->getArg(i))->getDef();
422     if (argDef->isSubClassOf(opVarClass))
423       argDef = argDef->getValueAsDef("constraint");
424 
425     if (argDef->isSubClassOf(typeConstraintClass)) {
426       attrOrOperandMapping.push_back(
427           {OperandOrAttribute::Kind::Operand, operandIndex});
428       arguments.emplace_back(&operands[operandIndex++]);
429     } else {
430       assert(argDef->isSubClassOf(attrClass));
431       attrOrOperandMapping.push_back(
432           {OperandOrAttribute::Kind::Attribute, attrIndex});
433       arguments.emplace_back(&attributes[attrIndex++]);
434     }
435   }
436 
437   auto *resultsDag = def.getValueAsDag("results");
438   auto *outsOp = dyn_cast<DefInit>(resultsDag->getOperator());
439   if (!outsOp || outsOp->getDef()->getName() != "outs") {
440     PrintFatalError(def.getLoc(), "'results' must have 'outs' directive");
441   }
442 
443   // Handle results.
444   for (unsigned i = 0, e = resultsDag->getNumArgs(); i < e; ++i) {
445     auto name = resultsDag->getArgNameStr(i);
446     auto *resultInit = dyn_cast<DefInit>(resultsDag->getArg(i));
447     if (!resultInit) {
448       PrintFatalError(def.getLoc(),
449                       Twine("undefined type for result #") + Twine(i));
450     }
451     auto *resultDef = resultInit->getDef();
452     if (resultDef->isSubClassOf(opVarClass))
453       resultDef = resultDef->getValueAsDef("constraint");
454     results.push_back({name, TypeConstraint(resultDef)});
455     if (!name.empty())
456       argumentsAndResultsIndex[name] = resultIndex(i);
457   }
458 
459   // Handle successors
460   auto *successorsDag = def.getValueAsDag("successors");
461   auto *successorsOp = dyn_cast<DefInit>(successorsDag->getOperator());
462   if (!successorsOp || successorsOp->getDef()->getName() != "successor") {
463     PrintFatalError(def.getLoc(),
464                     "'successors' must have 'successor' directive");
465   }
466 
467   for (unsigned i = 0, e = successorsDag->getNumArgs(); i < e; ++i) {
468     auto name = successorsDag->getArgNameStr(i);
469     auto *successorInit = dyn_cast<DefInit>(successorsDag->getArg(i));
470     if (!successorInit) {
471       PrintFatalError(def.getLoc(),
472                       Twine("undefined kind for successor #") + Twine(i));
473     }
474     Successor successor(successorInit->getDef());
475 
476     // Only support variadic successors if it is the last one for now.
477     if (i != e - 1 && successor.isVariadic())
478       PrintFatalError(def.getLoc(), "only the last successor can be variadic");
479     successors.push_back({name, successor});
480   }
481 
482   // Create list of traits, skipping over duplicates: appending to lists in
483   // tablegen is easy, making them unique less so, so dedupe here.
484   if (auto *traitList = def.getValueAsListInit("traits")) {
485     // This is uniquing based on pointers of the trait.
486     SmallPtrSet<const llvm::Init *, 32> traitSet;
487     traits.reserve(traitSet.size());
488     for (auto *traitInit : *traitList) {
489       // Keep traits in the same order while skipping over duplicates.
490       if (traitSet.insert(traitInit).second)
491         traits.push_back(OpTrait::create(traitInit));
492     }
493   }
494 
495   populateTypeInferenceInfo(argumentsAndResultsIndex);
496 
497   // Handle regions
498   auto *regionsDag = def.getValueAsDag("regions");
499   auto *regionsOp = dyn_cast<DefInit>(regionsDag->getOperator());
500   if (!regionsOp || regionsOp->getDef()->getName() != "region") {
501     PrintFatalError(def.getLoc(), "'regions' must have 'region' directive");
502   }
503 
504   for (unsigned i = 0, e = regionsDag->getNumArgs(); i < e; ++i) {
505     auto name = regionsDag->getArgNameStr(i);
506     auto *regionInit = dyn_cast<DefInit>(regionsDag->getArg(i));
507     if (!regionInit) {
508       PrintFatalError(def.getLoc(),
509                       Twine("undefined kind for region #") + Twine(i));
510     }
511     Region region(regionInit->getDef());
512     if (region.isVariadic()) {
513       // Only support variadic regions if it is the last one for now.
514       if (i != e - 1)
515         PrintFatalError(def.getLoc(), "only the last region can be variadic");
516       if (name.empty())
517         PrintFatalError(def.getLoc(), "variadic regions must be named");
518     }
519 
520     regions.push_back({name, region});
521   }
522 
523   LLVM_DEBUG(print(llvm::dbgs()));
524 }
525 
526 auto Operator::getSameTypeAsResult(int index) const -> ArrayRef<ArgOrType> {
527   assert(allResultTypesKnown());
528   return resultTypeMapping[index];
529 }
530 
531 ArrayRef<llvm::SMLoc> Operator::getLoc() const { return def.getLoc(); }
532 
533 bool Operator::hasDescription() const {
534   return def.getValue("description") != nullptr;
535 }
536 
537 StringRef Operator::getDescription() const {
538   return def.getValueAsString("description");
539 }
540 
541 bool Operator::hasSummary() const { return def.getValue("summary") != nullptr; }
542 
543 StringRef Operator::getSummary() const {
544   return def.getValueAsString("summary");
545 }
546 
547 bool Operator::hasAssemblyFormat() const {
548   auto *valueInit = def.getValueInit("assemblyFormat");
549   return isa<llvm::CodeInit, llvm::StringInit>(valueInit);
550 }
551 
552 StringRef Operator::getAssemblyFormat() const {
553   return TypeSwitch<llvm::Init *, StringRef>(def.getValueInit("assemblyFormat"))
554       .Case<llvm::StringInit, llvm::CodeInit>(
555           [&](auto *init) { return init->getValue(); });
556 }
557 
558 void Operator::print(llvm::raw_ostream &os) const {
559   os << "op '" << getOperationName() << "'\n";
560   for (Argument arg : arguments) {
561     if (auto *attr = arg.dyn_cast<NamedAttribute *>())
562       os << "[attribute] " << attr->name << '\n';
563     else
564       os << "[operand] " << arg.get<NamedTypeConstraint *>()->name << '\n';
565   }
566 }
567 
568 auto Operator::VariableDecoratorIterator::unwrap(llvm::Init *init)
569     -> VariableDecorator {
570   return VariableDecorator(cast<llvm::DefInit>(init)->getDef());
571 }
572 
573 auto Operator::getArgToOperandOrAttribute(int index) const
574     -> OperandOrAttribute {
575   return attrOrOperandMapping[index];
576 }
577