-
Notifications
You must be signed in to change notification settings - Fork 38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add control-flow based optimizer passes #1697
Draft
bbannier
wants to merge
6
commits into
main
Choose a base branch
from
topic/bbannier/cfg
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
868b941
Add mising base class specifier.
bbannier 7260cb9
Add class to compute control flow graphs for blocks.
bbannier 23dbdd9
Compute CFGs for top-level blocks.
bbannier d3d7794
Add helper function to get all CFG nodes without incoming edges.
bbannier d32b642
Add optimizer pass removing unreachable code.
bbannier 610def0
Remove unused `nodeTag` method.
bbannier File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
// Copyright (c) 2020-2023 by the Zeek Project. See LICENSE for details. | ||
|
||
#pragma once | ||
|
||
#include <cstdint> | ||
#include <memory> | ||
#include <string> | ||
#include <type_traits> | ||
#include <unordered_set> | ||
#include <utility> | ||
|
||
#include <hilti/ast/ast-context.h> | ||
#include <hilti/ast/node.h> | ||
|
||
#include <CXXGraph/CXXGraph.hpp> | ||
|
||
namespace hilti { | ||
|
||
// Needed for CXXGraph, but left unimplemented. | ||
std::istream& operator>>(std::istream&, Node*); | ||
|
||
namespace node::tag { | ||
enum : uint16_t { | ||
MetaNode = 10000, | ||
Start, | ||
End, | ||
Flow, | ||
}; | ||
} | ||
|
||
namespace detail::cfg { | ||
struct MetaNode : Node { | ||
MetaNode(node::Tags node_tags) : Node(nullptr, node_tags, {}, {}) {} | ||
HILTI_NODE_0(MetaNode, override); | ||
}; | ||
|
||
// A meta node for the start of a control flow. | ||
struct Start : MetaNode { | ||
Start() : MetaNode(NodeTags) {} | ||
HILTI_NODE_1(Start, MetaNode, final); | ||
}; | ||
|
||
// A meta node for the end of a control flow. | ||
struct End : MetaNode { | ||
End() : MetaNode(NodeTags) {} | ||
HILTI_NODE_1(End, MetaNode, final); | ||
}; | ||
|
||
// A meta node joining or splitting control flow with no matching source statement. | ||
struct Flow : MetaNode { | ||
Flow() : MetaNode(NodeTags) {} | ||
HILTI_NODE_1(Flow, MetaNode, final); | ||
}; | ||
|
||
class CFG { | ||
public: | ||
using N = Node*; | ||
using NodeP = std::shared_ptr<const CXXGraph::Node<N>>; | ||
|
||
CFG(const N& root); | ||
|
||
|
||
template<typename T, typename = std::enable_if_t<std::is_base_of_v<MetaNode, T>>> | ||
N create_meta_node() { | ||
auto n = std::make_unique<T>(); | ||
auto* r = n.get(); | ||
meta_nodes.insert(std::move(n)); | ||
return r; | ||
} | ||
|
||
NodeP get_or_add_node(const N& n); | ||
void add_edge(NodeP from, NodeP to); | ||
|
||
NodeP add_block(NodeP parent, const Nodes& stmts); | ||
NodeP add_while(NodeP parent, const statement::While& while_); | ||
NodeP add_if(NodeP parent, const statement::If& if_); | ||
NodeP add_try_catch(const NodeP& parent, const statement::Try& try_); | ||
NodeP add_return(const NodeP& parent, const N& expression); | ||
|
||
const auto& edges() const { return g.getEdgeSet(); } | ||
auto nodes() const { return g.getNodeSet(); } | ||
|
||
CXXGraph::T_NodeSet<N> unreachable_nodes() const; | ||
|
||
std::string dot() const; | ||
|
||
private: | ||
CXXGraph::Graph<N> g; | ||
|
||
std::unordered_set<std::unique_ptr<MetaNode>> meta_nodes; | ||
NodeP begin; | ||
NodeP end; | ||
}; | ||
} // namespace detail::cfg | ||
|
||
} // namespace hilti |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,241 @@ | ||
// Copyright (c) 2020-2023 by the Zeek Project. See LICENSE for details. | ||
|
||
#include "hilti/compiler/detail/cfg.h" | ||
|
||
#include <algorithm> | ||
#include <iterator> | ||
#include <utility> | ||
|
||
#include <hilti/ast/node.h> | ||
#include <hilti/ast/statement.h> | ||
#include <hilti/ast/statements/block.h> | ||
#include <hilti/ast/statements/expression.h> | ||
#include <hilti/ast/statements/if.h> | ||
#include <hilti/ast/statements/return.h> | ||
#include <hilti/ast/statements/throw.h> | ||
#include <hilti/ast/statements/try.h> | ||
#include <hilti/ast/statements/while.h> | ||
#include <hilti/base/util.h> | ||
|
||
namespace hilti { | ||
std::istream& operator>>(std::istream&, Node*) { util::cannotBeReached(); } | ||
|
||
std::string node_id(const Node* n) { return util::fmt("%d", n ? n->identity() : 0); } | ||
|
||
namespace detail::cfg { | ||
|
||
CFG::CFG(const N& root) | ||
: begin(get_or_add_node(create_meta_node<Start>())), end(get_or_add_node(create_meta_node<End>())) { | ||
assert(root && root->isA<statement::Block>() && "only building from blocks currently supported"); | ||
|
||
auto last = add_block(begin, root->children()); | ||
add_edge(last, end); | ||
} | ||
|
||
CFG::NodeP CFG::add_block(NodeP parent, const Nodes& stmts) { | ||
// If `children` directly has any statements which change control flow like | ||
// `throw` or `return` any statements after that are unreachable. To model | ||
// such ASTs we add a flow with all statements up to the "last" semantic | ||
// statement (either the last child or the control flow statement) to the | ||
// CFG under `parent`. Statements after that are added as children without | ||
// parents, and mixed with the previous flow. | ||
|
||
// After this block `last` is the last reachable statement, either end of | ||
// children or a control flow statement. | ||
auto last = std::find_if(stmts.begin(), stmts.end(), [](auto&& c) { | ||
return c && (c->template isA<statement::Return>() || c->template isA<statement::Throw>()); | ||
}); | ||
const bool has_dead_flow = last != stmts.end(); | ||
if ( has_dead_flow ) | ||
last = std::next(last); | ||
|
||
// Add all statements which are part of the normal flow. | ||
for ( auto&& c : (last != stmts.end() ? Nodes(stmts.begin(), last) : stmts) ) { | ||
if ( ! c || ! c->isA<Statement>() ) | ||
continue; | ||
|
||
if ( auto&& while_ = c->tryAs<statement::While>() ) | ||
parent = add_while(parent, *while_); | ||
|
||
else if ( auto&& if_ = c->tryAs<statement::If>() ) | ||
parent = add_if(parent, *if_); | ||
|
||
else if ( auto&& try_catch = c->tryAs<statement::Try>() ) | ||
parent = add_try_catch(parent, *try_catch); | ||
|
||
else if ( auto&& return_ = c->tryAs<statement::Return>() ) | ||
parent = add_return(parent, return_->expression()); | ||
|
||
else if ( auto&& throw_ = c->tryAs<statement::Throw>() ) | ||
parent = add_return(parent, throw_->expression()); | ||
|
||
else { | ||
auto cc = get_or_add_node(c); | ||
|
||
add_edge(parent, cc); | ||
add_block(parent, c->children()); | ||
|
||
// Update `last` so sibling nodes get chained. | ||
parent = std::move(cc); | ||
} | ||
} | ||
|
||
// Add unreachable flows. | ||
if ( has_dead_flow && last != stmts.end() ) { | ||
auto next = add_block(nullptr, Nodes{last, stmts.end()}); | ||
auto mix = get_or_add_node(create_meta_node<Flow>()); | ||
add_edge(parent, mix); | ||
add_edge(next, mix); | ||
parent = std::move(mix); | ||
} | ||
|
||
return parent; | ||
} | ||
|
||
CFG::NodeP CFG::add_while(NodeP parent, const statement::While& while_) { | ||
auto&& condition = get_or_add_node(while_.condition()); | ||
add_edge(std::move(parent), condition); | ||
|
||
auto body_end = add_block(condition, while_.body()->children()); | ||
add_edge(body_end, condition); | ||
if ( auto&& else_ = while_.else_() ) { | ||
auto&& else_end = add_block(condition, else_->children()); | ||
|
||
auto mix = get_or_add_node(create_meta_node<Flow>()); | ||
|
||
add_edge(else_end, mix); | ||
add_edge(condition, mix); | ||
|
||
return mix; | ||
} | ||
|
||
return condition; | ||
} | ||
|
||
CFG::NodeP CFG::add_if(NodeP parent, const statement::If& if_) { | ||
auto&& condition = get_or_add_node(if_.condition()); | ||
add_edge(std::move(parent), condition); | ||
|
||
auto true_end = add_block(condition, if_.true_()->children()); | ||
if ( auto false_ = if_.false_() ) { | ||
auto false_end = add_block(condition, false_->children()); | ||
auto mix = get_or_add_node(create_meta_node<Flow>()); | ||
|
||
add_edge(false_end, mix); | ||
add_edge(true_end, mix); | ||
|
||
return mix; | ||
} | ||
|
||
return true_end; | ||
} | ||
|
||
CFG::NodeP CFG::add_try_catch(const NodeP& parent, const statement::Try& try_catch) { | ||
auto try_ = add_block(parent, try_catch.body()->children()); | ||
auto mix = get_or_add_node(create_meta_node<Flow>()); | ||
add_edge(try_, mix); | ||
|
||
for ( auto&& catch_ : try_catch.catches() ) { | ||
auto catch_end = add_block(parent, catch_->body()->children()); | ||
add_edge(catch_end, mix); | ||
} | ||
|
||
return mix; | ||
} | ||
|
||
CFG::NodeP CFG::add_return(const NodeP& parent, const N& expression) { | ||
if ( expression ) { | ||
auto r = get_or_add_node(expression); | ||
add_edge(parent, r); | ||
return r; | ||
} | ||
|
||
return parent; | ||
} | ||
|
||
std::shared_ptr<const CXXGraph::Node<CFG::N>> CFG::get_or_add_node(const N& n) { | ||
const auto& id = node_id(n); | ||
if ( auto x = g.getNode(id) ) | ||
return *x; | ||
|
||
auto y = std::make_shared<CXXGraph::Node<N>>(id, n); | ||
g.addNode(y); | ||
return y; | ||
} | ||
|
||
void CFG::add_edge(NodeP from, NodeP to) { | ||
if ( ! from || ! to ) | ||
return; | ||
|
||
if ( const auto& xs = g.outEdges(from); | ||
xs.end() != std::find_if(xs.begin(), xs.end(), [&](const auto& e) { return e->getNodePair().second == to; }) ) | ||
return; | ||
else { | ||
auto e = | ||
std::make_shared<CXXGraph::DirectedEdge<CFG::N>>(g.getEdgeSet().size(), std::move(from), std::move(to)); | ||
g.addEdge(std::move(e)); | ||
return; | ||
} | ||
} | ||
|
||
std::string CFG::dot() const { | ||
std::stringstream ss; | ||
|
||
ss << "digraph {\n"; | ||
|
||
for ( auto&& n : g.getNodeSet() ) { | ||
auto&& data = n->getData(); | ||
if ( auto&& meta = data->tryAs<MetaNode>() ) { | ||
if ( data->isA<Start>() ) | ||
ss << util::fmt("\t%s [label=start shape=Mdiamond];\n", n->getId()); | ||
|
||
else if ( data->isA<End>() ) | ||
ss << util::fmt("\t%s [label=end shape=Msquare];\n", n->getId()); | ||
|
||
else if ( data->isA<Flow>() ) | ||
ss << util::fmt("\t%s [shape=point];\n", n->getId()); | ||
|
||
else | ||
util::cannotBeReached(); | ||
} | ||
|
||
else | ||
ss << util::fmt("\t%s [label=\"%s\"];\n", n->getId(), rt::escapeUTF8(data->print(), true)); | ||
} | ||
|
||
for ( auto&& e : g.getEdgeSet() ) { | ||
auto&& [from, to] = e->getNodePair(); | ||
ss << util::fmt("\t%s -> %s [label=\"%s\"];\n", from->getId(), to->getId(), e->getId()); | ||
} | ||
|
||
ss << "}"; | ||
|
||
return ss.str(); | ||
} | ||
|
||
CXXGraph::T_NodeSet<CFG::N> CFG::unreachable_nodes() const { | ||
auto xs = nodes(); | ||
|
||
// We cannot use `inOutEdges` to get a list of unreachable non-meta nodes | ||
// since it is completely broken for directed graphs, | ||
// https://github.com/ZigRazor/CXXGraph/issues/406. | ||
|
||
std::unordered_set<CXXGraph::id_t> has_in_edge; | ||
for ( auto&& e : g.getEdgeSet() ) { | ||
auto&& [_, to] = e->getNodePair(); | ||
has_in_edge.insert(to->getId()); | ||
} | ||
|
||
CXXGraph::T_NodeSet<N> result; | ||
for ( auto&& n : xs ) { | ||
auto&& data = n->getData(); | ||
if ( data && (! has_in_edge.count(n->getId()) && ! data->isA<MetaNode>()) ) | ||
result.insert(n); | ||
} | ||
|
||
return result; | ||
} | ||
|
||
} // namespace detail::cfg | ||
|
||
} // namespace hilti |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a temporary solution until we decide on a proper graph library (or implement one ourselves); we cannot use this library as it is licensed under AGPL-3.0. It also seems to be of poor quality (e.g., major bugs around directed graphs, poor test suite).