OSDN Git Service

1858fe941ae80de2eff988354d9be4e6f3ad680c
[android-x86/external-llvm.git] / lib / Support / CommandLine.cpp
1 //===-- CommandLine.cpp - Command line parser 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 // This class implements a command line argument processor that is useful when
10 // creating a tool.  It provides a simple, minimalistic interface that is easily
11 // extensible and supports nonlocal (library) command line options.
12 //
13 // Note that rather than trying to figure out what this code does, you could try
14 // reading the library documentation located in docs/CommandLine.html
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm-c/Support.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Config/config.h"
30 #include "llvm/Support/ConvertUTF.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/StringSaver.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <cstdlib>
42 #include <map>
43 using namespace llvm;
44 using namespace cl;
45
46 #define DEBUG_TYPE "commandline"
47
48 //===----------------------------------------------------------------------===//
49 // Template instantiations and anchors.
50 //
51 namespace llvm {
52 namespace cl {
53 template class basic_parser<bool>;
54 template class basic_parser<boolOrDefault>;
55 template class basic_parser<int>;
56 template class basic_parser<unsigned>;
57 template class basic_parser<unsigned long long>;
58 template class basic_parser<double>;
59 template class basic_parser<float>;
60 template class basic_parser<std::string>;
61 template class basic_parser<char>;
62
63 template class opt<unsigned>;
64 template class opt<int>;
65 template class opt<std::string>;
66 template class opt<char>;
67 template class opt<bool>;
68 }
69 } // end namespace llvm::cl
70
71 // Pin the vtables to this file.
72 void GenericOptionValue::anchor() {}
73 void OptionValue<boolOrDefault>::anchor() {}
74 void OptionValue<std::string>::anchor() {}
75 void Option::anchor() {}
76 void basic_parser_impl::anchor() {}
77 void parser<bool>::anchor() {}
78 void parser<boolOrDefault>::anchor() {}
79 void parser<int>::anchor() {}
80 void parser<unsigned>::anchor() {}
81 void parser<unsigned long long>::anchor() {}
82 void parser<double>::anchor() {}
83 void parser<float>::anchor() {}
84 void parser<std::string>::anchor() {}
85 void parser<char>::anchor() {}
86
87 //===----------------------------------------------------------------------===//
88
89 namespace {
90
91 class CommandLineParser {
92 public:
93   // Globals for name and overview of program.  Program name is not a string to
94   // avoid static ctor/dtor issues.
95   std::string ProgramName;
96   StringRef ProgramOverview;
97
98   // This collects additional help to be printed.
99   std::vector<StringRef> MoreHelp;
100
101   // This collects the different option categories that have been registered.
102   SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
103
104   // This collects the different subcommands that have been registered.
105   SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
106
107   CommandLineParser() : ActiveSubCommand(nullptr) {
108     registerSubCommand(&*TopLevelSubCommand);
109     registerSubCommand(&*AllSubCommands);
110   }
111
112   void ResetAllOptionOccurrences();
113
114   bool ParseCommandLineOptions(int argc, const char *const *argv,
115                                StringRef Overview, raw_ostream *Errs = nullptr);
116
117   void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
118     if (Opt.hasArgStr())
119       return;
120     if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
121       errs() << ProgramName << ": CommandLine Error: Option '" << Name
122              << "' registered more than once!\n";
123       report_fatal_error("inconsistency in registered CommandLine options");
124     }
125
126     // If we're adding this to all sub-commands, add it to the ones that have
127     // already been registered.
128     if (SC == &*AllSubCommands) {
129       for (const auto &Sub : RegisteredSubCommands) {
130         if (SC == Sub)
131           continue;
132         addLiteralOption(Opt, Sub, Name);
133       }
134     }
135   }
136
137   void addLiteralOption(Option &Opt, StringRef Name) {
138     if (Opt.Subs.empty())
139       addLiteralOption(Opt, &*TopLevelSubCommand, Name);
140     else {
141       for (auto SC : Opt.Subs)
142         addLiteralOption(Opt, SC, Name);
143     }
144   }
145
146   void addOption(Option *O, SubCommand *SC) {
147     bool HadErrors = false;
148     if (O->hasArgStr()) {
149       // Add argument to the argument map!
150       if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
151         errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
152                << "' registered more than once!\n";
153         HadErrors = true;
154       }
155     }
156
157     // Remember information about positional options.
158     if (O->getFormattingFlag() == cl::Positional)
159       SC->PositionalOpts.push_back(O);
160     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
161       SC->SinkOpts.push_back(O);
162     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
163       if (SC->ConsumeAfterOpt) {
164         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
165         HadErrors = true;
166       }
167       SC->ConsumeAfterOpt = O;
168     }
169
170     // Fail hard if there were errors. These are strictly unrecoverable and
171     // indicate serious issues such as conflicting option names or an
172     // incorrectly
173     // linked LLVM distribution.
174     if (HadErrors)
175       report_fatal_error("inconsistency in registered CommandLine options");
176
177     // If we're adding this to all sub-commands, add it to the ones that have
178     // already been registered.
179     if (SC == &*AllSubCommands) {
180       for (const auto &Sub : RegisteredSubCommands) {
181         if (SC == Sub)
182           continue;
183         addOption(O, Sub);
184       }
185     }
186   }
187
188   void addOption(Option *O) {
189     if (O->Subs.empty()) {
190       addOption(O, &*TopLevelSubCommand);
191     } else {
192       for (auto SC : O->Subs)
193         addOption(O, SC);
194     }
195   }
196
197   void removeOption(Option *O, SubCommand *SC) {
198     SmallVector<StringRef, 16> OptionNames;
199     O->getExtraOptionNames(OptionNames);
200     if (O->hasArgStr())
201       OptionNames.push_back(O->ArgStr);
202
203     SubCommand &Sub = *SC;
204     for (auto Name : OptionNames)
205       Sub.OptionsMap.erase(Name);
206
207     if (O->getFormattingFlag() == cl::Positional)
208       for (auto Opt = Sub.PositionalOpts.begin();
209            Opt != Sub.PositionalOpts.end(); ++Opt) {
210         if (*Opt == O) {
211           Sub.PositionalOpts.erase(Opt);
212           break;
213         }
214       }
215     else if (O->getMiscFlags() & cl::Sink)
216       for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
217         if (*Opt == O) {
218           Sub.SinkOpts.erase(Opt);
219           break;
220         }
221       }
222     else if (O == Sub.ConsumeAfterOpt)
223       Sub.ConsumeAfterOpt = nullptr;
224   }
225
226   void removeOption(Option *O) {
227     if (O->Subs.empty())
228       removeOption(O, &*TopLevelSubCommand);
229     else {
230       if (O->isInAllSubCommands()) {
231         for (auto SC : RegisteredSubCommands)
232           removeOption(O, SC);
233       } else {
234         for (auto SC : O->Subs)
235           removeOption(O, SC);
236       }
237     }
238   }
239
240   bool hasOptions(const SubCommand &Sub) const {
241     return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
242             nullptr != Sub.ConsumeAfterOpt);
243   }
244
245   bool hasOptions() const {
246     for (const auto &S : RegisteredSubCommands) {
247       if (hasOptions(*S))
248         return true;
249     }
250     return false;
251   }
252
253   SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
254
255   void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
256     SubCommand &Sub = *SC;
257     if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
258       errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
259              << "' registered more than once!\n";
260       report_fatal_error("inconsistency in registered CommandLine options");
261     }
262     Sub.OptionsMap.erase(O->ArgStr);
263   }
264
265   void updateArgStr(Option *O, StringRef NewName) {
266     if (O->Subs.empty())
267       updateArgStr(O, NewName, &*TopLevelSubCommand);
268     else {
269       for (auto SC : O->Subs)
270         updateArgStr(O, NewName, SC);
271     }
272   }
273
274   void printOptionValues();
275
276   void registerCategory(OptionCategory *cat) {
277     assert(count_if(RegisteredOptionCategories,
278                     [cat](const OptionCategory *Category) {
279              return cat->getName() == Category->getName();
280            }) == 0 &&
281            "Duplicate option categories");
282
283     RegisteredOptionCategories.insert(cat);
284   }
285
286   void registerSubCommand(SubCommand *sub) {
287     assert(count_if(RegisteredSubCommands,
288                     [sub](const SubCommand *Sub) {
289                       return (!sub->getName().empty()) &&
290                              (Sub->getName() == sub->getName());
291                     }) == 0 &&
292            "Duplicate subcommands");
293     RegisteredSubCommands.insert(sub);
294
295     // For all options that have been registered for all subcommands, add the
296     // option to this subcommand now.
297     if (sub != &*AllSubCommands) {
298       for (auto &E : AllSubCommands->OptionsMap) {
299         Option *O = E.second;
300         if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
301             O->hasArgStr())
302           addOption(O, sub);
303         else
304           addLiteralOption(*O, sub, E.first());
305       }
306     }
307   }
308
309   void unregisterSubCommand(SubCommand *sub) {
310     RegisteredSubCommands.erase(sub);
311   }
312
313   iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
314   getRegisteredSubcommands() {
315     return make_range(RegisteredSubCommands.begin(),
316                       RegisteredSubCommands.end());
317   }
318
319   void reset() {
320     ActiveSubCommand = nullptr;
321     ProgramName.clear();
322     ProgramOverview = StringRef();
323
324     MoreHelp.clear();
325     RegisteredOptionCategories.clear();
326
327     ResetAllOptionOccurrences();
328     RegisteredSubCommands.clear();
329
330     TopLevelSubCommand->reset();
331     AllSubCommands->reset();
332     registerSubCommand(&*TopLevelSubCommand);
333     registerSubCommand(&*AllSubCommands);
334   }
335
336 private:
337   SubCommand *ActiveSubCommand;
338
339   Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
340   SubCommand *LookupSubCommand(StringRef Name);
341 };
342
343 } // namespace
344
345 static ManagedStatic<CommandLineParser> GlobalParser;
346
347 void cl::AddLiteralOption(Option &O, StringRef Name) {
348   GlobalParser->addLiteralOption(O, Name);
349 }
350
351 extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
352   GlobalParser->MoreHelp.push_back(Help);
353 }
354
355 void Option::addArgument() {
356   GlobalParser->addOption(this);
357   FullyInitialized = true;
358 }
359
360 void Option::removeArgument() { GlobalParser->removeOption(this); }
361
362 void Option::setArgStr(StringRef S) {
363   if (FullyInitialized)
364     GlobalParser->updateArgStr(this, S);
365   assert((S.empty() || S[0] != '-') && "Option can't start with '-");
366   ArgStr = S;
367 }
368
369 // Initialise the general option category.
370 OptionCategory llvm::cl::GeneralCategory("General options");
371
372 void OptionCategory::registerCategory() {
373   GlobalParser->registerCategory(this);
374 }
375
376 // A special subcommand representing no subcommand. It is particularly important
377 // that this ManagedStatic uses constant initailization and not dynamic
378 // initialization because it is referenced from cl::opt constructors, which run
379 // dynamically in an arbitrary order.
380 ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
381
382 // A special subcommand that can be used to put an option into all subcommands.
383 ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
384
385 void SubCommand::registerSubCommand() {
386   GlobalParser->registerSubCommand(this);
387 }
388
389 void SubCommand::unregisterSubCommand() {
390   GlobalParser->unregisterSubCommand(this);
391 }
392
393 void SubCommand::reset() {
394   PositionalOpts.clear();
395   SinkOpts.clear();
396   OptionsMap.clear();
397
398   ConsumeAfterOpt = nullptr;
399 }
400
401 SubCommand::operator bool() const {
402   return (GlobalParser->getActiveSubCommand() == this);
403 }
404
405 //===----------------------------------------------------------------------===//
406 // Basic, shared command line option processing machinery.
407 //
408
409 /// LookupOption - Lookup the option specified by the specified option on the
410 /// command line.  If there is a value specified (after an equal sign) return
411 /// that as well.  This assumes that leading dashes have already been stripped.
412 Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
413                                         StringRef &Value) {
414   // Reject all dashes.
415   if (Arg.empty())
416     return nullptr;
417   assert(&Sub != &*AllSubCommands);
418
419   size_t EqualPos = Arg.find('=');
420
421   // If we have an equals sign, remember the value.
422   if (EqualPos == StringRef::npos) {
423     // Look up the option.
424     auto I = Sub.OptionsMap.find(Arg);
425     if (I == Sub.OptionsMap.end())
426       return nullptr;
427
428     return I != Sub.OptionsMap.end() ? I->second : nullptr;
429   }
430
431   // If the argument before the = is a valid option name and the option allows
432   // non-prefix form (ie is not AlwaysPrefix), we match.  If not, signal match
433   // failure by returning nullptr.
434   auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
435   if (I == Sub.OptionsMap.end())
436     return nullptr;
437
438   auto O = I->second;
439   if (O->getFormattingFlag() == cl::AlwaysPrefix)
440     return nullptr;
441
442   Value = Arg.substr(EqualPos + 1);
443   Arg = Arg.substr(0, EqualPos);
444   return I->second;
445 }
446
447 SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
448   if (Name.empty())
449     return &*TopLevelSubCommand;
450   for (auto S : RegisteredSubCommands) {
451     if (S == &*AllSubCommands)
452       continue;
453     if (S->getName().empty())
454       continue;
455
456     if (StringRef(S->getName()) == StringRef(Name))
457       return S;
458   }
459   return &*TopLevelSubCommand;
460 }
461
462 /// LookupNearestOption - Lookup the closest match to the option specified by
463 /// the specified option on the command line.  If there is a value specified
464 /// (after an equal sign) return that as well.  This assumes that leading dashes
465 /// have already been stripped.
466 static Option *LookupNearestOption(StringRef Arg,
467                                    const StringMap<Option *> &OptionsMap,
468                                    std::string &NearestString) {
469   // Reject all dashes.
470   if (Arg.empty())
471     return nullptr;
472
473   // Split on any equal sign.
474   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
475   StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
476   StringRef &RHS = SplitArg.second;
477
478   // Find the closest match.
479   Option *Best = nullptr;
480   unsigned BestDistance = 0;
481   for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
482                                            ie = OptionsMap.end();
483        it != ie; ++it) {
484     Option *O = it->second;
485     SmallVector<StringRef, 16> OptionNames;
486     O->getExtraOptionNames(OptionNames);
487     if (O->hasArgStr())
488       OptionNames.push_back(O->ArgStr);
489
490     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
491     StringRef Flag = PermitValue ? LHS : Arg;
492     for (auto Name : OptionNames) {
493       unsigned Distance = StringRef(Name).edit_distance(
494           Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
495       if (!Best || Distance < BestDistance) {
496         Best = O;
497         BestDistance = Distance;
498         if (RHS.empty() || !PermitValue)
499           NearestString = Name;
500         else
501           NearestString = (Twine(Name) + "=" + RHS).str();
502       }
503     }
504   }
505
506   return Best;
507 }
508
509 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
510 /// that does special handling of cl::CommaSeparated options.
511 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
512                                           StringRef ArgName, StringRef Value,
513                                           bool MultiArg = false) {
514   // Check to see if this option accepts a comma separated list of values.  If
515   // it does, we have to split up the value into multiple values.
516   if (Handler->getMiscFlags() & CommaSeparated) {
517     StringRef Val(Value);
518     StringRef::size_type Pos = Val.find(',');
519
520     while (Pos != StringRef::npos) {
521       // Process the portion before the comma.
522       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
523         return true;
524       // Erase the portion before the comma, AND the comma.
525       Val = Val.substr(Pos + 1);
526       // Check for another comma.
527       Pos = Val.find(',');
528     }
529
530     Value = Val;
531   }
532
533   return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
534 }
535
536 /// ProvideOption - For Value, this differentiates between an empty value ("")
537 /// and a null value (StringRef()).  The later is accepted for arguments that
538 /// don't allow a value (-foo) the former is rejected (-foo=).
539 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
540                                  StringRef Value, int argc,
541                                  const char *const *argv, int &i) {
542   // Is this a multi-argument option?
543   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
544
545   // Enforce value requirements
546   switch (Handler->getValueExpectedFlag()) {
547   case ValueRequired:
548     if (!Value.data()) { // No value specified?
549       // If no other argument or the option only supports prefix form, we
550       // cannot look at the next argument.
551       if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
552         return Handler->error("requires a value!");
553       // Steal the next argument, like for '-o filename'
554       assert(argv && "null check");
555       Value = StringRef(argv[++i]);
556     }
557     break;
558   case ValueDisallowed:
559     if (NumAdditionalVals > 0)
560       return Handler->error("multi-valued option specified"
561                             " with ValueDisallowed modifier!");
562
563     if (Value.data())
564       return Handler->error("does not allow a value! '" + Twine(Value) +
565                             "' specified.");
566     break;
567   case ValueOptional:
568     break;
569   }
570
571   // If this isn't a multi-arg option, just run the handler.
572   if (NumAdditionalVals == 0)
573     return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
574
575   // If it is, run the handle several times.
576   bool MultiArg = false;
577
578   if (Value.data()) {
579     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
580       return true;
581     --NumAdditionalVals;
582     MultiArg = true;
583   }
584
585   while (NumAdditionalVals > 0) {
586     if (i + 1 >= argc)
587       return Handler->error("not enough values!");
588     assert(argv && "null check");
589     Value = StringRef(argv[++i]);
590
591     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
592       return true;
593     MultiArg = true;
594     --NumAdditionalVals;
595   }
596   return false;
597 }
598
599 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
600   int Dummy = i;
601   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
602 }
603
604 // Option predicates...
605 static inline bool isGrouping(const Option *O) {
606   return O->getMiscFlags() & cl::Grouping;
607 }
608 static inline bool isPrefixedOrGrouping(const Option *O) {
609   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
610          O->getFormattingFlag() == cl::AlwaysPrefix;
611 }
612
613 // getOptionPred - Check to see if there are any options that satisfy the
614 // specified predicate with names that are the prefixes in Name.  This is
615 // checked by progressively stripping characters off of the name, checking to
616 // see if there options that satisfy the predicate.  If we find one, return it,
617 // otherwise return null.
618 //
619 static Option *getOptionPred(StringRef Name, size_t &Length,
620                              bool (*Pred)(const Option *),
621                              const StringMap<Option *> &OptionsMap) {
622
623   StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
624
625   // Loop while we haven't found an option and Name still has at least two
626   // characters in it (so that the next iteration will not be the empty
627   // string.
628   while (OMI == OptionsMap.end() && Name.size() > 1) {
629     Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
630     OMI = OptionsMap.find(Name);
631   }
632
633   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
634     Length = Name.size();
635     return OMI->second; // Found one!
636   }
637   return nullptr; // No option found!
638 }
639
640 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
641 /// with at least one '-') does not fully match an available option.  Check to
642 /// see if this is a prefix or grouped option.  If so, split arg into output an
643 /// Arg/Value pair and return the Option to parse it with.
644 static Option *
645 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
646                               bool &ErrorParsing,
647                               const StringMap<Option *> &OptionsMap) {
648   if (Arg.size() == 1)
649     return nullptr;
650
651   // Do the lookup!
652   size_t Length = 0;
653   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
654   if (!PGOpt)
655     return nullptr;
656
657   do {
658     StringRef MaybeValue =
659         (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
660     Arg = Arg.substr(0, Length);
661     assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
662
663     // cl::Prefix options do not preserve '=' when used separately.
664     // The behavior for them with grouped options should be the same.
665     if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
666         (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
667       Value = MaybeValue;
668       return PGOpt;
669     }
670
671     if (MaybeValue[0] == '=') {
672       Value = MaybeValue.substr(1);
673       return PGOpt;
674     }
675
676     // This must be a grouped option.
677     assert(isGrouping(PGOpt) && "Broken getOptionPred!");
678
679     // Grouping options inside a group can't have values.
680     if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
681       ErrorParsing |= PGOpt->error("may not occur within a group!");
682       return nullptr;
683     }
684
685     // Because the value for the option is not required, we don't need to pass
686     // argc/argv in.
687     int Dummy = 0;
688     ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
689
690     // Get the next grouping option.
691     Arg = MaybeValue;
692     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
693   } while (PGOpt);
694
695   // We could not find a grouping option in the remainder of Arg.
696   return nullptr;
697 }
698
699 static bool RequiresValue(const Option *O) {
700   return O->getNumOccurrencesFlag() == cl::Required ||
701          O->getNumOccurrencesFlag() == cl::OneOrMore;
702 }
703
704 static bool EatsUnboundedNumberOfValues(const Option *O) {
705   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
706          O->getNumOccurrencesFlag() == cl::OneOrMore;
707 }
708
709 static bool isWhitespace(char C) {
710   return C == ' ' || C == '\t' || C == '\r' || C == '\n';
711 }
712
713 static bool isWhitespaceOrNull(char C) {
714   return isWhitespace(C) || C == '\0';
715 }
716
717 static bool isQuote(char C) { return C == '\"' || C == '\''; }
718
719 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
720                                 SmallVectorImpl<const char *> &NewArgv,
721                                 bool MarkEOLs) {
722   SmallString<128> Token;
723   for (size_t I = 0, E = Src.size(); I != E; ++I) {
724     // Consume runs of whitespace.
725     if (Token.empty()) {
726       while (I != E && isWhitespace(Src[I])) {
727         // Mark the end of lines in response files
728         if (MarkEOLs && Src[I] == '\n')
729           NewArgv.push_back(nullptr);
730         ++I;
731       }
732       if (I == E)
733         break;
734     }
735
736     char C = Src[I];
737
738     // Backslash escapes the next character.
739     if (I + 1 < E && C == '\\') {
740       ++I; // Skip the escape.
741       Token.push_back(Src[I]);
742       continue;
743     }
744
745     // Consume a quoted string.
746     if (isQuote(C)) {
747       ++I;
748       while (I != E && Src[I] != C) {
749         // Backslash escapes the next character.
750         if (Src[I] == '\\' && I + 1 != E)
751           ++I;
752         Token.push_back(Src[I]);
753         ++I;
754       }
755       if (I == E)
756         break;
757       continue;
758     }
759
760     // End the token if this is whitespace.
761     if (isWhitespace(C)) {
762       if (!Token.empty())
763         NewArgv.push_back(Saver.save(StringRef(Token)).data());
764       Token.clear();
765       continue;
766     }
767
768     // This is a normal character.  Append it.
769     Token.push_back(C);
770   }
771
772   // Append the last token after hitting EOF with no whitespace.
773   if (!Token.empty())
774     NewArgv.push_back(Saver.save(StringRef(Token)).data());
775   // Mark the end of response files
776   if (MarkEOLs)
777     NewArgv.push_back(nullptr);
778 }
779
780 /// Backslashes are interpreted in a rather complicated way in the Windows-style
781 /// command line, because backslashes are used both to separate path and to
782 /// escape double quote. This method consumes runs of backslashes as well as the
783 /// following double quote if it's escaped.
784 ///
785 ///  * If an even number of backslashes is followed by a double quote, one
786 ///    backslash is output for every pair of backslashes, and the last double
787 ///    quote remains unconsumed. The double quote will later be interpreted as
788 ///    the start or end of a quoted string in the main loop outside of this
789 ///    function.
790 ///
791 ///  * If an odd number of backslashes is followed by a double quote, one
792 ///    backslash is output for every pair of backslashes, and a double quote is
793 ///    output for the last pair of backslash-double quote. The double quote is
794 ///    consumed in this case.
795 ///
796 ///  * Otherwise, backslashes are interpreted literally.
797 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
798   size_t E = Src.size();
799   int BackslashCount = 0;
800   // Skip the backslashes.
801   do {
802     ++I;
803     ++BackslashCount;
804   } while (I != E && Src[I] == '\\');
805
806   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
807   if (FollowedByDoubleQuote) {
808     Token.append(BackslashCount / 2, '\\');
809     if (BackslashCount % 2 == 0)
810       return I - 1;
811     Token.push_back('"');
812     return I;
813   }
814   Token.append(BackslashCount, '\\');
815   return I - 1;
816 }
817
818 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
819                                     SmallVectorImpl<const char *> &NewArgv,
820                                     bool MarkEOLs) {
821   SmallString<128> Token;
822
823   // This is a small state machine to consume characters until it reaches the
824   // end of the source string.
825   enum { INIT, UNQUOTED, QUOTED } State = INIT;
826   for (size_t I = 0, E = Src.size(); I != E; ++I) {
827     char C = Src[I];
828
829     // INIT state indicates that the current input index is at the start of
830     // the string or between tokens.
831     if (State == INIT) {
832       if (isWhitespaceOrNull(C)) {
833         // Mark the end of lines in response files
834         if (MarkEOLs && C == '\n')
835           NewArgv.push_back(nullptr);
836         continue;
837       }
838       if (C == '"') {
839         State = QUOTED;
840         continue;
841       }
842       if (C == '\\') {
843         I = parseBackslash(Src, I, Token);
844         State = UNQUOTED;
845         continue;
846       }
847       Token.push_back(C);
848       State = UNQUOTED;
849       continue;
850     }
851
852     // UNQUOTED state means that it's reading a token not quoted by double
853     // quotes.
854     if (State == UNQUOTED) {
855       // Whitespace means the end of the token.
856       if (isWhitespaceOrNull(C)) {
857         NewArgv.push_back(Saver.save(StringRef(Token)).data());
858         Token.clear();
859         State = INIT;
860         // Mark the end of lines in response files
861         if (MarkEOLs && C == '\n')
862           NewArgv.push_back(nullptr);
863         continue;
864       }
865       if (C == '"') {
866         State = QUOTED;
867         continue;
868       }
869       if (C == '\\') {
870         I = parseBackslash(Src, I, Token);
871         continue;
872       }
873       Token.push_back(C);
874       continue;
875     }
876
877     // QUOTED state means that it's reading a token quoted by double quotes.
878     if (State == QUOTED) {
879       if (C == '"') {
880         if (I < (E - 1) && Src[I + 1] == '"') {
881           // Consecutive double-quotes inside a quoted string implies one
882           // double-quote.
883           Token.push_back('"');
884           I = I + 1;
885           continue;
886         }
887         State = UNQUOTED;
888         continue;
889       }
890       if (C == '\\') {
891         I = parseBackslash(Src, I, Token);
892         continue;
893       }
894       Token.push_back(C);
895     }
896   }
897   // Append the last token after hitting EOF with no whitespace.
898   if (!Token.empty())
899     NewArgv.push_back(Saver.save(StringRef(Token)).data());
900   // Mark the end of response files
901   if (MarkEOLs)
902     NewArgv.push_back(nullptr);
903 }
904
905 void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
906                             SmallVectorImpl<const char *> &NewArgv,
907                             bool MarkEOLs) {
908   for (const char *Cur = Source.begin(); Cur != Source.end();) {
909     SmallString<128> Line;
910     // Check for comment line.
911     if (isWhitespace(*Cur)) {
912       while (Cur != Source.end() && isWhitespace(*Cur))
913         ++Cur;
914       continue;
915     }
916     if (*Cur == '#') {
917       while (Cur != Source.end() && *Cur != '\n')
918         ++Cur;
919       continue;
920     }
921     // Find end of the current line.
922     const char *Start = Cur;
923     for (const char *End = Source.end(); Cur != End; ++Cur) {
924       if (*Cur == '\\') {
925         if (Cur + 1 != End) {
926           ++Cur;
927           if (*Cur == '\n' ||
928               (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
929             Line.append(Start, Cur - 1);
930             if (*Cur == '\r')
931               ++Cur;
932             Start = Cur + 1;
933           }
934         }
935       } else if (*Cur == '\n')
936         break;
937     }
938     // Tokenize line.
939     Line.append(Start, Cur);
940     cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
941   }
942 }
943
944 // It is called byte order marker but the UTF-8 BOM is actually not affected
945 // by the host system's endianness.
946 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
947   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
948 }
949
950 static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
951                                TokenizerCallback Tokenizer,
952                                SmallVectorImpl<const char *> &NewArgv,
953                                bool MarkEOLs, bool RelativeNames) {
954   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
955       MemoryBuffer::getFile(FName);
956   if (!MemBufOrErr)
957     return false;
958   MemoryBuffer &MemBuf = *MemBufOrErr.get();
959   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
960
961   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
962   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
963   std::string UTF8Buf;
964   if (hasUTF16ByteOrderMark(BufRef)) {
965     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
966       return false;
967     Str = StringRef(UTF8Buf);
968   }
969   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
970   // these bytes before parsing.
971   // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
972   else if (hasUTF8ByteOrderMark(BufRef))
973     Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
974
975   // Tokenize the contents into NewArgv.
976   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
977
978   // If names of nested response files should be resolved relative to including
979   // file, replace the included response file names with their full paths
980   // obtained by required resolution.
981   if (RelativeNames)
982     for (unsigned I = 0; I < NewArgv.size(); ++I)
983       if (NewArgv[I]) {
984         StringRef Arg = NewArgv[I];
985         if (Arg.front() == '@') {
986           StringRef FileName = Arg.drop_front();
987           if (llvm::sys::path::is_relative(FileName)) {
988             SmallString<128> ResponseFile;
989             ResponseFile.append(1, '@');
990             if (llvm::sys::path::is_relative(FName)) {
991               SmallString<128> curr_dir;
992               llvm::sys::fs::current_path(curr_dir);
993               ResponseFile.append(curr_dir.str());
994             }
995             llvm::sys::path::append(
996                 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
997             NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
998           }
999         }
1000       }
1001
1002   return true;
1003 }
1004
1005 /// Expand response files on a command line recursively using the given
1006 /// StringSaver and tokenization strategy.
1007 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1008                              SmallVectorImpl<const char *> &Argv,
1009                              bool MarkEOLs, bool RelativeNames) {
1010   unsigned RspFiles = 0;
1011   bool AllExpanded = true;
1012
1013   // Don't cache Argv.size() because it can change.
1014   for (unsigned I = 0; I != Argv.size();) {
1015     const char *Arg = Argv[I];
1016     // Check if it is an EOL marker
1017     if (Arg == nullptr) {
1018       ++I;
1019       continue;
1020     }
1021     if (Arg[0] != '@') {
1022       ++I;
1023       continue;
1024     }
1025
1026     // If we have too many response files, leave some unexpanded.  This avoids
1027     // crashing on self-referential response files.
1028     if (RspFiles++ > 20)
1029       return false;
1030
1031     // Replace this response file argument with the tokenization of its
1032     // contents.  Nested response files are expanded in subsequent iterations.
1033     SmallVector<const char *, 0> ExpandedArgv;
1034     if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
1035                             MarkEOLs, RelativeNames)) {
1036       // We couldn't read this file, so we leave it in the argument stream and
1037       // move on.
1038       AllExpanded = false;
1039       ++I;
1040       continue;
1041     }
1042     Argv.erase(Argv.begin() + I);
1043     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1044   }
1045   return AllExpanded;
1046 }
1047
1048 bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
1049                         SmallVectorImpl<const char *> &Argv) {
1050   if (!ExpandResponseFile(CfgFile, Saver, cl::tokenizeConfigFile, Argv,
1051                           /*MarkEOLs*/ false, /*RelativeNames*/ true))
1052     return false;
1053   return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
1054                              /*MarkEOLs*/ false, /*RelativeNames*/ true);
1055 }
1056
1057 /// ParseEnvironmentOptions - An alternative entry point to the
1058 /// CommandLine library, which allows you to read the program's name
1059 /// from the caller (as PROGNAME) and its command-line arguments from
1060 /// an environment variable (whose name is given in ENVVAR).
1061 ///
1062 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
1063                                  const char *Overview) {
1064   // Check args.
1065   assert(progName && "Program name not specified");
1066   assert(envVar && "Environment variable name missing");
1067
1068   // Get the environment variable they want us to parse options out of.
1069   llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
1070   if (!envValue)
1071     return;
1072
1073   // Get program's "name", which we wouldn't know without the caller
1074   // telling us.
1075   SmallVector<const char *, 20> newArgv;
1076   BumpPtrAllocator A;
1077   StringSaver Saver(A);
1078   newArgv.push_back(Saver.save(progName).data());
1079
1080   // Parse the value of the environment variable into a "command line"
1081   // and hand it off to ParseCommandLineOptions().
1082   TokenizeGNUCommandLine(*envValue, Saver, newArgv);
1083   int newArgc = static_cast<int>(newArgv.size());
1084   ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
1085 }
1086
1087 bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1088                                  StringRef Overview, raw_ostream *Errs,
1089                                  const char *EnvVar) {
1090   SmallVector<const char *, 20> NewArgv;
1091   BumpPtrAllocator A;
1092   StringSaver Saver(A);
1093   NewArgv.push_back(argv[0]);
1094
1095   // Parse options from environment variable.
1096   if (EnvVar) {
1097     if (llvm::Optional<std::string> EnvValue =
1098             sys::Process::GetEnv(StringRef(EnvVar)))
1099       TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1100   }
1101
1102   // Append options from command line.
1103   for (int I = 1; I < argc; ++I)
1104     NewArgv.push_back(argv[I]);
1105   int NewArgc = static_cast<int>(NewArgv.size());
1106
1107   // Parse all options.
1108   return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
1109                                                Errs);
1110 }
1111
1112 void CommandLineParser::ResetAllOptionOccurrences() {
1113   // So that we can parse different command lines multiple times in succession
1114   // we reset all option values to look like they have never been seen before.
1115   for (auto SC : RegisteredSubCommands) {
1116     for (auto &O : SC->OptionsMap)
1117       O.second->reset();
1118   }
1119 }
1120
1121 bool CommandLineParser::ParseCommandLineOptions(int argc,
1122                                                 const char *const *argv,
1123                                                 StringRef Overview,
1124                                                 raw_ostream *Errs) {
1125   assert(hasOptions() && "No options specified!");
1126
1127   // Expand response files.
1128   SmallVector<const char *, 20> newArgv(argv, argv + argc);
1129   BumpPtrAllocator A;
1130   StringSaver Saver(A);
1131   ExpandResponseFiles(Saver,
1132          Triple(sys::getProcessTriple()).isOSWindows() ?
1133          cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine,
1134          newArgv);
1135   argv = &newArgv[0];
1136   argc = static_cast<int>(newArgv.size());
1137
1138   // Copy the program name into ProgName, making sure not to overflow it.
1139   ProgramName = sys::path::filename(StringRef(argv[0]));
1140
1141   ProgramOverview = Overview;
1142   bool IgnoreErrors = Errs;
1143   if (!Errs)
1144     Errs = &errs();
1145   bool ErrorParsing = false;
1146
1147   // Check out the positional arguments to collect information about them.
1148   unsigned NumPositionalRequired = 0;
1149
1150   // Determine whether or not there are an unlimited number of positionals
1151   bool HasUnlimitedPositionals = false;
1152
1153   int FirstArg = 1;
1154   SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
1155   if (argc >= 2 && argv[FirstArg][0] != '-') {
1156     // If the first argument specifies a valid subcommand, start processing
1157     // options from the second argument.
1158     ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
1159     if (ChosenSubCommand != &*TopLevelSubCommand)
1160       FirstArg = 2;
1161   }
1162   GlobalParser->ActiveSubCommand = ChosenSubCommand;
1163
1164   assert(ChosenSubCommand);
1165   auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1166   auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1167   auto &SinkOpts = ChosenSubCommand->SinkOpts;
1168   auto &OptionsMap = ChosenSubCommand->OptionsMap;
1169
1170   if (ConsumeAfterOpt) {
1171     assert(PositionalOpts.size() > 0 &&
1172            "Cannot specify cl::ConsumeAfter without a positional argument!");
1173   }
1174   if (!PositionalOpts.empty()) {
1175
1176     // Calculate how many positional values are _required_.
1177     bool UnboundedFound = false;
1178     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1179       Option *Opt = PositionalOpts[i];
1180       if (RequiresValue(Opt))
1181         ++NumPositionalRequired;
1182       else if (ConsumeAfterOpt) {
1183         // ConsumeAfter cannot be combined with "optional" positional options
1184         // unless there is only one positional argument...
1185         if (PositionalOpts.size() > 1) {
1186           if (!IgnoreErrors)
1187             Opt->error("error - this positional option will never be matched, "
1188                        "because it does not Require a value, and a "
1189                        "cl::ConsumeAfter option is active!");
1190           ErrorParsing = true;
1191         }
1192       } else if (UnboundedFound && !Opt->hasArgStr()) {
1193         // This option does not "require" a value...  Make sure this option is
1194         // not specified after an option that eats all extra arguments, or this
1195         // one will never get any!
1196         //
1197         if (!IgnoreErrors)
1198           Opt->error("error - option can never match, because "
1199                      "another positional argument will match an "
1200                      "unbounded number of values, and this option"
1201                      " does not require a value!");
1202         *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1203               << "' is all messed up!\n";
1204         *Errs << PositionalOpts.size();
1205         ErrorParsing = true;
1206       }
1207       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1208     }
1209     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1210   }
1211
1212   // PositionalVals - A vector of "positional" arguments we accumulate into
1213   // the process at the end.
1214   //
1215   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1216
1217   // If the program has named positional arguments, and the name has been run
1218   // across, keep track of which positional argument was named.  Otherwise put
1219   // the positional args into the PositionalVals list...
1220   Option *ActivePositionalArg = nullptr;
1221
1222   // Loop over all of the arguments... processing them.
1223   bool DashDashFound = false; // Have we read '--'?
1224   for (int i = FirstArg; i < argc; ++i) {
1225     Option *Handler = nullptr;
1226     Option *NearestHandler = nullptr;
1227     std::string NearestHandlerString;
1228     StringRef Value;
1229     StringRef ArgName = "";
1230
1231     // Check to see if this is a positional argument.  This argument is
1232     // considered to be positional if it doesn't start with '-', if it is "-"
1233     // itself, or if we have seen "--" already.
1234     //
1235     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1236       // Positional argument!
1237       if (ActivePositionalArg) {
1238         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1239         continue; // We are done!
1240       }
1241
1242       if (!PositionalOpts.empty()) {
1243         PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1244
1245         // All of the positional arguments have been fulfulled, give the rest to
1246         // the consume after option... if it's specified...
1247         //
1248         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1249           for (++i; i < argc; ++i)
1250             PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1251           break; // Handle outside of the argument processing loop...
1252         }
1253
1254         // Delay processing positional arguments until the end...
1255         continue;
1256       }
1257     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1258                !DashDashFound) {
1259       DashDashFound = true; // This is the mythical "--"?
1260       continue;             // Don't try to process it as an argument itself.
1261     } else if (ActivePositionalArg &&
1262                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1263       // If there is a positional argument eating options, check to see if this
1264       // option is another positional argument.  If so, treat it as an argument,
1265       // otherwise feed it to the eating positional.
1266       ArgName = StringRef(argv[i] + 1);
1267       // Eat leading dashes.
1268       while (!ArgName.empty() && ArgName[0] == '-')
1269         ArgName = ArgName.substr(1);
1270
1271       Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1272       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1273         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1274         continue; // We are done!
1275       }
1276
1277     } else { // We start with a '-', must be an argument.
1278       ArgName = StringRef(argv[i] + 1);
1279       // Eat leading dashes.
1280       while (!ArgName.empty() && ArgName[0] == '-')
1281         ArgName = ArgName.substr(1);
1282
1283       Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1284
1285       // Check to see if this "option" is really a prefixed or grouped argument.
1286       if (!Handler)
1287         Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1288                                                 OptionsMap);
1289
1290       // Otherwise, look for the closest available option to report to the user
1291       // in the upcoming error.
1292       if (!Handler && SinkOpts.empty())
1293         NearestHandler =
1294             LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1295     }
1296
1297     if (!Handler) {
1298       if (SinkOpts.empty()) {
1299         *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
1300               << "'.  Try: '" << argv[0] << " -help'\n";
1301
1302         if (NearestHandler) {
1303           // If we know a near match, report it as well.
1304           *Errs << ProgramName << ": Did you mean '-" << NearestHandlerString
1305                  << "'?\n";
1306         }
1307
1308         ErrorParsing = true;
1309       } else {
1310         for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
1311                                                  E = SinkOpts.end();
1312              I != E; ++I)
1313           (*I)->addOccurrence(i, "", StringRef(argv[i]));
1314       }
1315       continue;
1316     }
1317
1318     // If this is a named positional argument, just remember that it is the
1319     // active one...
1320     if (Handler->getFormattingFlag() == cl::Positional) {
1321       if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1322         Handler->error("This argument does not take a value.\n"
1323                        "\tInstead, it consumes any positional arguments until "
1324                        "the next recognized option.", *Errs);
1325         ErrorParsing = true;
1326       }
1327       ActivePositionalArg = Handler;
1328     }
1329     else
1330       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1331   }
1332
1333   // Check and handle positional arguments now...
1334   if (NumPositionalRequired > PositionalVals.size()) {
1335       *Errs << ProgramName
1336              << ": Not enough positional command line arguments specified!\n"
1337              << "Must specify at least " << NumPositionalRequired
1338              << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1339              << ": See: " << argv[0] << " -help\n";
1340
1341     ErrorParsing = true;
1342   } else if (!HasUnlimitedPositionals &&
1343              PositionalVals.size() > PositionalOpts.size()) {
1344     *Errs << ProgramName << ": Too many positional arguments specified!\n"
1345           << "Can specify at most " << PositionalOpts.size()
1346           << " positional arguments: See: " << argv[0] << " -help\n";
1347     ErrorParsing = true;
1348
1349   } else if (!ConsumeAfterOpt) {
1350     // Positional args have already been handled if ConsumeAfter is specified.
1351     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1352     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1353       if (RequiresValue(PositionalOpts[i])) {
1354         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1355                                 PositionalVals[ValNo].second);
1356         ValNo++;
1357         --NumPositionalRequired; // We fulfilled our duty...
1358       }
1359
1360       // If we _can_ give this option more arguments, do so now, as long as we
1361       // do not give it values that others need.  'Done' controls whether the
1362       // option even _WANTS_ any more.
1363       //
1364       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1365       while (NumVals - ValNo > NumPositionalRequired && !Done) {
1366         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1367         case cl::Optional:
1368           Done = true; // Optional arguments want _at most_ one value
1369           LLVM_FALLTHROUGH;
1370         case cl::ZeroOrMore: // Zero or more will take all they can get...
1371         case cl::OneOrMore:  // One or more will take all they can get...
1372           ProvidePositionalOption(PositionalOpts[i],
1373                                   PositionalVals[ValNo].first,
1374                                   PositionalVals[ValNo].second);
1375           ValNo++;
1376           break;
1377         default:
1378           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1379                            "positional argument processing!");
1380         }
1381       }
1382     }
1383   } else {
1384     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1385     unsigned ValNo = 0;
1386     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1387       if (RequiresValue(PositionalOpts[j])) {
1388         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1389                                                 PositionalVals[ValNo].first,
1390                                                 PositionalVals[ValNo].second);
1391         ValNo++;
1392       }
1393
1394     // Handle the case where there is just one positional option, and it's
1395     // optional.  In this case, we want to give JUST THE FIRST option to the
1396     // positional option and keep the rest for the consume after.  The above
1397     // loop would have assigned no values to positional options in this case.
1398     //
1399     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1400       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1401                                               PositionalVals[ValNo].first,
1402                                               PositionalVals[ValNo].second);
1403       ValNo++;
1404     }
1405
1406     // Handle over all of the rest of the arguments to the
1407     // cl::ConsumeAfter command line option...
1408     for (; ValNo != PositionalVals.size(); ++ValNo)
1409       ErrorParsing |=
1410           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1411                                   PositionalVals[ValNo].second);
1412   }
1413
1414   // Loop over args and make sure all required args are specified!
1415   for (const auto &Opt : OptionsMap) {
1416     switch (Opt.second->getNumOccurrencesFlag()) {
1417     case Required:
1418     case OneOrMore:
1419       if (Opt.second->getNumOccurrences() == 0) {
1420         Opt.second->error("must be specified at least once!");
1421         ErrorParsing = true;
1422       }
1423       LLVM_FALLTHROUGH;
1424     default:
1425       break;
1426     }
1427   }
1428
1429   // Now that we know if -debug is specified, we can use it.
1430   // Note that if ReadResponseFiles == true, this must be done before the
1431   // memory allocated for the expanded command line is free()d below.
1432   LLVM_DEBUG(dbgs() << "Args: ";
1433              for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1434              dbgs() << '\n';);
1435
1436   // Free all of the memory allocated to the map.  Command line options may only
1437   // be processed once!
1438   MoreHelp.clear();
1439
1440   // If we had an error processing our arguments, don't let the program execute
1441   if (ErrorParsing) {
1442     if (!IgnoreErrors)
1443       exit(1);
1444     return false;
1445   }
1446   return true;
1447 }
1448
1449 //===----------------------------------------------------------------------===//
1450 // Option Base class implementation
1451 //
1452
1453 bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1454   if (!ArgName.data())
1455     ArgName = ArgStr;
1456   if (ArgName.empty())
1457     Errs << HelpStr; // Be nice for positional arguments
1458   else
1459     Errs << GlobalParser->ProgramName << ": for the -" << ArgName;
1460
1461   Errs << " option: " << Message << "\n";
1462   return true;
1463 }
1464
1465 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1466                            bool MultiArg) {
1467   if (!MultiArg)
1468     NumOccurrences++; // Increment the number of times we have been seen
1469
1470   switch (getNumOccurrencesFlag()) {
1471   case Optional:
1472     if (NumOccurrences > 1)
1473       return error("may only occur zero or one times!", ArgName);
1474     break;
1475   case Required:
1476     if (NumOccurrences > 1)
1477       return error("must occur exactly one time!", ArgName);
1478     LLVM_FALLTHROUGH;
1479   case OneOrMore:
1480   case ZeroOrMore:
1481   case ConsumeAfter:
1482     break;
1483   }
1484
1485   return handleOccurrence(pos, ArgName, Value);
1486 }
1487
1488 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1489 // has been specified yet.
1490 //
1491 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1492   if (O.ValueStr.empty())
1493     return DefaultMsg;
1494   return O.ValueStr;
1495 }
1496
1497 static StringRef ArgPrefix = "  -";
1498 static StringRef ArgHelpPrefix = " - ";
1499 static size_t ArgPrefixesSize = ArgPrefix.size() + ArgHelpPrefix.size();
1500
1501 //===----------------------------------------------------------------------===//
1502 // cl::alias class implementation
1503 //
1504
1505 // Return the width of the option tag for printing...
1506 size_t alias::getOptionWidth() const { return ArgStr.size() + ArgPrefixesSize; }
1507
1508 void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1509                           size_t FirstLineIndentedBy) {
1510   assert(Indent >= FirstLineIndentedBy);
1511   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1512   outs().indent(Indent - FirstLineIndentedBy)
1513       << ArgHelpPrefix << Split.first << "\n";
1514   while (!Split.second.empty()) {
1515     Split = Split.second.split('\n');
1516     outs().indent(Indent) << Split.first << "\n";
1517   }
1518 }
1519
1520 // Print out the option for the alias.
1521 void alias::printOptionInfo(size_t GlobalWidth) const {
1522   outs() << ArgPrefix << ArgStr;
1523   printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + ArgPrefixesSize);
1524 }
1525
1526 //===----------------------------------------------------------------------===//
1527 // Parser Implementation code...
1528 //
1529
1530 // basic_parser implementation
1531 //
1532
1533 // Return the width of the option tag for printing...
1534 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1535   size_t Len = O.ArgStr.size();
1536   auto ValName = getValueName();
1537   if (!ValName.empty()) {
1538     size_t FormattingLen = 3;
1539     if (O.getMiscFlags() & PositionalEatsArgs)
1540       FormattingLen = 6;
1541     Len += getValueStr(O, ValName).size() + FormattingLen;
1542   }
1543
1544   return Len + ArgPrefixesSize;
1545 }
1546
1547 // printOptionInfo - Print out information about this option.  The
1548 // to-be-maintained width is specified.
1549 //
1550 void basic_parser_impl::printOptionInfo(const Option &O,
1551                                         size_t GlobalWidth) const {
1552   outs() << ArgPrefix << O.ArgStr;
1553
1554   auto ValName = getValueName();
1555   if (!ValName.empty()) {
1556     if (O.getMiscFlags() & PositionalEatsArgs) {
1557       outs() << " <" << getValueStr(O, ValName) << ">...";
1558     } else {
1559       outs() << "=<" << getValueStr(O, ValName) << '>';
1560     }
1561   }
1562
1563   Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1564 }
1565
1566 void basic_parser_impl::printOptionName(const Option &O,
1567                                         size_t GlobalWidth) const {
1568   outs() << ArgPrefix << O.ArgStr;
1569   outs().indent(GlobalWidth - O.ArgStr.size());
1570 }
1571
1572 // parser<bool> implementation
1573 //
1574 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1575                          bool &Value) {
1576   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1577       Arg == "1") {
1578     Value = true;
1579     return false;
1580   }
1581
1582   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1583     Value = false;
1584     return false;
1585   }
1586   return O.error("'" + Arg +
1587                  "' is invalid value for boolean argument! Try 0 or 1");
1588 }
1589
1590 // parser<boolOrDefault> implementation
1591 //
1592 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1593                                   boolOrDefault &Value) {
1594   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1595       Arg == "1") {
1596     Value = BOU_TRUE;
1597     return false;
1598   }
1599   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1600     Value = BOU_FALSE;
1601     return false;
1602   }
1603
1604   return O.error("'" + Arg +
1605                  "' is invalid value for boolean argument! Try 0 or 1");
1606 }
1607
1608 // parser<int> implementation
1609 //
1610 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1611                         int &Value) {
1612   if (Arg.getAsInteger(0, Value))
1613     return O.error("'" + Arg + "' value invalid for integer argument!");
1614   return false;
1615 }
1616
1617 // parser<unsigned> implementation
1618 //
1619 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1620                              unsigned &Value) {
1621
1622   if (Arg.getAsInteger(0, Value))
1623     return O.error("'" + Arg + "' value invalid for uint argument!");
1624   return false;
1625 }
1626
1627 // parser<unsigned long long> implementation
1628 //
1629 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1630                                        StringRef Arg,
1631                                        unsigned long long &Value) {
1632
1633   if (Arg.getAsInteger(0, Value))
1634     return O.error("'" + Arg + "' value invalid for uint argument!");
1635   return false;
1636 }
1637
1638 // parser<double>/parser<float> implementation
1639 //
1640 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1641   if (to_float(Arg, Value))
1642     return false;
1643   return O.error("'" + Arg + "' value invalid for floating point argument!");
1644 }
1645
1646 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1647                            double &Val) {
1648   return parseDouble(O, Arg, Val);
1649 }
1650
1651 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1652                           float &Val) {
1653   double dVal;
1654   if (parseDouble(O, Arg, dVal))
1655     return true;
1656   Val = (float)dVal;
1657   return false;
1658 }
1659
1660 // generic_parser_base implementation
1661 //
1662
1663 // findOption - Return the option number corresponding to the specified
1664 // argument string.  If the option is not found, getNumOptions() is returned.
1665 //
1666 unsigned generic_parser_base::findOption(StringRef Name) {
1667   unsigned e = getNumOptions();
1668
1669   for (unsigned i = 0; i != e; ++i) {
1670     if (getOption(i) == Name)
1671       return i;
1672   }
1673   return e;
1674 }
1675
1676 static StringRef EqValue = "=<value>";
1677 static StringRef EmptyOption = "<empty>";
1678 static StringRef OptionPrefix = "    =";
1679 static size_t OptionPrefixesSize = OptionPrefix.size() + ArgHelpPrefix.size();
1680
1681 static bool shouldPrintOption(StringRef Name, StringRef Description,
1682                               const Option &O) {
1683   return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
1684          !Description.empty();
1685 }
1686
1687 // Return the width of the option tag for printing...
1688 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1689   if (O.hasArgStr()) {
1690     size_t Size = O.ArgStr.size() + ArgPrefixesSize + EqValue.size();
1691     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1692       StringRef Name = getOption(i);
1693       if (!shouldPrintOption(Name, getDescription(i), O))
1694         continue;
1695       size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
1696       Size = std::max(Size, NameSize + OptionPrefixesSize);
1697     }
1698     return Size;
1699   } else {
1700     size_t BaseSize = 0;
1701     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1702       BaseSize = std::max(BaseSize, getOption(i).size() + 8);
1703     return BaseSize;
1704   }
1705 }
1706
1707 // printOptionInfo - Print out information about this option.  The
1708 // to-be-maintained width is specified.
1709 //
1710 void generic_parser_base::printOptionInfo(const Option &O,
1711                                           size_t GlobalWidth) const {
1712   if (O.hasArgStr()) {
1713     // When the value is optional, first print a line just describing the
1714     // option without values.
1715     if (O.getValueExpectedFlag() == ValueOptional) {
1716       for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1717         if (getOption(i).empty()) {
1718           outs() << ArgPrefix << O.ArgStr;
1719           Option::printHelpStr(O.HelpStr, GlobalWidth,
1720                                O.ArgStr.size() + ArgPrefixesSize);
1721           break;
1722         }
1723       }
1724     }
1725
1726     outs() << ArgPrefix << O.ArgStr << EqValue;
1727     Option::printHelpStr(O.HelpStr, GlobalWidth,
1728                          O.ArgStr.size() + EqValue.size() + ArgPrefixesSize);
1729     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1730       StringRef OptionName = getOption(i);
1731       StringRef Description = getDescription(i);
1732       if (!shouldPrintOption(OptionName, Description, O))
1733         continue;
1734       assert(GlobalWidth >= OptionName.size() + OptionPrefixesSize);
1735       size_t NumSpaces = GlobalWidth - OptionName.size() - OptionPrefixesSize;
1736       outs() << OptionPrefix << OptionName;
1737       if (OptionName.empty()) {
1738         outs() << EmptyOption;
1739         assert(NumSpaces >= EmptyOption.size());
1740         NumSpaces -= EmptyOption.size();
1741       }
1742       if (!Description.empty())
1743         outs().indent(NumSpaces) << ArgHelpPrefix << "  " << Description;
1744       outs() << '\n';
1745     }
1746   } else {
1747     if (!O.HelpStr.empty())
1748       outs() << "  " << O.HelpStr << '\n';
1749     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1750       auto Option = getOption(i);
1751       outs() << "    -" << Option;
1752       Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
1753     }
1754   }
1755 }
1756
1757 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1758
1759 // printGenericOptionDiff - Print the value of this option and it's default.
1760 //
1761 // "Generic" options have each value mapped to a name.
1762 void generic_parser_base::printGenericOptionDiff(
1763     const Option &O, const GenericOptionValue &Value,
1764     const GenericOptionValue &Default, size_t GlobalWidth) const {
1765   outs() << "  -" << O.ArgStr;
1766   outs().indent(GlobalWidth - O.ArgStr.size());
1767
1768   unsigned NumOpts = getNumOptions();
1769   for (unsigned i = 0; i != NumOpts; ++i) {
1770     if (Value.compare(getOptionValue(i)))
1771       continue;
1772
1773     outs() << "= " << getOption(i);
1774     size_t L = getOption(i).size();
1775     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1776     outs().indent(NumSpaces) << " (default: ";
1777     for (unsigned j = 0; j != NumOpts; ++j) {
1778       if (Default.compare(getOptionValue(j)))
1779         continue;
1780       outs() << getOption(j);
1781       break;
1782     }
1783     outs() << ")\n";
1784     return;
1785   }
1786   outs() << "= *unknown option value*\n";
1787 }
1788
1789 // printOptionDiff - Specializations for printing basic value types.
1790 //
1791 #define PRINT_OPT_DIFF(T)                                                      \
1792   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
1793                                   size_t GlobalWidth) const {                  \
1794     printOptionName(O, GlobalWidth);                                           \
1795     std::string Str;                                                           \
1796     {                                                                          \
1797       raw_string_ostream SS(Str);                                              \
1798       SS << V;                                                                 \
1799     }                                                                          \
1800     outs() << "= " << Str;                                                     \
1801     size_t NumSpaces =                                                         \
1802         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
1803     outs().indent(NumSpaces) << " (default: ";                                 \
1804     if (D.hasValue())                                                          \
1805       outs() << D.getValue();                                                  \
1806     else                                                                       \
1807       outs() << "*no default*";                                                \
1808     outs() << ")\n";                                                           \
1809   }
1810
1811 PRINT_OPT_DIFF(bool)
1812 PRINT_OPT_DIFF(boolOrDefault)
1813 PRINT_OPT_DIFF(int)
1814 PRINT_OPT_DIFF(unsigned)
1815 PRINT_OPT_DIFF(unsigned long long)
1816 PRINT_OPT_DIFF(double)
1817 PRINT_OPT_DIFF(float)
1818 PRINT_OPT_DIFF(char)
1819
1820 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1821                                           const OptionValue<std::string> &D,
1822                                           size_t GlobalWidth) const {
1823   printOptionName(O, GlobalWidth);
1824   outs() << "= " << V;
1825   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1826   outs().indent(NumSpaces) << " (default: ";
1827   if (D.hasValue())
1828     outs() << D.getValue();
1829   else
1830     outs() << "*no default*";
1831   outs() << ")\n";
1832 }
1833
1834 // Print a placeholder for options that don't yet support printOptionDiff().
1835 void basic_parser_impl::printOptionNoValue(const Option &O,
1836                                            size_t GlobalWidth) const {
1837   printOptionName(O, GlobalWidth);
1838   outs() << "= *cannot print option value*\n";
1839 }
1840
1841 //===----------------------------------------------------------------------===//
1842 // -help and -help-hidden option implementation
1843 //
1844
1845 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1846                           const std::pair<const char *, Option *> *RHS) {
1847   return strcmp(LHS->first, RHS->first);
1848 }
1849
1850 static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
1851                           const std::pair<const char *, SubCommand *> *RHS) {
1852   return strcmp(LHS->first, RHS->first);
1853 }
1854
1855 // Copy Options into a vector so we can sort them as we like.
1856 static void sortOpts(StringMap<Option *> &OptMap,
1857                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1858                      bool ShowHidden) {
1859   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
1860
1861   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1862        I != E; ++I) {
1863     // Ignore really-hidden options.
1864     if (I->second->getOptionHiddenFlag() == ReallyHidden)
1865       continue;
1866
1867     // Unless showhidden is set, ignore hidden flags.
1868     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1869       continue;
1870
1871     // If we've already seen this option, don't add it to the list again.
1872     if (!OptionSet.insert(I->second).second)
1873       continue;
1874
1875     Opts.push_back(
1876         std::pair<const char *, Option *>(I->getKey().data(), I->second));
1877   }
1878
1879   // Sort the options list alphabetically.
1880   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1881 }
1882
1883 static void
1884 sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
1885                 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
1886   for (const auto &S : SubMap) {
1887     if (S->getName().empty())
1888       continue;
1889     Subs.push_back(std::make_pair(S->getName().data(), S));
1890   }
1891   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
1892 }
1893
1894 namespace {
1895
1896 class HelpPrinter {
1897 protected:
1898   const bool ShowHidden;
1899   typedef SmallVector<std::pair<const char *, Option *>, 128>
1900       StrOptionPairVector;
1901   typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
1902       StrSubCommandPairVector;
1903   // Print the options. Opts is assumed to be alphabetically sorted.
1904   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1905     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1906       Opts[i].second->printOptionInfo(MaxArgLen);
1907   }
1908
1909   void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
1910     for (const auto &S : Subs) {
1911       outs() << "  " << S.first;
1912       if (!S.second->getDescription().empty()) {
1913         outs().indent(MaxSubLen - strlen(S.first));
1914         outs() << " - " << S.second->getDescription();
1915       }
1916       outs() << "\n";
1917     }
1918   }
1919
1920 public:
1921   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1922   virtual ~HelpPrinter() {}
1923
1924   // Invoke the printer.
1925   void operator=(bool Value) {
1926     if (!Value)
1927       return;
1928     printHelp();
1929
1930     // Halt the program since help information was printed
1931     exit(0);
1932   }
1933
1934   void printHelp() {
1935     SubCommand *Sub = GlobalParser->getActiveSubCommand();
1936     auto &OptionsMap = Sub->OptionsMap;
1937     auto &PositionalOpts = Sub->PositionalOpts;
1938     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
1939
1940     StrOptionPairVector Opts;
1941     sortOpts(OptionsMap, Opts, ShowHidden);
1942
1943     StrSubCommandPairVector Subs;
1944     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
1945
1946     if (!GlobalParser->ProgramOverview.empty())
1947       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1948
1949     if (Sub == &*TopLevelSubCommand) {
1950       outs() << "USAGE: " << GlobalParser->ProgramName;
1951       if (Subs.size() > 2)
1952         outs() << " [subcommand]";
1953       outs() << " [options]";
1954     } else {
1955       if (!Sub->getDescription().empty()) {
1956         outs() << "SUBCOMMAND '" << Sub->getName()
1957                << "': " << Sub->getDescription() << "\n\n";
1958       }
1959       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
1960              << " [options]";
1961     }
1962
1963     for (auto Opt : PositionalOpts) {
1964       if (Opt->hasArgStr())
1965         outs() << " --" << Opt->ArgStr;
1966       outs() << " " << Opt->HelpStr;
1967     }
1968
1969     // Print the consume after option info if it exists...
1970     if (ConsumeAfterOpt)
1971       outs() << " " << ConsumeAfterOpt->HelpStr;
1972
1973     if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
1974       // Compute the maximum subcommand length...
1975       size_t MaxSubLen = 0;
1976       for (size_t i = 0, e = Subs.size(); i != e; ++i)
1977         MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
1978
1979       outs() << "\n\n";
1980       outs() << "SUBCOMMANDS:\n\n";
1981       printSubCommands(Subs, MaxSubLen);
1982       outs() << "\n";
1983       outs() << "  Type \"" << GlobalParser->ProgramName
1984              << " <subcommand> -help\" to get more help on a specific "
1985                 "subcommand";
1986     }
1987
1988     outs() << "\n\n";
1989
1990     // Compute the maximum argument length...
1991     size_t MaxArgLen = 0;
1992     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1993       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1994
1995     outs() << "OPTIONS:\n";
1996     printOptions(Opts, MaxArgLen);
1997
1998     // Print any extra help the user has declared.
1999     for (auto I : GlobalParser->MoreHelp)
2000       outs() << I;
2001     GlobalParser->MoreHelp.clear();
2002   }
2003 };
2004
2005 class CategorizedHelpPrinter : public HelpPrinter {
2006 public:
2007   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2008
2009   // Helper function for printOptions().
2010   // It shall return a negative value if A's name should be lexicographically
2011   // ordered before B's name. It returns a value greater than zero if B's name
2012   // should be ordered before A's name, and it returns 0 otherwise.
2013   static int OptionCategoryCompare(OptionCategory *const *A,
2014                                    OptionCategory *const *B) {
2015     return (*A)->getName().compare((*B)->getName());
2016   }
2017
2018   // Make sure we inherit our base class's operator=()
2019   using HelpPrinter::operator=;
2020
2021 protected:
2022   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2023     std::vector<OptionCategory *> SortedCategories;
2024     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2025
2026     // Collect registered option categories into vector in preparation for
2027     // sorting.
2028     for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
2029               E = GlobalParser->RegisteredOptionCategories.end();
2030          I != E; ++I) {
2031       SortedCategories.push_back(*I);
2032     }
2033
2034     // Sort the different option categories alphabetically.
2035     assert(SortedCategories.size() > 0 && "No option categories registered!");
2036     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2037                    OptionCategoryCompare);
2038
2039     // Create map to empty vectors.
2040     for (std::vector<OptionCategory *>::const_iterator
2041              I = SortedCategories.begin(),
2042              E = SortedCategories.end();
2043          I != E; ++I)
2044       CategorizedOptions[*I] = std::vector<Option *>();
2045
2046     // Walk through pre-sorted options and assign into categories.
2047     // Because the options are already alphabetically sorted the
2048     // options within categories will also be alphabetically sorted.
2049     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
2050       Option *Opt = Opts[I].second;
2051       assert(CategorizedOptions.count(Opt->Category) > 0 &&
2052              "Option has an unregistered category");
2053       CategorizedOptions[Opt->Category].push_back(Opt);
2054     }
2055
2056     // Now do printing.
2057     for (std::vector<OptionCategory *>::const_iterator
2058              Category = SortedCategories.begin(),
2059              E = SortedCategories.end();
2060          Category != E; ++Category) {
2061       // Hide empty categories for -help, but show for -help-hidden.
2062       const auto &CategoryOptions = CategorizedOptions[*Category];
2063       bool IsEmptyCategory = CategoryOptions.empty();
2064       if (!ShowHidden && IsEmptyCategory)
2065         continue;
2066
2067       // Print category information.
2068       outs() << "\n";
2069       outs() << (*Category)->getName() << ":\n";
2070
2071       // Check if description is set.
2072       if (!(*Category)->getDescription().empty())
2073         outs() << (*Category)->getDescription() << "\n\n";
2074       else
2075         outs() << "\n";
2076
2077       // When using -help-hidden explicitly state if the category has no
2078       // options associated with it.
2079       if (IsEmptyCategory) {
2080         outs() << "  This option category has no options.\n";
2081         continue;
2082       }
2083       // Loop over the options in the category and print.
2084       for (const Option *Opt : CategoryOptions)
2085         Opt->printOptionInfo(MaxArgLen);
2086     }
2087   }
2088 };
2089
2090 // This wraps the Uncategorizing and Categorizing printers and decides
2091 // at run time which should be invoked.
2092 class HelpPrinterWrapper {
2093 private:
2094   HelpPrinter &UncategorizedPrinter;
2095   CategorizedHelpPrinter &CategorizedPrinter;
2096
2097 public:
2098   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2099                               CategorizedHelpPrinter &CategorizedPrinter)
2100       : UncategorizedPrinter(UncategorizedPrinter),
2101         CategorizedPrinter(CategorizedPrinter) {}
2102
2103   // Invoke the printer.
2104   void operator=(bool Value);
2105 };
2106
2107 } // End anonymous namespace
2108
2109 // Declare the four HelpPrinter instances that are used to print out help, or
2110 // help-hidden as an uncategorized list or in categories.
2111 static HelpPrinter UncategorizedNormalPrinter(false);
2112 static HelpPrinter UncategorizedHiddenPrinter(true);
2113 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
2114 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
2115
2116 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2117 // a categorizing help printer
2118 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
2119                                                CategorizedNormalPrinter);
2120 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
2121                                                CategorizedHiddenPrinter);
2122
2123 // Define a category for generic options that all tools should have.
2124 static cl::OptionCategory GenericCategory("Generic Options");
2125
2126 // Define uncategorized help printers.
2127 // -help-list is hidden by default because if Option categories are being used
2128 // then -help behaves the same as -help-list.
2129 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
2130     "help-list",
2131     cl::desc("Display list of available options (-help-list-hidden for more)"),
2132     cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
2133     cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2134
2135 static cl::opt<HelpPrinter, true, parser<bool>>
2136     HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
2137           cl::location(UncategorizedHiddenPrinter), cl::Hidden,
2138           cl::ValueDisallowed, cl::cat(GenericCategory),
2139           cl::sub(*AllSubCommands));
2140
2141 // Define uncategorized/categorized help printers. These printers change their
2142 // behaviour at runtime depending on whether one or more Option categories have
2143 // been declared.
2144 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2145     HOp("help", cl::desc("Display available options (-help-hidden for more)"),
2146         cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
2147         cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2148
2149 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
2150     HHOp("help-hidden", cl::desc("Display all available options"),
2151          cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
2152          cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2153
2154 static cl::opt<bool> PrintOptions(
2155     "print-options",
2156     cl::desc("Print non-default options after command line parsing"),
2157     cl::Hidden, cl::init(false), cl::cat(GenericCategory),
2158     cl::sub(*AllSubCommands));
2159
2160 static cl::opt<bool> PrintAllOptions(
2161     "print-all-options",
2162     cl::desc("Print all option values after command line parsing"), cl::Hidden,
2163     cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
2164
2165 void HelpPrinterWrapper::operator=(bool Value) {
2166   if (!Value)
2167     return;
2168
2169   // Decide which printer to invoke. If more than one option category is
2170   // registered then it is useful to show the categorized help instead of
2171   // uncategorized help.
2172   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2173     // unhide -help-list option so user can have uncategorized output if they
2174     // want it.
2175     HLOp.setHiddenFlag(NotHidden);
2176
2177     CategorizedPrinter = true; // Invoke categorized printer
2178   } else
2179     UncategorizedPrinter = true; // Invoke uncategorized printer
2180 }
2181
2182 // Print the value of each option.
2183 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2184
2185 void CommandLineParser::printOptionValues() {
2186   if (!PrintOptions && !PrintAllOptions)
2187     return;
2188
2189   SmallVector<std::pair<const char *, Option *>, 128> Opts;
2190   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2191
2192   // Compute the maximum argument length...
2193   size_t MaxArgLen = 0;
2194   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2195     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2196
2197   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2198     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
2199 }
2200
2201 static VersionPrinterTy OverrideVersionPrinter = nullptr;
2202
2203 static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr;
2204
2205 namespace {
2206 class VersionPrinter {
2207 public:
2208   void print() {
2209     raw_ostream &OS = outs();
2210 #ifdef PACKAGE_VENDOR
2211     OS << PACKAGE_VENDOR << " ";
2212 #else
2213     OS << "LLVM (http://llvm.org/):\n  ";
2214 #endif
2215     OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
2216 #ifdef LLVM_VERSION_INFO
2217     OS << " " << LLVM_VERSION_INFO;
2218 #endif
2219     OS << "\n  ";
2220 #ifndef __OPTIMIZE__
2221     OS << "DEBUG build";
2222 #else
2223     OS << "Optimized build";
2224 #endif
2225 #ifndef NDEBUG
2226     OS << " with assertions";
2227 #endif
2228 #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
2229     std::string CPU = sys::getHostCPUName();
2230     if (CPU == "generic")
2231       CPU = "(unknown)";
2232     OS << ".\n"
2233        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
2234        << "  Host CPU: " << CPU;
2235 #endif
2236     OS << '\n';
2237   }
2238   void operator=(bool OptionWasSpecified) {
2239     if (!OptionWasSpecified)
2240       return;
2241
2242     if (OverrideVersionPrinter != nullptr) {
2243       OverrideVersionPrinter(outs());
2244       exit(0);
2245     }
2246     print();
2247
2248     // Iterate over any registered extra printers and call them to add further
2249     // information.
2250     if (ExtraVersionPrinters != nullptr) {
2251       outs() << '\n';
2252       for (auto I : *ExtraVersionPrinters)
2253         I(outs());
2254     }
2255
2256     exit(0);
2257   }
2258 };
2259 } // End anonymous namespace
2260
2261 // Define the --version option that prints out the LLVM version for the tool
2262 static VersionPrinter VersionPrinterInstance;
2263
2264 static cl::opt<VersionPrinter, true, parser<bool>>
2265     VersOp("version", cl::desc("Display the version of this program"),
2266            cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2267            cl::cat(GenericCategory));
2268
2269 // Utility function for printing the help message.
2270 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2271   if (!Hidden && !Categorized)
2272     UncategorizedNormalPrinter.printHelp();
2273   else if (!Hidden && Categorized)
2274     CategorizedNormalPrinter.printHelp();
2275   else if (Hidden && !Categorized)
2276     UncategorizedHiddenPrinter.printHelp();
2277   else
2278     CategorizedHiddenPrinter.printHelp();
2279 }
2280
2281 /// Utility function for printing version number.
2282 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
2283
2284 void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; }
2285
2286 void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2287   if (!ExtraVersionPrinters)
2288     ExtraVersionPrinters = new std::vector<VersionPrinterTy>;
2289
2290   ExtraVersionPrinters->push_back(func);
2291 }
2292
2293 StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2294   auto &Subs = GlobalParser->RegisteredSubCommands;
2295   (void)Subs;
2296   assert(is_contained(Subs, &Sub));
2297   return Sub.OptionsMap;
2298 }
2299
2300 iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
2301 cl::getRegisteredSubcommands() {
2302   return GlobalParser->getRegisteredSubcommands();
2303 }
2304
2305 void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2306   for (auto &I : Sub.OptionsMap) {
2307     if (I.second->Category != &Category &&
2308         I.second->Category != &GenericCategory)
2309       I.second->setHiddenFlag(cl::ReallyHidden);
2310   }
2311 }
2312
2313 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2314                               SubCommand &Sub) {
2315   auto CategoriesBegin = Categories.begin();
2316   auto CategoriesEnd = Categories.end();
2317   for (auto &I : Sub.OptionsMap) {
2318     if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
2319             CategoriesEnd &&
2320         I.second->Category != &GenericCategory)
2321       I.second->setHiddenFlag(cl::ReallyHidden);
2322   }
2323 }
2324
2325 void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2326 void cl::ResetAllOptionOccurrences() {
2327   GlobalParser->ResetAllOptionOccurrences();
2328 }
2329
2330 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2331                                  const char *Overview) {
2332   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2333                                     &llvm::nulls());
2334 }