2 * Copyright (C) 2016 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 // Based on system/update_engine/payload_generator/tarjan.cc
19 #ifndef LIBMEMUNREACHABLE_TARJAN_H_
20 #define LIBMEMUNREACHABLE_TARJAN_H_
24 #include "Allocator.h"
29 allocator::set<Node<T>*> references_in;
30 allocator::set<Node<T>*> references_out;
36 Node(T* ptr, Allocator<Node> allocator) : references_in(allocator), references_out(allocator),
38 Node(Node&& rhs) = default;
39 void Edge(Node<T>* ref) {
40 references_out.emplace(ref);
41 ref->references_in.emplace(this);
45 for (auto& node: references_out) {
50 DISALLOW_COPY_AND_ASSIGN(Node<T>);
54 using Graph = allocator::vector<Node<T>*>;
57 using SCC = allocator::vector<Node<T>*>;
60 using SCCList = allocator::vector<SCC<T>>;
63 class TarjanAlgorithm {
65 TarjanAlgorithm(Allocator<void> allocator) : index_(0),
66 stack_(allocator), components_(allocator) {}
68 void Execute(Graph<T>& graph, SCCList<T>& out);
70 static constexpr size_t UNDEFINED_INDEX = static_cast<size_t>(-1);
71 void Tarjan(Node<T>* vertex, Graph<T>& graph);
74 allocator::vector<Node<T>*> stack_;
75 SCCList<T> components_;
79 void TarjanAlgorithm<T>::Execute(Graph<T>& graph, SCCList<T>& out) {
83 for (auto& it: graph) {
84 it->index = UNDEFINED_INDEX;
85 it->lowlink = UNDEFINED_INDEX;
88 for (auto& it: graph) {
89 if (it->index == UNDEFINED_INDEX) {
93 out.swap(components_);
97 void TarjanAlgorithm<T>::Tarjan(Node<T>* vertex, Graph<T>& graph) {
98 assert(vertex->index == UNDEFINED_INDEX);
99 vertex->index = index_;
100 vertex->lowlink = index_;
102 stack_.push_back(vertex);
103 for (auto& it: vertex->references_out) {
104 Node<T>* vertex_next = it;
105 if (vertex_next->index == UNDEFINED_INDEX) {
106 Tarjan(vertex_next, graph);
107 vertex->lowlink = std::min(vertex->lowlink, vertex_next->lowlink);
108 } else if (std::find(stack_.begin(), stack_.end(), vertex_next) != stack_.end()) {
109 vertex->lowlink = std::min(vertex->lowlink, vertex_next->index);
112 if (vertex->lowlink == vertex->index) {
113 SCC<T> component{components_.get_allocator()};
114 Node<T>* other_vertex;
116 other_vertex = stack_.back();
118 component.push_back(other_vertex);
119 } while (other_vertex != vertex && !stack_.empty());
121 components_.emplace_back(component);
126 void Tarjan(Graph<T>& graph, SCCList<T>& out) {
127 TarjanAlgorithm<T> tarjan{graph.get_allocator()};
128 tarjan.Execute(graph, out);
131 #endif // LIBMEMUNREACHABLE_TARJAN_H_