1 //===- Predicate.cpp - Predicate 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 // Wrapper around predicates defined in TableGen.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "mlir/TableGen/Predicate.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/FormatVariadic.h"
27 #include "llvm/TableGen/Error.h"
28 #include "llvm/TableGen/Record.h"
29 
30 using namespace mlir;
31 
32 // Construct a Predicate from a record.
33 tblgen::Pred::Pred(const llvm::Record *record) : def(record) {
34   assert(def->isSubClassOf("Pred") &&
35          "must be a subclass of TableGen 'Pred' class");
36 }
37 
38 // Construct a Predicate from an initializer.
39 tblgen::Pred::Pred(const llvm::Init *init) : def(nullptr) {
40   if (const auto *defInit = dyn_cast_or_null<llvm::DefInit>(init))
41     def = defInit->getDef();
42 }
43 
44 std::string tblgen::Pred::getCondition() const {
45   // Static dispatch to subclasses.
46   if (def->isSubClassOf("CombinedPred"))
47     return static_cast<const CombinedPred *>(this)->getConditionImpl();
48   if (def->isSubClassOf("CPred"))
49     return static_cast<const CPred *>(this)->getConditionImpl();
50   llvm_unreachable("Pred::getCondition must be overridden in subclasses");
51 }
52 
53 bool tblgen::Pred::isCombined() const {
54   return def && def->isSubClassOf("CombinedPred");
55 }
56 
57 ArrayRef<llvm::SMLoc> tblgen::Pred::getLoc() const { return def->getLoc(); }
58 
59 tblgen::CPred::CPred(const llvm::Record *record) : Pred(record) {
60   assert(def->isSubClassOf("CPred") &&
61          "must be a subclass of Tablegen 'CPred' class");
62 }
63 
64 tblgen::CPred::CPred(const llvm::Init *init) : Pred(init) {
65   assert((!def || def->isSubClassOf("CPred")) &&
66          "must be a subclass of Tablegen 'CPred' class");
67 }
68 
69 // Get condition of the C Predicate.
70 std::string tblgen::CPred::getConditionImpl() const {
71   assert(!isNull() && "null predicate does not have a condition");
72   return def->getValueAsString("predCall");
73 }
74 
75 tblgen::CombinedPred::CombinedPred(const llvm::Record *record) : Pred(record) {
76   assert(def->isSubClassOf("CombinedPred") &&
77          "must be a subclass of Tablegen 'CombinedPred' class");
78 }
79 
80 tblgen::CombinedPred::CombinedPred(const llvm::Init *init) : Pred(init) {
81   assert((!def || def->isSubClassOf("CombinedPred")) &&
82          "must be a subclass of Tablegen 'CombinedPred' class");
83 }
84 
85 const llvm::Record *tblgen::CombinedPred::getCombinerDef() const {
86   assert(def->getValue("kind") && "CombinedPred must have a value 'kind'");
87   return def->getValueAsDef("kind");
88 }
89 
90 const std::vector<llvm::Record *> tblgen::CombinedPred::getChildren() const {
91   assert(def->getValue("children") &&
92          "CombinedPred must have a value 'children'");
93   return def->getValueAsListOfDefs("children");
94 }
95 
96 namespace {
97 // Kinds of nodes in a logical predicate tree.
98 enum class PredCombinerKind {
99   Leaf,
100   And,
101   Or,
102   Not,
103   SubstLeaves,
104   // Special kinds that are used in simplification.
105   False,
106   True
107 };
108 
109 // A node in a logical predicate tree.
110 struct PredNode {
111   PredCombinerKind kind;
112   const tblgen::Pred *predicate;
113   SmallVector<PredNode *, 4> children;
114   std::string expr;
115 };
116 } // end anonymous namespace
117 
118 // Get a predicate tree node kind based on the kind used in the predicate
119 // TableGen record.
120 static PredCombinerKind getPredCombinerKind(const tblgen::Pred &pred) {
121   if (!pred.isCombined())
122     return PredCombinerKind::Leaf;
123 
124   const auto &combinedPred = static_cast<const tblgen::CombinedPred &>(pred);
125   return llvm::StringSwitch<PredCombinerKind>(
126              combinedPred.getCombinerDef()->getName())
127       .Case("PredCombinerAnd", PredCombinerKind::And)
128       .Case("PredCombinerOr", PredCombinerKind::Or)
129       .Case("PredCombinerNot", PredCombinerKind::Not)
130       .Case("PredCombinerSubstLeaves", PredCombinerKind::SubstLeaves);
131 }
132 
133 namespace {
134 // Substitution<pattern, replacement>.
135 using Subst = std::pair<StringRef, StringRef>;
136 } // end anonymous namespace
137 
138 // Build the predicate tree starting from the top-level predicate, which may
139 // have children, and perform leaf substitutions inplace.  Note that after
140 // substitution, nodes are still pointing to the original TableGen record.
141 // All nodes are created within "allocator".
142 static PredNode *buildPredicateTree(const tblgen::Pred &root,
143                                     llvm::BumpPtrAllocator &allocator,
144                                     ArrayRef<Subst> substitutions) {
145   auto *rootNode = allocator.Allocate<PredNode>();
146   new (rootNode) PredNode;
147   rootNode->kind = getPredCombinerKind(root);
148   rootNode->predicate = &root;
149   if (!root.isCombined()) {
150     rootNode->expr = root.getCondition();
151     // Apply all parent substitutions from innermost to outermost.
152     for (const auto &subst : llvm::reverse(substitutions)) {
153       size_t start = 0;
154       while (auto pos =
155                  rootNode->expr.find(subst.first, start) != std::string::npos) {
156         rootNode->expr.replace(pos, subst.first.size(), subst.second);
157         start = pos + subst.second.size();
158       }
159     }
160     return rootNode;
161   }
162 
163   // If the current combined predicate is a leaf substitution, append it to the
164   // list before contiuing.
165   auto allSubstitutions = llvm::to_vector<4>(substitutions);
166   if (rootNode->kind == PredCombinerKind::SubstLeaves) {
167     const auto &substPred = static_cast<const tblgen::SubstLeavesPred &>(root);
168     allSubstitutions.push_back(
169         {substPred.getPattern(), substPred.getReplacement()});
170   }
171 
172   // Build child subtrees.
173   auto combined = static_cast<const tblgen::CombinedPred &>(root);
174   for (const auto *record : combined.getChildren()) {
175     auto childTree =
176         buildPredicateTree(tblgen::Pred(record), allocator, allSubstitutions);
177     rootNode->children.push_back(childTree);
178   }
179   return rootNode;
180 }
181 
182 // Simplify a predicate tree rooted at "node" using the predicates that are
183 // known to be true(false).  For AND(OR) combined predicates, if any of the
184 // children is known to be false(true), the result is also false(true).
185 // Furthermore, for AND(OR) combined predicates, children that are known to be
186 // true(false) don't have to be checked dynamically.
187 static PredNode *propagateGroundTruth(
188     PredNode *node, const llvm::SmallPtrSetImpl<tblgen::Pred *> &knownTruePreds,
189     const llvm::SmallPtrSetImpl<tblgen::Pred *> &knownFalsePreds) {
190   // If the current predicate is known to be true or false, change the kind of
191   // the node and return immediately.
192   if (knownTruePreds.count(node->predicate) != 0) {
193     node->kind = PredCombinerKind::True;
194     node->children.clear();
195     return node;
196   }
197   if (knownFalsePreds.count(node->predicate) != 0) {
198     node->kind = PredCombinerKind::False;
199     node->children.clear();
200     return node;
201   }
202 
203   // If the current node is a substitution, stop recursion now.
204   // The expressions in the leaves below this node were rewritten, but the nodes
205   // still point to the original predicate records.  While the original
206   // predicate may be known to be true or false, it is not necessarily the case
207   // after rewriting.
208   // TODO(zinenko,jpienaar): we can support ground truth for rewritten
209   // predicates by either (a) having our own unique'ing of the predicates
210   // instead of relying on TableGen record pointers or (b) taking ground truth
211   // values optinally prefixed with a list of substitutions to apply, e.g.
212   // "predX is true by itself as well as predSubY leaf substitution had been
213   // applied to it".
214   if (node->kind == PredCombinerKind::SubstLeaves) {
215     return node;
216   }
217 
218   // Otherwise, look at child nodes.
219 
220   // Move child nodes into some local variable so that they can be optimized
221   // separately and re-added if necessary.
222   llvm::SmallVector<PredNode *, 4> children;
223   std::swap(node->children, children);
224 
225   for (auto &child : children) {
226     // First, simplify the child.  This maintains the predicate as it was.
227     auto simplifiedChild =
228         propagateGroundTruth(child, knownTruePreds, knownFalsePreds);
229 
230     // Just add the child if we don't know how to simplify the current node.
231     if (node->kind != PredCombinerKind::And &&
232         node->kind != PredCombinerKind::Or) {
233       node->children.push_back(simplifiedChild);
234       continue;
235     }
236 
237     // Second, based on the type define which known values of child predicates
238     // immediately collapse this predicate to a known value, and which others
239     // may be safely ignored.
240     //   OR(..., True, ...) = True
241     //   OR(..., False, ...) = OR(..., ...)
242     //   AND(..., False, ...) = False
243     //   AND(..., True, ...) = AND(..., ...)
244     auto collapseKind = node->kind == PredCombinerKind::And
245                             ? PredCombinerKind::False
246                             : PredCombinerKind::True;
247     auto eraseKind = node->kind == PredCombinerKind::And
248                          ? PredCombinerKind::True
249                          : PredCombinerKind::False;
250     const auto &collapseList =
251         node->kind == PredCombinerKind::And ? knownFalsePreds : knownTruePreds;
252     const auto &eraseList =
253         node->kind == PredCombinerKind::And ? knownTruePreds : knownFalsePreds;
254     if (simplifiedChild->kind == collapseKind ||
255         collapseList.count(simplifiedChild->predicate) != 0) {
256       node->kind = collapseKind;
257       node->children.clear();
258       return node;
259     } else if (simplifiedChild->kind == eraseKind ||
260                eraseList.count(simplifiedChild->predicate) != 0) {
261       continue;
262     }
263     node->children.push_back(simplifiedChild);
264   }
265   return node;
266 }
267 
268 // Combine a list of predicate expressions using a binary combiner.  If a list
269 // is empty, return "init".
270 static std::string combineBinary(ArrayRef<std::string> children,
271                                  std::string combiner, std::string init) {
272   if (children.empty())
273     return init;
274 
275   auto size = children.size();
276   if (size == 1)
277     return children.front();
278 
279   std::string str;
280   llvm::raw_string_ostream os(str);
281   os << '(' << children.front() << ')';
282   for (unsigned i = 1; i < size; ++i) {
283     os << ' ' << combiner << " (" << children[i] << ')';
284   }
285   return os.str();
286 }
287 
288 // Prepend negation to the only condition in the predicate expression list.
289 static std::string combineNot(ArrayRef<std::string> children) {
290   assert(children.size() == 1 && "expected exactly one child predicate of Neg");
291   return (Twine("!(") + children.front() + Twine(')')).str();
292 }
293 
294 // Recursively traverse the predicate tree in depth-first post-order and build
295 // the final expression.
296 static std::string getCombinedCondition(const PredNode &root) {
297   // Immediately return for non-combiner predicates that don't have children.
298   if (root.kind == PredCombinerKind::Leaf)
299     return root.expr;
300   if (root.kind == PredCombinerKind::True)
301     return "true";
302   if (root.kind == PredCombinerKind::False)
303     return "false";
304 
305   // Recurse into children.
306   llvm::SmallVector<std::string, 4> childExpressions;
307   childExpressions.reserve(root.children.size());
308   for (const auto &child : root.children)
309     childExpressions.push_back(getCombinedCondition(*child));
310 
311   // Combine the expressions based on the predicate node kind.
312   if (root.kind == PredCombinerKind::And)
313     return combineBinary(childExpressions, "&&", "true");
314   if (root.kind == PredCombinerKind::Or)
315     return combineBinary(childExpressions, "||", "false");
316   if (root.kind == PredCombinerKind::Not)
317     return combineNot(childExpressions);
318 
319   // Substitutions were applied before so just ignore them.
320   if (root.kind == PredCombinerKind::SubstLeaves) {
321     assert(childExpressions.size() == 1 &&
322            "substitution predicate must have one child");
323     return childExpressions[0];
324   }
325 
326   llvm::PrintFatalError(root.predicate->getLoc(), "unsupported predicate kind");
327 }
328 
329 std::string tblgen::CombinedPred::getConditionImpl() const {
330   llvm::BumpPtrAllocator allocator;
331   auto predicateTree = buildPredicateTree(*this, allocator, {});
332   predicateTree = propagateGroundTruth(
333       predicateTree,
334       /*knownTruePreds=*/llvm::SmallPtrSet<tblgen::Pred *, 2>(),
335       /*knownFalsePreds=*/llvm::SmallPtrSet<tblgen::Pred *, 2>());
336 
337   return getCombinedCondition(*predicateTree);
338 }
339 
340 StringRef tblgen::SubstLeavesPred::getPattern() const {
341   return def->getValueAsString("pattern");
342 }
343 
344 StringRef tblgen::SubstLeavesPred::getReplacement() const {
345   return def->getValueAsString("replacement");
346 }
347