1//===----------------------------------------------------------------------===//
2// DuckDB
3//
4// duckdb/optimizer/cse_optimizer.hpp
5//
6//
7//===----------------------------------------------------------------------===//
8
9#pragma once
10
11#include "duckdb/optimizer/rule.hpp"
12#include "duckdb/parser/expression_map.hpp"
13#include "duckdb/planner/logical_operator_visitor.hpp"
14
15namespace duckdb {
16class Binder;
17struct CSEReplacementState;
18
19//! The CommonSubExpression optimizer traverses the expressions of a LogicalOperator to look for duplicate expressions
20//! if there are any, it pushes a projection under the operator that resolves these expressions
21class CommonSubExpressionOptimizer : public LogicalOperatorVisitor {
22public:
23 explicit CommonSubExpressionOptimizer(Binder &binder) : binder(binder) {
24 }
25
26public:
27 void VisitOperator(LogicalOperator &op) override;
28
29private:
30 //! First iteration: count how many times each expression occurs
31 void CountExpressions(Expression &expr, CSEReplacementState &state);
32 //! Second iteration: perform the actual replacement of the duplicate expressions with common subexpressions nodes
33 void PerformCSEReplacement(unique_ptr<Expression> &expr, CSEReplacementState &state);
34
35 //! Main method to extract common subexpressions
36 void ExtractCommonSubExpresions(LogicalOperator &op);
37
38private:
39 Binder &binder;
40};
41} // namespace duckdb
42