LLVM 24.0.0git
PassManager.h
Go to the documentation of this file.
1//===- PassManager.h --------------------------------------------*- 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//
9// Registers and executes the Sandbox IR passes.
10//
11// The pass manager contains an ordered sequence of passes that it runs in
12// order. The passes are owned by the PassRegistry, not by the PassManager.
13//
14// Note that in this design a pass manager is also a pass. So a pass manager
15// runs when it is it's turn to run in its parent pass-manager pass pipeline.
16//
17
18#ifndef LLVM_SANDBOXIR_PASSMANAGER_H
19#define LLVM_SANDBOXIR_PASSMANAGER_H
20
22#include <memory>
23
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/SandboxIR/Pass.h"
27#include "llvm/Support/Debug.h"
28
29namespace llvm::sandboxir {
30
31/// Base class.
32template <typename ParentPass, typename ContainedPass>
33class PassManager : public ParentPass {
34public:
35 // CreatePassFunc(StringRef PassName, StringRef PassArgs, StringRef AuxArg)
36 using CreatePassFunc = std::function<std::unique_ptr<ContainedPass>(
38
39protected:
40 /// The list of passes that this pass manager will run.
42
44 PassManager(StringRef Name, StringRef Pipeline, CreatePassFunc CreatePass)
45 : ParentPass(Name) {
46 setPassPipeline(Pipeline, CreatePass);
47 }
48 PassManager(const PassManager &) = delete;
49 PassManager(PassManager &&) = default;
50 ~PassManager() override = default;
51 PassManager &operator=(const PassManager &) = delete;
52
53public:
54 /// Adds \p Pass to the pass pipeline.
55 void addPass(std::unique_ptr<ContainedPass> Pass) {
56 // TODO: Check that Pass's class type works with this PassManager type.
57 Passes.push_back(std::move(Pass));
58 }
59
60 static constexpr char EndToken = '\0';
61 static constexpr char BeginArgsToken = '<';
62 static constexpr char EndArgsToken = '>';
63 static constexpr char BeginAuxArgsToken = '(';
64 static constexpr char EndAuxArgsToken = ')';
65 static constexpr char PassDelimToken = ',';
66
67 /// Parses \p Pipeline as a comma-separated sequence of pass names and sets
68 /// the pass pipeline, using \p CreatePass to instantiate passes by name.
69 ///
70 /// Passes can have two types of arguments:
71 /// - The standard pass arguments within < >, which are commonly used for
72 /// passing a comma-separated list of pass names, for example:
73 /// "pass1<arg1,arg2>,pass2,pass3<arg3,arg4>"
74 /// - An auxiliary pass argument within ( ), which is used as a secondary
75 /// argument, for example:
76 /// "pass1(foo),pass2,pass3(bar)"
77 /// Note that both types of arguments can be combined, like:
78 /// "pass1(foo)<arg1,arg2>,pass2,pass3(bar)<arg3,arg4>"
79 /// The reason why there is more than one type of pass argument, is to make
80 /// it easier for passes to parse the argument contents, and make the pass
81 /// pipeline more consistent and easier to read, than relying on some
82 /// formatting that the passes might expect.
83 ///
84 /// The arguments between both bracket types are treated as a mostly opaque
85 /// string and each pass is responsible for parsing its arguments. The
86 /// exception to this are nested brackets, which must match pair-wise to
87 /// allow arguments to contain nested pipelines or nested aux arguments, like:
88 ///
89 /// "pass1<subpass1,subpass2<arg1,arg2>,subpass3>"
90 /// or
91 /// "pass1(arg1(nestedarg))"
92 ///
93 /// An empty args string is treated the same as no args, so "pass" and
94 /// "pass<>" are equivalent.
95 ///
96 void setPassPipeline(StringRef Pipeline, CreatePassFunc CreatePass) {
97 assert(Passes.empty() &&
98 "setPassPipeline called on a non-empty sandboxir::PassManager");
99
100 // Accept an empty pipeline as a special case. This can be useful, for
101 // example, to test conversion to SandboxIR without running any passes on
102 // it.
103 if (Pipeline.empty())
104 return;
105
106 // Add EndToken to the end to ease parsing.
107 std::string PipelineStr = std::string(Pipeline) + EndToken;
108 Pipeline = StringRef(PipelineStr);
109
110 auto AddPass = [this, CreatePass](StringRef PassName, StringRef PassArgs,
111 StringRef AuxArg) {
112 if (PassName.empty()) {
113 errs() << "Found empty pass name.\n";
114 exit(1);
115 }
116 // Get the pass that corresponds to PassName and add it to the pass
117 // manager.
118 auto Pass = CreatePass(PassName, PassArgs, AuxArg);
119 if (Pass == nullptr) {
120 errs() << "Pass '" << PassName << "' not registered!\n";
121 exit(1);
122 }
123 addPass(std::move(Pass));
124 };
125
126 enum class State {
127 ScanName, // reading a pass name
128 ScanArgs, // reading a list of args
129 ArgsEnded, // read the last '>' in an args list, must read delimiter next
130 ScanAuxArgs, // reading the auxiliary argument
131 AuxArgsEnded, // read the last ')' in aux args list
132 } CurrentState = State::ScanName;
133 int PassBeginIdx = 0;
134 int ArgsBeginIdx;
135 int AuxArgsBeginIdx = 0;
137 StringRef AuxArg;
138 int NestedArgs = 0;
139 int NestedAuxArgs = 0;
140 for (auto [Idx, C] : enumerate(Pipeline)) {
141 switch (CurrentState) {
142 case State::ScanName:
143 if (C == BeginArgsToken) {
144 // Save pass name for later and begin scanning args.
145 PassName = Pipeline.slice(PassBeginIdx, Idx);
146 ArgsBeginIdx = Idx + 1;
147 ++NestedArgs;
148 CurrentState = State::ScanArgs;
149 break;
150 }
151 if (C == BeginAuxArgsToken) {
152 // Save pass name for later and begin scanning args.
153 PassName = Pipeline.slice(PassBeginIdx, Idx);
154 AuxArgsBeginIdx = Idx + 1;
155 ++NestedAuxArgs;
156 CurrentState = State::ScanAuxArgs;
157 AuxArg = StringRef();
158 break;
159 }
160 if (C == EndArgsToken || C == EndAuxArgsToken) {
161 errs() << "Unexpected '" << C << "' in pass pipeline.\n";
162 exit(1);
163 }
164 if (C == EndToken || C == PassDelimToken) {
165 // Delimiter found, add the pass (with empty args), stay in the
166 // ScanName state.
167 AddPass(Pipeline.slice(PassBeginIdx, Idx), StringRef(), AuxArg);
168 PassBeginIdx = Idx + 1;
169 }
170 break;
171 case State::ScanArgs:
172 // While scanning args, we only care about making sure nesting of angle
173 // brackets is correct.
174 if (C == BeginArgsToken) {
175 ++NestedArgs;
176 break;
177 }
178 if (C == EndArgsToken) {
179 --NestedArgs;
180 if (NestedArgs == 0) {
181 // Done scanning args.
182 AddPass(PassName, Pipeline.slice(ArgsBeginIdx, Idx), AuxArg);
183 CurrentState = State::ArgsEnded;
184 } else if (NestedArgs < 0) {
185 errs() << "Unexpected '>' in pass pipeline.\n";
186 exit(1);
187 }
188 break;
189 }
190 if (C == EndToken) {
191 errs() << "Missing '>' in pass pipeline. End-of-string reached while "
192 "reading arguments for pass '"
193 << PassName << "'.\n";
194 exit(1);
195 }
196 break;
197 case State::ArgsEnded:
198 // Once we're done scanning args, only a delimiter is valid. This avoids
199 // accepting strings like "foo<args><more-args>" or "foo<args>bar".
200 if (C == EndToken || C == PassDelimToken) {
201 PassBeginIdx = Idx + 1;
202 AuxArg = StringRef();
203 CurrentState = State::ScanName;
204 } else {
205 errs() << "Expected delimiter or end-of-string after pass "
206 "arguments.\n";
207 exit(1);
208 }
209 break;
210 case State::ScanAuxArgs:
211 if (C == BeginAuxArgsToken) {
212 ++NestedAuxArgs;
213 break;
214 }
215 if (C == EndAuxArgsToken) {
216 --NestedAuxArgs;
217 if (NestedAuxArgs == 0) {
218 AuxArg = Pipeline.slice(AuxArgsBeginIdx, Idx);
219 CurrentState = State::AuxArgsEnded;
220 } else if (NestedAuxArgs < 0) {
221 errs() << "Unexpected '" << EndAuxArgsToken
222 << "' in pass pipeline.\n";
223 exit(1);
224 }
225 break;
226 }
227 if (C == EndToken) {
228 errs() << "Missing '" << EndAuxArgsToken
229 << "' in pass pipeline. End-of-string reached while "
230 "reading arguments for pass '"
231 << PassName << "'.\n";
232 exit(1);
233 }
234 break;
235 case State::AuxArgsEnded:
236 if (C == EndToken) {
237 AddPass(PassName, StringRef(), AuxArg);
238 CurrentState = State::ScanName;
239 } else if (C == PassDelimToken) {
240 AddPass(PassName, StringRef(), AuxArg);
241 PassBeginIdx = Idx + 1;
242 AuxArg = StringRef();
243 CurrentState = State::ScanName;
244 } else if (C == BeginArgsToken) {
245 ++NestedArgs;
246 ArgsBeginIdx = Idx + 1;
247 CurrentState = State::ScanArgs;
248 } else {
249 errs() << "Expected delimiter, begin-of-args or end-of-string after "
250 "pass aux argument.\n";
251 exit(1);
252 }
253 break;
254 }
255 }
256 }
257
258#ifndef NDEBUG
259 void print(raw_ostream &OS) const override {
260 OS << this->getName();
261 OS << BeginArgsToken;
262 std::string Delim(1, PassDelimToken);
263 interleave(Passes, OS, [&OS](auto &Pass) { Pass->print(OS); }, Delim);
264 OS << EndArgsToken;
265 }
266 LLVM_DUMP_METHOD void dump() const override {
267 print(dbgs());
268 dbgs() << "\n";
269 }
270#endif
271 /// Similar to print() but prints one pass per line. Used for testing.
272 void printPipeline(raw_ostream &OS) const override {
273 OS << this->getName() << "\n";
274 for (const auto &PassPtr : Passes)
275 PassPtr->printPipeline(OS);
276 }
277};
278
280 : public PassManager<FunctionPass, FunctionPass> {
281public:
284 CreatePassFunc CreatePass)
285 : PassManager(Name, Pipeline, CreatePass) {}
286 bool runOnFunction(Function &F, const Analyses &A) final;
287};
288
290 : public PassManager<RegionPass, RegionPass> {
291public:
294 CreatePassFunc CreatePass)
295 : PassManager(Name, Pipeline, CreatePass) {}
296 bool runOnRegion(Region &R, const Analyses &A) final;
297};
298
299} // namespace llvm::sandboxir
300
301#endif // LLVM_SANDBOXIR_PASSMANAGER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define F(x, y, z)
Definition MD5.cpp:54
static StringRef getName(Value *V)
This file contains some templates that are useful if you are working with the STL at all.
static const char PassName[]
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:712
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
FunctionPassManager(StringRef Name, StringRef Pipeline, CreatePassFunc CreatePass)
PassManager(const PassManager &)=delete
static constexpr char EndAuxArgsToken
Definition PassManager.h:64
void addPass(std::unique_ptr< ContainedPass > Pass)
Adds Pass to the pass pipeline.
Definition PassManager.h:55
std::function< std::unique_ptr< ContainedPass >( StringRef, StringRef, StringRef)> CreatePassFunc
Definition PassManager.h:36
void printPipeline(raw_ostream &OS) const override
Similar to print() but prints one pass per line. Used for testing.
static constexpr char EndToken
Definition PassManager.h:60
PassManager(StringRef Name)
Definition PassManager.h:43
void setPassPipeline(StringRef Pipeline, CreatePassFunc CreatePass)
Parses Pipeline as a comma-separated sequence of pass names and sets the pass pipeline,...
Definition PassManager.h:96
PassManager(PassManager &&)=default
static constexpr char BeginArgsToken
Definition PassManager.h:61
void print(raw_ostream &OS) const override
~PassManager() override=default
PassManager(StringRef Name, StringRef Pipeline, CreatePassFunc CreatePass)
Definition PassManager.h:44
PassManager & operator=(const PassManager &)=delete
LLVM_DUMP_METHOD void dump() const override
static constexpr char PassDelimToken
Definition PassManager.h:65
SmallVector< std::unique_ptr< ContainedPass > > Passes
The list of passes that this pass manager will run.
Definition PassManager.h:41
static constexpr char BeginAuxArgsToken
Definition PassManager.h:63
static constexpr char EndArgsToken
Definition PassManager.h:62
The base class of a Sandbox IR Pass.
Definition Pass.h:53
const std::string Name
The pass name.
Definition Pass.h:57
virtual void print(raw_ostream &OS) const
Definition Pass.h:74
RegionPassManager(StringRef Name, StringRef Pipeline, CreatePassFunc CreatePass)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
void interleave(ForwardIterator begin, ForwardIterator end, UnaryFunctor each_fn, NullaryFunctor between_fn)
An STL-style algorithm similar to std::for_each that applies a second functor between every pair of e...
Definition STLExtras.h:2296
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.