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