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/Predicate.h"
15 #include "mlir/TableGen/Trait.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/StringExtras.h"
22 #include "llvm/ADT/TypeSwitch.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/FormatVariadic.h"
26 #include "llvm/TableGen/Error.h"
27 #include "llvm/TableGen/Record.h"
28 
29 #define DEBUG_TYPE "mlir-tblgen-operator"
30 
31 using namespace mlir;
32 using namespace mlir::tblgen;
33 
34 using llvm::DagInit;
35 using llvm::DefInit;
36 using llvm::Record;
37 
38 Operator::Operator(const llvm::Record &def)
39     : dialect(def.getValueAsDef("opDialect")), def(def) {
40   // The first `_` in the op's TableGen def name is treated as separating the
41   // dialect prefix and the op class name. The dialect prefix will be ignored if
42   // not empty. Otherwise, if def name starts with a `_`, the `_` is considered
43   // as part of the class name.
44   StringRef prefix;
45   std::tie(prefix, cppClassName) = def.getName().split('_');
46   if (prefix.empty()) {
47     // Class name with a leading underscore and without dialect prefix
48     cppClassName = def.getName();
49   } else if (cppClassName.empty()) {
50     // Class name without dialect prefix
51     cppClassName = prefix;
52   }
53 
54   cppNamespace = def.getValueAsString("cppNamespace");
55 
56   populateOpStructure();
57   assertInvariants();
58 }
59 
60 std::string Operator::getOperationName() const {
61   auto prefix = dialect.getName();
62   auto opName = def.getValueAsString("opName");
63   if (prefix.empty())
64     return std::string(opName);
65   return std::string(llvm::formatv("{0}.{1}", prefix, opName));
66 }
67 
68 std::string Operator::getAdaptorName() const {
69   return std::string(llvm::formatv("{0}Adaptor", getCppClassName()));
70 }
71 
72 void Operator::assertInvariants() const {
73   // Check that the name of arguments/results/regions/successors don't overlap.
74   DenseMap<StringRef, StringRef> existingNames;
75   auto checkName = [&](StringRef name, StringRef entity) {
76     if (name.empty())
77       return;
78     auto insertion = existingNames.insert({name, entity});
79     if (insertion.second)
80       return;
81     if (entity == insertion.first->second)
82       PrintFatalError(getLoc(), "op has a conflict with two " + entity +
83                                     " having the same name '" + name + "'");
84     PrintFatalError(getLoc(), "op has a conflict with " +
85                                   insertion.first->second + " and " + entity +
86                                   " both having an entry with the name '" +
87                                   name + "'");
88   };
89   // Check operands amongst themselves.
90   for (int i : llvm::seq<int>(0, getNumOperands()))
91     checkName(getOperand(i).name, "operands");
92 
93   // Check results amongst themselves and against operands.
94   for (int i : llvm::seq<int>(0, getNumResults()))
95     checkName(getResult(i).name, "results");
96 
97   // Check regions amongst themselves and against operands and results.
98   for (int i : llvm::seq<int>(0, getNumRegions()))
99     checkName(getRegion(i).name, "regions");
100 
101   // Check successors amongst themselves and against operands, results, and
102   // regions.
103   for (int i : llvm::seq<int>(0, getNumSuccessors()))
104     checkName(getSuccessor(i).name, "successors");
105 }
106 
107 StringRef Operator::getDialectName() const { return dialect.getName(); }
108 
109 StringRef Operator::getCppClassName() const { return cppClassName; }
110 
111 std::string Operator::getQualCppClassName() const {
112   if (cppNamespace.empty())
113     return std::string(cppClassName);
114   return std::string(llvm::formatv("{0}::{1}", cppNamespace, cppClassName));
115 }
116 
117 StringRef Operator::getCppNamespace() const { return cppNamespace; }
118 
119 int Operator::getNumResults() const {
120   DagInit *results = def.getValueAsDag("results");
121   return results->getNumArgs();
122 }
123 
124 StringRef Operator::getExtraClassDeclaration() const {
125   constexpr auto attr = "extraClassDeclaration";
126   if (def.isValueUnset(attr))
127     return {};
128   return def.getValueAsString(attr);
129 }
130 
131 StringRef Operator::getExtraClassDefinition() const {
132   constexpr auto attr = "extraClassDefinition";
133   if (def.isValueUnset(attr))
134     return {};
135   return def.getValueAsString(attr);
136 }
137 
138 const llvm::Record &Operator::getDef() const { return def; }
139 
140 bool Operator::skipDefaultBuilders() const {
141   return def.getValueAsBit("skipDefaultBuilders");
142 }
143 
144 auto Operator::result_begin() const -> const_value_iterator {
145   return results.begin();
146 }
147 
148 auto Operator::result_end() const -> const_value_iterator {
149   return results.end();
150 }
151 
152 auto Operator::getResults() const -> const_value_range {
153   return {result_begin(), result_end()};
154 }
155 
156 TypeConstraint Operator::getResultTypeConstraint(int index) const {
157   DagInit *results = def.getValueAsDag("results");
158   return TypeConstraint(cast<DefInit>(results->getArg(index)));
159 }
160 
161 StringRef Operator::getResultName(int index) const {
162   DagInit *results = def.getValueAsDag("results");
163   return results->getArgNameStr(index);
164 }
165 
166 auto Operator::getResultDecorators(int index) const -> var_decorator_range {
167   Record *result =
168       cast<DefInit>(def.getValueAsDag("results")->getArg(index))->getDef();
169   if (!result->isSubClassOf("OpVariable"))
170     return var_decorator_range(nullptr, nullptr);
171   return *result->getValueAsListInit("decorators");
172 }
173 
174 unsigned Operator::getNumVariableLengthResults() const {
175   return llvm::count_if(results, [](const NamedTypeConstraint &c) {
176     return c.constraint.isVariableLength();
177   });
178 }
179 
180 unsigned Operator::getNumVariableLengthOperands() const {
181   return llvm::count_if(operands, [](const NamedTypeConstraint &c) {
182     return c.constraint.isVariableLength();
183   });
184 }
185 
186 bool Operator::hasSingleVariadicArg() const {
187   return getNumArgs() == 1 && getArg(0).is<NamedTypeConstraint *>() &&
188          getOperand(0).isVariadic();
189 }
190 
191 Operator::arg_iterator Operator::arg_begin() const { return arguments.begin(); }
192 
193 Operator::arg_iterator Operator::arg_end() const { return arguments.end(); }
194 
195 Operator::arg_range Operator::getArgs() const {
196   return {arg_begin(), arg_end()};
197 }
198 
199 StringRef Operator::getArgName(int index) const {
200   DagInit *argumentValues = def.getValueAsDag("arguments");
201   return argumentValues->getArgNameStr(index);
202 }
203 
204 auto Operator::getArgDecorators(int index) const -> var_decorator_range {
205   Record *arg =
206       cast<DefInit>(def.getValueAsDag("arguments")->getArg(index))->getDef();
207   if (!arg->isSubClassOf("OpVariable"))
208     return var_decorator_range(nullptr, nullptr);
209   return *arg->getValueAsListInit("decorators");
210 }
211 
212 const Trait *Operator::getTrait(StringRef trait) const {
213   for (const auto &t : traits) {
214     if (const auto *traitDef = dyn_cast<NativeTrait>(&t)) {
215       if (traitDef->getFullyQualifiedTraitName() == trait)
216         return traitDef;
217     } else if (const auto *traitDef = dyn_cast<InternalTrait>(&t)) {
218       if (traitDef->getFullyQualifiedTraitName() == trait)
219         return traitDef;
220     } else if (const auto *traitDef = dyn_cast<InterfaceTrait>(&t)) {
221       if (traitDef->getFullyQualifiedTraitName() == trait)
222         return traitDef;
223     }
224   }
225   return nullptr;
226 }
227 
228 auto Operator::region_begin() const -> const_region_iterator {
229   return regions.begin();
230 }
231 auto Operator::region_end() const -> const_region_iterator {
232   return regions.end();
233 }
234 auto Operator::getRegions() const
235     -> llvm::iterator_range<const_region_iterator> {
236   return {region_begin(), region_end()};
237 }
238 
239 unsigned Operator::getNumRegions() const { return regions.size(); }
240 
241 const NamedRegion &Operator::getRegion(unsigned index) const {
242   return regions[index];
243 }
244 
245 unsigned Operator::getNumVariadicRegions() const {
246   return llvm::count_if(regions,
247                         [](const NamedRegion &c) { return c.isVariadic(); });
248 }
249 
250 auto Operator::successor_begin() const -> const_successor_iterator {
251   return successors.begin();
252 }
253 auto Operator::successor_end() const -> const_successor_iterator {
254   return successors.end();
255 }
256 auto Operator::getSuccessors() const
257     -> llvm::iterator_range<const_successor_iterator> {
258   return {successor_begin(), successor_end()};
259 }
260 
261 unsigned Operator::getNumSuccessors() const { return successors.size(); }
262 
263 const NamedSuccessor &Operator::getSuccessor(unsigned index) const {
264   return successors[index];
265 }
266 
267 unsigned Operator::getNumVariadicSuccessors() const {
268   return llvm::count_if(successors,
269                         [](const NamedSuccessor &c) { return c.isVariadic(); });
270 }
271 
272 auto Operator::trait_begin() const -> const_trait_iterator {
273   return traits.begin();
274 }
275 auto Operator::trait_end() const -> const_trait_iterator {
276   return traits.end();
277 }
278 auto Operator::getTraits() const -> llvm::iterator_range<const_trait_iterator> {
279   return {trait_begin(), trait_end()};
280 }
281 
282 auto Operator::attribute_begin() const -> attribute_iterator {
283   return attributes.begin();
284 }
285 auto Operator::attribute_end() const -> attribute_iterator {
286   return attributes.end();
287 }
288 auto Operator::getAttributes() const
289     -> llvm::iterator_range<attribute_iterator> {
290   return {attribute_begin(), attribute_end()};
291 }
292 
293 auto Operator::operand_begin() const -> const_value_iterator {
294   return operands.begin();
295 }
296 auto Operator::operand_end() const -> const_value_iterator {
297   return operands.end();
298 }
299 auto Operator::getOperands() const -> const_value_range {
300   return {operand_begin(), operand_end()};
301 }
302 
303 auto Operator::getArg(int index) const -> Argument { return arguments[index]; }
304 
305 // Mapping from result index to combined argument and result index. Arguments
306 // are indexed to match getArg index, while the result indexes are mapped to
307 // avoid overlap.
308 static int resultIndex(int i) { return -1 - i; }
309 
310 bool Operator::isVariadic() const {
311   return any_of(llvm::concat<const NamedTypeConstraint>(operands, results),
312                 [](const NamedTypeConstraint &op) { return op.isVariadic(); });
313 }
314 
315 void Operator::populateTypeInferenceInfo(
316     const llvm::StringMap<int> &argumentsAndResultsIndex) {
317   // If the type inference op interface is not registered, then do not attempt
318   // to determine if the result types an be inferred.
319   auto &recordKeeper = def.getRecords();
320   auto *inferTrait = recordKeeper.getDef(inferTypeOpInterface);
321   allResultsHaveKnownTypes = false;
322   if (!inferTrait)
323     return;
324 
325   // If there are no results, the skip this else the build method generated
326   // overlaps with another autogenerated builder.
327   if (getNumResults() == 0)
328     return;
329 
330   // Skip ops with variadic or optional results.
331   if (getNumVariableLengthResults() > 0)
332     return;
333 
334   // Skip cases currently being custom generated.
335   // TODO: Remove special cases.
336   if (getTrait("::mlir::OpTrait::SameOperandsAndResultType"))
337     return;
338 
339   // We create equivalence classes of argument/result types where arguments
340   // and results are mapped into the same index space and indices corresponding
341   // to the same type are in the same equivalence class.
342   llvm::EquivalenceClasses<int> ecs;
343   resultTypeMapping.resize(getNumResults());
344   // Captures the argument whose type matches a given result type. Preference
345   // towards capturing operands first before attributes.
346   auto captureMapping = [&](int i) {
347     bool found = false;
348     ecs.insert(resultIndex(i));
349     auto mi = ecs.findLeader(resultIndex(i));
350     for (auto me = ecs.member_end(); mi != me; ++mi) {
351       if (*mi < 0) {
352         auto tc = getResultTypeConstraint(i);
353         if (tc.getBuilderCall().hasValue()) {
354           resultTypeMapping[i].emplace_back(tc);
355           found = true;
356         }
357         continue;
358       }
359 
360       if (getArg(*mi).is<NamedAttribute *>()) {
361         // TODO: Handle attributes.
362         continue;
363       }
364       resultTypeMapping[i].emplace_back(*mi);
365       found = true;
366     }
367     return found;
368   };
369 
370   for (const Trait &trait : traits) {
371     const llvm::Record &def = trait.getDef();
372     // If the infer type op interface was manually added, then treat it as
373     // intention that the op needs special handling.
374     // TODO: Reconsider whether to always generate, this is more conservative
375     // and keeps existing behavior so starting that way for now.
376     if (def.isSubClassOf(
377             llvm::formatv("{0}::Trait", inferTypeOpInterface).str()))
378       return;
379     if (const auto *traitDef = dyn_cast<InterfaceTrait>(&trait))
380       if (&traitDef->getDef() == inferTrait)
381         return;
382 
383     if (!def.isSubClassOf("AllTypesMatch"))
384       continue;
385 
386     auto values = def.getValueAsListOfStrings("values");
387     auto root = argumentsAndResultsIndex.lookup(values.front());
388     for (StringRef str : values)
389       ecs.unionSets(argumentsAndResultsIndex.lookup(str), root);
390   }
391 
392   // Verifies that all output types have a corresponding known input type
393   // and chooses matching operand or attribute (in that order) that
394   // matches it.
395   allResultsHaveKnownTypes =
396       all_of(llvm::seq<int>(0, getNumResults()), captureMapping);
397 
398   // If the types could be computed, then add type inference trait.
399   if (allResultsHaveKnownTypes)
400     traits.push_back(Trait::create(inferTrait->getDefInit()));
401 }
402 
403 void Operator::populateOpStructure() {
404   auto &recordKeeper = def.getRecords();
405   auto *typeConstraintClass = recordKeeper.getClass("TypeConstraint");
406   auto *attrClass = recordKeeper.getClass("Attr");
407   auto *derivedAttrClass = recordKeeper.getClass("DerivedAttr");
408   auto *opVarClass = recordKeeper.getClass("OpVariable");
409   numNativeAttributes = 0;
410 
411   DagInit *argumentValues = def.getValueAsDag("arguments");
412   unsigned numArgs = argumentValues->getNumArgs();
413 
414   // Mapping from name of to argument or result index. Arguments are indexed
415   // to match getArg index, while the results are negatively indexed.
416   llvm::StringMap<int> argumentsAndResultsIndex;
417 
418   // Handle operands and native attributes.
419   for (unsigned i = 0; i != numArgs; ++i) {
420     auto *arg = argumentValues->getArg(i);
421     auto givenName = argumentValues->getArgNameStr(i);
422     auto *argDefInit = dyn_cast<DefInit>(arg);
423     if (!argDefInit)
424       PrintFatalError(def.getLoc(),
425                       Twine("undefined type for argument #") + Twine(i));
426     Record *argDef = argDefInit->getDef();
427     if (argDef->isSubClassOf(opVarClass))
428       argDef = argDef->getValueAsDef("constraint");
429 
430     if (argDef->isSubClassOf(typeConstraintClass)) {
431       operands.push_back(
432           NamedTypeConstraint{givenName, TypeConstraint(argDef)});
433     } else if (argDef->isSubClassOf(attrClass)) {
434       if (givenName.empty())
435         PrintFatalError(argDef->getLoc(), "attributes must be named");
436       if (argDef->isSubClassOf(derivedAttrClass))
437         PrintFatalError(argDef->getLoc(),
438                         "derived attributes not allowed in argument list");
439       attributes.push_back({givenName, Attribute(argDef)});
440       ++numNativeAttributes;
441     } else {
442       PrintFatalError(def.getLoc(), "unexpected def type; only defs deriving "
443                                     "from TypeConstraint or Attr are allowed");
444     }
445     if (!givenName.empty())
446       argumentsAndResultsIndex[givenName] = i;
447   }
448 
449   // Handle derived attributes.
450   for (const auto &val : def.getValues()) {
451     if (auto *record = dyn_cast<llvm::RecordRecTy>(val.getType())) {
452       if (!record->isSubClassOf(attrClass))
453         continue;
454       if (!record->isSubClassOf(derivedAttrClass))
455         PrintFatalError(def.getLoc(),
456                         "unexpected Attr where only DerivedAttr is allowed");
457 
458       if (record->getClasses().size() != 1) {
459         PrintFatalError(
460             def.getLoc(),
461             "unsupported attribute modelling, only single class expected");
462       }
463       attributes.push_back(
464           {cast<llvm::StringInit>(val.getNameInit())->getValue(),
465            Attribute(cast<DefInit>(val.getValue()))});
466     }
467   }
468 
469   // Populate `arguments`. This must happen after we've finalized `operands` and
470   // `attributes` because we will put their elements' pointers in `arguments`.
471   // SmallVector may perform re-allocation under the hood when adding new
472   // elements.
473   int operandIndex = 0, attrIndex = 0;
474   for (unsigned i = 0; i != numArgs; ++i) {
475     Record *argDef = dyn_cast<DefInit>(argumentValues->getArg(i))->getDef();
476     if (argDef->isSubClassOf(opVarClass))
477       argDef = argDef->getValueAsDef("constraint");
478 
479     if (argDef->isSubClassOf(typeConstraintClass)) {
480       attrOrOperandMapping.push_back(
481           {OperandOrAttribute::Kind::Operand, operandIndex});
482       arguments.emplace_back(&operands[operandIndex++]);
483     } else {
484       assert(argDef->isSubClassOf(attrClass));
485       attrOrOperandMapping.push_back(
486           {OperandOrAttribute::Kind::Attribute, attrIndex});
487       arguments.emplace_back(&attributes[attrIndex++]);
488     }
489   }
490 
491   auto *resultsDag = def.getValueAsDag("results");
492   auto *outsOp = dyn_cast<DefInit>(resultsDag->getOperator());
493   if (!outsOp || outsOp->getDef()->getName() != "outs") {
494     PrintFatalError(def.getLoc(), "'results' must have 'outs' directive");
495   }
496 
497   // Handle results.
498   for (unsigned i = 0, e = resultsDag->getNumArgs(); i < e; ++i) {
499     auto name = resultsDag->getArgNameStr(i);
500     auto *resultInit = dyn_cast<DefInit>(resultsDag->getArg(i));
501     if (!resultInit) {
502       PrintFatalError(def.getLoc(),
503                       Twine("undefined type for result #") + Twine(i));
504     }
505     auto *resultDef = resultInit->getDef();
506     if (resultDef->isSubClassOf(opVarClass))
507       resultDef = resultDef->getValueAsDef("constraint");
508     results.push_back({name, TypeConstraint(resultDef)});
509     if (!name.empty())
510       argumentsAndResultsIndex[name] = resultIndex(i);
511 
512     // We currently only support VariadicOfVariadic operands.
513     if (results.back().constraint.isVariadicOfVariadic()) {
514       PrintFatalError(
515           def.getLoc(),
516           "'VariadicOfVariadic' results are currently not supported");
517     }
518   }
519 
520   // Handle successors
521   auto *successorsDag = def.getValueAsDag("successors");
522   auto *successorsOp = dyn_cast<DefInit>(successorsDag->getOperator());
523   if (!successorsOp || successorsOp->getDef()->getName() != "successor") {
524     PrintFatalError(def.getLoc(),
525                     "'successors' must have 'successor' directive");
526   }
527 
528   for (unsigned i = 0, e = successorsDag->getNumArgs(); i < e; ++i) {
529     auto name = successorsDag->getArgNameStr(i);
530     auto *successorInit = dyn_cast<DefInit>(successorsDag->getArg(i));
531     if (!successorInit) {
532       PrintFatalError(def.getLoc(),
533                       Twine("undefined kind for successor #") + Twine(i));
534     }
535     Successor successor(successorInit->getDef());
536 
537     // Only support variadic successors if it is the last one for now.
538     if (i != e - 1 && successor.isVariadic())
539       PrintFatalError(def.getLoc(), "only the last successor can be variadic");
540     successors.push_back({name, successor});
541   }
542 
543   // Create list of traits, skipping over duplicates: appending to lists in
544   // tablegen is easy, making them unique less so, so dedupe here.
545   if (auto *traitList = def.getValueAsListInit("traits")) {
546     // This is uniquing based on pointers of the trait.
547     SmallPtrSet<const llvm::Init *, 32> traitSet;
548     traits.reserve(traitSet.size());
549 
550     // The declaration order of traits imply the verification order of traits.
551     // Some traits may require other traits to be verified first then they can
552     // do further verification based on those verified facts. If you see this
553     // error, fix the traits declaration order by checking the `dependentTraits`
554     // field.
555     auto verifyTraitValidity = [&](Record *trait) {
556       auto *dependentTraits = trait->getValueAsListInit("dependentTraits");
557       for (auto *traitInit : *dependentTraits)
558         if (traitSet.find(traitInit) == traitSet.end())
559           PrintFatalError(
560               def.getLoc(),
561               trait->getValueAsString("trait") + " requires " +
562                   cast<DefInit>(traitInit)->getDef()->getValueAsString(
563                       "trait") +
564                   " to precede it in traits list");
565     };
566 
567     std::function<void(llvm::ListInit *)> insert;
568     insert = [&](llvm::ListInit *traitList) {
569       for (auto *traitInit : *traitList) {
570         auto *def = cast<DefInit>(traitInit)->getDef();
571         if (def->isSubClassOf("TraitList")) {
572           insert(def->getValueAsListInit("traits"));
573           continue;
574         }
575 
576         // Verify if the trait has all the dependent traits declared before
577         // itself.
578         verifyTraitValidity(def);
579 
580         // Keep traits in the same order while skipping over duplicates.
581         if (traitSet.insert(traitInit).second)
582           traits.push_back(Trait::create(traitInit));
583       }
584     };
585     insert(traitList);
586   }
587 
588   populateTypeInferenceInfo(argumentsAndResultsIndex);
589 
590   // Handle regions
591   auto *regionsDag = def.getValueAsDag("regions");
592   auto *regionsOp = dyn_cast<DefInit>(regionsDag->getOperator());
593   if (!regionsOp || regionsOp->getDef()->getName() != "region") {
594     PrintFatalError(def.getLoc(), "'regions' must have 'region' directive");
595   }
596 
597   for (unsigned i = 0, e = regionsDag->getNumArgs(); i < e; ++i) {
598     auto name = regionsDag->getArgNameStr(i);
599     auto *regionInit = dyn_cast<DefInit>(regionsDag->getArg(i));
600     if (!regionInit) {
601       PrintFatalError(def.getLoc(),
602                       Twine("undefined kind for region #") + Twine(i));
603     }
604     Region region(regionInit->getDef());
605     if (region.isVariadic()) {
606       // Only support variadic regions if it is the last one for now.
607       if (i != e - 1)
608         PrintFatalError(def.getLoc(), "only the last region can be variadic");
609       if (name.empty())
610         PrintFatalError(def.getLoc(), "variadic regions must be named");
611     }
612 
613     regions.push_back({name, region});
614   }
615 
616   // Populate the builders.
617   auto *builderList =
618       dyn_cast_or_null<llvm::ListInit>(def.getValueInit("builders"));
619   if (builderList && !builderList->empty()) {
620     for (llvm::Init *init : builderList->getValues())
621       builders.emplace_back(cast<llvm::DefInit>(init)->getDef(), def.getLoc());
622   } else if (skipDefaultBuilders()) {
623     PrintFatalError(
624         def.getLoc(),
625         "default builders are skipped and no custom builders provided");
626   }
627 
628   LLVM_DEBUG(print(llvm::dbgs()));
629 }
630 
631 auto Operator::getSameTypeAsResult(int index) const -> ArrayRef<ArgOrType> {
632   assert(allResultTypesKnown());
633   return resultTypeMapping[index];
634 }
635 
636 ArrayRef<SMLoc> Operator::getLoc() const { return def.getLoc(); }
637 
638 bool Operator::hasDescription() const {
639   return def.getValue("description") != nullptr;
640 }
641 
642 StringRef Operator::getDescription() const {
643   return def.getValueAsString("description");
644 }
645 
646 bool Operator::hasSummary() const { return def.getValue("summary") != nullptr; }
647 
648 StringRef Operator::getSummary() const {
649   return def.getValueAsString("summary");
650 }
651 
652 bool Operator::hasAssemblyFormat() const {
653   auto *valueInit = def.getValueInit("assemblyFormat");
654   return isa<llvm::StringInit>(valueInit);
655 }
656 
657 StringRef Operator::getAssemblyFormat() const {
658   return TypeSwitch<llvm::Init *, StringRef>(def.getValueInit("assemblyFormat"))
659       .Case<llvm::StringInit>([&](auto *init) { return init->getValue(); });
660 }
661 
662 void Operator::print(llvm::raw_ostream &os) const {
663   os << "op '" << getOperationName() << "'\n";
664   for (Argument arg : arguments) {
665     if (auto *attr = arg.dyn_cast<NamedAttribute *>())
666       os << "[attribute] " << attr->name << '\n';
667     else
668       os << "[operand] " << arg.get<NamedTypeConstraint *>()->name << '\n';
669   }
670 }
671 
672 auto Operator::VariableDecoratorIterator::unwrap(llvm::Init *init)
673     -> VariableDecorator {
674   return VariableDecorator(cast<llvm::DefInit>(init)->getDef());
675 }
676 
677 auto Operator::getArgToOperandOrAttribute(int index) const
678     -> OperandOrAttribute {
679   return attrOrOperandMapping[index];
680 }
681 
682 // Helper to return the names for accessor.
683 static SmallVector<std::string, 2>
684 getGetterOrSetterNames(bool isGetter, const Operator &op, StringRef name) {
685   Dialect::EmitPrefix prefixType = op.getDialect().getEmitAccessorPrefix();
686   std::string prefix;
687   if (prefixType != Dialect::EmitPrefix::Raw)
688     prefix = isGetter ? "get" : "set";
689 
690   SmallVector<std::string, 2> names;
691   bool rawToo = prefixType == Dialect::EmitPrefix::Both;
692 
693   // Whether to skip generating prefixed form for argument. This just does some
694   // basic checks.
695   //
696   // There are a little bit more invasive checks possible for cases where not
697   // all ops have the trait that would cause overlap. For many cases here,
698   // renaming would be better (e.g., we can only guard in limited manner against
699   // methods from traits and interfaces here, so avoiding these in op definition
700   // is safer).
701   auto skip = [&](StringRef newName) {
702     bool shouldSkip = newName == "getAttributeNames" ||
703                       newName == "getAttributes" || newName == "getOperation";
704     if (newName == "getOperands") {
705       // To reduce noise, skip generating the prefixed form and the warning if
706       // $operands correspond to single variadic argument.
707       if (op.getNumOperands() == 1 && op.getNumVariableLengthOperands() == 1)
708         return true;
709       shouldSkip = true;
710     }
711     if (newName == "getRegions") {
712       if (op.getNumRegions() == 1 && op.getNumVariadicRegions() == 1)
713         return true;
714       shouldSkip = true;
715     }
716     if (newName == "getType") {
717       if (op.getNumResults() == 0)
718         return false;
719       shouldSkip = true;
720     }
721     if (!shouldSkip)
722       return false;
723 
724     // This note could be avoided where the final function generated would
725     // have been identical. But preferably in the op definition avoiding using
726     // the generic name and then getting a more specialize type is better.
727     PrintNote(op.getLoc(),
728               "Skipping generation of prefixed accessor `" + newName +
729                   "` as it overlaps with default one; generating raw form (`" +
730                   name + "`) still");
731     return true;
732   };
733 
734   if (!prefix.empty()) {
735     names.push_back(
736         prefix + convertToCamelFromSnakeCase(name, /*capitalizeFirst=*/true));
737     // Skip cases which would overlap with default ones for now.
738     if (skip(names.back())) {
739       rawToo = true;
740       names.clear();
741     } else if (rawToo) {
742       LLVM_DEBUG(llvm::errs() << "WITH_GETTER(\"" << op.getQualCppClassName()
743                               << "::" << name << "\")\n"
744                               << "WITH_GETTER(\"" << op.getQualCppClassName()
745                               << "Adaptor::" << name << "\")\n";);
746     }
747   }
748 
749   if (prefix.empty() || rawToo)
750     names.push_back(name.str());
751   return names;
752 }
753 
754 SmallVector<std::string, 2> Operator::getGetterNames(StringRef name) const {
755   return getGetterOrSetterNames(/*isGetter=*/true, *this, name);
756 }
757 
758 SmallVector<std::string, 2> Operator::getSetterNames(StringRef name) const {
759   return getGetterOrSetterNames(/*isGetter=*/false, *this, name);
760 }
761