Files
clang-p2996/mlir/lib/Conversion/PDLToPDLInterp/PredicateTree.h
River Riddle 8a1ca2cd34 [mlir] Add a conversion pass between PDL and the PDL Interpreter Dialect
The conversion between PDL and the interpreter is split into several different parts.
** The Matcher:

The matching section of all incoming pdl.pattern operations is converted into a predicate tree and merged. Each pattern is first converted into an ordered list of predicates starting from the root operation. A predicate is composed of three distinct parts:
* Position
  - A position refers to a specific location on the input DAG, i.e. an
    existing MLIR entity being matched. These can be attributes, operands,
    operations, results, and types. Each position also defines a relation to
    its parent. For example, the operand `[0] -> 1` has a parent operation
    position `[0]` (the root).
* Question
  - A question refers to a query on a specific positional value. For
  example, an operation name question checks the name of an operation
  position.
* Answer
  - An answer is the expected result of a question. For example, when
  matching an operation with the name "foo.op". The question would be an
  operation name question, with an expected answer of "foo.op".

After the predicate lists have been created and ordered(based on occurrence of common predicates and other factors), they are formed into a tree of nodes that represent the branching flow of a pattern match. This structure allows for efficient construction and merging of the input patterns. There are currently only 4 simple nodes in the tree:
* ExitNode: Represents the termination of a match
* SuccessNode: Represents a successful match of a specific pattern
* BoolNode/SwitchNode: Branch to a specific child node based on the expected answer to a predicate question.

Once the matcher tree has been generated, this tree is walked to generate the corresponding interpreter operations.

 ** The Rewriter:
The rewriter portion of a pattern is generated in a very straightforward manor, similarly to lowerings in other dialects. Each PDL operation that may exist within a rewrite has a mapping into the interpreter dialect. The code for the rewriter is generated within a FuncOp, that is invoked by the interpreter on a successful pattern match. Referenced values defined in the matcher become inputs the generated rewriter function.

An example lowering is shown below:

```mlir
// The following high level PDL pattern:
pdl.pattern : benefit(1) {
  %resultType = pdl.type
  %inputOperand = pdl.input
  %root, %results = pdl.operation "foo.op"(%inputOperand) -> %resultType
  pdl.rewrite %root {
    pdl.replace %root with (%inputOperand)
  }
}

// is lowered to the following:
module {
  // The matcher function takes the root operation as an input.
  func @matcher(%arg0: !pdl.operation) {
    pdl_interp.check_operation_name of %arg0 is "foo.op" -> ^bb2, ^bb1
  ^bb1:
    pdl_interp.return
  ^bb2:
    pdl_interp.check_operand_count of %arg0 is 1 -> ^bb3, ^bb1
  ^bb3:
    pdl_interp.check_result_count of %arg0 is 1 -> ^bb4, ^bb1
  ^bb4:
    %0 = pdl_interp.get_operand 0 of %arg0
    pdl_interp.is_not_null %0 : !pdl.value -> ^bb5, ^bb1
  ^bb5:
    %1 = pdl_interp.get_result 0 of %arg0
    pdl_interp.is_not_null %1 : !pdl.value -> ^bb6, ^bb1
  ^bb6:
    // This operation corresponds to a successful pattern match.
    pdl_interp.record_match @rewriters::@rewriter(%0, %arg0 : !pdl.value, !pdl.operation) : benefit(1), loc([%arg0]), root("foo.op") -> ^bb1
  }
  module @rewriters {
    // The inputs to the rewriter from the matcher are passed as arguments.
    func @rewriter(%arg0: !pdl.value, %arg1: !pdl.operation) {
      pdl_interp.replace %arg1 with(%arg0)
      pdl_interp.return
    }
  }
}
```

Differential Revision: https://reviews.llvm.org/D84580
2020-10-26 18:01:06 -07:00

201 lines
7.2 KiB
C++

