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