LLVM 24.0.0git
SuffixTree.h
Go to the documentation of this file.
1//===- llvm/ADT/SuffixTree.h - Tree for substrings --------------*- C++ -*-===//
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// A data structure for fast substring queries.
9//
10// Suffix trees represent the suffixes of their input strings in their leaves.
11// A suffix tree is a type of compressed trie structure where each node
12// represents an entire substring rather than a single character. Each leaf
13// of the tree is a suffix.
14//
15// A suffix tree can be seen as a type of state machine where each state is a
16// substring of the full string. The tree is structured so that, for a string
17// of length N, there are exactly N leaves before pruning. This structure allows
18// us to quickly find repeated substrings of the input string.
19//
20// In this implementation, a "string" is a vector of unsigned integers.
21// These integers may result from hashing some data type. A suffix tree can
22// contain 1 or many strings, which can then be queried as one large string.
23//
24// The suffix tree is implemented using Ukkonen's algorithm for linear-time
25// suffix tree construction. Ukkonen's algorithm is explained in more detail
26// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
27// paper is available at
28//
29// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
30//===----------------------------------------------------------------------===//
31
32#ifndef LLVM_SUPPORT_SUFFIXTREE_H
33#define LLVM_SUPPORT_SUFFIXTREE_H
34
35#include "llvm/ADT/ArrayRef.h"
39#include <optional>
40
41namespace llvm {
43public:
44 /// Each element is an integer representing an instruction in the module.
46
47 /// Whether to consider leaf descendants or only leaf children.
49
50 /// A repeated substring in the tree.
52 /// The length of the string.
53 unsigned Length;
54
55 /// The start indices of each occurrence.
57 };
58
59private:
60 /// The minimum length of a repeated substring to find.
61 /// Since we're outlining, we want at least two instructions in the range.
62 /// FIXME: This may not be true for targets like X86 which support many
63 /// instruction lengths.
64 static constexpr unsigned MinLength = 2;
65
66 const std::optional<unsigned> BoundaryStart;
67
68 bool isBoundary(unsigned Value) const {
69 return BoundaryStart && Value >= *BoundaryStart;
70 }
71
72 /// Maintains internal nodes in the tree.
74 /// Maintains leaf nodes in the tree.
76
77 /// The root of the suffix tree.
78 ///
79 /// The root represents the empty string. It is maintained by the
80 /// \p NodeAllocator like every other node in the tree.
81 SuffixTreeInternalNode *Root = nullptr;
82
83 /// The end index of each leaf in the tree.
84 unsigned LeafEndIdx = SuffixTreeNode::EmptyIdx;
85
86 /// Helper struct which keeps track of the next insertion point in
87 /// Ukkonen's algorithm.
88 struct ActiveState {
89 /// The next node to insert at.
91
92 /// The index of the first character in the substring currently being added.
93 unsigned Idx = SuffixTreeNode::EmptyIdx;
94
95 /// The length of the substring we have to add at the current step.
96 unsigned Len = 0;
97 };
98
99 /// The point the next insertion will take place at in the
100 /// construction algorithm.
101 ActiveState Active;
102
103 /// Allocate a leaf node and add it to the tree.
104 ///
105 /// \param Parent The parent of this node.
106 /// \param StartIdx The start index of this node's associated string.
107 /// \param Edge The label on the edge leaving \p Parent to this node.
108 ///
109 /// \returns A pointer to the allocated leaf node.
110 SuffixTreeNode *insertLeaf(SuffixTreeInternalNode &Parent, unsigned StartIdx,
111 unsigned Edge);
112
113 /// Allocate an internal node and add it to the tree.
114 ///
115 /// \param Parent The parent of this node. Only null when allocating the root.
116 /// \param StartIdx The start index of this node's associated string.
117 /// \param EndIdx The end index of this node's associated string.
118 /// \param Edge The label on the edge leaving \p Parent to this node.
119 ///
120 /// \returns A pointer to the allocated internal node.
121 SuffixTreeInternalNode *insertInternalNode(SuffixTreeInternalNode *Parent,
122 unsigned StartIdx, unsigned EndIdx,
123 unsigned Edge);
124
125 /// Allocate the root node and add it to the tree.
126 ///
127 /// \returns A pointer to the root.
128 SuffixTreeInternalNode *insertRoot();
129
130 /// Construct the suffix tree for the prefix of the input ending at
131 /// \p EndIdx.
132 ///
133 /// Used to construct the full suffix tree iteratively. At the end of each
134 /// step, the constructed suffix tree is either a valid suffix tree, or a
135 /// suffix tree with implicit suffixes. At the end of the final step, the
136 /// suffix tree is a valid tree.
137 ///
138 /// \param EndIdx The end index of the current prefix in the main string.
139 /// \param SuffixesToAdd The number of suffixes that must be added
140 /// to complete the suffix tree at the current phase.
141 ///
142 /// \returns The number of suffixes that have not been added at the end of
143 /// this step.
144 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd);
145
146 /// This vector contains all leaf nodes of this suffix tree. These leaf nodes
147 /// are identified using post-order depth-first traversal, so that the order
148 /// of these leaf nodes in the vector matches the order of the leaves in the
149 /// tree from left to right if one were to draw the tree on paper.
150 std::vector<SuffixTreeLeafNode *> LeafNodes;
151
152 /// Perform a post-order depth-first traversal of the tree and perform two
153 /// tasks during the traversal. The first is to populate LeafNodes, adding
154 /// nodes in order of the traversal. The second is to keep track of the leaf
155 /// descendants of every internal node by assigning values to LeftLeafIndex
156 /// and RightLefIndex fields of SuffixTreeNode for all internal nodes.
157 void setLeafNodes();
158
159public:
160 /// Construct a suffix tree from a sequence of unsigned integers.
161 ///
162 /// \param Str The string to construct the suffix tree for.
163 /// \param OutlinerLeafDescendants Whether to consider leaf descendants or
164 /// only leaf children (used by Machine Outliner).
165 /// \param BoundaryStart Values at or above this lower bound must be unique
166 /// terminators. If omitted, no symbols are treated as unique terminators.
167 LLVM_ABI SuffixTree(const ArrayRef<unsigned> &Str,
168 bool OutlinerLeafDescendants = false,
169 std::optional<unsigned> BoundaryStart = std::nullopt);
170
171 /// Iterator for finding all repeated substrings in the suffix tree.
173 private:
174 /// The current node we're visiting.
175 SuffixTreeNode *N = nullptr;
176
177 /// The repeated substring associated with this node.
179
180 /// The nodes left to visit.
181 SmallVector<SuffixTreeInternalNode *> InternalNodesToVisit;
182
183 /// Vector of leaf nodes of the suffix tree.
184 const std::vector<SuffixTreeLeafNode *> &LeafNodes;
185
186 /// Whether to consider leaf descendants or only leaf children.
187 bool OutlinerLeafDescendants = !LeafNodes.empty();
188
189 /// Move the iterator to the next repeated substring.
190 LLVM_ABI void advance();
191
192 public:
193 /// Return the current repeated substring.
194 RepeatedSubstring &operator*() { return RS; }
195
197 advance();
198 return *this;
199 }
200
203 advance();
204 return It;
205 }
206
208 return N == Other.N;
209 }
211 return !(*this == Other);
212 }
213
216 const std::vector<SuffixTreeLeafNode *> &LeafNodes = {})
217 : N(N), LeafNodes(LeafNodes) {
218 // Do we have a non-null node?
219 if (!N)
220 return;
221 // Yes. At the first step, we need to visit all of N's children.
222 // Note: This means that we visit N last.
223 InternalNodesToVisit.push_back(N);
224 advance();
225 }
226 };
227
229 iterator begin() { return iterator(Root, LeafNodes); }
230 iterator end() { return iterator(nullptr); }
231};
232
233} // namespace llvm
234
235#endif // LLVM_SUPPORT_SUFFIXTREE_H
This file defines the BumpPtrAllocator interface.
#define LLVM_ABI
Definition Compiler.h:211
#define I(x, y, z)
Definition MD5.cpp:57
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A BumpPtrAllocator that allows only elements of a specific type to be allocated.
Definition Allocator.h:398
iterator begin()
Definition SuffixTree.h:229
LLVM_ABI SuffixTree(const ArrayRef< unsigned > &Str, bool OutlinerLeafDescendants=false, std::optional< unsigned > BoundaryStart=std::nullopt)
Construct a suffix tree from a sequence of unsigned integers.
iterator end()
Definition SuffixTree.h:230
ArrayRef< unsigned > Str
Each element is an integer representing an instruction in the module.
Definition SuffixTree.h:45
RepeatedSubstringIterator iterator
Definition SuffixTree.h:228
bool OutlinerLeafDescendants
Whether to consider leaf descendants or only leaf children.
Definition SuffixTree.h:48
LLVM Value Representation.
Definition Value.h:75
This is an optimization pass for GlobalISel generic memory operations.
@ Other
Any other memory.
Definition ModRef.h:68
#define N
A node in a suffix tree which represents a substring or suffix.
static const unsigned EmptyIdx
Represents an undefined index in the suffix tree.
Iterator for finding all repeated substrings in the suffix tree.
Definition SuffixTree.h:172
RepeatedSubstringIterator operator++(int I)
Definition SuffixTree.h:201
RepeatedSubstringIterator(SuffixTreeInternalNode *N, const std::vector< SuffixTreeLeafNode * > &LeafNodes={})
Definition SuffixTree.h:214
bool operator!=(const RepeatedSubstringIterator &Other) const
Definition SuffixTree.h:210
RepeatedSubstring & operator*()
Return the current repeated substring.
Definition SuffixTree.h:194
bool operator==(const RepeatedSubstringIterator &Other) const
Definition SuffixTree.h:207
RepeatedSubstringIterator & operator++()
Definition SuffixTree.h:196
A repeated substring in the tree.
Definition SuffixTree.h:51
SmallVector< unsigned > StartIndices
The start indices of each occurrence.
Definition SuffixTree.h:56
unsigned Length
The length of the string.
Definition SuffixTree.h:53