xref: /llvm-project/llvm/lib/Support/CommandLine.cpp (revision 7423f40674b16c746dfaa94dfc4b3f962dd6b156)
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 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
519 
520 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
521                                 SmallVectorImpl<const char *> &NewArgv,
522                                 bool MarkEOLs) {
523   SmallString<128> Token;
524   for (size_t I = 0, E = Src.size(); I != E; ++I) {
525     // Consume runs of whitespace.
526     if (Token.empty()) {
527       while (I != E && isWhitespace(Src[I])) {
528         // Mark the end of lines in response files
529         if (MarkEOLs && Src[I] == '\n')
530           NewArgv.push_back(nullptr);
531         ++I;
532       }
533       if (I == E)
534         break;
535     }
536 
537     // Backslashes can escape backslashes, spaces, and other quotes.  Otherwise
538     // they are literal.  This makes it much easier to read Windows file paths.
539     if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
540       ++I; // Skip the escape.
541       Token.push_back(Src[I]);
542       continue;
543     }
544 
545     // Consume a quoted string.
546     if (isQuote(Src[I])) {
547       char Quote = Src[I++];
548       while (I != E && Src[I] != Quote) {
549         // Backslashes are literal, unless they escape a special character.
550         if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
551           ++I;
552         Token.push_back(Src[I]);
553         ++I;
554       }
555       if (I == E)
556         break;
557       continue;
558     }
559 
560     // End the token if this is whitespace.
561     if (isWhitespace(Src[I])) {
562       if (!Token.empty())
563         NewArgv.push_back(Saver.save(Token.c_str()));
564       Token.clear();
565       continue;
566     }
567 
568     // This is a normal character.  Append it.
569     Token.push_back(Src[I]);
570   }
571 
572   // Append the last token after hitting EOF with no whitespace.
573   if (!Token.empty())
574     NewArgv.push_back(Saver.save(Token.c_str()));
575   // Mark the end of response files
576   if (MarkEOLs)
577     NewArgv.push_back(nullptr);
578 }
579 
580 /// Backslashes are interpreted in a rather complicated way in the Windows-style
581 /// command line, because backslashes are used both to separate path and to
582 /// escape double quote. This method consumes runs of backslashes as well as the
583 /// following double quote if it's escaped.
584 ///
585 ///  * If an even number of backslashes is followed by a double quote, one
586 ///    backslash is output for every pair of backslashes, and the last double
587 ///    quote remains unconsumed. The double quote will later be interpreted as
588 ///    the start or end of a quoted string in the main loop outside of this
589 ///    function.
590 ///
591 ///  * If an odd number of backslashes is followed by a double quote, one
592 ///    backslash is output for every pair of backslashes, and a double quote is
593 ///    output for the last pair of backslash-double quote. The double quote is
594 ///    consumed in this case.
595 ///
596 ///  * Otherwise, backslashes are interpreted literally.
597 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
598   size_t E = Src.size();
599   int BackslashCount = 0;
600   // Skip the backslashes.
601   do {
602     ++I;
603     ++BackslashCount;
604   } while (I != E && Src[I] == '\\');
605 
606   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
607   if (FollowedByDoubleQuote) {
608     Token.append(BackslashCount / 2, '\\');
609     if (BackslashCount % 2 == 0)
610       return I - 1;
611     Token.push_back('"');
612     return I;
613   }
614   Token.append(BackslashCount, '\\');
615   return I - 1;
616 }
617 
618 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
619                                     SmallVectorImpl<const char *> &NewArgv,
620                                     bool MarkEOLs) {
621   SmallString<128> Token;
622 
623   // This is a small state machine to consume characters until it reaches the
624   // end of the source string.
625   enum { INIT, UNQUOTED, QUOTED } State = INIT;
626   for (size_t I = 0, E = Src.size(); I != E; ++I) {
627     // INIT state indicates that the current input index is at the start of
628     // the string or between tokens.
629     if (State == INIT) {
630       if (isWhitespace(Src[I])) {
631         // Mark the end of lines in response files
632         if (MarkEOLs && Src[I] == '\n')
633           NewArgv.push_back(nullptr);
634         continue;
635       }
636       if (Src[I] == '"') {
637         State = QUOTED;
638         continue;
639       }
640       if (Src[I] == '\\') {
641         I = parseBackslash(Src, I, Token);
642         State = UNQUOTED;
643         continue;
644       }
645       Token.push_back(Src[I]);
646       State = UNQUOTED;
647       continue;
648     }
649 
650     // UNQUOTED state means that it's reading a token not quoted by double
651     // quotes.
652     if (State == UNQUOTED) {
653       // Whitespace means the end of the token.
654       if (isWhitespace(Src[I])) {
655         NewArgv.push_back(Saver.save(Token.c_str()));
656         Token.clear();
657         State = INIT;
658         // Mark the end of lines in response files
659         if (MarkEOLs && Src[I] == '\n')
660           NewArgv.push_back(nullptr);
661         continue;
662       }
663       if (Src[I] == '"') {
664         State = QUOTED;
665         continue;
666       }
667       if (Src[I] == '\\') {
668         I = parseBackslash(Src, I, Token);
669         continue;
670       }
671       Token.push_back(Src[I]);
672       continue;
673     }
674 
675     // QUOTED state means that it's reading a token quoted by double quotes.
676     if (State == QUOTED) {
677       if (Src[I] == '"') {
678         State = UNQUOTED;
679         continue;
680       }
681       if (Src[I] == '\\') {
682         I = parseBackslash(Src, I, Token);
683         continue;
684       }
685       Token.push_back(Src[I]);
686     }
687   }
688   // Append the last token after hitting EOF with no whitespace.
689   if (!Token.empty())
690     NewArgv.push_back(Saver.save(Token.c_str()));
691   // Mark the end of response files
692   if (MarkEOLs)
693     NewArgv.push_back(nullptr);
694 }
695 
696 // It is called byte order marker but the UTF-8 BOM is actually not affected
697 // by the host system's endianness.
698 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
699   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
700 }
701 
702 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
703                                TokenizerCallback Tokenizer,
704                                SmallVectorImpl<const char *> &NewArgv,
705                                bool MarkEOLs = false) {
706   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
707       MemoryBuffer::getFile(FName);
708   if (!MemBufOrErr)
709     return false;
710   MemoryBuffer &MemBuf = *MemBufOrErr.get();
711   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
712 
713   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
714   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
715   std::string UTF8Buf;
716   if (hasUTF16ByteOrderMark(BufRef)) {
717     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
718       return false;
719     Str = StringRef(UTF8Buf);
720   }
721   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
722   // these bytes before parsing.
723   // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
724   else if (hasUTF8ByteOrderMark(BufRef))
725     Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
726 
727   // Tokenize the contents into NewArgv.
728   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
729 
730   return true;
731 }
732 
733 /// \brief Expand response files on a command line recursively using the given
734 /// StringSaver and tokenization strategy.
735 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
736                              SmallVectorImpl<const char *> &Argv,
737                              bool MarkEOLs) {
738   unsigned RspFiles = 0;
739   bool AllExpanded = true;
740 
741   // Don't cache Argv.size() because it can change.
742   for (unsigned I = 0; I != Argv.size();) {
743     const char *Arg = Argv[I];
744     // Check if it is an EOL marker
745     if (Arg == nullptr) {
746       ++I;
747       continue;
748     }
749     if (Arg[0] != '@') {
750       ++I;
751       continue;
752     }
753 
754     // If we have too many response files, leave some unexpanded.  This avoids
755     // crashing on self-referential response files.
756     if (RspFiles++ > 20)
757       return false;
758 
759     // Replace this response file argument with the tokenization of its
760     // contents.  Nested response files are expanded in subsequent iterations.
761     // FIXME: If a nested response file uses a relative path, is it relative to
762     // the cwd of the process or the response file?
763     SmallVector<const char *, 0> ExpandedArgv;
764     if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
765                             MarkEOLs)) {
766       // We couldn't read this file, so we leave it in the argument stream and
767       // move on.
768       AllExpanded = false;
769       ++I;
770       continue;
771     }
772     Argv.erase(Argv.begin() + I);
773     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
774   }
775   return AllExpanded;
776 }
777 
778 /// ParseEnvironmentOptions - An alternative entry point to the
779 /// CommandLine library, which allows you to read the program's name
780 /// from the caller (as PROGNAME) and its command-line arguments from
781 /// an environment variable (whose name is given in ENVVAR).
782 ///
783 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
784                                  const char *Overview) {
785   // Check args.
786   assert(progName && "Program name not specified");
787   assert(envVar && "Environment variable name missing");
788 
789   // Get the environment variable they want us to parse options out of.
790 #ifdef _WIN32
791   std::wstring wenvVar;
792   if (!llvm::ConvertUTF8toWide(envVar, wenvVar)) {
793     assert(false &&
794            "Unicode conversion of environment variable name failed");
795     return;
796   }
797   const wchar_t *wenvValue = _wgetenv(wenvVar.c_str());
798   if (!wenvValue)
799     return;
800   std::string envValueBuffer;
801   if (!llvm::convertWideToUTF8(wenvValue, envValueBuffer)) {
802     assert(false &&
803            "Unicode conversion of environment variable value failed");
804     return;
805   }
806   const char *envValue = envValueBuffer.c_str();
807 #else
808   const char *envValue = getenv(envVar);
809   if (!envValue)
810     return;
811 #endif
812 
813   // Get program's "name", which we wouldn't know without the caller
814   // telling us.
815   SmallVector<const char *, 20> newArgv;
816   BumpPtrAllocator A;
817   StringSaver Saver(A);
818   newArgv.push_back(Saver.save(progName));
819 
820   // Parse the value of the environment variable into a "command line"
821   // and hand it off to ParseCommandLineOptions().
822   TokenizeGNUCommandLine(envValue, Saver, newArgv);
823   int newArgc = static_cast<int>(newArgv.size());
824   ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
825 }
826 
827 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
828                                  const char *Overview) {
829   GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
830 }
831 
832 void CommandLineParser::ParseCommandLineOptions(int argc,
833                                                 const char *const *argv,
834                                                 const char *Overview) {
835   assert(hasOptions() && "No options specified!");
836 
837   // Expand response files.
838   SmallVector<const char *, 20> newArgv(argv, argv + argc);
839   BumpPtrAllocator A;
840   StringSaver Saver(A);
841   ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
842   argv = &newArgv[0];
843   argc = static_cast<int>(newArgv.size());
844 
845   // Copy the program name into ProgName, making sure not to overflow it.
846   ProgramName = sys::path::filename(argv[0]);
847 
848   ProgramOverview = Overview;
849   bool ErrorParsing = false;
850 
851   // Check out the positional arguments to collect information about them.
852   unsigned NumPositionalRequired = 0;
853 
854   // Determine whether or not there are an unlimited number of positionals
855   bool HasUnlimitedPositionals = false;
856 
857   if (ConsumeAfterOpt) {
858     assert(PositionalOpts.size() > 0 &&
859            "Cannot specify cl::ConsumeAfter without a positional argument!");
860   }
861   if (!PositionalOpts.empty()) {
862 
863     // Calculate how many positional values are _required_.
864     bool UnboundedFound = false;
865     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
866       Option *Opt = PositionalOpts[i];
867       if (RequiresValue(Opt))
868         ++NumPositionalRequired;
869       else if (ConsumeAfterOpt) {
870         // ConsumeAfter cannot be combined with "optional" positional options
871         // unless there is only one positional argument...
872         if (PositionalOpts.size() > 1)
873           ErrorParsing |= Opt->error(
874               "error - this positional option will never be matched, "
875               "because it does not Require a value, and a "
876               "cl::ConsumeAfter option is active!");
877       } else if (UnboundedFound && !Opt->hasArgStr()) {
878         // This option does not "require" a value...  Make sure this option is
879         // not specified after an option that eats all extra arguments, or this
880         // one will never get any!
881         //
882         ErrorParsing |= Opt->error("error - option can never match, because "
883                                    "another positional argument will match an "
884                                    "unbounded number of values, and this option"
885                                    " does not require a value!");
886         errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
887                << "' is all messed up!\n";
888         errs() << PositionalOpts.size();
889       }
890       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
891     }
892     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
893   }
894 
895   // PositionalVals - A vector of "positional" arguments we accumulate into
896   // the process at the end.
897   //
898   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
899 
900   // If the program has named positional arguments, and the name has been run
901   // across, keep track of which positional argument was named.  Otherwise put
902   // the positional args into the PositionalVals list...
903   Option *ActivePositionalArg = nullptr;
904 
905   // Loop over all of the arguments... processing them.
906   bool DashDashFound = false; // Have we read '--'?
907   for (int i = 1; i < argc; ++i) {
908     Option *Handler = nullptr;
909     Option *NearestHandler = nullptr;
910     std::string NearestHandlerString;
911     StringRef Value;
912     StringRef ArgName = "";
913 
914     // Check to see if this is a positional argument.  This argument is
915     // considered to be positional if it doesn't start with '-', if it is "-"
916     // itself, or if we have seen "--" already.
917     //
918     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
919       // Positional argument!
920       if (ActivePositionalArg) {
921         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
922         continue; // We are done!
923       }
924 
925       if (!PositionalOpts.empty()) {
926         PositionalVals.push_back(std::make_pair(argv[i], i));
927 
928         // All of the positional arguments have been fulfulled, give the rest to
929         // the consume after option... if it's specified...
930         //
931         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
932           for (++i; i < argc; ++i)
933             PositionalVals.push_back(std::make_pair(argv[i], i));
934           break; // Handle outside of the argument processing loop...
935         }
936 
937         // Delay processing positional arguments until the end...
938         continue;
939       }
940     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
941                !DashDashFound) {
942       DashDashFound = true; // This is the mythical "--"?
943       continue;             // Don't try to process it as an argument itself.
944     } else if (ActivePositionalArg &&
945                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
946       // If there is a positional argument eating options, check to see if this
947       // option is another positional argument.  If so, treat it as an argument,
948       // otherwise feed it to the eating positional.
949       ArgName = argv[i] + 1;
950       // Eat leading dashes.
951       while (!ArgName.empty() && ArgName[0] == '-')
952         ArgName = ArgName.substr(1);
953 
954       Handler = LookupOption(ArgName, Value);
955       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
956         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
957         continue; // We are done!
958       }
959 
960     } else { // We start with a '-', must be an argument.
961       ArgName = argv[i] + 1;
962       // Eat leading dashes.
963       while (!ArgName.empty() && ArgName[0] == '-')
964         ArgName = ArgName.substr(1);
965 
966       Handler = LookupOption(ArgName, Value);
967 
968       // Check to see if this "option" is really a prefixed or grouped argument.
969       if (!Handler)
970         Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
971                                                 OptionsMap);
972 
973       // Otherwise, look for the closest available option to report to the user
974       // in the upcoming error.
975       if (!Handler && SinkOpts.empty())
976         NearestHandler =
977             LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
978     }
979 
980     if (!Handler) {
981       if (SinkOpts.empty()) {
982         errs() << ProgramName << ": Unknown command line argument '" << argv[i]
983                << "'.  Try: '" << argv[0] << " -help'\n";
984 
985         if (NearestHandler) {
986           // If we know a near match, report it as well.
987           errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
988                  << "'?\n";
989         }
990 
991         ErrorParsing = true;
992       } else {
993         for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
994                                                  E = SinkOpts.end();
995              I != E; ++I)
996           (*I)->addOccurrence(i, "", argv[i]);
997       }
998       continue;
999     }
1000 
1001     // If this is a named positional argument, just remember that it is the
1002     // active one...
1003     if (Handler->getFormattingFlag() == cl::Positional)
1004       ActivePositionalArg = Handler;
1005     else
1006       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1007   }
1008 
1009   // Check and handle positional arguments now...
1010   if (NumPositionalRequired > PositionalVals.size()) {
1011     errs() << ProgramName
1012            << ": Not enough positional command line arguments specified!\n"
1013            << "Must specify at least " << NumPositionalRequired
1014            << " positional arguments: See: " << argv[0] << " -help\n";
1015 
1016     ErrorParsing = true;
1017   } else if (!HasUnlimitedPositionals &&
1018              PositionalVals.size() > PositionalOpts.size()) {
1019     errs() << ProgramName << ": Too many positional arguments specified!\n"
1020            << "Can specify at most " << PositionalOpts.size()
1021            << " positional arguments: See: " << argv[0] << " -help\n";
1022     ErrorParsing = true;
1023 
1024   } else if (!ConsumeAfterOpt) {
1025     // Positional args have already been handled if ConsumeAfter is specified.
1026     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1027     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1028       if (RequiresValue(PositionalOpts[i])) {
1029         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1030                                 PositionalVals[ValNo].second);
1031         ValNo++;
1032         --NumPositionalRequired; // We fulfilled our duty...
1033       }
1034 
1035       // If we _can_ give this option more arguments, do so now, as long as we
1036       // do not give it values that others need.  'Done' controls whether the
1037       // option even _WANTS_ any more.
1038       //
1039       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1040       while (NumVals - ValNo > NumPositionalRequired && !Done) {
1041         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1042         case cl::Optional:
1043           Done = true; // Optional arguments want _at most_ one value
1044         // FALL THROUGH
1045         case cl::ZeroOrMore: // Zero or more will take all they can get...
1046         case cl::OneOrMore:  // One or more will take all they can get...
1047           ProvidePositionalOption(PositionalOpts[i],
1048                                   PositionalVals[ValNo].first,
1049                                   PositionalVals[ValNo].second);
1050           ValNo++;
1051           break;
1052         default:
1053           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1054                            "positional argument processing!");
1055         }
1056       }
1057     }
1058   } else {
1059     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1060     unsigned ValNo = 0;
1061     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1062       if (RequiresValue(PositionalOpts[j])) {
1063         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1064                                                 PositionalVals[ValNo].first,
1065                                                 PositionalVals[ValNo].second);
1066         ValNo++;
1067       }
1068 
1069     // Handle the case where there is just one positional option, and it's
1070     // optional.  In this case, we want to give JUST THE FIRST option to the
1071     // positional option and keep the rest for the consume after.  The above
1072     // loop would have assigned no values to positional options in this case.
1073     //
1074     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1075       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1076                                               PositionalVals[ValNo].first,
1077                                               PositionalVals[ValNo].second);
1078       ValNo++;
1079     }
1080 
1081     // Handle over all of the rest of the arguments to the
1082     // cl::ConsumeAfter command line option...
1083     for (; ValNo != PositionalVals.size(); ++ValNo)
1084       ErrorParsing |=
1085           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1086                                   PositionalVals[ValNo].second);
1087   }
1088 
1089   // Loop over args and make sure all required args are specified!
1090   for (const auto &Opt : OptionsMap) {
1091     switch (Opt.second->getNumOccurrencesFlag()) {
1092     case Required:
1093     case OneOrMore:
1094       if (Opt.second->getNumOccurrences() == 0) {
1095         Opt.second->error("must be specified at least once!");
1096         ErrorParsing = true;
1097       }
1098     // Fall through
1099     default:
1100       break;
1101     }
1102   }
1103 
1104   // Now that we know if -debug is specified, we can use it.
1105   // Note that if ReadResponseFiles == true, this must be done before the
1106   // memory allocated for the expanded command line is free()d below.
1107   DEBUG(dbgs() << "Args: ";
1108         for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1109         dbgs() << '\n';);
1110 
1111   // Free all of the memory allocated to the map.  Command line options may only
1112   // be processed once!
1113   MoreHelp.clear();
1114 
1115   // If we had an error processing our arguments, don't let the program execute
1116   if (ErrorParsing)
1117     exit(1);
1118 }
1119 
1120 //===----------------------------------------------------------------------===//
1121 // Option Base class implementation
1122 //
1123 
1124 bool Option::error(const Twine &Message, StringRef ArgName) {
1125   if (!ArgName.data())
1126     ArgName = ArgStr;
1127   if (ArgName.empty())
1128     errs() << HelpStr; // Be nice for positional arguments
1129   else
1130     errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1131 
1132   errs() << " option: " << Message << "\n";
1133   return true;
1134 }
1135 
1136 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1137                            bool MultiArg) {
1138   if (!MultiArg)
1139     NumOccurrences++; // Increment the number of times we have been seen
1140 
1141   switch (getNumOccurrencesFlag()) {
1142   case Optional:
1143     if (NumOccurrences > 1)
1144       return error("may only occur zero or one times!", ArgName);
1145     break;
1146   case Required:
1147     if (NumOccurrences > 1)
1148       return error("must occur exactly one time!", ArgName);
1149   // Fall through
1150   case OneOrMore:
1151   case ZeroOrMore:
1152   case ConsumeAfter:
1153     break;
1154   }
1155 
1156   return handleOccurrence(pos, ArgName, Value);
1157 }
1158 
1159 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1160 // has been specified yet.
1161 //
1162 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1163   if (O.ValueStr.empty())
1164     return DefaultMsg;
1165   return O.ValueStr;
1166 }
1167 
1168 //===----------------------------------------------------------------------===//
1169 // cl::alias class implementation
1170 //
1171 
1172 // Return the width of the option tag for printing...
1173 size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
1174 
1175 static void printHelpStr(StringRef HelpStr, size_t Indent,
1176                          size_t FirstLineIndentedBy) {
1177   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1178   outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1179   while (!Split.second.empty()) {
1180     Split = Split.second.split('\n');
1181     outs().indent(Indent) << Split.first << "\n";
1182   }
1183 }
1184 
1185 // Print out the option for the alias.
1186 void alias::printOptionInfo(size_t GlobalWidth) const {
1187   outs() << "  -" << ArgStr;
1188   printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1189 }
1190 
1191 //===----------------------------------------------------------------------===//
1192 // Parser Implementation code...
1193 //
1194 
1195 // basic_parser implementation
1196 //
1197 
1198 // Return the width of the option tag for printing...
1199 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1200   size_t Len = O.ArgStr.size();
1201   if (const char *ValName = getValueName())
1202     Len += getValueStr(O, ValName).size() + 3;
1203 
1204   return Len + 6;
1205 }
1206 
1207 // printOptionInfo - Print out information about this option.  The
1208 // to-be-maintained width is specified.
1209 //
1210 void basic_parser_impl::printOptionInfo(const Option &O,
1211                                         size_t GlobalWidth) const {
1212   outs() << "  -" << O.ArgStr;
1213 
1214   if (const char *ValName = getValueName())
1215     outs() << "=<" << getValueStr(O, ValName) << '>';
1216 
1217   printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1218 }
1219 
1220 void basic_parser_impl::printOptionName(const Option &O,
1221                                         size_t GlobalWidth) const {
1222   outs() << "  -" << O.ArgStr;
1223   outs().indent(GlobalWidth - O.ArgStr.size());
1224 }
1225 
1226 // parser<bool> implementation
1227 //
1228 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1229                          bool &Value) {
1230   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1231       Arg == "1") {
1232     Value = true;
1233     return false;
1234   }
1235 
1236   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1237     Value = false;
1238     return false;
1239   }
1240   return O.error("'" + Arg +
1241                  "' is invalid value for boolean argument! Try 0 or 1");
1242 }
1243 
1244 // parser<boolOrDefault> implementation
1245 //
1246 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1247                                   boolOrDefault &Value) {
1248   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1249       Arg == "1") {
1250     Value = BOU_TRUE;
1251     return false;
1252   }
1253   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1254     Value = BOU_FALSE;
1255     return false;
1256   }
1257 
1258   return O.error("'" + Arg +
1259                  "' is invalid value for boolean argument! Try 0 or 1");
1260 }
1261 
1262 // parser<int> implementation
1263 //
1264 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1265                         int &Value) {
1266   if (Arg.getAsInteger(0, Value))
1267     return O.error("'" + Arg + "' value invalid for integer argument!");
1268   return false;
1269 }
1270 
1271 // parser<unsigned> implementation
1272 //
1273 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1274                              unsigned &Value) {
1275 
1276   if (Arg.getAsInteger(0, Value))
1277     return O.error("'" + Arg + "' value invalid for uint argument!");
1278   return false;
1279 }
1280 
1281 // parser<unsigned long long> implementation
1282 //
1283 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1284                                        StringRef Arg,
1285                                        unsigned long long &Value) {
1286 
1287   if (Arg.getAsInteger(0, Value))
1288     return O.error("'" + Arg + "' value invalid for uint argument!");
1289   return false;
1290 }
1291 
1292 // parser<double>/parser<float> implementation
1293 //
1294 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1295   SmallString<32> TmpStr(Arg.begin(), Arg.end());
1296   const char *ArgStart = TmpStr.c_str();
1297   char *End;
1298   Value = strtod(ArgStart, &End);
1299   if (*End != 0)
1300     return O.error("'" + Arg + "' value invalid for floating point argument!");
1301   return false;
1302 }
1303 
1304 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1305                            double &Val) {
1306   return parseDouble(O, Arg, Val);
1307 }
1308 
1309 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1310                           float &Val) {
1311   double dVal;
1312   if (parseDouble(O, Arg, dVal))
1313     return true;
1314   Val = (float)dVal;
1315   return false;
1316 }
1317 
1318 // generic_parser_base implementation
1319 //
1320 
1321 // findOption - Return the option number corresponding to the specified
1322 // argument string.  If the option is not found, getNumOptions() is returned.
1323 //
1324 unsigned generic_parser_base::findOption(const char *Name) {
1325   unsigned e = getNumOptions();
1326 
1327   for (unsigned i = 0; i != e; ++i) {
1328     if (strcmp(getOption(i), Name) == 0)
1329       return i;
1330   }
1331   return e;
1332 }
1333 
1334 // Return the width of the option tag for printing...
1335 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1336   if (O.hasArgStr()) {
1337     size_t Size = O.ArgStr.size() + 6;
1338     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1339       Size = std::max(Size, std::strlen(getOption(i)) + 8);
1340     return Size;
1341   } else {
1342     size_t BaseSize = 0;
1343     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1344       BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1345     return BaseSize;
1346   }
1347 }
1348 
1349 // printOptionInfo - Print out information about this option.  The
1350 // to-be-maintained width is specified.
1351 //
1352 void generic_parser_base::printOptionInfo(const Option &O,
1353                                           size_t GlobalWidth) const {
1354   if (O.hasArgStr()) {
1355     outs() << "  -" << O.ArgStr;
1356     printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
1357 
1358     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1359       size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1360       outs() << "    =" << getOption(i);
1361       outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
1362     }
1363   } else {
1364     if (!O.HelpStr.empty())
1365       outs() << "  " << O.HelpStr << '\n';
1366     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1367       const char *Option = getOption(i);
1368       outs() << "    -" << Option;
1369       printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1370     }
1371   }
1372 }
1373 
1374 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1375 
1376 // printGenericOptionDiff - Print the value of this option and it's default.
1377 //
1378 // "Generic" options have each value mapped to a name.
1379 void generic_parser_base::printGenericOptionDiff(
1380     const Option &O, const GenericOptionValue &Value,
1381     const GenericOptionValue &Default, size_t GlobalWidth) const {
1382   outs() << "  -" << O.ArgStr;
1383   outs().indent(GlobalWidth - O.ArgStr.size());
1384 
1385   unsigned NumOpts = getNumOptions();
1386   for (unsigned i = 0; i != NumOpts; ++i) {
1387     if (Value.compare(getOptionValue(i)))
1388       continue;
1389 
1390     outs() << "= " << getOption(i);
1391     size_t L = std::strlen(getOption(i));
1392     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1393     outs().indent(NumSpaces) << " (default: ";
1394     for (unsigned j = 0; j != NumOpts; ++j) {
1395       if (Default.compare(getOptionValue(j)))
1396         continue;
1397       outs() << getOption(j);
1398       break;
1399     }
1400     outs() << ")\n";
1401     return;
1402   }
1403   outs() << "= *unknown option value*\n";
1404 }
1405 
1406 // printOptionDiff - Specializations for printing basic value types.
1407 //
1408 #define PRINT_OPT_DIFF(T)                                                      \
1409   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
1410                                   size_t GlobalWidth) const {                  \
1411     printOptionName(O, GlobalWidth);                                           \
1412     std::string Str;                                                           \
1413     {                                                                          \
1414       raw_string_ostream SS(Str);                                              \
1415       SS << V;                                                                 \
1416     }                                                                          \
1417     outs() << "= " << Str;                                                     \
1418     size_t NumSpaces =                                                         \
1419         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
1420     outs().indent(NumSpaces) << " (default: ";                                 \
1421     if (D.hasValue())                                                          \
1422       outs() << D.getValue();                                                  \
1423     else                                                                       \
1424       outs() << "*no default*";                                                \
1425     outs() << ")\n";                                                           \
1426   }
1427 
1428 PRINT_OPT_DIFF(bool)
1429 PRINT_OPT_DIFF(boolOrDefault)
1430 PRINT_OPT_DIFF(int)
1431 PRINT_OPT_DIFF(unsigned)
1432 PRINT_OPT_DIFF(unsigned long long)
1433 PRINT_OPT_DIFF(double)
1434 PRINT_OPT_DIFF(float)
1435 PRINT_OPT_DIFF(char)
1436 
1437 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1438                                           OptionValue<std::string> D,
1439                                           size_t GlobalWidth) const {
1440   printOptionName(O, GlobalWidth);
1441   outs() << "= " << V;
1442   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1443   outs().indent(NumSpaces) << " (default: ";
1444   if (D.hasValue())
1445     outs() << D.getValue();
1446   else
1447     outs() << "*no default*";
1448   outs() << ")\n";
1449 }
1450 
1451 // Print a placeholder for options that don't yet support printOptionDiff().
1452 void basic_parser_impl::printOptionNoValue(const Option &O,
1453                                            size_t GlobalWidth) const {
1454   printOptionName(O, GlobalWidth);
1455   outs() << "= *cannot print option value*\n";
1456 }
1457 
1458 //===----------------------------------------------------------------------===//
1459 // -help and -help-hidden option implementation
1460 //
1461 
1462 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1463                           const std::pair<const char *, Option *> *RHS) {
1464   return strcmp(LHS->first, RHS->first);
1465 }
1466 
1467 // Copy Options into a vector so we can sort them as we like.
1468 static void sortOpts(StringMap<Option *> &OptMap,
1469                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1470                      bool ShowHidden) {
1471   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
1472 
1473   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1474        I != E; ++I) {
1475     // Ignore really-hidden options.
1476     if (I->second->getOptionHiddenFlag() == ReallyHidden)
1477       continue;
1478 
1479     // Unless showhidden is set, ignore hidden flags.
1480     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1481       continue;
1482 
1483     // If we've already seen this option, don't add it to the list again.
1484     if (!OptionSet.insert(I->second).second)
1485       continue;
1486 
1487     Opts.push_back(
1488         std::pair<const char *, Option *>(I->getKey().data(), I->second));
1489   }
1490 
1491   // Sort the options list alphabetically.
1492   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1493 }
1494 
1495 namespace {
1496 
1497 class HelpPrinter {
1498 protected:
1499   const bool ShowHidden;
1500   typedef SmallVector<std::pair<const char *, Option *>, 128>
1501       StrOptionPairVector;
1502   // Print the options. Opts is assumed to be alphabetically sorted.
1503   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1504     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1505       Opts[i].second->printOptionInfo(MaxArgLen);
1506   }
1507 
1508 public:
1509   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1510   virtual ~HelpPrinter() {}
1511 
1512   // Invoke the printer.
1513   void operator=(bool Value) {
1514     if (!Value)
1515       return;
1516 
1517     StrOptionPairVector Opts;
1518     sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
1519 
1520     if (GlobalParser->ProgramOverview)
1521       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1522 
1523     outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
1524 
1525     for (auto Opt : GlobalParser->PositionalOpts) {
1526       if (Opt->hasArgStr())
1527         outs() << " --" << Opt->ArgStr;
1528       outs() << " " << Opt->HelpStr;
1529     }
1530 
1531     // Print the consume after option info if it exists...
1532     if (GlobalParser->ConsumeAfterOpt)
1533       outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
1534 
1535     outs() << "\n\n";
1536 
1537     // Compute the maximum argument length...
1538     size_t MaxArgLen = 0;
1539     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1540       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1541 
1542     outs() << "OPTIONS:\n";
1543     printOptions(Opts, MaxArgLen);
1544 
1545     // Print any extra help the user has declared.
1546     for (auto I : GlobalParser->MoreHelp)
1547       outs() << I;
1548     GlobalParser->MoreHelp.clear();
1549 
1550     // Halt the program since help information was printed
1551     exit(0);
1552   }
1553 };
1554 
1555 class CategorizedHelpPrinter : public HelpPrinter {
1556 public:
1557   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1558 
1559   // Helper function for printOptions().
1560   // It shall return a negative value if A's name should be lexicographically
1561   // ordered before B's name. It returns a value greater equal zero otherwise.
1562   static int OptionCategoryCompare(OptionCategory *const *A,
1563                                    OptionCategory *const *B) {
1564     return strcmp((*A)->getName(), (*B)->getName());
1565   }
1566 
1567   // Make sure we inherit our base class's operator=()
1568   using HelpPrinter::operator=;
1569 
1570 protected:
1571   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1572     std::vector<OptionCategory *> SortedCategories;
1573     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1574 
1575     // Collect registered option categories into vector in preparation for
1576     // sorting.
1577     for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1578               E = GlobalParser->RegisteredOptionCategories.end();
1579          I != E; ++I) {
1580       SortedCategories.push_back(*I);
1581     }
1582 
1583     // Sort the different option categories alphabetically.
1584     assert(SortedCategories.size() > 0 && "No option categories registered!");
1585     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1586                    OptionCategoryCompare);
1587 
1588     // Create map to empty vectors.
1589     for (std::vector<OptionCategory *>::const_iterator
1590              I = SortedCategories.begin(),
1591              E = SortedCategories.end();
1592          I != E; ++I)
1593       CategorizedOptions[*I] = std::vector<Option *>();
1594 
1595     // Walk through pre-sorted options and assign into categories.
1596     // Because the options are already alphabetically sorted the
1597     // options within categories will also be alphabetically sorted.
1598     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1599       Option *Opt = Opts[I].second;
1600       assert(CategorizedOptions.count(Opt->Category) > 0 &&
1601              "Option has an unregistered category");
1602       CategorizedOptions[Opt->Category].push_back(Opt);
1603     }
1604 
1605     // Now do printing.
1606     for (std::vector<OptionCategory *>::const_iterator
1607              Category = SortedCategories.begin(),
1608              E = SortedCategories.end();
1609          Category != E; ++Category) {
1610       // Hide empty categories for -help, but show for -help-hidden.
1611       bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1612       if (!ShowHidden && IsEmptyCategory)
1613         continue;
1614 
1615       // Print category information.
1616       outs() << "\n";
1617       outs() << (*Category)->getName() << ":\n";
1618 
1619       // Check if description is set.
1620       if ((*Category)->getDescription() != nullptr)
1621         outs() << (*Category)->getDescription() << "\n\n";
1622       else
1623         outs() << "\n";
1624 
1625       // When using -help-hidden explicitly state if the category has no
1626       // options associated with it.
1627       if (IsEmptyCategory) {
1628         outs() << "  This option category has no options.\n";
1629         continue;
1630       }
1631       // Loop over the options in the category and print.
1632       for (std::vector<Option *>::const_iterator
1633                Opt = CategorizedOptions[*Category].begin(),
1634                E = CategorizedOptions[*Category].end();
1635            Opt != E; ++Opt)
1636         (*Opt)->printOptionInfo(MaxArgLen);
1637     }
1638   }
1639 };
1640 
1641 // This wraps the Uncategorizing and Categorizing printers and decides
1642 // at run time which should be invoked.
1643 class HelpPrinterWrapper {
1644 private:
1645   HelpPrinter &UncategorizedPrinter;
1646   CategorizedHelpPrinter &CategorizedPrinter;
1647 
1648 public:
1649   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1650                               CategorizedHelpPrinter &CategorizedPrinter)
1651       : UncategorizedPrinter(UncategorizedPrinter),
1652         CategorizedPrinter(CategorizedPrinter) {}
1653 
1654   // Invoke the printer.
1655   void operator=(bool Value);
1656 };
1657 
1658 } // End anonymous namespace
1659 
1660 // Declare the four HelpPrinter instances that are used to print out help, or
1661 // help-hidden as an uncategorized list or in categories.
1662 static HelpPrinter UncategorizedNormalPrinter(false);
1663 static HelpPrinter UncategorizedHiddenPrinter(true);
1664 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1665 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1666 
1667 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1668 // a categorizing help printer
1669 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1670                                                CategorizedNormalPrinter);
1671 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1672                                                CategorizedHiddenPrinter);
1673 
1674 // Define a category for generic options that all tools should have.
1675 static cl::OptionCategory GenericCategory("Generic Options");
1676 
1677 // Define uncategorized help printers.
1678 // -help-list is hidden by default because if Option categories are being used
1679 // then -help behaves the same as -help-list.
1680 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1681     "help-list",
1682     cl::desc("Display list of available options (-help-list-hidden for more)"),
1683     cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1684     cl::cat(GenericCategory));
1685 
1686 static cl::opt<HelpPrinter, true, parser<bool>>
1687     HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1688           cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1689           cl::ValueDisallowed, cl::cat(GenericCategory));
1690 
1691 // Define uncategorized/categorized help printers. These printers change their
1692 // behaviour at runtime depending on whether one or more Option categories have
1693 // been declared.
1694 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1695     HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1696         cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1697         cl::cat(GenericCategory));
1698 
1699 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1700     HHOp("help-hidden", cl::desc("Display all available options"),
1701          cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1702          cl::cat(GenericCategory));
1703 
1704 static cl::opt<bool> PrintOptions(
1705     "print-options",
1706     cl::desc("Print non-default options after command line parsing"),
1707     cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1708 
1709 static cl::opt<bool> PrintAllOptions(
1710     "print-all-options",
1711     cl::desc("Print all option values after command line parsing"), cl::Hidden,
1712     cl::init(false), cl::cat(GenericCategory));
1713 
1714 void HelpPrinterWrapper::operator=(bool Value) {
1715   if (!Value)
1716     return;
1717 
1718   // Decide which printer to invoke. If more than one option category is
1719   // registered then it is useful to show the categorized help instead of
1720   // uncategorized help.
1721   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
1722     // unhide -help-list option so user can have uncategorized output if they
1723     // want it.
1724     HLOp.setHiddenFlag(NotHidden);
1725 
1726     CategorizedPrinter = true; // Invoke categorized printer
1727   } else
1728     UncategorizedPrinter = true; // Invoke uncategorized printer
1729 }
1730 
1731 // Print the value of each option.
1732 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1733 
1734 void CommandLineParser::printOptionValues() {
1735   if (!PrintOptions && !PrintAllOptions)
1736     return;
1737 
1738   SmallVector<std::pair<const char *, Option *>, 128> Opts;
1739   sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
1740 
1741   // Compute the maximum argument length...
1742   size_t MaxArgLen = 0;
1743   for (size_t i = 0, e = Opts.size(); i != e; ++i)
1744     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1745 
1746   for (size_t i = 0, e = Opts.size(); i != e; ++i)
1747     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1748 }
1749 
1750 static void (*OverrideVersionPrinter)() = nullptr;
1751 
1752 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1753 
1754 namespace {
1755 class VersionPrinter {
1756 public:
1757   void print() {
1758     raw_ostream &OS = outs();
1759     OS << "LLVM (http://llvm.org/):\n"
1760        << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1761 #ifdef LLVM_VERSION_INFO
1762     OS << " " << LLVM_VERSION_INFO;
1763 #endif
1764     OS << "\n  ";
1765 #ifndef __OPTIMIZE__
1766     OS << "DEBUG build";
1767 #else
1768     OS << "Optimized build";
1769 #endif
1770 #ifndef NDEBUG
1771     OS << " with assertions";
1772 #endif
1773     std::string CPU = sys::getHostCPUName();
1774     if (CPU == "generic")
1775       CPU = "(unknown)";
1776     OS << ".\n"
1777 #if (ENABLE_TIMESTAMPS == 1)
1778        << "  Built " << __DATE__ << " (" << __TIME__ << ").\n"
1779 #endif
1780        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
1781        << "  Host CPU: " << CPU << '\n';
1782   }
1783   void operator=(bool OptionWasSpecified) {
1784     if (!OptionWasSpecified)
1785       return;
1786 
1787     if (OverrideVersionPrinter != nullptr) {
1788       (*OverrideVersionPrinter)();
1789       exit(0);
1790     }
1791     print();
1792 
1793     // Iterate over any registered extra printers and call them to add further
1794     // information.
1795     if (ExtraVersionPrinters != nullptr) {
1796       outs() << '\n';
1797       for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1798                                              E = ExtraVersionPrinters->end();
1799            I != E; ++I)
1800         (*I)();
1801     }
1802 
1803     exit(0);
1804   }
1805 };
1806 } // End anonymous namespace
1807 
1808 // Define the --version option that prints out the LLVM version for the tool
1809 static VersionPrinter VersionPrinterInstance;
1810 
1811 static cl::opt<VersionPrinter, true, parser<bool>>
1812     VersOp("version", cl::desc("Display the version of this program"),
1813            cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1814            cl::cat(GenericCategory));
1815 
1816 // Utility function for printing the help message.
1817 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1818   // This looks weird, but it actually prints the help message. The Printers are
1819   // types of HelpPrinter and the help gets printed when its operator= is
1820   // invoked. That's because the "normal" usages of the help printer is to be
1821   // assigned true/false depending on whether -help or -help-hidden was given or
1822   // not.  Since we're circumventing that we have to make it look like -help or
1823   // -help-hidden were given, so we assign true.
1824 
1825   if (!Hidden && !Categorized)
1826     UncategorizedNormalPrinter = true;
1827   else if (!Hidden && Categorized)
1828     CategorizedNormalPrinter = true;
1829   else if (Hidden && !Categorized)
1830     UncategorizedHiddenPrinter = true;
1831   else
1832     CategorizedHiddenPrinter = true;
1833 }
1834 
1835 /// Utility function for printing version number.
1836 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1837 
1838 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1839 
1840 void cl::AddExtraVersionPrinter(void (*func)()) {
1841   if (!ExtraVersionPrinters)
1842     ExtraVersionPrinters = new std::vector<void (*)()>;
1843 
1844   ExtraVersionPrinters->push_back(func);
1845 }
1846 
1847 StringMap<Option *> &cl::getRegisteredOptions() {
1848   return GlobalParser->OptionsMap;
1849 }
1850 
1851 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1852   for (auto &I : GlobalParser->OptionsMap) {
1853     if (I.second->Category != &Category &&
1854         I.second->Category != &GenericCategory)
1855       I.second->setHiddenFlag(cl::ReallyHidden);
1856   }
1857 }
1858 
1859 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
1860   auto CategoriesBegin = Categories.begin();
1861   auto CategoriesEnd = Categories.end();
1862   for (auto &I : GlobalParser->OptionsMap) {
1863     if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1864             CategoriesEnd &&
1865         I.second->Category != &GenericCategory)
1866       I.second->setHiddenFlag(cl::ReallyHidden);
1867   }
1868 }
1869 
1870 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1871                                  const char *Overview) {
1872   llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1873 }
1874