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("predExpr"); 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 auto pos = rootNode->expr.find(subst.first); 154 while (pos != std::string::npos) { 155 rootNode->expr.replace(pos, subst.first.size(), subst.second); 156 // Skip the newly inserted substring, which itself may consider the 157 // pattern to match. 158 pos += subst.second.size(); 159 // Find the next possible match position. 160 pos = rootNode->expr.find(subst.first, pos); 161 } 162 } 163 return rootNode; 164 } 165 166 // If the current combined predicate is a leaf substitution, append it to the 167 // list before contiuing. 168 auto allSubstitutions = llvm::to_vector<4>(substitutions); 169 if (rootNode->kind == PredCombinerKind::SubstLeaves) { 170 const auto &substPred = static_cast<const tblgen::SubstLeavesPred &>(root); 171 allSubstitutions.push_back( 172 {substPred.getPattern(), substPred.getReplacement()}); 173 } 174 175 // Build child subtrees. 176 auto combined = static_cast<const tblgen::CombinedPred &>(root); 177 for (const auto *record : combined.getChildren()) { 178 auto childTree = 179 buildPredicateTree(tblgen::Pred(record), allocator, allSubstitutions); 180 rootNode->children.push_back(childTree); 181 } 182 return rootNode; 183 } 184 185 // Simplify a predicate tree rooted at "node" using the predicates that are 186 // known to be true(false). For AND(OR) combined predicates, if any of the 187 // children is known to be false(true), the result is also false(true). 188 // Furthermore, for AND(OR) combined predicates, children that are known to be 189 // true(false) don't have to be checked dynamically. 190 static PredNode *propagateGroundTruth( 191 PredNode *node, const llvm::SmallPtrSetImpl<tblgen::Pred *> &knownTruePreds, 192 const llvm::SmallPtrSetImpl<tblgen::Pred *> &knownFalsePreds) { 193 // If the current predicate is known to be true or false, change the kind of 194 // the node and return immediately. 195 if (knownTruePreds.count(node->predicate) != 0) { 196 node->kind = PredCombinerKind::True; 197 node->children.clear(); 198 return node; 199 } 200 if (knownFalsePreds.count(node->predicate) != 0) { 201 node->kind = PredCombinerKind::False; 202 node->children.clear(); 203 return node; 204 } 205 206 // If the current node is a substitution, stop recursion now. 207 // The expressions in the leaves below this node were rewritten, but the nodes 208 // still point to the original predicate records. While the original 209 // predicate may be known to be true or false, it is not necessarily the case 210 // after rewriting. 211 // TODO(zinenko,jpienaar): we can support ground truth for rewritten 212 // predicates by either (a) having our own unique'ing of the predicates 213 // instead of relying on TableGen record pointers or (b) taking ground truth 214 // values optinally prefixed with a list of substitutions to apply, e.g. 215 // "predX is true by itself as well as predSubY leaf substitution had been 216 // applied to it". 217 if (node->kind == PredCombinerKind::SubstLeaves) { 218 return node; 219 } 220 221 // Otherwise, look at child nodes. 222 223 // Move child nodes into some local variable so that they can be optimized 224 // separately and re-added if necessary. 225 llvm::SmallVector<PredNode *, 4> children; 226 std::swap(node->children, children); 227 228 for (auto &child : children) { 229 // First, simplify the child. This maintains the predicate as it was. 230 auto simplifiedChild = 231 propagateGroundTruth(child, knownTruePreds, knownFalsePreds); 232 233 // Just add the child if we don't know how to simplify the current node. 234 if (node->kind != PredCombinerKind::And && 235 node->kind != PredCombinerKind::Or) { 236 node->children.push_back(simplifiedChild); 237 continue; 238 } 239 240 // Second, based on the type define which known values of child predicates 241 // immediately collapse this predicate to a known value, and which others 242 // may be safely ignored. 243 // OR(..., True, ...) = True 244 // OR(..., False, ...) = OR(..., ...) 245 // AND(..., False, ...) = False 246 // AND(..., True, ...) = AND(..., ...) 247 auto collapseKind = node->kind == PredCombinerKind::And 248 ? PredCombinerKind::False 249 : PredCombinerKind::True; 250 auto eraseKind = node->kind == PredCombinerKind::And 251 ? PredCombinerKind::True 252 : PredCombinerKind::False; 253 const auto &collapseList = 254 node->kind == PredCombinerKind::And ? knownFalsePreds : knownTruePreds; 255 const auto &eraseList = 256 node->kind == PredCombinerKind::And ? knownTruePreds : knownFalsePreds; 257 if (simplifiedChild->kind == collapseKind || 258 collapseList.count(simplifiedChild->predicate) != 0) { 259 node->kind = collapseKind; 260 node->children.clear(); 261 return node; 262 } else if (simplifiedChild->kind == eraseKind || 263 eraseList.count(simplifiedChild->predicate) != 0) { 264 continue; 265 } 266 node->children.push_back(simplifiedChild); 267 } 268 return node; 269 } 270 271 // Combine a list of predicate expressions using a binary combiner. If a list 272 // is empty, return "init". 273 static std::string combineBinary(ArrayRef<std::string> children, 274 std::string combiner, std::string init) { 275 if (children.empty()) 276 return init; 277 278 auto size = children.size(); 279 if (size == 1) 280 return children.front(); 281 282 std::string str; 283 llvm::raw_string_ostream os(str); 284 os << '(' << children.front() << ')'; 285 for (unsigned i = 1; i < size; ++i) { 286 os << ' ' << combiner << " (" << children[i] << ')'; 287 } 288 return os.str(); 289 } 290 291 // Prepend negation to the only condition in the predicate expression list. 292 static std::string combineNot(ArrayRef<std::string> children) { 293 assert(children.size() == 1 && "expected exactly one child predicate of Neg"); 294 return (Twine("!(") + children.front() + Twine(')')).str(); 295 } 296 297 // Recursively traverse the predicate tree in depth-first post-order and build 298 // the final expression. 299 static std::string getCombinedCondition(const PredNode &root) { 300 // Immediately return for non-combiner predicates that don't have children. 301 if (root.kind == PredCombinerKind::Leaf) 302 return root.expr; 303 if (root.kind == PredCombinerKind::True) 304 return "true"; 305 if (root.kind == PredCombinerKind::False) 306 return "false"; 307 308 // Recurse into children. 309 llvm::SmallVector<std::string, 4> childExpressions; 310 childExpressions.reserve(root.children.size()); 311 for (const auto &child : root.children) 312 childExpressions.push_back(getCombinedCondition(*child)); 313 314 // Combine the expressions based on the predicate node kind. 315 if (root.kind == PredCombinerKind::And) 316 return combineBinary(childExpressions, "&&", "true"); 317 if (root.kind == PredCombinerKind::Or) 318 return combineBinary(childExpressions, "||", "false"); 319 if (root.kind == PredCombinerKind::Not) 320 return combineNot(childExpressions); 321 322 // Substitutions were applied before so just ignore them. 323 if (root.kind == PredCombinerKind::SubstLeaves) { 324 assert(childExpressions.size() == 1 && 325 "substitution predicate must have one child"); 326 return childExpressions[0]; 327 } 328 329 llvm::PrintFatalError(root.predicate->getLoc(), "unsupported predicate kind"); 330 } 331 332 std::string tblgen::CombinedPred::getConditionImpl() const { 333 llvm::BumpPtrAllocator allocator; 334 auto predicateTree = buildPredicateTree(*this, allocator, {}); 335 predicateTree = propagateGroundTruth( 336 predicateTree, 337 /*knownTruePreds=*/llvm::SmallPtrSet<tblgen::Pred *, 2>(), 338 /*knownFalsePreds=*/llvm::SmallPtrSet<tblgen::Pred *, 2>()); 339 340 return getCombinedCondition(*predicateTree); 341 } 342 343 StringRef tblgen::SubstLeavesPred::getPattern() const { 344 return def->getValueAsString("pattern"); 345 } 346 347 StringRef tblgen::SubstLeavesPred::getReplacement() const { 348 return def->getValueAsString("replacement"); 349 } 350