//===- PredicateTree.h - Predicate tree node definitions --------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains definitions for nodes of a tree structure for representing
// the general control flow within a pattern match.
//
//===----------------------------------------------------------------------===//
#ifndef MLIR_LIB_CONVERSION_PDLTOPDLINTERP_PREDICATETREE_H_
#define MLIR_LIB_CONVERSION_PDLTOPDLINTERP_PREDICATETREE_H_
#include "Predicate.h"
#include "mlir/Dialect/PDL/IR/PDL.h"
#include "llvm/ADT/MapVector.h"
namespace mlir {
namespace pdl_to_pdl_interp {
class MatcherNode;
/// A PositionalPredicate is a predicate that is associated with a specific
/// positional value.
struct PositionalPredicate {
PositionalPredicate(Position *pos,
const PredicateBuilder::Predicate &predicate)
: position(pos), question(predicate.first), answer(predicate.second) {}
/// The position the predicate is applied to.
Position *position;
/// The question that the predicate applies.
Qualifier *question;
/// The expected answer of the predicate.
Qualifier *answer;
};
//===----------------------------------------------------------------------===//
// MatcherNode
//===----------------------------------------------------------------------===//
/// This class represents the base of a predicate matcher node.
class MatcherNode {
public:
virtual ~MatcherNode() = default;
/// Given a module containing PDL pattern operations, generate a matcher tree
/// using the patterns within the given module and return the root matcher
/// node. `valueToPosition` is a map that is populated with the original
/// pdl values and their corresponding positions in the matcher tree.
static std::unique_ptr<MatcherNode>
generateMatcherTree(ModuleOp module, PredicateBuilder &builder,
DenseMap<Value, Position *> &valueToPosition);
/// Returns the position on which the question predicate should be checked.
Position *getPosition() const { return position; }
/// Returns the predicate checked on this node.
Qualifier *getQuestion() const { return question; }
/// Returns the node that should be visited if this, or a subsequent node
/// fails.
std::unique_ptr<MatcherNode> &getFailureNode() { return failureNode; }
/// Sets the node that should be visited if this, or a subsequent node fails.
void setFailureNode(std::unique_ptr<MatcherNode> node) {
failureNode = std::move(node);
}
/// Returns the unique type ID of this matcher instance. This should not be
/// used directly, and is provided to support type casting.
TypeID getMatcherTypeID() const { return matcherTypeID; }
protected:
MatcherNode(TypeID matcherTypeID, Position *position = nullptr,
Qualifier *question = nullptr,
std::unique_ptr<MatcherNode> failureNode = nullptr);
private:
/// The position on which the predicate should be checked.
Position *position;
/// The predicate that is checked on the given position.
Qualifier *question;
/// The node to visit if this node fails.
std::unique_ptr<MatcherNode> failureNode;
/// An owning store for the failure node if it is owned by this node.
std::unique_ptr<MatcherNode> failureNodeStorage;
/// A unique identifier for the derived matcher node, used for type casting.
TypeID matcherTypeID;
};
//===----------------------------------------------------------------------===//
// BoolNode
/// A BoolNode denotes a question with a boolean-like result. These nodes branch
/// to a single node on a successful result, otherwise defaulting to the failure
/// node.
struct BoolNode : public MatcherNode {
BoolNode(Position *position, Qualifier *question, Qualifier *answer,
std::unique_ptr<MatcherNode> successNode,
std::unique_ptr<MatcherNode> failureNode = nullptr);
/// Returns if the given matcher node is an instance of this class, used to
/// support type casting.
static bool classof(const MatcherNode *node) {
return node->getMatcherTypeID() == TypeID::get<BoolNode>();
}
/// Returns the expected answer of this boolean node.
Qualifier *getAnswer() const { return answer; }
/// Returns the node that should be visited on success.
std::unique_ptr<MatcherNode> &getSuccessNode() { return successNode; }
private:
/// The expected answer of this boolean node.
Qualifier *answer;
/// The next node if this node succeeds. Otherwise, go to the failure node.
std::unique_ptr<MatcherNode> successNode;
};
//===----------------------------------------------------------------------===//
// ExitNode
/// An ExitNode is a special sentinel node that denotes the end of matcher.
struct ExitNode : public MatcherNode {
ExitNode() : MatcherNode(TypeID::get<ExitNode>()) {}
/// Returns if the given matcher node is an instance of this class, used to
/// support type casting.
static bool classof(const MatcherNode *node) {
return node->getMatcherTypeID() == TypeID::get<ExitNode>();
}
};
//===----------------------------------------------------------------------===//
// SuccessNode
/// A SuccessNode denotes that a given high level pattern has successfully been
/// matched. This does not terminate the matcher, as there may be multiple
/// successful matches.
struct SuccessNode : public MatcherNode {
explicit SuccessNode(pdl::PatternOp pattern,
std::unique_ptr<MatcherNode> failureNode);
/// Returns if the given matcher node is an instance of this class, used to
/// support type casting.
static bool classof(const MatcherNode *node) {
return node->getMatcherTypeID() == TypeID::get<SuccessNode>();
}
/// Return the high level pattern operation that is matched with this node.
pdl::PatternOp getPattern() const { return pattern; }
private:
/// The high level pattern operation that was successfully matched with this
/// node.
pdl::PatternOp pattern;
};
//===----------------------------------------------------------------------===//
// SwitchNode
/// A SwitchNode denotes a question with multiple potential results. These nodes
/// branch to a specific node based on the result of the question.
struct SwitchNode : public MatcherNode {
SwitchNode(Position *position, Qualifier *question);
/// Returns if the given matcher node is an instance of this class, used to
/// support type casting.
static bool classof(const MatcherNode *node) {
return node->getMatcherTypeID() == TypeID::get<SwitchNode>();
}
/// Returns the children of this switch node. The children are contained
/// within a mapping between the various case answers to destination matcher
/// nodes.
using ChildMapT = llvm::MapVector<Qualifier *, std::unique_ptr<MatcherNode>>;
ChildMapT &getChildren() { return children; }
private:
/// Switch predicate "answers" select the child. Answers that are not found
/// default to the failure node.
ChildMapT children;
};
} // end namespace pdl_to_pdl_interp
} // end namespace mlir
#endif // MLIR_CONVERSION_PDLTOPDLINTERP_PREDICATETREE_H_