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