MLIR 24.0.0git
PassOptions.h
Go to the documentation of this file.
1//===- PassOptions.h - Pass Option Utilities --------------------*- 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// This file contains utilities for registering options with compiler passes and
10// pipelines.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef MLIR_PASS_PASSOPTIONS_H_
15#define MLIR_PASS_PASSOPTIONS_H_
16
17#include "mlir/Support/LLVM.h"
18#include "llvm/ADT/FunctionExtras.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/Support/CommandLine.h"
21#include "llvm/Support/Compiler.h"
22#include <memory>
23
24namespace mlir {
25class OpPassManager;
26
27namespace detail {
28namespace pass_options {
29/// Parse a string containing a list of comma-delimited elements, invoking the
30/// given parser for each sub-element and passing them to the provided
31/// element-append functor.
32LogicalResult
33parseCommaSeparatedList(llvm::cl::Option &opt, StringRef argName,
34 StringRef optionStr,
35 function_ref<LogicalResult(StringRef)> elementParseFn);
36template <typename ElementParser, typename ElementAppendFn>
37LogicalResult parseCommaSeparatedList(llvm::cl::Option &opt, StringRef argName,
38 StringRef optionStr,
39 ElementParser &elementParser,
40 ElementAppendFn &&appendFn) {
42 opt, argName, optionStr, [&](StringRef valueStr) {
43 typename ElementParser::parser_data_type value = {};
44 if (elementParser.parse(opt, argName, valueStr, value))
45 return failure();
46 appendFn(value);
47 return success();
48 });
49}
50
51/// Trait used to detect if a type has a operator<< method.
52template <typename T>
54 decltype(std::declval<raw_ostream &>() << std::declval<T>());
55template <typename T>
56using has_stream_operator = llvm::is_detected<has_stream_operator_trait, T>;
57
58/// Utility methods for printing option values.
59template <typename ParserT>
60void printOptionValue(raw_ostream &os, const bool &value) {
61 os << (value ? StringRef("true") : StringRef("false"));
62}
63template <typename ParserT>
64void printOptionValue(raw_ostream &os, const std::string &str) {
65 // Check if the string needs to be escaped before writing it to the ostream.
66 const size_t spaceIndex = str.find_first_of(' ');
67 const size_t escapeIndex =
68 std::min({str.find_first_of('{'), str.find_first_of('\''),
69 str.find_first_of('"')});
70 const bool requiresEscape = spaceIndex < escapeIndex;
71 if (requiresEscape)
72 os << "{";
73 os << str;
74 if (requiresEscape)
75 os << "}";
76}
77template <typename ParserT, typename DataT>
78void printOptionValue(raw_ostream &os, const DataT &value) {
80 os << value;
81 else
82 // If the value can't be streamed, fallback to checking for a print in the
83 // parser.
84 ParserT::print(os, value);
85}
86} // namespace pass_options
87
88/// Base container class and manager for all pass options.
90private:
91 /// This is the type-erased option base class. This provides some additional
92 /// hooks into the options that are not available via llvm::cl::Option.
93 class OptionBase {
94 public:
95 virtual ~OptionBase() = default;
96
97 /// Out of line virtual function to provide home for the class.
98 virtual void anchor();
99
100 /// Print the name and value of this option to the given stream.
101 virtual void print(raw_ostream &os) = 0;
102
103 /// Return the argument string of this option.
104 StringRef getArgStr() const { return getOption()->ArgStr; }
105
106 /// Returns true if this option has any value assigned to it.
107 bool hasValue() const { return optHasValue; }
108
109 protected:
110 /// Return the main option instance.
111 virtual const llvm::cl::Option *getOption() const = 0;
112
113 /// Copy the value from the given option into this one.
114 virtual void copyValueFrom(const OptionBase &other) = 0;
115
116 /// Flag indicating if this option has a value.
117 bool optHasValue = false;
118
119 /// Allow access to private methods.
120 friend PassOptions;
121 };
122
123 /// This is the parser that is used by pass options that use literal options.
124 /// This is a thin wrapper around the llvm::cl::parser, that exposes some
125 /// additional methods.
126 template <typename DataType>
127 struct GenericOptionParser : public llvm::cl::parser<DataType> {
128 using llvm::cl::parser<DataType>::parser;
129
130 /// Returns an argument name that maps to the specified value.
131 std::optional<StringRef> findArgStrForValue(const DataType &value) {
132 for (auto &it : this->Values)
133 if (it.V.compare(value))
134 return it.Name;
135 return std::nullopt;
136 }
137 };
138
139 /// This is the parser that is used by pass options that wrap PassOptions
140 /// instances. Like GenericOptionParser, this is a thin wrapper around
141 /// llvm::cl::basic_parser.
142 template <typename PassOptionsT>
143 struct PassOptionsParser : public llvm::cl::basic_parser<PassOptionsT> {
144 using llvm::cl::basic_parser<PassOptionsT>::basic_parser;
145 // Parse the options object by delegating to
146 // `PassOptionsT::parseFromString`.
147 bool parse(llvm::cl::Option &, StringRef, StringRef arg,
148 PassOptionsT &value) {
149 return failed(value.parseFromString(arg));
150 }
151
152 // Print the options object by delegating to `PassOptionsT::print`.
153 static void print(llvm::raw_ostream &os, const PassOptionsT &value) {
154 value.print(os);
155 }
156 };
157
158 /// Utility methods for printing option values.
159 template <typename DataT>
160 static void printValue(raw_ostream &os, GenericOptionParser<DataT> &parser,
161 const DataT &value) {
162 if (std::optional<StringRef> argStr = parser.findArgStrForValue(value))
163 os << *argStr;
164 else
165 llvm_unreachable("unknown data value for option");
166 }
167 template <typename DataT, typename ParserT>
168 static void printValue(raw_ostream &os, ParserT &parser, const DataT &value) {
170 }
171
172public:
173 /// The specific parser to use. This is necessary because we need to provide
174 /// additional methods for certain data type parsers.
175 template <typename DataType>
176 using OptionParser = std::conditional_t<
177 // If the data type is derived from PassOptions, use the
178 // PassOptionsParser.
179 std::is_base_of_v<PassOptions, DataType>, PassOptionsParser<DataType>,
180 // Otherwise, use GenericOptionParser where it is well formed, and fall
181 // back to llvm::cl::parser otherwise.
182 // TODO: We should upstream the methods in GenericOptionParser to avoid
183 // the need to do this.
184 std::conditional_t<std::is_base_of<llvm::cl::generic_parser_base,
186 GenericOptionParser<DataType>,
188
189 /// This class represents a specific pass option, with a provided
190 /// data type.
191 template <typename DataType, typename OptionParser = OptionParser<DataType>>
192 class Option
193 : public llvm::cl::opt<DataType, /*ExternalStorage=*/false, OptionParser>,
194 public OptionBase {
195 public:
196 template <typename... Args>
197 Option(PassOptions &parent, StringRef arg, Args &&...args)
198 : llvm::cl::opt<DataType, /*ExternalStorage=*/false, OptionParser>(
199 arg, llvm::cl::sub(parent), std::forward<Args>(args)...) {
200 assert(!this->isPositional() && "positional options are not supported");
201 parent.options.push_back(this);
202
203 // Set a callback to track if this option has a value.
204 this->setCallback([this](const auto &) { this->optHasValue = true; });
205 }
206 ~Option() override = default;
207 using llvm::cl::opt<DataType, /*ExternalStorage=*/false,
208 OptionParser>::operator=;
209 Option &operator=(const Option &other) {
210 *this = other.getValue();
211 return *this;
212 }
213
214 private:
215 /// Return the main option instance.
216 const llvm::cl::Option *getOption() const final { return this; }
217
218 /// Print the name and value of this option to the given stream.
219 void print(raw_ostream &os) final {
220 os << this->ArgStr << '=';
221 printValue(os, this->getParser(), this->getValue());
222 }
223
224 /// Copy the value from the given option into this one.
225 void copyValueFrom(const OptionBase &other) final {
226 this->setValue(static_cast<const Option<DataType, OptionParser> &>(other)
227 .getValue());
228 optHasValue = other.optHasValue;
229 }
230 };
231
232 /// This class represents a specific pass option that contains a list of
233 /// values of the provided data type. The elements within the textual form of
234 /// this option are parsed assuming they are comma-separated. Delimited
235 /// sub-ranges within individual elements of the list may contain commas that
236 /// are not treated as separators for the top-level list.
237 template <typename DataType, typename OptionParser = OptionParser<DataType>>
239 : public llvm::cl::list<DataType, /*StorageClass=*/bool, OptionParser>,
240 public OptionBase {
241 public:
242 template <typename... Args>
243 ListOption(PassOptions &parent, StringRef arg, Args &&...args)
244 : llvm::cl::list<DataType, /*StorageClass=*/bool, OptionParser>(
245 arg, llvm::cl::sub(parent), std::forward<Args>(args)...),
246 elementParser(*this) {
247 assert(!this->isPositional() && "positional options are not supported");
248 assert(!(this->getMiscFlags() & llvm::cl::MiscFlags::CommaSeparated) &&
249 "ListOption is implicitly comma separated, specifying "
250 "CommaSeparated is extraneous");
251
252 // Make the default explicitly "empty" if no default was given.
253 if (!this->isDefaultAssigned())
254 this->setInitialValues({});
255
256 parent.options.push_back(this);
257 elementParser.initialize();
258 }
259 ~ListOption() override = default;
262 *this = ArrayRef<DataType>(other);
263 this->optHasValue = other.optHasValue;
264 return *this;
265 }
266
267 bool handleOccurrence(unsigned pos, StringRef argName,
268 StringRef arg) override {
269 if (this->isDefaultAssigned()) {
270 this->clear();
271 this->overwriteDefault();
272 }
273 this->optHasValue = true;
275 *this, argName, arg, elementParser,
276 [&](const DataType &value) { this->addValue(value); }));
277 }
278
279 /// Allow assigning from an ArrayRef.
281 ((std::vector<DataType> &)*this).assign(values.begin(), values.end());
282 optHasValue = true;
283 return *this;
284 }
285
286 /// Allow accessing the data held by this option.
288 return static_cast<std::vector<DataType> &>(*this);
289 }
291 return static_cast<const std::vector<DataType> &>(*this);
292 }
293
294 private:
295 /// Return the main option instance.
296 const llvm::cl::Option *getOption() const final { return this; }
297
298 /// Print the name and value of this option to the given stream.
299 /// Note that there is currently a limitation with regards to
300 /// `ListOption<string>`: parsing 'option=""` will result in `option` being
301 /// set to the empty list, not to a size-1 list containing an empty string.
302 void print(raw_ostream &os) final {
303 // Don't print the list if the value is the default value.
304 if (this->isDefaultAssigned() &&
305 this->getDefault().size() == (**this).size()) {
306 unsigned i = 0;
307 for (unsigned e = (**this).size(); i < e; i++) {
308 if (!this->getDefault()[i].compare((**this)[i]))
309 break;
310 }
311 if (i == (**this).size())
312 return;
313 }
314
315 os << this->ArgStr << "={";
316 auto printElementFn = [&](const DataType &value) {
317 printValue(os, this->getParser(), value);
318 };
319 llvm::interleave(*this, os, printElementFn, ",");
320 os << "}";
321 }
322
323 /// Copy the value from the given option into this one.
324 void copyValueFrom(const OptionBase &other) final {
325 *this = static_cast<const ListOption<DataType, OptionParser> &>(other);
326 }
327
328 /// The parser to use for parsing the list elements.
330 };
331
332 PassOptions() = default;
333 /// Delete the copy constructor to avoid copying the internal options map.
334 PassOptions(const PassOptions &) = delete;
335 PassOptions(PassOptions &&) = delete;
336
337 /// Copy the option values from 'other' into 'this', where 'other' has the
338 /// same options as 'this'.
339 void copyOptionValuesFrom(const PassOptions &other);
340
341 /// Parse options out as key=value pairs that can then be handed off to the
342 /// `llvm::cl` command line passing infrastructure. Everything is space
343 /// separated.
344 LogicalResult parseFromString(StringRef options,
345 raw_ostream &errorStream = llvm::errs());
346
347 /// Print the options held by this struct in a form that can be parsed via
348 /// 'parseFromString'.
349 void print(raw_ostream &os) const;
350
351 /// Print the help string for the options held by this struct. `descIndent` is
352 /// the indent that the descriptions should be aligned.
353 void printHelp(size_t indent, size_t descIndent) const;
354
355 /// Return the maximum width required when printing the help string.
356 size_t getOptionWidth() const;
357
358private:
359 /// A list of all of the opaque options.
360 std::vector<OptionBase *> options;
361};
362} // namespace detail
363
364//===----------------------------------------------------------------------===//
365// PassPipelineOptions
366//===----------------------------------------------------------------------===//
367
368/// Subclasses of PassPipelineOptions provide a set of options that can be used
369/// to initialize a pass pipeline. See PassPipelineRegistration for usage
370/// details.
371///
372/// Usage:
373///
374/// struct MyPipelineOptions : PassPipelineOptions<MyPassOptions> {
375/// ListOption<int> someListFlag{*this, "flag-name", llvm::cl::desc("...")};
376/// };
377template <typename T>
378class PassPipelineOptions : public virtual detail::PassOptions {
379public:
380 /// Factory that parses the provided options and returns a unique_ptr to the
381 /// struct.
382 static std::unique_ptr<T> createFromString(StringRef options) {
383 auto result = std::make_unique<T>();
384 if (failed(result->parseFromString(options)))
385 return nullptr;
386 return result;
387 }
388};
389
390/// A default empty option struct to be used for passes that do not need to take
391/// any options.
392struct EmptyPipelineOptions : public PassPipelineOptions<EmptyPipelineOptions> {
393};
394} // namespace mlir
395
396//===----------------------------------------------------------------------===//
397// MLIR Options
398//===----------------------------------------------------------------------===//
399
400namespace llvm {
401namespace cl {
402//===----------------------------------------------------------------------===//
403// std::vector+SmallVector
404//===----------------------------------------------------------------------===//
405
406namespace detail {
407template <typename VectorT, typename ElementT>
408class VectorParserBase : public basic_parser_impl {
409public:
410 VectorParserBase(Option &opt) : basic_parser_impl(opt), elementParser(opt) {}
411
412 using parser_data_type = VectorT;
413
414 bool parse(Option &opt, StringRef argName, StringRef arg,
415 parser_data_type &vector) {
416 if (!arg.consume_front("[") || !arg.consume_back("]")) {
417 return opt.error("expected vector option to be wrapped with '[]'",
418 argName);
419 }
420
422 opt, argName, arg, elementParser,
423 [&](const ElementT &value) { vector.push_back(value); }));
424 }
425
426 static void print(raw_ostream &os, const VectorT &vector) {
427 llvm::interleave(
428 vector, os,
429 [&](const ElementT &value) {
431 llvm::cl::parser<ElementT>>(os, value);
432 },
433 ",");
434 }
435
436 void printOptionInfo(const Option &opt, size_t globalWidth) const {
437 // Add the `vector<>` qualifier to the option info.
438 outs() << " --" << opt.ArgStr;
439 outs() << "=<vector<" << elementParser.getValueName() << ">>";
440 Option::printHelpStr(opt.HelpStr, globalWidth, getOptionWidth(opt));
441 }
442
443 size_t getOptionWidth(const Option &opt) const {
444 // Add the `vector<>` qualifier to the option width.
445 StringRef vectorExt("vector<>");
446 return elementParser.getOptionWidth(opt) + vectorExt.size();
447 }
448
449private:
451};
452} // namespace detail
453
454template <typename T>
455class parser<std::vector<T>>
456 : public detail::VectorParserBase<std::vector<T>, T> {
457public:
458 parser(Option &opt) : detail::VectorParserBase<std::vector<T>, T>(opt) {}
459};
460template <typename T, unsigned N>
461class parser<SmallVector<T, N>>
462 : public detail::VectorParserBase<SmallVector<T, N>, T> {
463public:
464 parser(Option &opt) : detail::VectorParserBase<SmallVector<T, N>, T>(opt) {}
465};
466
467//===----------------------------------------------------------------------===//
468// OpPassManager: OptionValue
469//===----------------------------------------------------------------------===//
470
471template <>
474
480
481 /// Returns if the current option has a value.
482 bool hasValue() const { return value.get(); }
483
484 /// Returns the current value of the option.
486 assert(hasValue() && "invalid option value");
487 return *value;
488 }
489
490 /// Set the value of the option.
491 void setValue(const mlir::OpPassManager &newValue);
492 void setValue(StringRef pipelineStr);
493
494 /// Compare the option with the provided value.
495 bool compare(const mlir::OpPassManager &rhs) const;
496 bool compare(const GenericOptionValue &rhs) const override {
497 const auto &rhsOV =
498 static_cast<const OptionValue<mlir::OpPassManager> &>(rhs);
499 if (!rhsOV.hasValue())
500 return false;
501 return compare(rhsOV.getValue());
502 }
503
504private:
505 void anchor() override;
506
507 /// The underlying pass manager. We use a unique_ptr to avoid the need for the
508 /// full type definition.
509 std::unique_ptr<mlir::OpPassManager> value;
510};
511
512//===----------------------------------------------------------------------===//
513// OpPassManager: Parser
514//===----------------------------------------------------------------------===//
515
516extern template class basic_parser<mlir::OpPassManager>;
517
518template <>
520public:
521 /// A utility struct used when parsing a pass manager that prevents the need
522 /// for a default constructor on OpPassManager.
527 operator const mlir::OpPassManager &() const {
528 assert(value && "parsed value was invalid");
529 return *value;
530 }
531
532 std::unique_ptr<mlir::OpPassManager> value;
533 };
535 using OptVal = OptionValue<mlir::OpPassManager>;
536
537 parser(Option &opt) : basic_parser(opt) {}
538
539 bool parse(Option &, StringRef, StringRef arg, ParsedPassManager &value);
540
541 /// Print an instance of the underling option value to the given stream.
542 static void print(raw_ostream &os, const mlir::OpPassManager &value);
543
544 // Overload in subclass to provide a better default value.
545 StringRef getValueName() const override { return "pass-manager"; }
546
547 void printOptionDiff(const Option &opt, mlir::OpPassManager &pm,
548 const OptVal &defaultValue, size_t globalWidth) const;
549
550 // An out-of-line virtual method to provide a 'home' for this class.
551 void anchor() override;
552};
553
554} // namespace cl
555} // namespace llvm
556
557#endif // MLIR_PASS_PASSOPTIONS_H_
return success()
values clear()
false
Parses a map_entries map type from a string format back into its numeric value.
static llvm::ManagedStatic< PassManagerOptions > options
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
This class represents a pass manager that runs passes on either a specific operation type,...
Definition PassManager.h:46
ListOption< DataType, OptionParser > & operator=(const ListOption< DataType, OptionParser > &other)
ListOption< DataType, OptionParser > & operator=(ArrayRef< DataType > values)
Allow assigning from an ArrayRef.
ArrayRef< DataType > operator*() const
ListOption(PassOptions &parent, StringRef arg, Args &&...args)
MutableArrayRef< DataType > operator*()
Allow accessing the data held by this option.
bool handleOccurrence(unsigned pos, StringRef argName, StringRef arg) override
Option & operator=(const Option &other)
Option(PassOptions &parent, StringRef arg, Args &&...args)
Base container class and manager for all pass options.
Definition PassOptions.h:89
mlir::detail::PassOptions::ListOption elementParser
std::conditional_t< std::is_base_of_v< PassOptions, DataType >, PassOptionsParser< DataType >, std::conditional_t< std::is_base_of< llvm::cl::generic_parser_base, llvm::cl::parser< DataType > >::value, GenericOptionParser< DataType >, llvm::cl::parser< DataType > > > OptionParser
The specific parser to use.
void printOptionDiff(const Option &opt, mlir::OpPassManager &pm, const OptVal &defaultValue, size_t globalWidth) const
StringRef getValueName() const override
static void print(raw_ostream &os, const mlir::OpPassManager &value)
Print an instance of the underling option value to the given stream.
OptionValue< mlir::OpPassManager > OptVal
bool parse(Option &, StringRef, StringRef arg, ParsedPassManager &value)
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:227
llvm::is_detected< has_stream_operator_trait, T > has_stream_operator
Definition PassOptions.h:56
void printOptionValue(raw_ostream &os, const bool &value)
Utility methods for printing option values.
Definition PassOptions.h:60
LogicalResult parseCommaSeparatedList(llvm::cl::Option &opt, StringRef argName, StringRef optionStr, function_ref< LogicalResult(StringRef)> elementParseFn)
Parse a string containing a list of comma-delimited elements, invoking the given parser for each sub-...
decltype(std::declval< raw_ostream & >()<< std::declval< T >()) has_stream_operator_trait
Trait used to detect if a type has a operator<< method.
Definition PassOptions.h:53
AttrTypeReplacer.
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
Definition Query.cpp:21
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:734
Include the generated interface declarations.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:147
bool compare(const GenericOptionValue &rhs) const override
mlir::OpPassManager & getValue() const
Returns the current value of the option.
bool compare(const mlir::OpPassManager &rhs) const
Compare the option with the provided value.
void setValue(const mlir::OpPassManager &newValue)
Set the value of the option.
void setValue(StringRef pipelineStr)
OptionValue(const mlir::OpPassManager &value)
bool hasValue() const
Returns if the current option has a value.
OptionValue(const OptionValue< mlir::OpPassManager > &rhs)
OptionValue< mlir::OpPassManager > & operator=(const mlir::OpPassManager &rhs)
A utility struct used when parsing a pass manager that prevents the need for a default constructor on...
std::unique_ptr< mlir::OpPassManager > value