1 //===- OptTable.cpp - Option Table Implementation -------------------------===//
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 "llvm/Option/OptTable.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/StringRef.h"
12 #include "llvm/ADT/StringSet.h"
13 #include "llvm/Option/Arg.h"
14 #include "llvm/Option/ArgList.h"
15 #include "llvm/Option/OptSpecifier.h"
16 #include "llvm/Option/Option.h"
17 #include "llvm/Support/CommandLine.h" // for expandResponseFiles
18 #include "llvm/Support/Compiler.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <algorithm>
22 #include <cassert>
23 #include <cctype>
24 #include <cstring>
25 #include <map>
26 #include <string>
27 #include <utility>
28 #include <vector>
29 
30 using namespace llvm;
31 using namespace llvm::opt;
32 
33 namespace llvm {
34 namespace opt {
35 
36 // Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
37 // with an exception. '\0' comes at the end of the alphabet instead of the
38 // beginning (thus options precede any other options which prefix them).
39 static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
40   const char *X = A, *Y = B;
41   char a = tolower(*A), b = tolower(*B);
42   while (a == b) {
43     if (a == '\0')
44       return 0;
45 
46     a = tolower(*++X);
47     b = tolower(*++Y);
48   }
49 
50   if (a == '\0') // A is a prefix of B.
51     return 1;
52   if (b == '\0') // B is a prefix of A.
53     return -1;
54 
55   // Otherwise lexicographic.
56   return (a < b) ? -1 : 1;
57 }
58 
59 #ifndef NDEBUG
60 static int StrCmpOptionName(const char *A, const char *B) {
61   if (int N = StrCmpOptionNameIgnoreCase(A, B))
62     return N;
63   return strcmp(A, B);
64 }
65 
66 static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
67   if (&A == &B)
68     return false;
69 
70   if (int N = StrCmpOptionName(A.Name, B.Name))
71     return N < 0;
72 
73   for (const char * const *APre = A.Prefixes,
74                   * const *BPre = B.Prefixes;
75                           *APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
76     if (int N = StrCmpOptionName(*APre, *BPre))
77       return N < 0;
78   }
79 
80   // Names are the same, check that classes are in order; exactly one
81   // should be joined, and it should succeed the other.
82   assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
83          "Unexpected classes for options with same name.");
84   return B.Kind == Option::JoinedClass;
85 }
86 #endif
87 
88 // Support lower_bound between info and an option name.
89 static inline bool operator<(const OptTable::Info &I, const char *Name) {
90   return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
91 }
92 
93 } // end namespace opt
94 } // end namespace llvm
95 
96 OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
97 
98 OptTable::OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
99     : OptionInfos(OptionInfos), IgnoreCase(IgnoreCase) {
100   // Explicitly zero initialize the error to work around a bug in array
101   // value-initialization on MinGW with gcc 4.3.5.
102 
103   // Find start of normal options.
104   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
105     unsigned Kind = getInfo(i + 1).Kind;
106     if (Kind == Option::InputClass) {
107       assert(!TheInputOptionID && "Cannot have multiple input options!");
108       TheInputOptionID = getInfo(i + 1).ID;
109     } else if (Kind == Option::UnknownClass) {
110       assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
111       TheUnknownOptionID = getInfo(i + 1).ID;
112     } else if (Kind != Option::GroupClass) {
113       FirstSearchableIndex = i;
114       break;
115     }
116   }
117   assert(FirstSearchableIndex != 0 && "No searchable options?");
118 
119 #ifndef NDEBUG
120   // Check that everything after the first searchable option is a
121   // regular option class.
122   for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
123     Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
124     assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
125             Kind != Option::GroupClass) &&
126            "Special options should be defined first!");
127   }
128 
129   // Check that options are in order.
130   for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
131     if (!(getInfo(i) < getInfo(i + 1))) {
132       getOption(i).dump();
133       getOption(i + 1).dump();
134       llvm_unreachable("Options are not in order!");
135     }
136   }
137 #endif
138 
139   // Build prefixes.
140   for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
141                 i != e; ++i) {
142     if (const char *const *P = getInfo(i).Prefixes) {
143       for (; *P != nullptr; ++P) {
144         PrefixesUnion.insert(*P);
145       }
146     }
147   }
148 
149   // Build prefix chars.
150   for (StringSet<>::const_iterator I = PrefixesUnion.begin(),
151                                    E = PrefixesUnion.end(); I != E; ++I) {
152     StringRef Prefix = I->getKey();
153     for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
154                                    C != CE; ++C)
155       if (!is_contained(PrefixChars, *C))
156         PrefixChars.push_back(*C);
157   }
158 }
159 
160 OptTable::~OptTable() = default;
161 
162 const Option OptTable::getOption(OptSpecifier Opt) const {
163   unsigned id = Opt.getID();
164   if (id == 0)
165     return Option(nullptr, nullptr);
166   assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
167   return Option(&getInfo(id), this);
168 }
169 
170 static bool isInput(const StringSet<> &Prefixes, StringRef Arg) {
171   if (Arg == "-")
172     return true;
173   for (StringSet<>::const_iterator I = Prefixes.begin(),
174                                    E = Prefixes.end(); I != E; ++I)
175     if (Arg.startswith(I->getKey()))
176       return false;
177   return true;
178 }
179 
180 /// \returns Matched size. 0 means no match.
181 static unsigned matchOption(const OptTable::Info *I, StringRef Str,
182                             bool IgnoreCase) {
183   for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
184     StringRef Prefix(*Pre);
185     if (Str.startswith(Prefix)) {
186       StringRef Rest = Str.substr(Prefix.size());
187       bool Matched = IgnoreCase
188           ? Rest.startswith_lower(I->Name)
189           : Rest.startswith(I->Name);
190       if (Matched)
191         return Prefix.size() + StringRef(I->Name).size();
192     }
193   }
194   return 0;
195 }
196 
197 // Returns true if one of the Prefixes + In.Names matches Option
198 static bool optionMatches(const OptTable::Info &In, StringRef Option) {
199   if (In.Prefixes)
200     for (size_t I = 0; In.Prefixes[I]; I++)
201       if (Option == std::string(In.Prefixes[I]) + In.Name)
202         return true;
203   return false;
204 }
205 
206 // This function is for flag value completion.
207 // Eg. When "-stdlib=" and "l" was passed to this function, it will return
208 // appropiriate values for stdlib, which starts with l.
209 std::vector<std::string>
210 OptTable::suggestValueCompletions(StringRef Option, StringRef Arg) const {
211   // Search all options and return possible values.
212   for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
213     const Info &In = OptionInfos[I];
214     if (!In.Values || !optionMatches(In, Option))
215       continue;
216 
217     SmallVector<StringRef, 8> Candidates;
218     StringRef(In.Values).split(Candidates, ",", -1, false);
219 
220     std::vector<std::string> Result;
221     for (StringRef Val : Candidates)
222       if (Val.startswith(Arg) && Arg.compare(Val))
223         Result.push_back(std::string(Val));
224     return Result;
225   }
226   return {};
227 }
228 
229 std::vector<std::string>
230 OptTable::findByPrefix(StringRef Cur, unsigned short DisableFlags) const {
231   std::vector<std::string> Ret;
232   for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
233     const Info &In = OptionInfos[I];
234     if (!In.Prefixes || (!In.HelpText && !In.GroupID))
235       continue;
236     if (In.Flags & DisableFlags)
237       continue;
238 
239     for (int I = 0; In.Prefixes[I]; I++) {
240       std::string S = std::string(In.Prefixes[I]) + std::string(In.Name) + "\t";
241       if (In.HelpText)
242         S += In.HelpText;
243       if (StringRef(S).startswith(Cur) && S.compare(std::string(Cur) + "\t"))
244         Ret.push_back(S);
245     }
246   }
247   return Ret;
248 }
249 
250 unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
251                                unsigned FlagsToInclude, unsigned FlagsToExclude,
252                                unsigned MinimumLength) const {
253   assert(!Option.empty());
254 
255   // Consider each [option prefix + option name] pair as a candidate, finding
256   // the closest match.
257   unsigned BestDistance = UINT_MAX;
258   for (const Info &CandidateInfo :
259        ArrayRef<Info>(OptionInfos).drop_front(FirstSearchableIndex)) {
260     StringRef CandidateName = CandidateInfo.Name;
261 
262     // We can eliminate some option prefix/name pairs as candidates right away:
263     // * Ignore option candidates with empty names, such as "--", or names
264     //   that do not meet the minimum length.
265     if (CandidateName.empty() || CandidateName.size() < MinimumLength)
266       continue;
267 
268     // * If FlagsToInclude were specified, ignore options that don't include
269     //   those flags.
270     if (FlagsToInclude && !(CandidateInfo.Flags & FlagsToInclude))
271       continue;
272     // * Ignore options that contain the FlagsToExclude.
273     if (CandidateInfo.Flags & FlagsToExclude)
274       continue;
275 
276     // * Ignore positional argument option candidates (which do not
277     //   have prefixes).
278     if (!CandidateInfo.Prefixes)
279       continue;
280 
281     // Now check if the candidate ends with a character commonly used when
282     // delimiting an option from its value, such as '=' or ':'. If it does,
283     // attempt to split the given option based on that delimiter.
284     StringRef LHS, RHS;
285     char Last = CandidateName.back();
286     bool CandidateHasDelimiter = Last == '=' || Last == ':';
287     std::string NormalizedName = std::string(Option);
288     if (CandidateHasDelimiter) {
289       std::tie(LHS, RHS) = Option.split(Last);
290       NormalizedName = std::string(LHS);
291       if (Option.find(Last) == LHS.size())
292         NormalizedName += Last;
293     }
294 
295     // Consider each possible prefix for each candidate to find the most
296     // appropriate one. For example, if a user asks for "--helm", suggest
297     // "--help" over "-help".
298     for (int P = 0;
299          const char *const CandidatePrefix = CandidateInfo.Prefixes[P]; P++) {
300       std::string Candidate = (CandidatePrefix + CandidateName).str();
301       StringRef CandidateRef = Candidate;
302       unsigned Distance =
303           CandidateRef.edit_distance(NormalizedName, /*AllowReplacements=*/true,
304                                      /*MaxEditDistance=*/BestDistance);
305       if (RHS.empty() && CandidateHasDelimiter) {
306         // The Candidate ends with a = or : delimiter, but the option passed in
307         // didn't contain the delimiter (or doesn't have anything after it).
308         // In that case, penalize the correction: `-nodefaultlibs` is more
309         // likely to be a spello for `-nodefaultlib` than `-nodefaultlib:` even
310         // though both have an unmodified editing distance of 1, since the
311         // latter would need an argument.
312         ++Distance;
313       }
314       if (Distance < BestDistance) {
315         BestDistance = Distance;
316         NearestString = (Candidate + RHS).str();
317       }
318     }
319   }
320   return BestDistance;
321 }
322 
323 bool OptTable::addValues(const char *Option, const char *Values) {
324   for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
325     Info &In = OptionInfos[I];
326     if (optionMatches(In, Option)) {
327       In.Values = Values;
328       return true;
329     }
330   }
331   return false;
332 }
333 
334 // Parse a single argument, return the new argument, and update Index. If
335 // GroupedShortOptions is true, -a matches "-abc" and the argument in Args will
336 // be updated to "-bc". This overload does not support
337 // FlagsToInclude/FlagsToExclude or case insensitive options.
338 Arg *OptTable::parseOneArgGrouped(InputArgList &Args, unsigned &Index) const {
339   // Anything that doesn't start with PrefixesUnion is an input, as is '-'
340   // itself.
341   const char *CStr = Args.getArgString(Index);
342   StringRef Str(CStr);
343   if (isInput(PrefixesUnion, Str))
344     return new Arg(getOption(TheInputOptionID), Str, Index++, CStr);
345 
346   const Info *End = OptionInfos.data() + OptionInfos.size();
347   StringRef Name = Str.ltrim(PrefixChars);
348   const Info *Start = std::lower_bound(
349       OptionInfos.data() + FirstSearchableIndex, End, Name.data());
350   const Info *Fallback = nullptr;
351   unsigned Prev = Index;
352 
353   // Search for the option which matches Str.
354   for (; Start != End; ++Start) {
355     unsigned ArgSize = matchOption(Start, Str, IgnoreCase);
356     if (!ArgSize)
357       continue;
358 
359     Option Opt(Start, this);
360     if (Arg *A = Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
361                             false, Index))
362       return A;
363 
364     // If Opt is a Flag of length 2 (e.g. "-a"), we know it is a prefix of
365     // the current argument (e.g. "-abc"). Match it as a fallback if no longer
366     // option (e.g. "-ab") exists.
367     if (ArgSize == 2 && Opt.getKind() == Option::FlagClass)
368       Fallback = Start;
369 
370     // Otherwise, see if the argument is missing.
371     if (Prev != Index)
372       return nullptr;
373   }
374   if (Fallback) {
375     Option Opt(Fallback, this);
376     if (Arg *A = Opt.accept(Args, Str.substr(0, 2), true, Index)) {
377       if (Str.size() == 2)
378         ++Index;
379       else
380         Args.replaceArgString(Index, Twine('-') + Str.substr(2));
381       return A;
382     }
383   }
384 
385   return new Arg(getOption(TheUnknownOptionID), Str, Index++, CStr);
386 }
387 
388 Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
389                            unsigned FlagsToInclude,
390                            unsigned FlagsToExclude) const {
391   unsigned Prev = Index;
392   const char *Str = Args.getArgString(Index);
393 
394   // Anything that doesn't start with PrefixesUnion is an input, as is '-'
395   // itself.
396   if (isInput(PrefixesUnion, Str))
397     return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
398 
399   const Info *Start = OptionInfos.data() + FirstSearchableIndex;
400   const Info *End = OptionInfos.data() + OptionInfos.size();
401   StringRef Name = StringRef(Str).ltrim(PrefixChars);
402 
403   // Search for the first next option which could be a prefix.
404   Start = std::lower_bound(Start, End, Name.data());
405 
406   // Options are stored in sorted order, with '\0' at the end of the
407   // alphabet. Since the only options which can accept a string must
408   // prefix it, we iteratively search for the next option which could
409   // be a prefix.
410   //
411   // FIXME: This is searching much more than necessary, but I am
412   // blanking on the simplest way to make it fast. We can solve this
413   // problem when we move to TableGen.
414   for (; Start != End; ++Start) {
415     unsigned ArgSize = 0;
416     // Scan for first option which is a proper prefix.
417     for (; Start != End; ++Start)
418       if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
419         break;
420     if (Start == End)
421       break;
422 
423     Option Opt(Start, this);
424 
425     if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
426       continue;
427     if (Opt.hasFlag(FlagsToExclude))
428       continue;
429 
430     // See if this option matches.
431     if (Arg *A = Opt.accept(Args, StringRef(Args.getArgString(Index), ArgSize),
432                             false, Index))
433       return A;
434 
435     // Otherwise, see if this argument was missing values.
436     if (Prev != Index)
437       return nullptr;
438   }
439 
440   // If we failed to find an option and this arg started with /, then it's
441   // probably an input path.
442   if (Str[0] == '/')
443     return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
444 
445   return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
446 }
447 
448 InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
449                                  unsigned &MissingArgIndex,
450                                  unsigned &MissingArgCount,
451                                  unsigned FlagsToInclude,
452                                  unsigned FlagsToExclude) const {
453   InputArgList Args(ArgArr.begin(), ArgArr.end());
454 
455   // FIXME: Handle '@' args (or at least error on them).
456 
457   MissingArgIndex = MissingArgCount = 0;
458   unsigned Index = 0, End = ArgArr.size();
459   while (Index < End) {
460     // Ingore nullptrs, they are response file's EOL markers
461     if (Args.getArgString(Index) == nullptr) {
462       ++Index;
463       continue;
464     }
465     // Ignore empty arguments (other things may still take them as arguments).
466     StringRef Str = Args.getArgString(Index);
467     if (Str == "") {
468       ++Index;
469       continue;
470     }
471 
472     unsigned Prev = Index;
473     Arg *A = GroupedShortOptions
474                  ? parseOneArgGrouped(Args, Index)
475                  : ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
476     assert((Index > Prev || GroupedShortOptions) &&
477            "Parser failed to consume argument.");
478 
479     // Check for missing argument error.
480     if (!A) {
481       assert(Index >= End && "Unexpected parser error.");
482       assert(Index - Prev - 1 && "No missing arguments!");
483       MissingArgIndex = Prev;
484       MissingArgCount = Index - Prev - 1;
485       break;
486     }
487 
488     Args.append(A);
489   }
490 
491   return Args;
492 }
493 
494 InputArgList OptTable::parseArgs(int Argc, char *const *Argv,
495                                  OptSpecifier Unknown, StringSaver &Saver,
496                                  function_ref<void(StringRef)> ErrorFn) const {
497   SmallVector<const char *, 0> NewArgv;
498   // The environment variable specifies initial options which can be overridden
499   // by commnad line options.
500   cl::expandResponseFiles(Argc, Argv, EnvVar, Saver, NewArgv);
501 
502   unsigned MAI, MAC;
503   opt::InputArgList Args = ParseArgs(makeArrayRef(NewArgv), MAI, MAC);
504   if (MAC)
505     ErrorFn((Twine(Args.getArgString(MAI)) + ": missing argument").str());
506 
507   // For each unknwon option, call ErrorFn with a formatted error message. The
508   // message includes a suggested alternative option spelling if available.
509   std::string Nearest;
510   for (const opt::Arg *A : Args.filtered(Unknown)) {
511     std::string Spelling = A->getAsString(Args);
512     if (findNearest(Spelling, Nearest) > 1)
513       ErrorFn("unknown argument '" + A->getAsString(Args) + "'");
514     else
515       ErrorFn("unknown argument '" + A->getAsString(Args) +
516               "', did you mean '" + Nearest + "'?");
517   }
518   return Args;
519 }
520 
521 static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
522   const Option O = Opts.getOption(Id);
523   std::string Name = O.getPrefixedName();
524 
525   // Add metavar, if used.
526   switch (O.getKind()) {
527   case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
528     llvm_unreachable("Invalid option with help text.");
529 
530   case Option::MultiArgClass:
531     if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
532       // For MultiArgs, metavar is full list of all argument names.
533       Name += ' ';
534       Name += MetaVarName;
535     }
536     else {
537       // For MultiArgs<N>, if metavar not supplied, print <value> N times.
538       for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
539         Name += " <value>";
540       }
541     }
542     break;
543 
544   case Option::FlagClass:
545     break;
546 
547   case Option::ValuesClass:
548     break;
549 
550   case Option::SeparateClass: case Option::JoinedOrSeparateClass:
551   case Option::RemainingArgsClass: case Option::RemainingArgsJoinedClass:
552     Name += ' ';
553     LLVM_FALLTHROUGH;
554   case Option::JoinedClass: case Option::CommaJoinedClass:
555   case Option::JoinedAndSeparateClass:
556     if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
557       Name += MetaVarName;
558     else
559       Name += "<value>";
560     break;
561   }
562 
563   return Name;
564 }
565 
566 namespace {
567 struct OptionInfo {
568   std::string Name;
569   StringRef HelpText;
570 };
571 } // namespace
572 
573 static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
574                                 std::vector<OptionInfo> &OptionHelp) {
575   OS << Title << ":\n";
576 
577   // Find the maximum option length.
578   unsigned OptionFieldWidth = 0;
579   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
580     // Limit the amount of padding we are willing to give up for alignment.
581     unsigned Length = OptionHelp[i].Name.size();
582     if (Length <= 23)
583       OptionFieldWidth = std::max(OptionFieldWidth, Length);
584   }
585 
586   const unsigned InitialPad = 2;
587   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
588     const std::string &Option = OptionHelp[i].Name;
589     int Pad = OptionFieldWidth - int(Option.size());
590     OS.indent(InitialPad) << Option;
591 
592     // Break on long option names.
593     if (Pad < 0) {
594       OS << "\n";
595       Pad = OptionFieldWidth + InitialPad;
596     }
597     OS.indent(Pad + 1) << OptionHelp[i].HelpText << '\n';
598   }
599 }
600 
601 static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
602   unsigned GroupID = Opts.getOptionGroupID(Id);
603 
604   // If not in a group, return the default help group.
605   if (!GroupID)
606     return "OPTIONS";
607 
608   // Abuse the help text of the option groups to store the "help group"
609   // name.
610   //
611   // FIXME: Split out option groups.
612   if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
613     return GroupHelp;
614 
615   // Otherwise keep looking.
616   return getOptionHelpGroup(Opts, GroupID);
617 }
618 
619 void OptTable::PrintHelp(raw_ostream &OS, const char *Usage, const char *Title,
620                          bool ShowHidden, bool ShowAllAliases) const {
621   PrintHelp(OS, Usage, Title, /*Include*/ 0, /*Exclude*/
622             (ShowHidden ? 0 : HelpHidden), ShowAllAliases);
623 }
624 
625 void OptTable::PrintHelp(raw_ostream &OS, const char *Usage, const char *Title,
626                          unsigned FlagsToInclude, unsigned FlagsToExclude,
627                          bool ShowAllAliases) const {
628   OS << "OVERVIEW: " << Title << "\n\n";
629   OS << "USAGE: " << Usage << "\n\n";
630 
631   // Render help text into a map of group-name to a list of (option, help)
632   // pairs.
633   std::map<std::string, std::vector<OptionInfo>> GroupedOptionHelp;
634 
635   for (unsigned Id = 1, e = getNumOptions() + 1; Id != e; ++Id) {
636     // FIXME: Split out option groups.
637     if (getOptionKind(Id) == Option::GroupClass)
638       continue;
639 
640     unsigned Flags = getInfo(Id).Flags;
641     if (FlagsToInclude && !(Flags & FlagsToInclude))
642       continue;
643     if (Flags & FlagsToExclude)
644       continue;
645 
646     // If an alias doesn't have a help text, show a help text for the aliased
647     // option instead.
648     const char *HelpText = getOptionHelpText(Id);
649     if (!HelpText && ShowAllAliases) {
650       const Option Alias = getOption(Id).getAlias();
651       if (Alias.isValid())
652         HelpText = getOptionHelpText(Alias.getID());
653     }
654 
655     if (HelpText) {
656       const char *HelpGroup = getOptionHelpGroup(*this, Id);
657       const std::string &OptName = getOptionHelpName(*this, Id);
658       GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
659     }
660   }
661 
662   for (auto& OptionGroup : GroupedOptionHelp) {
663     if (OptionGroup.first != GroupedOptionHelp.begin()->first)
664       OS << "\n";
665     PrintHelpOptionList(OS, OptionGroup.first, OptionGroup.second);
666   }
667 
668   OS.flush();
669 }
670