1 //===- Pattern.cpp - Pattern wrapper class --------------------------------===//
2 //
3 // Copyright 2019 The MLIR Authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //   http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 // =============================================================================
17 //
18 // Pattern wrapper class to simplify using TableGen Record defining a MLIR
19 // Pattern.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "mlir/TableGen/Pattern.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/FormatVariadic.h"
27 #include "llvm/TableGen/Error.h"
28 #include "llvm/TableGen/Record.h"
29 
30 #define DEBUG_TYPE "mlir-tblgen-pattern"
31 
32 using namespace mlir;
33 
34 using llvm::formatv;
35 using mlir::tblgen::Operator;
36 
37 //===----------------------------------------------------------------------===//
38 // DagLeaf
39 //===----------------------------------------------------------------------===//
40 
41 bool tblgen::DagLeaf::isUnspecified() const {
42   return dyn_cast_or_null<llvm::UnsetInit>(def);
43 }
44 
45 bool tblgen::DagLeaf::isOperandMatcher() const {
46   // Operand matchers specify a type constraint.
47   return isSubClassOf("TypeConstraint");
48 }
49 
50 bool tblgen::DagLeaf::isAttrMatcher() const {
51   // Attribute matchers specify an attribute constraint.
52   return isSubClassOf("AttrConstraint");
53 }
54 
55 bool tblgen::DagLeaf::isNativeCodeCall() const {
56   return isSubClassOf("NativeCodeCall");
57 }
58 
59 bool tblgen::DagLeaf::isConstantAttr() const {
60   return isSubClassOf("ConstantAttr");
61 }
62 
63 bool tblgen::DagLeaf::isEnumAttrCase() const {
64   return isSubClassOf("EnumAttrCaseInfo");
65 }
66 
67 tblgen::Constraint tblgen::DagLeaf::getAsConstraint() const {
68   assert((isOperandMatcher() || isAttrMatcher()) &&
69          "the DAG leaf must be operand or attribute");
70   return Constraint(cast<llvm::DefInit>(def)->getDef());
71 }
72 
73 tblgen::ConstantAttr tblgen::DagLeaf::getAsConstantAttr() const {
74   assert(isConstantAttr() && "the DAG leaf must be constant attribute");
75   return ConstantAttr(cast<llvm::DefInit>(def));
76 }
77 
78 tblgen::EnumAttrCase tblgen::DagLeaf::getAsEnumAttrCase() const {
79   assert(isEnumAttrCase() && "the DAG leaf must be an enum attribute case");
80   return EnumAttrCase(cast<llvm::DefInit>(def));
81 }
82 
83 std::string tblgen::DagLeaf::getConditionTemplate() const {
84   return getAsConstraint().getConditionTemplate();
85 }
86 
87 llvm::StringRef tblgen::DagLeaf::getNativeCodeTemplate() const {
88   assert(isNativeCodeCall() && "the DAG leaf must be NativeCodeCall");
89   return cast<llvm::DefInit>(def)->getDef()->getValueAsString("expression");
90 }
91 
92 bool tblgen::DagLeaf::isSubClassOf(StringRef superclass) const {
93   if (auto *defInit = dyn_cast_or_null<llvm::DefInit>(def))
94     return defInit->getDef()->isSubClassOf(superclass);
95   return false;
96 }
97 
98 void tblgen::DagLeaf::print(raw_ostream &os) const {
99   if (def)
100     def->print(os);
101 }
102 
103 //===----------------------------------------------------------------------===//
104 // DagNode
105 //===----------------------------------------------------------------------===//
106 
107 bool tblgen::DagNode::isNativeCodeCall() const {
108   if (auto *defInit = dyn_cast_or_null<llvm::DefInit>(node->getOperator()))
109     return defInit->getDef()->isSubClassOf("NativeCodeCall");
110   return false;
111 }
112 
113 bool tblgen::DagNode::isOperation() const {
114   return !(isNativeCodeCall() || isReplaceWithValue());
115 }
116 
117 llvm::StringRef tblgen::DagNode::getNativeCodeTemplate() const {
118   assert(isNativeCodeCall() && "the DAG leaf must be NativeCodeCall");
119   return cast<llvm::DefInit>(node->getOperator())
120       ->getDef()
121       ->getValueAsString("expression");
122 }
123 
124 llvm::StringRef tblgen::DagNode::getSymbol() const {
125   return node->getNameStr();
126 }
127 
128 Operator &tblgen::DagNode::getDialectOp(RecordOperatorMap *mapper) const {
129   llvm::Record *opDef = cast<llvm::DefInit>(node->getOperator())->getDef();
130   auto it = mapper->find(opDef);
131   if (it != mapper->end())
132     return *it->second;
133   return *mapper->try_emplace(opDef, std::make_unique<Operator>(opDef))
134               .first->second;
135 }
136 
137 int tblgen::DagNode::getNumOps() const {
138   int count = isReplaceWithValue() ? 0 : 1;
139   for (int i = 0, e = getNumArgs(); i != e; ++i) {
140     if (auto child = getArgAsNestedDag(i))
141       count += child.getNumOps();
142   }
143   return count;
144 }
145 
146 int tblgen::DagNode::getNumArgs() const { return node->getNumArgs(); }
147 
148 bool tblgen::DagNode::isNestedDagArg(unsigned index) const {
149   return isa<llvm::DagInit>(node->getArg(index));
150 }
151 
152 tblgen::DagNode tblgen::DagNode::getArgAsNestedDag(unsigned index) const {
153   return DagNode(dyn_cast_or_null<llvm::DagInit>(node->getArg(index)));
154 }
155 
156 tblgen::DagLeaf tblgen::DagNode::getArgAsLeaf(unsigned index) const {
157   assert(!isNestedDagArg(index));
158   return DagLeaf(node->getArg(index));
159 }
160 
161 StringRef tblgen::DagNode::getArgName(unsigned index) const {
162   return node->getArgNameStr(index);
163 }
164 
165 bool tblgen::DagNode::isReplaceWithValue() const {
166   auto *dagOpDef = cast<llvm::DefInit>(node->getOperator())->getDef();
167   return dagOpDef->getName() == "replaceWithValue";
168 }
169 
170 void tblgen::DagNode::print(raw_ostream &os) const {
171   if (node)
172     node->print(os);
173 }
174 
175 //===----------------------------------------------------------------------===//
176 // SymbolInfoMap
177 //===----------------------------------------------------------------------===//
178 
179 StringRef tblgen::SymbolInfoMap::getValuePackName(StringRef symbol,
180                                                   int *index) {
181   StringRef name, indexStr;
182   int idx = -1;
183   std::tie(name, indexStr) = symbol.rsplit("__");
184 
185   if (indexStr.consumeInteger(10, idx)) {
186     // The second part is not an index; we return the whole symbol as-is.
187     return symbol;
188   }
189   if (index) {
190     *index = idx;
191   }
192   return name;
193 }
194 
195 tblgen::SymbolInfoMap::SymbolInfo::SymbolInfo(const Operator *op,
196                                               SymbolInfo::Kind kind,
197                                               Optional<int> index)
198     : op(op), kind(kind), argIndex(index) {}
199 
200 int tblgen::SymbolInfoMap::SymbolInfo::getStaticValueCount() const {
201   switch (kind) {
202   case Kind::Attr:
203   case Kind::Operand:
204   case Kind::Value:
205     return 1;
206   case Kind::Result:
207     return op->getNumResults();
208   }
209   llvm_unreachable("unknown kind");
210 }
211 
212 std::string
213 tblgen::SymbolInfoMap::SymbolInfo::getVarDecl(StringRef name) const {
214   switch (kind) {
215   case Kind::Attr: {
216     auto type =
217         op->getArg(*argIndex).get<NamedAttribute *>()->attr.getStorageType();
218     return formatv("{0} {1};\n", type, name);
219   }
220   case Kind::Operand: {
221     // Use operand range for captured operands (to support potential variadic
222     // operands).
223     return formatv("Operation::operand_range {0}(op0->getOperands());\n", name);
224   }
225   case Kind::Value: {
226     return formatv("ArrayRef<Value *> {0};\n", name);
227   }
228   case Kind::Result: {
229     // Use the op itself for captured results.
230     return formatv("{0} {1};\n", op->getQualCppClassName(), name);
231   }
232   }
233   llvm_unreachable("unknown kind");
234 }
235 
236 std::string tblgen::SymbolInfoMap::SymbolInfo::getValueAndRangeUse(
237     StringRef name, int index, const char *fmt, const char *separator) const {
238   LLVM_DEBUG(llvm::dbgs() << "getValueAndRangeUse for '" << name << "': ");
239   switch (kind) {
240   case Kind::Attr: {
241     assert(index < 0);
242     auto repl = formatv(fmt, name);
243     LLVM_DEBUG(llvm::dbgs() << repl << " (Attr)\n");
244     return repl;
245   }
246   case Kind::Operand: {
247     assert(index < 0);
248     auto *operand = op->getArg(*argIndex).get<NamedTypeConstraint *>();
249     // If this operand is variadic, then return a range. Otherwise, return the
250     // value itself.
251     if (operand->isVariadic()) {
252       auto repl = formatv(fmt, name);
253       LLVM_DEBUG(llvm::dbgs() << repl << " (VariadicOperand)\n");
254       return repl;
255     }
256     auto repl = formatv(fmt, formatv("(*{0}.begin())", name));
257     LLVM_DEBUG(llvm::dbgs() << repl << " (SingleOperand)\n");
258     return repl;
259   }
260   case Kind::Result: {
261     // If `index` is greater than zero, then we are referencing a specific
262     // result of a multi-result op. The result can still be variadic.
263     if (index >= 0) {
264       std::string v = formatv("{0}.getODSResults({1})", name, index);
265       if (!op->getResult(index).isVariadic())
266         v = formatv("(*{0}.begin())", v);
267       auto repl = formatv(fmt, v);
268       LLVM_DEBUG(llvm::dbgs() << repl << " (SingleResult)\n");
269       return repl;
270     }
271 
272     // If this op has no result at all but still we bind a symbol to it, it
273     // means we want to capture the op itself.
274     if (op->getNumResults() == 0) {
275       LLVM_DEBUG(llvm::dbgs() << name << " (Op)\n");
276       return name;
277     }
278 
279     // We are referencing all results of the multi-result op. A specific result
280     // can either be a value or a range. Then join them with `separator`.
281     SmallVector<std::string, 4> values;
282     values.reserve(op->getNumResults());
283 
284     for (int i = 0, e = op->getNumResults(); i < e; ++i) {
285       std::string v = formatv("{0}.getODSResults({1})", name, i);
286       if (!op->getResult(i).isVariadic()) {
287         v = formatv("(*{0}.begin())", v);
288       }
289       values.push_back(formatv(fmt, v));
290     }
291     auto repl = llvm::join(values, separator);
292     LLVM_DEBUG(llvm::dbgs() << repl << " (VariadicResult)\n");
293     return repl;
294   }
295   case Kind::Value: {
296     assert(index < 0);
297     assert(op == nullptr);
298     auto repl = formatv(fmt, name);
299     LLVM_DEBUG(llvm::dbgs() << repl << " (Value)\n");
300     return repl;
301   }
302   }
303   llvm_unreachable("unknown kind");
304 }
305 
306 std::string tblgen::SymbolInfoMap::SymbolInfo::getAllRangeUse(
307     StringRef name, int index, const char *fmt, const char *separator) const {
308   LLVM_DEBUG(llvm::dbgs() << "getAllRangeUse for '" << name << "': ");
309   switch (kind) {
310   case Kind::Attr:
311   case Kind::Operand: {
312     assert(index < 0 && "only allowed for symbol bound to result");
313     auto repl = formatv(fmt, name);
314     LLVM_DEBUG(llvm::dbgs() << repl << " (Operand/Attr)\n");
315     return repl;
316   }
317   case Kind::Result: {
318     if (index >= 0) {
319       auto repl = formatv(fmt, formatv("{0}.getODSResults({1})", name, index));
320       LLVM_DEBUG(llvm::dbgs() << repl << " (SingleResult)\n");
321       return repl;
322     }
323 
324     // We are referencing all results of the multi-result op. Each result should
325     // have a value range, and then join them with `separator`.
326     SmallVector<std::string, 4> values;
327     values.reserve(op->getNumResults());
328 
329     for (int i = 0, e = op->getNumResults(); i < e; ++i) {
330       values.push_back(
331           formatv(fmt, formatv("{0}.getODSResults({1})", name, i)));
332     }
333     auto repl = llvm::join(values, separator);
334     LLVM_DEBUG(llvm::dbgs() << repl << " (VariadicResult)\n");
335     return repl;
336   }
337   case Kind::Value: {
338     assert(index < 0 && "only allowed for symbol bound to result");
339     assert(op == nullptr);
340     auto repl = formatv(fmt, formatv("{{{0}}", name));
341     LLVM_DEBUG(llvm::dbgs() << repl << " (Value)\n");
342     return repl;
343   }
344   }
345   llvm_unreachable("unknown kind");
346 }
347 
348 bool tblgen::SymbolInfoMap::bindOpArgument(StringRef symbol, const Operator &op,
349                                            int argIndex) {
350   StringRef name = getValuePackName(symbol);
351   if (name != symbol) {
352     auto error = formatv(
353         "symbol '{0}' with trailing index cannot bind to op argument", symbol);
354     PrintFatalError(loc, error);
355   }
356 
357   auto symInfo = op.getArg(argIndex).is<NamedAttribute *>()
358                      ? SymbolInfo::getAttr(&op, argIndex)
359                      : SymbolInfo::getOperand(&op, argIndex);
360 
361   return symbolInfoMap.insert({symbol, symInfo}).second;
362 }
363 
364 bool tblgen::SymbolInfoMap::bindOpResult(StringRef symbol, const Operator &op) {
365   StringRef name = getValuePackName(symbol);
366   return symbolInfoMap.insert({name, SymbolInfo::getResult(&op)}).second;
367 }
368 
369 bool tblgen::SymbolInfoMap::bindValue(StringRef symbol) {
370   return symbolInfoMap.insert({symbol, SymbolInfo::getValue()}).second;
371 }
372 
373 bool tblgen::SymbolInfoMap::contains(StringRef symbol) const {
374   return find(symbol) != symbolInfoMap.end();
375 }
376 
377 tblgen::SymbolInfoMap::const_iterator
378 tblgen::SymbolInfoMap::find(StringRef key) const {
379   StringRef name = getValuePackName(key);
380   return symbolInfoMap.find(name);
381 }
382 
383 int tblgen::SymbolInfoMap::getStaticValueCount(StringRef symbol) const {
384   StringRef name = getValuePackName(symbol);
385   if (name != symbol) {
386     // If there is a trailing index inside symbol, it references just one
387     // static value.
388     return 1;
389   }
390   // Otherwise, find how many it represents by querying the symbol's info.
391   return find(name)->getValue().getStaticValueCount();
392 }
393 
394 std::string
395 tblgen::SymbolInfoMap::getValueAndRangeUse(StringRef symbol, const char *fmt,
396                                            const char *separator) const {
397   int index = -1;
398   StringRef name = getValuePackName(symbol, &index);
399 
400   auto it = symbolInfoMap.find(name);
401   if (it == symbolInfoMap.end()) {
402     auto error = formatv("referencing unbound symbol '{0}'", symbol);
403     PrintFatalError(loc, error);
404   }
405 
406   return it->getValue().getValueAndRangeUse(name, index, fmt, separator);
407 }
408 
409 std::string tblgen::SymbolInfoMap::getAllRangeUse(StringRef symbol,
410                                                   const char *fmt,
411                                                   const char *separator) const {
412   int index = -1;
413   StringRef name = getValuePackName(symbol, &index);
414 
415   auto it = symbolInfoMap.find(name);
416   if (it == symbolInfoMap.end()) {
417     auto error = formatv("referencing unbound symbol '{0}'", symbol);
418     PrintFatalError(loc, error);
419   }
420 
421   return it->getValue().getAllRangeUse(name, index, fmt, separator);
422 }
423 
424 //===----------------------------------------------------------------------===//
425 // Pattern
426 //==----------------------------------------------------------------------===//
427 
428 tblgen::Pattern::Pattern(const llvm::Record *def, RecordOperatorMap *mapper)
429     : def(*def), recordOpMap(mapper) {}
430 
431 tblgen::DagNode tblgen::Pattern::getSourcePattern() const {
432   return tblgen::DagNode(def.getValueAsDag("sourcePattern"));
433 }
434 
435 int tblgen::Pattern::getNumResultPatterns() const {
436   auto *results = def.getValueAsListInit("resultPatterns");
437   return results->size();
438 }
439 
440 tblgen::DagNode tblgen::Pattern::getResultPattern(unsigned index) const {
441   auto *results = def.getValueAsListInit("resultPatterns");
442   return tblgen::DagNode(cast<llvm::DagInit>(results->getElement(index)));
443 }
444 
445 void tblgen::Pattern::collectSourcePatternBoundSymbols(
446     tblgen::SymbolInfoMap &infoMap) {
447   LLVM_DEBUG(llvm::dbgs() << "start collecting source pattern bound symbols\n");
448   collectBoundSymbols(getSourcePattern(), infoMap, /*isSrcPattern=*/true);
449   LLVM_DEBUG(llvm::dbgs() << "done collecting source pattern bound symbols\n");
450 }
451 
452 void tblgen::Pattern::collectResultPatternBoundSymbols(
453     tblgen::SymbolInfoMap &infoMap) {
454   LLVM_DEBUG(llvm::dbgs() << "start collecting result pattern bound symbols\n");
455   for (int i = 0, e = getNumResultPatterns(); i < e; ++i) {
456     auto pattern = getResultPattern(i);
457     collectBoundSymbols(pattern, infoMap, /*isSrcPattern=*/false);
458   }
459   LLVM_DEBUG(llvm::dbgs() << "done collecting result pattern bound symbols\n");
460 }
461 
462 const tblgen::Operator &tblgen::Pattern::getSourceRootOp() {
463   return getSourcePattern().getDialectOp(recordOpMap);
464 }
465 
466 tblgen::Operator &tblgen::Pattern::getDialectOp(DagNode node) {
467   return node.getDialectOp(recordOpMap);
468 }
469 
470 std::vector<tblgen::AppliedConstraint> tblgen::Pattern::getConstraints() const {
471   auto *listInit = def.getValueAsListInit("constraints");
472   std::vector<tblgen::AppliedConstraint> ret;
473   ret.reserve(listInit->size());
474 
475   for (auto it : *listInit) {
476     auto *dagInit = dyn_cast<llvm::DagInit>(it);
477     if (!dagInit)
478       PrintFatalError(def.getLoc(), "all elements in Pattern multi-entity "
479                                     "constraints should be DAG nodes");
480 
481     std::vector<std::string> entities;
482     entities.reserve(dagInit->arg_size());
483     for (auto *argName : dagInit->getArgNames())
484       entities.push_back(argName->getValue());
485 
486     ret.emplace_back(cast<llvm::DefInit>(dagInit->getOperator())->getDef(),
487                      dagInit->getNameStr(), std::move(entities));
488   }
489   return ret;
490 }
491 
492 int tblgen::Pattern::getBenefit() const {
493   // The initial benefit value is a heuristic with number of ops in the source
494   // pattern.
495   int initBenefit = getSourcePattern().getNumOps();
496   llvm::DagInit *delta = def.getValueAsDag("benefitDelta");
497   if (delta->getNumArgs() != 1 || !isa<llvm::IntInit>(delta->getArg(0))) {
498     PrintFatalError(def.getLoc(),
499                     "The 'addBenefit' takes and only takes one integer value");
500   }
501   return initBenefit + dyn_cast<llvm::IntInit>(delta->getArg(0))->getValue();
502 }
503 
504 std::vector<tblgen::Pattern::IdentifierLine>
505 tblgen::Pattern::getLocation() const {
506   std::vector<std::pair<StringRef, unsigned>> result;
507   result.reserve(def.getLoc().size());
508   for (auto loc : def.getLoc()) {
509     unsigned buf = llvm::SrcMgr.FindBufferContainingLoc(loc);
510     assert(buf && "invalid source location");
511     result.emplace_back(
512         llvm::SrcMgr.getBufferInfo(buf).Buffer->getBufferIdentifier(),
513         llvm::SrcMgr.getLineAndColumn(loc, buf).first);
514   }
515   return result;
516 }
517 
518 void tblgen::Pattern::collectBoundSymbols(DagNode tree, SymbolInfoMap &infoMap,
519                                           bool isSrcPattern) {
520   auto treeName = tree.getSymbol();
521   if (!tree.isOperation()) {
522     if (!treeName.empty()) {
523       PrintFatalError(
524           def.getLoc(),
525           formatv("binding symbol '{0}' to non-operation unsupported right now",
526                   treeName));
527     }
528     return;
529   }
530 
531   auto &op = getDialectOp(tree);
532   auto numOpArgs = op.getNumArgs();
533   auto numTreeArgs = tree.getNumArgs();
534 
535   if (numOpArgs != numTreeArgs) {
536     auto err = formatv("op '{0}' argument number mismatch: "
537                        "{1} in pattern vs. {2} in definition",
538                        op.getOperationName(), numTreeArgs, numOpArgs);
539     PrintFatalError(def.getLoc(), err);
540   }
541 
542   // The name attached to the DAG node's operator is for representing the
543   // results generated from this op. It should be remembered as bound results.
544   if (!treeName.empty()) {
545     LLVM_DEBUG(llvm::dbgs()
546                << "found symbol bound to op result: " << treeName << '\n');
547     if (!infoMap.bindOpResult(treeName, op))
548       PrintFatalError(def.getLoc(),
549                       formatv("symbol '{0}' bound more than once", treeName));
550   }
551 
552   for (int i = 0; i != numTreeArgs; ++i) {
553     if (auto treeArg = tree.getArgAsNestedDag(i)) {
554       // This DAG node argument is a DAG node itself. Go inside recursively.
555       collectBoundSymbols(treeArg, infoMap, isSrcPattern);
556     } else if (isSrcPattern) {
557       // We can only bind symbols to op arguments in source pattern. Those
558       // symbols are referenced in result patterns.
559       auto treeArgName = tree.getArgName(i);
560       if (!treeArgName.empty()) {
561         LLVM_DEBUG(llvm::dbgs() << "found symbol bound to op argument: "
562                                 << treeArgName << '\n');
563         if (!infoMap.bindOpArgument(treeArgName, op, i)) {
564           auto err = formatv("symbol '{0}' bound more than once", treeArgName);
565           PrintFatalError(def.getLoc(), err);
566         }
567       }
568     }
569   }
570 }
571