1 //===- PassRegistry.cpp - Pass Registration Utilities ---------------------===//
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 #include "mlir/Pass/PassRegistry.h"
10 #include "mlir/Pass/Pass.h"
11 #include "mlir/Pass/PassManager.h"
12 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/Support/ManagedStatic.h"
14 #include "llvm/Support/MemoryBuffer.h"
15 #include "llvm/Support/SourceMgr.h"
16 
17 using namespace mlir;
18 using namespace detail;
19 
20 /// Static mapping of all of the registered passes.
21 static llvm::ManagedStatic<DenseMap<TypeID, PassInfo>> passRegistry;
22 
23 /// Static mapping of all of the registered pass pipelines.
24 static llvm::ManagedStatic<llvm::StringMap<PassPipelineInfo>>
25     passPipelineRegistry;
26 
27 /// Utility to create a default registry function from a pass instance.
28 static PassRegistryFunction
29 buildDefaultRegistryFn(const PassAllocatorFunction &allocator) {
30   return [=](OpPassManager &pm, StringRef options) {
31     std::unique_ptr<Pass> pass = allocator();
32     LogicalResult result = pass->initializeOptions(options);
33     pm.addPass(std::move(pass));
34     return result;
35   };
36 }
37 
38 /// Utility to print the help string for a specific option.
39 static void printOptionHelp(StringRef arg, StringRef desc, size_t indent,
40                             size_t descIndent, bool isTopLevel) {
41   size_t numSpaces = descIndent - indent - 4;
42   llvm::outs().indent(indent)
43       << "--" << llvm::left_justify(arg, numSpaces) << "-   " << desc << '\n';
44 }
45 
46 //===----------------------------------------------------------------------===//
47 // PassRegistry
48 //===----------------------------------------------------------------------===//
49 
50 /// Print the help information for this pass. This includes the argument,
51 /// description, and any pass options. `descIndent` is the indent that the
52 /// descriptions should be aligned.
53 void PassRegistryEntry::printHelpStr(size_t indent, size_t descIndent) const {
54   printOptionHelp(getPassArgument(), getPassDescription(), indent, descIndent,
55                   /*isTopLevel=*/true);
56   // If this entry has options, print the help for those as well.
57   optHandler([=](const PassOptions &options) {
58     options.printHelp(indent, descIndent);
59   });
60 }
61 
62 /// Return the maximum width required when printing the options of this
63 /// entry.
64 size_t PassRegistryEntry::getOptionWidth() const {
65   size_t maxLen = 0;
66   optHandler([&](const PassOptions &options) mutable {
67     maxLen = options.getOptionWidth() + 2;
68   });
69   return maxLen;
70 }
71 
72 //===----------------------------------------------------------------------===//
73 // PassPipelineInfo
74 //===----------------------------------------------------------------------===//
75 
76 void mlir::registerPassPipeline(
77     StringRef arg, StringRef description, const PassRegistryFunction &function,
78     std::function<void(function_ref<void(const PassOptions &)>)> optHandler) {
79   PassPipelineInfo pipelineInfo(arg, description, function, optHandler);
80   bool inserted = passPipelineRegistry->try_emplace(arg, pipelineInfo).second;
81   assert(inserted && "Pass pipeline registered multiple times");
82   (void)inserted;
83 }
84 
85 //===----------------------------------------------------------------------===//
86 // PassInfo
87 //===----------------------------------------------------------------------===//
88 
89 PassInfo::PassInfo(StringRef arg, StringRef description, TypeID passID,
90                    const PassAllocatorFunction &allocator)
91     : PassRegistryEntry(
92           arg, description, buildDefaultRegistryFn(allocator),
93           // Use a temporary pass to provide an options instance.
94           [=](function_ref<void(const PassOptions &)> optHandler) {
95             optHandler(allocator()->passOptions);
96           }) {}
97 
98 void mlir::registerPass(StringRef arg, StringRef description,
99                         const PassAllocatorFunction &function) {
100   // TODO: We should use the 'arg' as the lookup key instead of the pass id.
101   TypeID passID = function()->getTypeID();
102   PassInfo passInfo(arg, description, passID, function);
103   passRegistry->try_emplace(passID, passInfo);
104 }
105 
106 /// Returns the pass info for the specified pass class or null if unknown.
107 const PassInfo *mlir::Pass::lookupPassInfo(TypeID passID) {
108   auto it = passRegistry->find(passID);
109   if (it == passRegistry->end())
110     return nullptr;
111   return &it->getSecond();
112 }
113 
114 //===----------------------------------------------------------------------===//
115 // PassOptions
116 //===----------------------------------------------------------------------===//
117 
118 /// Out of line virtual function to provide home for the class.
119 void detail::PassOptions::OptionBase::anchor() {}
120 
121 /// Copy the option values from 'other'.
122 void detail::PassOptions::copyOptionValuesFrom(const PassOptions &other) {
123   assert(options.size() == other.options.size());
124   if (options.empty())
125     return;
126   for (auto optionsIt : llvm::zip(options, other.options))
127     std::get<0>(optionsIt)->copyValueFrom(*std::get<1>(optionsIt));
128 }
129 
130 LogicalResult detail::PassOptions::parseFromString(StringRef options) {
131   // TODO(parkers): Handle escaping strings.
132   // NOTE: `options` is modified in place to always refer to the unprocessed
133   // part of the string.
134   while (!options.empty()) {
135     size_t spacePos = options.find(' ');
136     StringRef arg = options;
137     if (spacePos != StringRef::npos) {
138       arg = options.substr(0, spacePos);
139       options = options.substr(spacePos + 1);
140     } else {
141       options = StringRef();
142     }
143     if (arg.empty())
144       continue;
145 
146     // At this point, arg refers to everything that is non-space in options
147     // upto the next space, and options refers to the rest of the string after
148     // that point.
149 
150     // Split the individual option on '=' to form key and value. If there is no
151     // '=', then value is `StringRef()`.
152     size_t equalPos = arg.find('=');
153     StringRef key = arg;
154     StringRef value;
155     if (equalPos != StringRef::npos) {
156       key = arg.substr(0, equalPos);
157       value = arg.substr(equalPos + 1);
158     }
159     auto it = OptionsMap.find(key);
160     if (it == OptionsMap.end()) {
161       llvm::errs() << "<Pass-Options-Parser>: no such option " << key << "\n";
162       return failure();
163     }
164     if (llvm::cl::ProvidePositionalOption(it->second, value, 0))
165       return failure();
166   }
167 
168   return success();
169 }
170 
171 /// Print the options held by this struct in a form that can be parsed via
172 /// 'parseFromString'.
173 void detail::PassOptions::print(raw_ostream &os) {
174   // If there are no options, there is nothing left to do.
175   if (OptionsMap.empty())
176     return;
177 
178   // Sort the options to make the ordering deterministic.
179   SmallVector<OptionBase *, 4> orderedOps(options.begin(), options.end());
180   auto compareOptionArgs = [](OptionBase *const *lhs, OptionBase *const *rhs) {
181     return (*lhs)->getArgStr().compare((*rhs)->getArgStr());
182   };
183   llvm::array_pod_sort(orderedOps.begin(), orderedOps.end(), compareOptionArgs);
184 
185   // Interleave the options with ' '.
186   os << '{';
187   llvm::interleave(
188       orderedOps, os, [&](OptionBase *option) { option->print(os); }, " ");
189   os << '}';
190 }
191 
192 /// Print the help string for the options held by this struct. `descIndent` is
193 /// the indent within the stream that the descriptions should be aligned.
194 void detail::PassOptions::printHelp(size_t indent, size_t descIndent) const {
195   // Sort the options to make the ordering deterministic.
196   SmallVector<OptionBase *, 4> orderedOps(options.begin(), options.end());
197   auto compareOptionArgs = [](OptionBase *const *lhs, OptionBase *const *rhs) {
198     return (*lhs)->getArgStr().compare((*rhs)->getArgStr());
199   };
200   llvm::array_pod_sort(orderedOps.begin(), orderedOps.end(), compareOptionArgs);
201   for (OptionBase *option : orderedOps) {
202     // TODO(riverriddle) printOptionInfo assumes a specific indent and will
203     // print options with values with incorrect indentation. We should add
204     // support to llvm::cl::Option for passing in a base indent to use when
205     // printing.
206     llvm::outs().indent(indent);
207     option->getOption()->printOptionInfo(descIndent - indent);
208   }
209 }
210 
211 /// Return the maximum width required when printing the help string.
212 size_t detail::PassOptions::getOptionWidth() const {
213   size_t max = 0;
214   for (auto *option : options)
215     max = std::max(max, option->getOption()->getOptionWidth());
216   return max;
217 }
218 
219 //===----------------------------------------------------------------------===//
220 // TextualPassPipeline Parser
221 //===----------------------------------------------------------------------===//
222 
223 namespace {
224 /// This class represents a textual description of a pass pipeline.
225 class TextualPipeline {
226 public:
227   /// Try to initialize this pipeline with the given pipeline text.
228   /// `errorStream` is the output stream to emit errors to.
229   LogicalResult initialize(StringRef text, raw_ostream &errorStream);
230 
231   /// Add the internal pipeline elements to the provided pass manager.
232   LogicalResult addToPipeline(OpPassManager &pm) const;
233 
234 private:
235   /// A functor used to emit errors found during pipeline handling. The first
236   /// parameter corresponds to the raw location within the pipeline string. This
237   /// should always return failure.
238   using ErrorHandlerT = function_ref<LogicalResult(const char *, Twine)>;
239 
240   /// A struct to capture parsed pass pipeline names.
241   ///
242   /// A pipeline is defined as a series of names, each of which may in itself
243   /// recursively contain a nested pipeline. A name is either the name of a pass
244   /// (e.g. "cse") or the name of an operation type (e.g. "func"). If the name
245   /// is the name of a pass, the InnerPipeline is empty, since passes cannot
246   /// contain inner pipelines.
247   struct PipelineElement {
248     PipelineElement(StringRef name) : name(name), registryEntry(nullptr) {}
249 
250     StringRef name;
251     StringRef options;
252     const PassRegistryEntry *registryEntry;
253     std::vector<PipelineElement> innerPipeline;
254   };
255 
256   /// Parse the given pipeline text into the internal pipeline vector. This
257   /// function only parses the structure of the pipeline, and does not resolve
258   /// its elements.
259   LogicalResult parsePipelineText(StringRef text, ErrorHandlerT errorHandler);
260 
261   /// Resolve the elements of the pipeline, i.e. connect passes and pipelines to
262   /// the corresponding registry entry.
263   LogicalResult
264   resolvePipelineElements(MutableArrayRef<PipelineElement> elements,
265                           ErrorHandlerT errorHandler);
266 
267   /// Resolve a single element of the pipeline.
268   LogicalResult resolvePipelineElement(PipelineElement &element,
269                                        ErrorHandlerT errorHandler);
270 
271   /// Add the given pipeline elements to the provided pass manager.
272   LogicalResult addToPipeline(ArrayRef<PipelineElement> elements,
273                               OpPassManager &pm) const;
274 
275   std::vector<PipelineElement> pipeline;
276 };
277 
278 } // end anonymous namespace
279 
280 /// Try to initialize this pipeline with the given pipeline text. An option is
281 /// given to enable accurate error reporting.
282 LogicalResult TextualPipeline::initialize(StringRef text,
283                                           raw_ostream &errorStream) {
284   // Build a source manager to use for error reporting.
285   llvm::SourceMgr pipelineMgr;
286   pipelineMgr.AddNewSourceBuffer(llvm::MemoryBuffer::getMemBuffer(
287                                      text, "MLIR Textual PassPipeline Parser"),
288                                  llvm::SMLoc());
289   auto errorHandler = [&](const char *rawLoc, Twine msg) {
290     pipelineMgr.PrintMessage(errorStream, llvm::SMLoc::getFromPointer(rawLoc),
291                              llvm::SourceMgr::DK_Error, msg);
292     return failure();
293   };
294 
295   // Parse the provided pipeline string.
296   if (failed(parsePipelineText(text, errorHandler)))
297     return failure();
298   return resolvePipelineElements(pipeline, errorHandler);
299 }
300 
301 /// Add the internal pipeline elements to the provided pass manager.
302 LogicalResult TextualPipeline::addToPipeline(OpPassManager &pm) const {
303   return addToPipeline(pipeline, pm);
304 }
305 
306 /// Parse the given pipeline text into the internal pipeline vector. This
307 /// function only parses the structure of the pipeline, and does not resolve
308 /// its elements.
309 LogicalResult TextualPipeline::parsePipelineText(StringRef text,
310                                                  ErrorHandlerT errorHandler) {
311   SmallVector<std::vector<PipelineElement> *, 4> pipelineStack = {&pipeline};
312   for (;;) {
313     std::vector<PipelineElement> &pipeline = *pipelineStack.back();
314     size_t pos = text.find_first_of(",(){");
315     pipeline.emplace_back(/*name=*/text.substr(0, pos).trim());
316 
317     // If we have a single terminating name, we're done.
318     if (pos == text.npos)
319       break;
320 
321     text = text.substr(pos);
322     char sep = text[0];
323 
324     // Handle pulling ... from 'pass{...}' out as PipelineElement.options.
325     if (sep == '{') {
326       text = text.substr(1);
327 
328       // Skip over everything until the closing '}' and store as options.
329       size_t close = text.find('}');
330 
331       // TODO(parkers): Handle skipping over quoted sub-strings.
332       if (close == StringRef::npos) {
333         return errorHandler(
334             /*rawLoc=*/text.data() - 1,
335             "missing closing '}' while processing pass options");
336       }
337       pipeline.back().options = text.substr(0, close);
338       text = text.substr(close + 1);
339 
340       // Skip checking for '(' because nested pipelines cannot have options.
341     } else if (sep == '(') {
342       text = text.substr(1);
343 
344       // Push the inner pipeline onto the stack to continue processing.
345       pipelineStack.push_back(&pipeline.back().innerPipeline);
346       continue;
347     }
348 
349     // When handling the close parenthesis, we greedily consume them to avoid
350     // empty strings in the pipeline.
351     while (text.consume_front(")")) {
352       // If we try to pop the outer pipeline we have unbalanced parentheses.
353       if (pipelineStack.size() == 1)
354         return errorHandler(/*rawLoc=*/text.data() - 1,
355                             "encountered extra closing ')' creating unbalanced "
356                             "parentheses while parsing pipeline");
357 
358       pipelineStack.pop_back();
359     }
360 
361     // Check if we've finished parsing.
362     if (text.empty())
363       break;
364 
365     // Otherwise, the end of an inner pipeline always has to be followed by
366     // a comma, and then we can continue.
367     if (!text.consume_front(","))
368       return errorHandler(text.data(), "expected ',' after parsing pipeline");
369   }
370 
371   // Check for unbalanced parentheses.
372   if (pipelineStack.size() > 1)
373     return errorHandler(
374         text.data(),
375         "encountered unbalanced parentheses while parsing pipeline");
376 
377   assert(pipelineStack.back() == &pipeline &&
378          "wrong pipeline at the bottom of the stack");
379   return success();
380 }
381 
382 /// Resolve the elements of the pipeline, i.e. connect passes and pipelines to
383 /// the corresponding registry entry.
384 LogicalResult TextualPipeline::resolvePipelineElements(
385     MutableArrayRef<PipelineElement> elements, ErrorHandlerT errorHandler) {
386   for (auto &elt : elements)
387     if (failed(resolvePipelineElement(elt, errorHandler)))
388       return failure();
389   return success();
390 }
391 
392 /// Resolve a single element of the pipeline.
393 LogicalResult
394 TextualPipeline::resolvePipelineElement(PipelineElement &element,
395                                         ErrorHandlerT errorHandler) {
396   // If the inner pipeline of this element is not empty, this is an operation
397   // pipeline.
398   if (!element.innerPipeline.empty())
399     return resolvePipelineElements(element.innerPipeline, errorHandler);
400 
401   // Otherwise, this must be a pass or pass pipeline.
402   // Check to see if a pipeline was registered with this name.
403   auto pipelineRegistryIt = passPipelineRegistry->find(element.name);
404   if (pipelineRegistryIt != passPipelineRegistry->end()) {
405     element.registryEntry = &pipelineRegistryIt->second;
406     return success();
407   }
408 
409   // If not, then this must be a specific pass name.
410   for (auto &passIt : *passRegistry) {
411     if (passIt.second.getPassArgument() == element.name) {
412       element.registryEntry = &passIt.second;
413       return success();
414     }
415   }
416 
417   // Emit an error for the unknown pass.
418   auto *rawLoc = element.name.data();
419   return errorHandler(rawLoc, "'" + element.name +
420                                   "' does not refer to a "
421                                   "registered pass or pass pipeline");
422 }
423 
424 /// Add the given pipeline elements to the provided pass manager.
425 LogicalResult TextualPipeline::addToPipeline(ArrayRef<PipelineElement> elements,
426                                              OpPassManager &pm) const {
427   for (auto &elt : elements) {
428     if (elt.registryEntry) {
429       if (failed(elt.registryEntry->addToPipeline(pm, elt.options)))
430         return failure();
431     } else if (failed(addToPipeline(elt.innerPipeline, pm.nest(elt.name)))) {
432       return failure();
433     }
434   }
435   return success();
436 }
437 
438 /// This function parses the textual representation of a pass pipeline, and adds
439 /// the result to 'pm' on success. This function returns failure if the given
440 /// pipeline was invalid. 'errorStream' is an optional parameter that, if
441 /// non-null, will be used to emit errors found during parsing.
442 LogicalResult mlir::parsePassPipeline(StringRef pipeline, OpPassManager &pm,
443                                       raw_ostream &errorStream) {
444   TextualPipeline pipelineParser;
445   if (failed(pipelineParser.initialize(pipeline, errorStream)))
446     return failure();
447   if (failed(pipelineParser.addToPipeline(pm)))
448     return failure();
449   return success();
450 }
451 
452 //===----------------------------------------------------------------------===//
453 // PassNameParser
454 //===----------------------------------------------------------------------===//
455 
456 namespace {
457 /// This struct represents the possible data entries in a parsed pass pipeline
458 /// list.
459 struct PassArgData {
460   PassArgData() : registryEntry(nullptr) {}
461   PassArgData(const PassRegistryEntry *registryEntry)
462       : registryEntry(registryEntry) {}
463 
464   /// This field is used when the parsed option corresponds to a registered pass
465   /// or pass pipeline.
466   const PassRegistryEntry *registryEntry;
467 
468   /// This field is set when instance specific pass options have been provided
469   /// on the command line.
470   StringRef options;
471 
472   /// This field is used when the parsed option corresponds to an explicit
473   /// pipeline.
474   TextualPipeline pipeline;
475 };
476 } // end anonymous namespace
477 
478 namespace llvm {
479 namespace cl {
480 /// Define a valid OptionValue for the command line pass argument.
481 template <>
482 struct OptionValue<PassArgData> final
483     : OptionValueBase<PassArgData, /*isClass=*/true> {
484   OptionValue(const PassArgData &value) { this->setValue(value); }
485   OptionValue() = default;
486   void anchor() override {}
487 
488   bool hasValue() const { return true; }
489   const PassArgData &getValue() const { return value; }
490   void setValue(const PassArgData &value) { this->value = value; }
491 
492   PassArgData value;
493 };
494 } // end namespace cl
495 } // end namespace llvm
496 
497 namespace {
498 
499 /// The name for the command line option used for parsing the textual pass
500 /// pipeline.
501 static constexpr StringLiteral passPipelineArg = "pass-pipeline";
502 
503 /// Adds command line option for each registered pass or pass pipeline, as well
504 /// as textual pass pipelines.
505 struct PassNameParser : public llvm::cl::parser<PassArgData> {
506   PassNameParser(llvm::cl::Option &opt) : llvm::cl::parser<PassArgData>(opt) {}
507 
508   void initialize();
509   void printOptionInfo(const llvm::cl::Option &opt,
510                        size_t globalWidth) const override;
511   size_t getOptionWidth(const llvm::cl::Option &opt) const override;
512   bool parse(llvm::cl::Option &opt, StringRef argName, StringRef arg,
513              PassArgData &value);
514 };
515 } // namespace
516 
517 void PassNameParser::initialize() {
518   llvm::cl::parser<PassArgData>::initialize();
519 
520   /// Add an entry for the textual pass pipeline option.
521   addLiteralOption(passPipelineArg, PassArgData(),
522                    "A textual description of a pass pipeline to run");
523 
524   /// Add the pass entries.
525   for (const auto &kv : *passRegistry) {
526     addLiteralOption(kv.second.getPassArgument(), &kv.second,
527                      kv.second.getPassDescription());
528   }
529   /// Add the pass pipeline entries.
530   for (const auto &kv : *passPipelineRegistry) {
531     addLiteralOption(kv.second.getPassArgument(), &kv.second,
532                      kv.second.getPassDescription());
533   }
534 }
535 
536 void PassNameParser::printOptionInfo(const llvm::cl::Option &opt,
537                                      size_t globalWidth) const {
538   // Print the information for the top-level option.
539   if (opt.hasArgStr()) {
540     llvm::outs() << "  --" << opt.ArgStr;
541     opt.printHelpStr(opt.HelpStr, globalWidth, opt.ArgStr.size() + 7);
542   } else {
543     llvm::outs() << "  " << opt.HelpStr << '\n';
544   }
545 
546   // Print the top-level pipeline argument.
547   printOptionHelp(passPipelineArg,
548                   "A textual description of a pass pipeline to run",
549                   /*indent=*/4, globalWidth, /*isTopLevel=*/!opt.hasArgStr());
550 
551   // Functor used to print the ordered entries of a registration map.
552   auto printOrderedEntries = [&](StringRef header, auto &map) {
553     llvm::SmallVector<PassRegistryEntry *, 32> orderedEntries;
554     for (auto &kv : map)
555       orderedEntries.push_back(&kv.second);
556     llvm::array_pod_sort(
557         orderedEntries.begin(), orderedEntries.end(),
558         [](PassRegistryEntry *const *lhs, PassRegistryEntry *const *rhs) {
559           return (*lhs)->getPassArgument().compare((*rhs)->getPassArgument());
560         });
561 
562     llvm::outs().indent(4) << header << ":\n";
563     for (PassRegistryEntry *entry : orderedEntries)
564       entry->printHelpStr(/*indent=*/6, globalWidth);
565   };
566 
567   // Print the available passes.
568   printOrderedEntries("Passes", *passRegistry);
569 
570   // Print the available pass pipelines.
571   if (!passPipelineRegistry->empty())
572     printOrderedEntries("Pass Pipelines", *passPipelineRegistry);
573 }
574 
575 size_t PassNameParser::getOptionWidth(const llvm::cl::Option &opt) const {
576   size_t maxWidth = llvm::cl::parser<PassArgData>::getOptionWidth(opt) + 2;
577 
578   // Check for any wider pass or pipeline options.
579   for (auto &entry : *passRegistry)
580     maxWidth = std::max(maxWidth, entry.second.getOptionWidth() + 4);
581   for (auto &entry : *passPipelineRegistry)
582     maxWidth = std::max(maxWidth, entry.second.getOptionWidth() + 4);
583   return maxWidth;
584 }
585 
586 bool PassNameParser::parse(llvm::cl::Option &opt, StringRef argName,
587                            StringRef arg, PassArgData &value) {
588   // Handle the pipeline option explicitly.
589   if (argName == passPipelineArg)
590     return failed(value.pipeline.initialize(arg, llvm::errs()));
591 
592   // Otherwise, default to the base for handling.
593   if (llvm::cl::parser<PassArgData>::parse(opt, argName, arg, value))
594     return true;
595   value.options = arg;
596   return false;
597 }
598 
599 //===----------------------------------------------------------------------===//
600 // PassPipelineCLParser
601 //===----------------------------------------------------------------------===//
602 
603 namespace mlir {
604 namespace detail {
605 struct PassPipelineCLParserImpl {
606   PassPipelineCLParserImpl(StringRef arg, StringRef description)
607       : passList(arg, llvm::cl::desc(description)) {
608     passList.setValueExpectedFlag(llvm::cl::ValueExpected::ValueOptional);
609   }
610 
611   /// The set of passes and pass pipelines to run.
612   llvm::cl::list<PassArgData, bool, PassNameParser> passList;
613 };
614 } // end namespace detail
615 } // end namespace mlir
616 
617 /// Construct a pass pipeline parser with the given command line description.
618 PassPipelineCLParser::PassPipelineCLParser(StringRef arg, StringRef description)
619     : impl(std::make_unique<detail::PassPipelineCLParserImpl>(arg,
620                                                               description)) {}
621 PassPipelineCLParser::~PassPipelineCLParser() {}
622 
623 /// Returns true if this parser contains any valid options to add.
624 bool PassPipelineCLParser::hasAnyOccurrences() const {
625   return impl->passList.getNumOccurrences() != 0;
626 }
627 
628 /// Returns true if the given pass registry entry was registered at the
629 /// top-level of the parser, i.e. not within an explicit textual pipeline.
630 bool PassPipelineCLParser::contains(const PassRegistryEntry *entry) const {
631   return llvm::any_of(impl->passList, [&](const PassArgData &data) {
632     return data.registryEntry == entry;
633   });
634 }
635 
636 /// Adds the passes defined by this parser entry to the given pass manager.
637 LogicalResult PassPipelineCLParser::addToPipeline(OpPassManager &pm) const {
638   for (auto &passIt : impl->passList) {
639     if (passIt.registryEntry) {
640       if (failed(passIt.registryEntry->addToPipeline(pm, passIt.options)))
641         return failure();
642     } else if (failed(passIt.pipeline.addToPipeline(pm))) {
643       return failure();
644     }
645   }
646   return success();
647 }
648