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