1 //===- PredicateTree.cpp - Predicate tree merging -------------------------===// 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 #include "PredicateTree.h" 10 #include "RootOrdering.h" 11 12 #include "mlir/Dialect/PDL/IR/PDL.h" 13 #include "mlir/Dialect/PDL/IR/PDLTypes.h" 14 #include "mlir/Dialect/PDLInterp/IR/PDLInterp.h" 15 #include "mlir/IR/BuiltinOps.h" 16 #include "mlir/Interfaces/InferTypeOpInterface.h" 17 #include "llvm/ADT/MapVector.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/TypeSwitch.h" 20 #include "llvm/Support/Debug.h" 21 #include <queue> 22 23 #define DEBUG_TYPE "pdl-predicate-tree" 24 25 using namespace mlir; 26 using namespace mlir::pdl_to_pdl_interp; 27 28 //===----------------------------------------------------------------------===// 29 // Predicate List Building 30 //===----------------------------------------------------------------------===// 31 32 static void getTreePredicates(std::vector<PositionalPredicate> &predList, 33 Value val, PredicateBuilder &builder, 34 DenseMap<Value, Position *> &inputs, 35 Position *pos); 36 37 /// Compares the depths of two positions. 38 static bool comparePosDepth(Position *lhs, Position *rhs) { 39 return lhs->getOperationDepth() < rhs->getOperationDepth(); 40 } 41 42 /// Returns the number of non-range elements within `values`. 43 static unsigned getNumNonRangeValues(ValueRange values) { 44 return llvm::count_if(values.getTypes(), 45 [](Type type) { return !isa<pdl::RangeType>(type); }); 46 } 47 48 static void getTreePredicates(std::vector<PositionalPredicate> &predList, 49 Value val, PredicateBuilder &builder, 50 DenseMap<Value, Position *> &inputs, 51 AttributePosition *pos) { 52 assert(isa<pdl::AttributeType>(val.getType()) && "expected attribute type"); 53 predList.emplace_back(pos, builder.getIsNotNull()); 54 55 if (auto attr = dyn_cast<pdl::AttributeOp>(val.getDefiningOp())) { 56 // If the attribute has a type or value, add a constraint. 57 if (Value type = attr.getValueType()) 58 getTreePredicates(predList, type, builder, inputs, builder.getType(pos)); 59 else if (Attribute value = attr.getValueAttr()) 60 predList.emplace_back(pos, builder.getAttributeConstraint(value)); 61 } 62 } 63 64 /// Collect all of the predicates for the given operand position. 65 static void getOperandTreePredicates(std::vector<PositionalPredicate> &predList, 66 Value val, PredicateBuilder &builder, 67 DenseMap<Value, Position *> &inputs, 68 Position *pos) { 69 Type valueType = val.getType(); 70 bool isVariadic = isa<pdl::RangeType>(valueType); 71 72 // If this is a typed operand, add a type constraint. 73 TypeSwitch<Operation *>(val.getDefiningOp()) 74 .Case<pdl::OperandOp, pdl::OperandsOp>([&](auto op) { 75 // Prevent traversal into a null value if the operand has a proper 76 // index. 77 if (std::is_same<pdl::OperandOp, decltype(op)>::value || 78 cast<OperandGroupPosition>(pos)->getOperandGroupNumber()) 79 predList.emplace_back(pos, builder.getIsNotNull()); 80 81 if (Value type = op.getValueType()) 82 getTreePredicates(predList, type, builder, inputs, 83 builder.getType(pos)); 84 }) 85 .Case<pdl::ResultOp, pdl::ResultsOp>([&](auto op) { 86 std::optional<unsigned> index = op.getIndex(); 87 88 // Prevent traversal into a null value if the result has a proper index. 89 if (index) 90 predList.emplace_back(pos, builder.getIsNotNull()); 91 92 // Get the parent operation of this operand. 93 OperationPosition *parentPos = builder.getOperandDefiningOp(pos); 94 predList.emplace_back(parentPos, builder.getIsNotNull()); 95 96 // Ensure that the operands match the corresponding results of the 97 // parent operation. 98 Position *resultPos = nullptr; 99 if (std::is_same<pdl::ResultOp, decltype(op)>::value) 100 resultPos = builder.getResult(parentPos, *index); 101 else 102 resultPos = builder.getResultGroup(parentPos, index, isVariadic); 103 predList.emplace_back(resultPos, builder.getEqualTo(pos)); 104 105 // Collect the predicates of the parent operation. 106 getTreePredicates(predList, op.getParent(), builder, inputs, 107 (Position *)parentPos); 108 }); 109 } 110 111 static void 112 getTreePredicates(std::vector<PositionalPredicate> &predList, Value val, 113 PredicateBuilder &builder, 114 DenseMap<Value, Position *> &inputs, OperationPosition *pos, 115 std::optional<unsigned> ignoreOperand = std::nullopt) { 116 assert(isa<pdl::OperationType>(val.getType()) && "expected operation"); 117 pdl::OperationOp op = cast<pdl::OperationOp>(val.getDefiningOp()); 118 OperationPosition *opPos = cast<OperationPosition>(pos); 119 120 // Ensure getDefiningOp returns a non-null operation. 121 if (!opPos->isRoot()) 122 predList.emplace_back(pos, builder.getIsNotNull()); 123 124 // Check that this is the correct root operation. 125 if (std::optional<StringRef> opName = op.getOpName()) 126 predList.emplace_back(pos, builder.getOperationName(*opName)); 127 128 // Check that the operation has the proper number of operands. If there are 129 // any variable length operands, we check a minimum instead of an exact count. 130 OperandRange operands = op.getOperandValues(); 131 unsigned minOperands = getNumNonRangeValues(operands); 132 if (minOperands != operands.size()) { 133 if (minOperands) 134 predList.emplace_back(pos, builder.getOperandCountAtLeast(minOperands)); 135 } else { 136 predList.emplace_back(pos, builder.getOperandCount(minOperands)); 137 } 138 139 // Check that the operation has the proper number of results. If there are 140 // any variable length results, we check a minimum instead of an exact count. 141 OperandRange types = op.getTypeValues(); 142 unsigned minResults = getNumNonRangeValues(types); 143 if (minResults == types.size()) 144 predList.emplace_back(pos, builder.getResultCount(types.size())); 145 else if (minResults) 146 predList.emplace_back(pos, builder.getResultCountAtLeast(minResults)); 147 148 // Recurse into any attributes, operands, or results. 149 for (auto [attrName, attr] : 150 llvm::zip(op.getAttributeValueNames(), op.getAttributeValues())) { 151 getTreePredicates( 152 predList, attr, builder, inputs, 153 builder.getAttribute(opPos, cast<StringAttr>(attrName).getValue())); 154 } 155 156 // Process the operands and results of the operation. For all values up to 157 // the first variable length value, we use the concrete operand/result 158 // number. After that, we use the "group" given that we can't know the 159 // concrete indices until runtime. If there is only one variadic operand 160 // group, we treat it as all of the operands/results of the operation. 161 /// Operands. 162 if (operands.size() == 1 && isa<pdl::RangeType>(operands[0].getType())) { 163 // Ignore the operands if we are performing an upward traversal (in that 164 // case, they have already been visited). 165 if (opPos->isRoot() || opPos->isOperandDefiningOp()) 166 getTreePredicates(predList, operands.front(), builder, inputs, 167 builder.getAllOperands(opPos)); 168 } else { 169 bool foundVariableLength = false; 170 for (const auto &operandIt : llvm::enumerate(operands)) { 171 bool isVariadic = isa<pdl::RangeType>(operandIt.value().getType()); 172 foundVariableLength |= isVariadic; 173 174 // Ignore the specified operand, usually because this position was 175 // visited in an upward traversal via an iterative choice. 176 if (ignoreOperand && *ignoreOperand == operandIt.index()) 177 continue; 178 179 Position *pos = 180 foundVariableLength 181 ? builder.getOperandGroup(opPos, operandIt.index(), isVariadic) 182 : builder.getOperand(opPos, operandIt.index()); 183 getTreePredicates(predList, operandIt.value(), builder, inputs, pos); 184 } 185 } 186 /// Results. 187 if (types.size() == 1 && isa<pdl::RangeType>(types[0].getType())) { 188 getTreePredicates(predList, types.front(), builder, inputs, 189 builder.getType(builder.getAllResults(opPos))); 190 return; 191 } 192 193 bool foundVariableLength = false; 194 for (auto [idx, typeValue] : llvm::enumerate(types)) { 195 bool isVariadic = isa<pdl::RangeType>(typeValue.getType()); 196 foundVariableLength |= isVariadic; 197 198 auto *resultPos = foundVariableLength 199 ? builder.getResultGroup(pos, idx, isVariadic) 200 : builder.getResult(pos, idx); 201 predList.emplace_back(resultPos, builder.getIsNotNull()); 202 getTreePredicates(predList, typeValue, builder, inputs, 203 builder.getType(resultPos)); 204 } 205 } 206 207 static void getTreePredicates(std::vector<PositionalPredicate> &predList, 208 Value val, PredicateBuilder &builder, 209 DenseMap<Value, Position *> &inputs, 210 TypePosition *pos) { 211 // Check for a constraint on a constant type. 212 if (pdl::TypeOp typeOp = val.getDefiningOp<pdl::TypeOp>()) { 213 if (Attribute type = typeOp.getConstantTypeAttr()) 214 predList.emplace_back(pos, builder.getTypeConstraint(type)); 215 } else if (pdl::TypesOp typeOp = val.getDefiningOp<pdl::TypesOp>()) { 216 if (Attribute typeAttr = typeOp.getConstantTypesAttr()) 217 predList.emplace_back(pos, builder.getTypeConstraint(typeAttr)); 218 } 219 } 220 221 /// Collect the tree predicates anchored at the given value. 222 static void getTreePredicates(std::vector<PositionalPredicate> &predList, 223 Value val, PredicateBuilder &builder, 224 DenseMap<Value, Position *> &inputs, 225 Position *pos) { 226 // Make sure this input value is accessible to the rewrite. 227 auto it = inputs.try_emplace(val, pos); 228 if (!it.second) { 229 // If this is an input value that has been visited in the tree, add a 230 // constraint to ensure that both instances refer to the same value. 231 if (isa<pdl::AttributeOp, pdl::OperandOp, pdl::OperandsOp, pdl::OperationOp, 232 pdl::TypeOp>(val.getDefiningOp())) { 233 auto minMaxPositions = 234 std::minmax(pos, it.first->second, comparePosDepth); 235 predList.emplace_back(minMaxPositions.second, 236 builder.getEqualTo(minMaxPositions.first)); 237 } 238 return; 239 } 240 241 TypeSwitch<Position *>(pos) 242 .Case<AttributePosition, OperationPosition, TypePosition>([&](auto *pos) { 243 getTreePredicates(predList, val, builder, inputs, pos); 244 }) 245 .Case<OperandPosition, OperandGroupPosition>([&](auto *pos) { 246 getOperandTreePredicates(predList, val, builder, inputs, pos); 247 }) 248 .Default([](auto *) { llvm_unreachable("unexpected position kind"); }); 249 } 250 251 static void getAttributePredicates(pdl::AttributeOp op, 252 std::vector<PositionalPredicate> &predList, 253 PredicateBuilder &builder, 254 DenseMap<Value, Position *> &inputs) { 255 Position *&attrPos = inputs[op]; 256 if (attrPos) 257 return; 258 Attribute value = op.getValueAttr(); 259 assert(value && "expected non-tree `pdl.attribute` to contain a value"); 260 attrPos = builder.getAttributeLiteral(value); 261 } 262 263 static void getConstraintPredicates(pdl::ApplyNativeConstraintOp op, 264 std::vector<PositionalPredicate> &predList, 265 PredicateBuilder &builder, 266 DenseMap<Value, Position *> &inputs) { 267 OperandRange arguments = op.getArgs(); 268 269 std::vector<Position *> allPositions; 270 allPositions.reserve(arguments.size()); 271 for (Value arg : arguments) 272 allPositions.push_back(inputs.lookup(arg)); 273 274 // Push the constraint to the furthest position. 275 Position *pos = *std::max_element(allPositions.begin(), allPositions.end(), 276 comparePosDepth); 277 ResultRange results = op.getResults(); 278 PredicateBuilder::Predicate pred = builder.getConstraint( 279 op.getName(), allPositions, SmallVector<Type>(results.getTypes()), 280 op.getIsNegated()); 281 282 // For each result register a position so it can be used later 283 for (auto [i, result] : llvm::enumerate(results)) { 284 ConstraintQuestion *q = cast<ConstraintQuestion>(pred.first); 285 ConstraintPosition *pos = builder.getConstraintPosition(q, i); 286 auto [it, inserted] = inputs.insert({result, pos}); 287 // If this is an input value that has been visited in the tree, add a 288 // constraint to ensure that both instances refer to the same value. 289 if (!inserted) { 290 auto minMaxPositions = 291 std::minmax<Position *>(pos, it->second, comparePosDepth); 292 predList.emplace_back(minMaxPositions.second, 293 builder.getEqualTo(minMaxPositions.first)); 294 } 295 } 296 predList.emplace_back(pos, pred); 297 } 298 299 static void getResultPredicates(pdl::ResultOp op, 300 std::vector<PositionalPredicate> &predList, 301 PredicateBuilder &builder, 302 DenseMap<Value, Position *> &inputs) { 303 Position *&resultPos = inputs[op]; 304 if (resultPos) 305 return; 306 307 // Ensure that the result isn't null. 308 auto *parentPos = cast<OperationPosition>(inputs.lookup(op.getParent())); 309 resultPos = builder.getResult(parentPos, op.getIndex()); 310 predList.emplace_back(resultPos, builder.getIsNotNull()); 311 } 312 313 static void getResultPredicates(pdl::ResultsOp op, 314 std::vector<PositionalPredicate> &predList, 315 PredicateBuilder &builder, 316 DenseMap<Value, Position *> &inputs) { 317 Position *&resultPos = inputs[op]; 318 if (resultPos) 319 return; 320 321 // Ensure that the result isn't null if the result has an index. 322 auto *parentPos = cast<OperationPosition>(inputs.lookup(op.getParent())); 323 bool isVariadic = isa<pdl::RangeType>(op.getType()); 324 std::optional<unsigned> index = op.getIndex(); 325 resultPos = builder.getResultGroup(parentPos, index, isVariadic); 326 if (index) 327 predList.emplace_back(resultPos, builder.getIsNotNull()); 328 } 329 330 static void getTypePredicates(Value typeValue, 331 function_ref<Attribute()> typeAttrFn, 332 PredicateBuilder &builder, 333 DenseMap<Value, Position *> &inputs) { 334 Position *&typePos = inputs[typeValue]; 335 if (typePos) 336 return; 337 Attribute typeAttr = typeAttrFn(); 338 assert(typeAttr && 339 "expected non-tree `pdl.type`/`pdl.types` to contain a value"); 340 typePos = builder.getTypeLiteral(typeAttr); 341 } 342 343 /// Collect all of the predicates that cannot be determined via walking the 344 /// tree. 345 static void getNonTreePredicates(pdl::PatternOp pattern, 346 std::vector<PositionalPredicate> &predList, 347 PredicateBuilder &builder, 348 DenseMap<Value, Position *> &inputs) { 349 for (Operation &op : pattern.getBodyRegion().getOps()) { 350 TypeSwitch<Operation *>(&op) 351 .Case([&](pdl::AttributeOp attrOp) { 352 getAttributePredicates(attrOp, predList, builder, inputs); 353 }) 354 .Case<pdl::ApplyNativeConstraintOp>([&](auto constraintOp) { 355 getConstraintPredicates(constraintOp, predList, builder, inputs); 356 }) 357 .Case<pdl::ResultOp, pdl::ResultsOp>([&](auto resultOp) { 358 getResultPredicates(resultOp, predList, builder, inputs); 359 }) 360 .Case([&](pdl::TypeOp typeOp) { 361 getTypePredicates( 362 typeOp, [&] { return typeOp.getConstantTypeAttr(); }, builder, 363 inputs); 364 }) 365 .Case([&](pdl::TypesOp typeOp) { 366 getTypePredicates( 367 typeOp, [&] { return typeOp.getConstantTypesAttr(); }, builder, 368 inputs); 369 }); 370 } 371 } 372 373 namespace { 374 375 /// An op accepting a value at an optional index. 376 struct OpIndex { 377 Value parent; 378 std::optional<unsigned> index; 379 }; 380 381 /// The parent and operand index of each operation for each root, stored 382 /// as a nested map [root][operation]. 383 using ParentMaps = DenseMap<Value, DenseMap<Value, OpIndex>>; 384 385 } // namespace 386 387 /// Given a pattern, determines the set of roots present in this pattern. 388 /// These are the operations whose results are not consumed by other operations. 389 static SmallVector<Value> detectRoots(pdl::PatternOp pattern) { 390 // First, collect all the operations that are used as operands 391 // to other operations. These are not roots by default. 392 DenseSet<Value> used; 393 for (auto operationOp : pattern.getBodyRegion().getOps<pdl::OperationOp>()) { 394 for (Value operand : operationOp.getOperandValues()) 395 TypeSwitch<Operation *>(operand.getDefiningOp()) 396 .Case<pdl::ResultOp, pdl::ResultsOp>( 397 [&used](auto resultOp) { used.insert(resultOp.getParent()); }); 398 } 399 400 // Remove the specified root from the use set, so that we can 401 // always select it as a root, even if it is used by other operations. 402 if (Value root = pattern.getRewriter().getRoot()) 403 used.erase(root); 404 405 // Finally, collect all the unused operations. 406 SmallVector<Value> roots; 407 for (Value operationOp : pattern.getBodyRegion().getOps<pdl::OperationOp>()) 408 if (!used.contains(operationOp)) 409 roots.push_back(operationOp); 410 411 return roots; 412 } 413 414 /// Given a list of candidate roots, builds the cost graph for connecting them. 415 /// The graph is formed by traversing the DAG of operations starting from each 416 /// root and marking the depth of each connector value (operand). Then we join 417 /// the candidate roots based on the common connector values, taking the one 418 /// with the minimum depth. Along the way, we compute, for each candidate root, 419 /// a mapping from each operation (in the DAG underneath this root) to its 420 /// parent operation and the corresponding operand index. 421 static void buildCostGraph(ArrayRef<Value> roots, RootOrderingGraph &graph, 422 ParentMaps &parentMaps) { 423 424 // The entry of a queue. The entry consists of the following items: 425 // * the value in the DAG underneath the root; 426 // * the parent of the value; 427 // * the operand index of the value in its parent; 428 // * the depth of the visited value. 429 struct Entry { 430 Entry(Value value, Value parent, std::optional<unsigned> index, 431 unsigned depth) 432 : value(value), parent(parent), index(index), depth(depth) {} 433 434 Value value; 435 Value parent; 436 std::optional<unsigned> index; 437 unsigned depth; 438 }; 439 440 // A root of a value and its depth (distance from root to the value). 441 struct RootDepth { 442 Value root; 443 unsigned depth = 0; 444 }; 445 446 // Map from candidate connector values to their roots and depths. Using a 447 // small vector with 1 entry because most values belong to a single root. 448 llvm::MapVector<Value, SmallVector<RootDepth, 1>> connectorsRootsDepths; 449 450 // Perform a breadth-first traversal of the op DAG rooted at each root. 451 for (Value root : roots) { 452 // The queue of visited values. A value may be present multiple times in 453 // the queue, for multiple parents. We only accept the first occurrence, 454 // which is guaranteed to have the lowest depth. 455 std::queue<Entry> toVisit; 456 toVisit.emplace(root, Value(), 0, 0); 457 458 // The map from value to its parent for the current root. 459 DenseMap<Value, OpIndex> &parentMap = parentMaps[root]; 460 461 while (!toVisit.empty()) { 462 Entry entry = toVisit.front(); 463 toVisit.pop(); 464 // Skip if already visited. 465 if (!parentMap.insert({entry.value, {entry.parent, entry.index}}).second) 466 continue; 467 468 // Mark the root and depth of the value. 469 connectorsRootsDepths[entry.value].push_back({root, entry.depth}); 470 471 // Traverse the operands of an operation and result ops. 472 // We intentionally do not traverse attributes and types, because those 473 // are expensive to join on. 474 TypeSwitch<Operation *>(entry.value.getDefiningOp()) 475 .Case<pdl::OperationOp>([&](auto operationOp) { 476 OperandRange operands = operationOp.getOperandValues(); 477 // Special case when we pass all the operands in one range. 478 // For those, the index is empty. 479 if (operands.size() == 1 && 480 isa<pdl::RangeType>(operands[0].getType())) { 481 toVisit.emplace(operands[0], entry.value, std::nullopt, 482 entry.depth + 1); 483 return; 484 } 485 486 // Default case: visit all the operands. 487 for (const auto &p : 488 llvm::enumerate(operationOp.getOperandValues())) 489 toVisit.emplace(p.value(), entry.value, p.index(), 490 entry.depth + 1); 491 }) 492 .Case<pdl::ResultOp, pdl::ResultsOp>([&](auto resultOp) { 493 toVisit.emplace(resultOp.getParent(), entry.value, 494 resultOp.getIndex(), entry.depth); 495 }); 496 } 497 } 498 499 // Now build the cost graph. 500 // This is simply a minimum over all depths for the target root. 501 unsigned nextID = 0; 502 for (const auto &connectorRootsDepths : connectorsRootsDepths) { 503 Value value = connectorRootsDepths.first; 504 ArrayRef<RootDepth> rootsDepths = connectorRootsDepths.second; 505 // If there is only one root for this value, this will not trigger 506 // any edges in the cost graph (a perf optimization). 507 if (rootsDepths.size() == 1) 508 continue; 509 510 for (const RootDepth &p : rootsDepths) { 511 for (const RootDepth &q : rootsDepths) { 512 if (&p == &q) 513 continue; 514 // Insert or retrieve the property of edge from p to q. 515 RootOrderingEntry &entry = graph[q.root][p.root]; 516 if (!entry.connector /* new edge */ || entry.cost.first > q.depth) { 517 if (!entry.connector) 518 entry.cost.second = nextID++; 519 entry.cost.first = q.depth; 520 entry.connector = value; 521 } 522 } 523 } 524 } 525 526 assert((llvm::hasSingleElement(roots) || graph.size() == roots.size()) && 527 "the pattern contains a candidate root disconnected from the others"); 528 } 529 530 /// Returns true if the operand at the given index needs to be queried using an 531 /// operand group, i.e., if it is variadic itself or follows a variadic operand. 532 static bool useOperandGroup(pdl::OperationOp op, unsigned index) { 533 OperandRange operands = op.getOperandValues(); 534 assert(index < operands.size() && "operand index out of range"); 535 for (unsigned i = 0; i <= index; ++i) 536 if (isa<pdl::RangeType>(operands[i].getType())) 537 return true; 538 return false; 539 } 540 541 /// Visit a node during upward traversal. 542 static void visitUpward(std::vector<PositionalPredicate> &predList, 543 OpIndex opIndex, PredicateBuilder &builder, 544 DenseMap<Value, Position *> &valueToPosition, 545 Position *&pos, unsigned rootID) { 546 Value value = opIndex.parent; 547 TypeSwitch<Operation *>(value.getDefiningOp()) 548 .Case<pdl::OperationOp>([&](auto operationOp) { 549 LLVM_DEBUG(llvm::dbgs() << " * Value: " << value << "\n"); 550 551 // Get users and iterate over them. 552 Position *usersPos = builder.getUsers(pos, /*useRepresentative=*/true); 553 Position *foreachPos = builder.getForEach(usersPos, rootID); 554 OperationPosition *opPos = builder.getPassthroughOp(foreachPos); 555 556 // Compare the operand(s) of the user against the input value(s). 557 Position *operandPos; 558 if (!opIndex.index) { 559 // We are querying all the operands of the operation. 560 operandPos = builder.getAllOperands(opPos); 561 } else if (useOperandGroup(operationOp, *opIndex.index)) { 562 // We are querying an operand group. 563 Type type = operationOp.getOperandValues()[*opIndex.index].getType(); 564 bool variadic = isa<pdl::RangeType>(type); 565 operandPos = builder.getOperandGroup(opPos, opIndex.index, variadic); 566 } else { 567 // We are querying an individual operand. 568 operandPos = builder.getOperand(opPos, *opIndex.index); 569 } 570 predList.emplace_back(operandPos, builder.getEqualTo(pos)); 571 572 // Guard against duplicate upward visits. These are not possible, 573 // because if this value was already visited, it would have been 574 // cheaper to start the traversal at this value rather than at the 575 // `connector`, violating the optimality of our spanning tree. 576 bool inserted = valueToPosition.try_emplace(value, opPos).second; 577 (void)inserted; 578 assert(inserted && "duplicate upward visit"); 579 580 // Obtain the tree predicates at the current value. 581 getTreePredicates(predList, value, builder, valueToPosition, opPos, 582 opIndex.index); 583 584 // Update the position 585 pos = opPos; 586 }) 587 .Case<pdl::ResultOp>([&](auto resultOp) { 588 // Traverse up an individual result. 589 auto *opPos = dyn_cast<OperationPosition>(pos); 590 assert(opPos && "operations and results must be interleaved"); 591 pos = builder.getResult(opPos, *opIndex.index); 592 593 // Insert the result position in case we have not visited it yet. 594 valueToPosition.try_emplace(value, pos); 595 }) 596 .Case<pdl::ResultsOp>([&](auto resultOp) { 597 // Traverse up a group of results. 598 auto *opPos = dyn_cast<OperationPosition>(pos); 599 assert(opPos && "operations and results must be interleaved"); 600 bool isVariadic = isa<pdl::RangeType>(value.getType()); 601 if (opIndex.index) 602 pos = builder.getResultGroup(opPos, opIndex.index, isVariadic); 603 else 604 pos = builder.getAllResults(opPos); 605 606 // Insert the result position in case we have not visited it yet. 607 valueToPosition.try_emplace(value, pos); 608 }); 609 } 610 611 /// Given a pattern operation, build the set of matcher predicates necessary to 612 /// match this pattern. 613 static Value buildPredicateList(pdl::PatternOp pattern, 614 PredicateBuilder &builder, 615 std::vector<PositionalPredicate> &predList, 616 DenseMap<Value, Position *> &valueToPosition) { 617 SmallVector<Value> roots = detectRoots(pattern); 618 619 // Build the root ordering graph and compute the parent maps. 620 RootOrderingGraph graph; 621 ParentMaps parentMaps; 622 buildCostGraph(roots, graph, parentMaps); 623 LLVM_DEBUG({ 624 llvm::dbgs() << "Graph:\n"; 625 for (auto &target : graph) { 626 llvm::dbgs() << " * " << target.first.getLoc() << " " << target.first 627 << "\n"; 628 for (auto &source : target.second) { 629 RootOrderingEntry &entry = source.second; 630 llvm::dbgs() << " <- " << source.first << ": " << entry.cost.first 631 << ":" << entry.cost.second << " via " 632 << entry.connector.getLoc() << "\n"; 633 } 634 } 635 }); 636 637 // Solve the optimal branching problem for each candidate root, or use the 638 // provided one. 639 Value bestRoot = pattern.getRewriter().getRoot(); 640 OptimalBranching::EdgeList bestEdges; 641 if (!bestRoot) { 642 unsigned bestCost = 0; 643 LLVM_DEBUG(llvm::dbgs() << "Candidate roots:\n"); 644 for (Value root : roots) { 645 OptimalBranching solver(graph, root); 646 unsigned cost = solver.solve(); 647 LLVM_DEBUG(llvm::dbgs() << " * " << root << ": " << cost << "\n"); 648 if (!bestRoot || bestCost > cost) { 649 bestCost = cost; 650 bestRoot = root; 651 bestEdges = solver.preOrderTraversal(roots); 652 } 653 } 654 } else { 655 OptimalBranching solver(graph, bestRoot); 656 solver.solve(); 657 bestEdges = solver.preOrderTraversal(roots); 658 } 659 660 // Print the best solution. 661 LLVM_DEBUG({ 662 llvm::dbgs() << "Best tree:\n"; 663 for (const std::pair<Value, Value> &edge : bestEdges) { 664 llvm::dbgs() << " * " << edge.first; 665 if (edge.second) 666 llvm::dbgs() << " <- " << edge.second; 667 llvm::dbgs() << "\n"; 668 } 669 }); 670 671 LLVM_DEBUG(llvm::dbgs() << "Calling key getTreePredicates:\n"); 672 LLVM_DEBUG(llvm::dbgs() << " * Value: " << bestRoot << "\n"); 673 674 // The best root is the starting point for the traversal. Get the tree 675 // predicates for the DAG rooted at bestRoot. 676 getTreePredicates(predList, bestRoot, builder, valueToPosition, 677 builder.getRoot()); 678 679 // Traverse the selected optimal branching. For all edges in order, traverse 680 // up starting from the connector, until the candidate root is reached, and 681 // call getTreePredicates at every node along the way. 682 for (const auto &it : llvm::enumerate(bestEdges)) { 683 Value target = it.value().first; 684 Value source = it.value().second; 685 686 // Check if we already visited the target root. This happens in two cases: 687 // 1) the initial root (bestRoot); 688 // 2) a root that is dominated by (contained in the subtree rooted at) an 689 // already visited root. 690 if (valueToPosition.count(target)) 691 continue; 692 693 // Determine the connector. 694 Value connector = graph[target][source].connector; 695 assert(connector && "invalid edge"); 696 LLVM_DEBUG(llvm::dbgs() << " * Connector: " << connector.getLoc() << "\n"); 697 DenseMap<Value, OpIndex> parentMap = parentMaps.lookup(target); 698 Position *pos = valueToPosition.lookup(connector); 699 assert(pos && "connector has not been traversed yet"); 700 701 // Traverse from the connector upwards towards the target root. 702 for (Value value = connector; value != target;) { 703 OpIndex opIndex = parentMap.lookup(value); 704 assert(opIndex.parent && "missing parent"); 705 visitUpward(predList, opIndex, builder, valueToPosition, pos, it.index()); 706 value = opIndex.parent; 707 } 708 } 709 710 getNonTreePredicates(pattern, predList, builder, valueToPosition); 711 712 return bestRoot; 713 } 714 715 //===----------------------------------------------------------------------===// 716 // Pattern Predicate Tree Merging 717 //===----------------------------------------------------------------------===// 718 719 namespace { 720 721 /// This class represents a specific predicate applied to a position, and 722 /// provides hashing and ordering operators. This class allows for computing a 723 /// frequence sum and ordering predicates based on a cost model. 724 struct OrderedPredicate { 725 OrderedPredicate(const std::pair<Position *, Qualifier *> &ip) 726 : position(ip.first), question(ip.second) {} 727 OrderedPredicate(const PositionalPredicate &ip) 728 : position(ip.position), question(ip.question) {} 729 730 /// The position this predicate is applied to. 731 Position *position; 732 733 /// The question that is applied by this predicate onto the position. 734 Qualifier *question; 735 736 /// The first and second order benefit sums. 737 /// The primary sum is the number of occurrences of this predicate among all 738 /// of the patterns. 739 unsigned primary = 0; 740 /// The secondary sum is a squared summation of the primary sum of all of the 741 /// predicates within each pattern that contains this predicate. This allows 742 /// for favoring predicates that are more commonly shared within a pattern, as 743 /// opposed to those shared across patterns. 744 unsigned secondary = 0; 745 746 /// The tie breaking ID, used to preserve a deterministic (insertion) order 747 /// among all the predicates with the same priority, depth, and position / 748 /// predicate dependency. 749 unsigned id = 0; 750 751 /// A map between a pattern operation and the answer to the predicate question 752 /// within that pattern. 753 DenseMap<Operation *, Qualifier *> patternToAnswer; 754 755 /// Returns true if this predicate is ordered before `rhs`, based on the cost 756 /// model. 757 bool operator<(const OrderedPredicate &rhs) const { 758 // Sort by: 759 // * higher first and secondary order sums 760 // * lower depth 761 // * lower position dependency 762 // * lower predicate dependency 763 // * lower tie breaking ID 764 auto *rhsPos = rhs.position; 765 return std::make_tuple(primary, secondary, rhsPos->getOperationDepth(), 766 rhsPos->getKind(), rhs.question->getKind(), rhs.id) > 767 std::make_tuple(rhs.primary, rhs.secondary, 768 position->getOperationDepth(), position->getKind(), 769 question->getKind(), id); 770 } 771 }; 772 773 /// A DenseMapInfo for OrderedPredicate based solely on the position and 774 /// question. 775 struct OrderedPredicateDenseInfo { 776 using Base = DenseMapInfo<std::pair<Position *, Qualifier *>>; 777 778 static OrderedPredicate getEmptyKey() { return Base::getEmptyKey(); } 779 static OrderedPredicate getTombstoneKey() { return Base::getTombstoneKey(); } 780 static bool isEqual(const OrderedPredicate &lhs, 781 const OrderedPredicate &rhs) { 782 return lhs.position == rhs.position && lhs.question == rhs.question; 783 } 784 static unsigned getHashValue(const OrderedPredicate &p) { 785 return llvm::hash_combine(p.position, p.question); 786 } 787 }; 788 789 /// This class wraps a set of ordered predicates that are used within a specific 790 /// pattern operation. 791 struct OrderedPredicateList { 792 OrderedPredicateList(pdl::PatternOp pattern, Value root) 793 : pattern(pattern), root(root) {} 794 795 pdl::PatternOp pattern; 796 Value root; 797 DenseSet<OrderedPredicate *> predicates; 798 }; 799 } // namespace 800 801 /// Returns true if the given matcher refers to the same predicate as the given 802 /// ordered predicate. This means that the position and questions of the two 803 /// match. 804 static bool isSamePredicate(MatcherNode *node, OrderedPredicate *predicate) { 805 return node->getPosition() == predicate->position && 806 node->getQuestion() == predicate->question; 807 } 808 809 /// Get or insert a child matcher for the given parent switch node, given a 810 /// predicate and parent pattern. 811 std::unique_ptr<MatcherNode> &getOrCreateChild(SwitchNode *node, 812 OrderedPredicate *predicate, 813 pdl::PatternOp pattern) { 814 assert(isSamePredicate(node, predicate) && 815 "expected matcher to equal the given predicate"); 816 817 auto it = predicate->patternToAnswer.find(pattern); 818 assert(it != predicate->patternToAnswer.end() && 819 "expected pattern to exist in predicate"); 820 return node->getChildren().insert({it->second, nullptr}).first->second; 821 } 822 823 /// Build the matcher CFG by "pushing" patterns through by sorted predicate 824 /// order. A pattern will traverse as far as possible using common predicates 825 /// and then either diverge from the CFG or reach the end of a branch and start 826 /// creating new nodes. 827 static void propagatePattern(std::unique_ptr<MatcherNode> &node, 828 OrderedPredicateList &list, 829 std::vector<OrderedPredicate *>::iterator current, 830 std::vector<OrderedPredicate *>::iterator end) { 831 if (current == end) { 832 // We've hit the end of a pattern, so create a successful result node. 833 node = 834 std::make_unique<SuccessNode>(list.pattern, list.root, std::move(node)); 835 836 // If the pattern doesn't contain this predicate, ignore it. 837 } else if (!list.predicates.contains(*current)) { 838 propagatePattern(node, list, std::next(current), end); 839 840 // If the current matcher node is invalid, create a new one for this 841 // position and continue propagation. 842 } else if (!node) { 843 // Create a new node at this position and continue 844 node = std::make_unique<SwitchNode>((*current)->position, 845 (*current)->question); 846 propagatePattern( 847 getOrCreateChild(cast<SwitchNode>(&*node), *current, list.pattern), 848 list, std::next(current), end); 849 850 // If the matcher has already been created, and it is for this predicate we 851 // continue propagation to the child. 852 } else if (isSamePredicate(node.get(), *current)) { 853 propagatePattern( 854 getOrCreateChild(cast<SwitchNode>(&*node), *current, list.pattern), 855 list, std::next(current), end); 856 857 // If the matcher doesn't match the current predicate, insert a branch as 858 // the common set of matchers has diverged. 859 } else { 860 propagatePattern(node->getFailureNode(), list, current, end); 861 } 862 } 863 864 /// Fold any switch nodes nested under `node` to boolean nodes when possible. 865 /// `node` is updated in-place if it is a switch. 866 static void foldSwitchToBool(std::unique_ptr<MatcherNode> &node) { 867 if (!node) 868 return; 869 870 if (SwitchNode *switchNode = dyn_cast<SwitchNode>(&*node)) { 871 SwitchNode::ChildMapT &children = switchNode->getChildren(); 872 for (auto &it : children) 873 foldSwitchToBool(it.second); 874 875 // If the node only contains one child, collapse it into a boolean predicate 876 // node. 877 if (children.size() == 1) { 878 auto *childIt = children.begin(); 879 node = std::make_unique<BoolNode>( 880 node->getPosition(), node->getQuestion(), childIt->first, 881 std::move(childIt->second), std::move(node->getFailureNode())); 882 } 883 } else if (BoolNode *boolNode = dyn_cast<BoolNode>(&*node)) { 884 foldSwitchToBool(boolNode->getSuccessNode()); 885 } 886 887 foldSwitchToBool(node->getFailureNode()); 888 } 889 890 /// Insert an exit node at the end of the failure path of the `root`. 891 static void insertExitNode(std::unique_ptr<MatcherNode> *root) { 892 while (*root) 893 root = &(*root)->getFailureNode(); 894 *root = std::make_unique<ExitNode>(); 895 } 896 897 /// Sorts the range begin/end with the partial order given by cmp. 898 template <typename Iterator, typename Compare> 899 static void stableTopologicalSort(Iterator begin, Iterator end, Compare cmp) { 900 while (begin != end) { 901 // Cannot compute sortBeforeOthers in the predicate of stable_partition 902 // because stable_partition will not keep the [begin, end) range intact 903 // while it runs. 904 llvm::SmallPtrSet<typename Iterator::value_type, 16> sortBeforeOthers; 905 for (auto i = begin; i != end; ++i) { 906 if (std::none_of(begin, end, [&](auto const &b) { return cmp(b, *i); })) 907 sortBeforeOthers.insert(*i); 908 } 909 910 auto const next = std::stable_partition(begin, end, [&](auto const &a) { 911 return sortBeforeOthers.contains(a); 912 }); 913 assert(next != begin && "not a partial ordering"); 914 begin = next; 915 } 916 } 917 918 /// Returns true if 'b' depends on a result of 'a'. 919 static bool dependsOn(OrderedPredicate *a, OrderedPredicate *b) { 920 auto *cqa = dyn_cast<ConstraintQuestion>(a->question); 921 if (!cqa) 922 return false; 923 924 auto positionDependsOnA = [&](Position *p) { 925 auto *cp = dyn_cast<ConstraintPosition>(p); 926 return cp && cp->getQuestion() == cqa; 927 }; 928 929 if (auto *cqb = dyn_cast<ConstraintQuestion>(b->question)) { 930 // Does any argument of b use a? 931 return llvm::any_of(cqb->getArgs(), positionDependsOnA); 932 } 933 if (auto *equalTo = dyn_cast<EqualToQuestion>(b->question)) { 934 return positionDependsOnA(b->position) || 935 positionDependsOnA(equalTo->getValue()); 936 } 937 return positionDependsOnA(b->position); 938 } 939 940 /// Given a module containing PDL pattern operations, generate a matcher tree 941 /// using the patterns within the given module and return the root matcher node. 942 std::unique_ptr<MatcherNode> 943 MatcherNode::generateMatcherTree(ModuleOp module, PredicateBuilder &builder, 944 DenseMap<Value, Position *> &valueToPosition) { 945 // The set of predicates contained within the pattern operations of the 946 // module. 947 struct PatternPredicates { 948 PatternPredicates(pdl::PatternOp pattern, Value root, 949 std::vector<PositionalPredicate> predicates) 950 : pattern(pattern), root(root), predicates(std::move(predicates)) {} 951 952 /// A pattern. 953 pdl::PatternOp pattern; 954 955 /// A root of the pattern chosen among the candidate roots in pdl.rewrite. 956 Value root; 957 958 /// The extracted predicates for this pattern and root. 959 std::vector<PositionalPredicate> predicates; 960 }; 961 962 SmallVector<PatternPredicates, 16> patternsAndPredicates; 963 for (pdl::PatternOp pattern : module.getOps<pdl::PatternOp>()) { 964 std::vector<PositionalPredicate> predicateList; 965 Value root = 966 buildPredicateList(pattern, builder, predicateList, valueToPosition); 967 patternsAndPredicates.emplace_back(pattern, root, std::move(predicateList)); 968 } 969 970 // Associate a pattern result with each unique predicate. 971 DenseSet<OrderedPredicate, OrderedPredicateDenseInfo> uniqued; 972 for (auto &patternAndPredList : patternsAndPredicates) { 973 for (auto &predicate : patternAndPredList.predicates) { 974 auto it = uniqued.insert(predicate); 975 it.first->patternToAnswer.try_emplace(patternAndPredList.pattern, 976 predicate.answer); 977 // Mark the insertion order (0-based indexing). 978 if (it.second) 979 it.first->id = uniqued.size() - 1; 980 } 981 } 982 983 // Associate each pattern to a set of its ordered predicates for later lookup. 984 std::vector<OrderedPredicateList> lists; 985 lists.reserve(patternsAndPredicates.size()); 986 for (auto &patternAndPredList : patternsAndPredicates) { 987 OrderedPredicateList list(patternAndPredList.pattern, 988 patternAndPredList.root); 989 for (auto &predicate : patternAndPredList.predicates) { 990 OrderedPredicate *orderedPredicate = &*uniqued.find(predicate); 991 list.predicates.insert(orderedPredicate); 992 993 // Increment the primary sum for each reference to a particular predicate. 994 ++orderedPredicate->primary; 995 } 996 lists.push_back(std::move(list)); 997 } 998 999 // For a particular pattern, get the total primary sum and add it to the 1000 // secondary sum of each predicate. Square the primary sums to emphasize 1001 // shared predicates within rather than across patterns. 1002 for (auto &list : lists) { 1003 unsigned total = 0; 1004 for (auto *predicate : list.predicates) 1005 total += predicate->primary * predicate->primary; 1006 for (auto *predicate : list.predicates) 1007 predicate->secondary += total; 1008 } 1009 1010 // Sort the set of predicates now that the cost primary and secondary sums 1011 // have been computed. 1012 std::vector<OrderedPredicate *> ordered; 1013 ordered.reserve(uniqued.size()); 1014 for (auto &ip : uniqued) 1015 ordered.push_back(&ip); 1016 llvm::sort(ordered, [](OrderedPredicate *lhs, OrderedPredicate *rhs) { 1017 return *lhs < *rhs; 1018 }); 1019 1020 // Mostly keep the now established order, but also ensure that 1021 // ConstraintQuestions come after the results they use. 1022 stableTopologicalSort(ordered.begin(), ordered.end(), dependsOn); 1023 1024 // Build the matchers for each of the pattern predicate lists. 1025 std::unique_ptr<MatcherNode> root; 1026 for (OrderedPredicateList &list : lists) 1027 propagatePattern(root, list, ordered.begin(), ordered.end()); 1028 1029 // Collapse the graph and insert the exit node. 1030 foldSwitchToBool(root); 1031 insertExitNode(&root); 1032 return root; 1033 } 1034 1035 //===----------------------------------------------------------------------===// 1036 // MatcherNode 1037 //===----------------------------------------------------------------------===// 1038 1039 MatcherNode::MatcherNode(TypeID matcherTypeID, Position *p, Qualifier *q, 1040 std::unique_ptr<MatcherNode> failureNode) 1041 : position(p), question(q), failureNode(std::move(failureNode)), 1042 matcherTypeID(matcherTypeID) {} 1043 1044 //===----------------------------------------------------------------------===// 1045 // BoolNode 1046 //===----------------------------------------------------------------------===// 1047 1048 BoolNode::BoolNode(Position *position, Qualifier *question, Qualifier *answer, 1049 std::unique_ptr<MatcherNode> successNode, 1050 std::unique_ptr<MatcherNode> failureNode) 1051 : MatcherNode(TypeID::get<BoolNode>(), position, question, 1052 std::move(failureNode)), 1053 answer(answer), successNode(std::move(successNode)) {} 1054 1055 //===----------------------------------------------------------------------===// 1056 // SuccessNode 1057 //===----------------------------------------------------------------------===// 1058 1059 SuccessNode::SuccessNode(pdl::PatternOp pattern, Value root, 1060 std::unique_ptr<MatcherNode> failureNode) 1061 : MatcherNode(TypeID::get<SuccessNode>(), /*position=*/nullptr, 1062 /*question=*/nullptr, std::move(failureNode)), 1063 pattern(pattern), root(root) {} 1064 1065 //===----------------------------------------------------------------------===// 1066 // SwitchNode 1067 //===----------------------------------------------------------------------===// 1068 1069 SwitchNode::SwitchNode(Position *position, Qualifier *question) 1070 : MatcherNode(TypeID::get<SwitchNode>(), position, question) {} 1071