[Orc][Kaleidoscope] Remove fixed sized buffers from string conversion code and
[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
195 } // namespace
196
197 static ManagedStatic<CommandLineParser> GlobalParser;
198
199 void cl::AddLiteralOption(Option &O, const char *Name) {
200   GlobalParser->addLiteralOption(O, Name);
201 }
202
203 extrahelp::extrahelp(const char *Help) : morehelp(Help) {
204   GlobalParser->MoreHelp.push_back(Help);
205 }
206
207 void Option::addArgument() {
208   GlobalParser->addOption(this);
209   FullyInitialized = true;
210 }
211
212 void Option::removeArgument() { GlobalParser->removeOption(this); }
213
214 void Option::setArgStr(const char *S) {
215   if (FullyInitialized)
216     GlobalParser->updateArgStr(this, S);
217   ArgStr = S;
218 }
219
220 // This collects the different option categories that have been registered.
221 typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet;
222 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
223
224 // Initialise the general option category.
225 OptionCategory llvm::cl::GeneralCategory("General options");
226
227 void OptionCategory::registerCategory() {
228   assert(std::count_if(RegisteredOptionCategories->begin(),
229                        RegisteredOptionCategories->end(),
230                        [this](const OptionCategory *Category) {
231                          return getName() == Category->getName();
232                        }) == 0 &&
233          "Duplicate option categories");
234
235   RegisteredOptionCategories->insert(this);
236 }
237
238 //===----------------------------------------------------------------------===//
239 // Basic, shared command line option processing machinery.
240 //
241
242 /// LookupOption - Lookup the option specified by the specified option on the
243 /// command line.  If there is a value specified (after an equal sign) return
244 /// that as well.  This assumes that leading dashes have already been stripped.
245 static Option *LookupOption(StringRef &Arg, StringRef &Value,
246                             const StringMap<Option *> &OptionsMap) {
247   // Reject all dashes.
248   if (Arg.empty())
249     return nullptr;
250
251   size_t EqualPos = Arg.find('=');
252
253   // If we have an equals sign, remember the value.
254   if (EqualPos == StringRef::npos) {
255     // Look up the option.
256     StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
257     return I != OptionsMap.end() ? I->second : nullptr;
258   }
259
260   // If the argument before the = is a valid option name, we match.  If not,
261   // return Arg unmolested.
262   StringMap<Option *>::const_iterator I =
263       OptionsMap.find(Arg.substr(0, EqualPos));
264   if (I == OptionsMap.end())
265     return nullptr;
266
267   Value = Arg.substr(EqualPos + 1);
268   Arg = Arg.substr(0, EqualPos);
269   return I->second;
270 }
271
272 /// LookupNearestOption - Lookup the closest match to the option specified by
273 /// the specified option on the command line.  If there is a value specified
274 /// (after an equal sign) return that as well.  This assumes that leading dashes
275 /// have already been stripped.
276 static Option *LookupNearestOption(StringRef Arg,
277                                    const StringMap<Option *> &OptionsMap,
278                                    std::string &NearestString) {
279   // Reject all dashes.
280   if (Arg.empty())
281     return nullptr;
282
283   // Split on any equal sign.
284   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
285   StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
286   StringRef &RHS = SplitArg.second;
287
288   // Find the closest match.
289   Option *Best = nullptr;
290   unsigned BestDistance = 0;
291   for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
292                                            ie = OptionsMap.end();
293        it != ie; ++it) {
294     Option *O = it->second;
295     SmallVector<const char *, 16> OptionNames;
296     O->getExtraOptionNames(OptionNames);
297     if (O->ArgStr[0])
298       OptionNames.push_back(O->ArgStr);
299
300     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
301     StringRef Flag = PermitValue ? LHS : Arg;
302     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
303       StringRef Name = OptionNames[i];
304       unsigned Distance = StringRef(Name).edit_distance(
305           Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
306       if (!Best || Distance < BestDistance) {
307         Best = O;
308         BestDistance = Distance;
309         if (RHS.empty() || !PermitValue)
310           NearestString = OptionNames[i];
311         else
312           NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
313       }
314     }
315   }
316
317   return Best;
318 }
319
320 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
321 /// that does special handling of cl::CommaSeparated options.
322 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
323                                           StringRef ArgName, StringRef Value,
324                                           bool MultiArg = false) {
325   // Check to see if this option accepts a comma separated list of values.  If
326   // it does, we have to split up the value into multiple values.
327   if (Handler->getMiscFlags() & CommaSeparated) {
328     StringRef Val(Value);
329     StringRef::size_type Pos = Val.find(',');
330
331     while (Pos != StringRef::npos) {
332       // Process the portion before the comma.
333       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
334         return true;
335       // Erase the portion before the comma, AND the comma.
336       Val = Val.substr(Pos + 1);
337       Value.substr(Pos + 1); // Increment the original value pointer as well.
338       // Check for another comma.
339       Pos = Val.find(',');
340     }
341
342     Value = Val;
343   }
344
345   if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
346     return true;
347
348   return false;
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.SaveString(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.SaveString(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.SaveString(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.SaveString(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 &&
700           S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
701 }
702
703 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
704                                TokenizerCallback Tokenizer,
705                                SmallVectorImpl<const char *> &NewArgv,
706                                bool MarkEOLs = false) {
707   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
708       MemoryBuffer::getFile(FName);
709   if (!MemBufOrErr)
710     return false;
711   MemoryBuffer &MemBuf = *MemBufOrErr.get();
712   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
713
714   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
715   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
716   std::string UTF8Buf;
717   if (hasUTF16ByteOrderMark(BufRef)) {
718     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
719       return false;
720     Str = StringRef(UTF8Buf);
721   }
722   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
723   // these bytes before parsing.
724   // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
725   else if (hasUTF8ByteOrderMark(BufRef))
726     Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
727
728   // Tokenize the contents into NewArgv.
729   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
730
731   return true;
732 }
733
734 /// \brief Expand response files on a command line recursively using the given
735 /// StringSaver and tokenization strategy.
736 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
737                              SmallVectorImpl<const char *> &Argv,
738                              bool MarkEOLs) {
739   unsigned RspFiles = 0;
740   bool AllExpanded = true;
741
742   // Don't cache Argv.size() because it can change.
743   for (unsigned I = 0; I != Argv.size();) {
744     const char *Arg = Argv[I];
745     // Check if it is an EOL marker
746     if (Arg == nullptr) {
747       ++I;
748       continue;
749     }
750     if (Arg[0] != '@') {
751       ++I;
752       continue;
753     }
754
755     // If we have too many response files, leave some unexpanded.  This avoids
756     // crashing on self-referential response files.
757     if (RspFiles++ > 20)
758       return false;
759
760     // Replace this response file argument with the tokenization of its
761     // contents.  Nested response files are expanded in subsequent iterations.
762     // FIXME: If a nested response file uses a relative path, is it relative to
763     // the cwd of the process or the response file?
764     SmallVector<const char *, 0> ExpandedArgv;
765     if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
766                             MarkEOLs)) {
767       // We couldn't read this file, so we leave it in the argument stream and
768       // move on.
769       AllExpanded = false;
770       ++I;
771       continue;
772     }
773     Argv.erase(Argv.begin() + I);
774     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
775   }
776   return AllExpanded;
777 }
778
779 namespace {
780 class StrDupSaver : public StringSaver {
781   std::vector<char *> Dups;
782
783 public:
784   ~StrDupSaver() {
785     for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
786          ++I) {
787       char *Dup = *I;
788       free(Dup);
789     }
790   }
791   const char *SaveString(const char *Str) override {
792     char *Dup = strdup(Str);
793     Dups.push_back(Dup);
794     return Dup;
795   }
796 };
797 }
798
799 /// ParseEnvironmentOptions - An alternative entry point to the
800 /// CommandLine library, which allows you to read the program's name
801 /// from the caller (as PROGNAME) and its command-line arguments from
802 /// an environment variable (whose name is given in ENVVAR).
803 ///
804 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
805                                  const char *Overview) {
806   // Check args.
807   assert(progName && "Program name not specified");
808   assert(envVar && "Environment variable name missing");
809
810   // Get the environment variable they want us to parse options out of.
811   const char *envValue = getenv(envVar);
812   if (!envValue)
813     return;
814
815   // Get program's "name", which we wouldn't know without the caller
816   // telling us.
817   SmallVector<const char *, 20> newArgv;
818   StrDupSaver Saver;
819   newArgv.push_back(Saver.SaveString(progName));
820
821   // Parse the value of the environment variable into a "command line"
822   // and hand it off to ParseCommandLineOptions().
823   TokenizeGNUCommandLine(envValue, Saver, newArgv);
824   int newArgc = static_cast<int>(newArgv.size());
825   ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
826 }
827
828 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
829                                  const char *Overview) {
830   GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
831 }
832
833 void CommandLineParser::ParseCommandLineOptions(int argc,
834                                                 const char *const *argv,
835                                                 const char *Overview) {
836   assert(hasOptions() && "No options specified!");
837
838   // Expand response files.
839   SmallVector<const char *, 20> newArgv;
840   for (int i = 0; i != argc; ++i)
841     newArgv.push_back(argv[i]);
842   StrDupSaver Saver;
843   ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
844   argv = &newArgv[0];
845   argc = static_cast<int>(newArgv.size());
846
847   // Copy the program name into ProgName, making sure not to overflow it.
848   ProgramName = sys::path::filename(argv[0]);
849
850   ProgramOverview = Overview;
851   bool ErrorParsing = false;
852
853   // Check out the positional arguments to collect information about them.
854   unsigned NumPositionalRequired = 0;
855
856   // Determine whether or not there are an unlimited number of positionals
857   bool HasUnlimitedPositionals = false;
858
859   if (ConsumeAfterOpt) {
860     assert(PositionalOpts.size() > 0 &&
861            "Cannot specify cl::ConsumeAfter without a positional argument!");
862   }
863   if (!PositionalOpts.empty()) {
864
865     // Calculate how many positional values are _required_.
866     bool UnboundedFound = false;
867     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
868       Option *Opt = PositionalOpts[i];
869       if (RequiresValue(Opt))
870         ++NumPositionalRequired;
871       else if (ConsumeAfterOpt) {
872         // ConsumeAfter cannot be combined with "optional" positional options
873         // unless there is only one positional argument...
874         if (PositionalOpts.size() > 1)
875           ErrorParsing |= Opt->error(
876               "error - this positional option will never be matched, "
877               "because it does not Require a value, and a "
878               "cl::ConsumeAfter option is active!");
879       } else if (UnboundedFound && !Opt->ArgStr[0]) {
880         // This option does not "require" a value...  Make sure this option is
881         // not specified after an option that eats all extra arguments, or this
882         // one will never get any!
883         //
884         ErrorParsing |= Opt->error("error - option can never match, because "
885                                    "another positional argument will match an "
886                                    "unbounded number of values, and this option"
887                                    " does not require a value!");
888         errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
889                << "' is all messed up!\n";
890         errs() << PositionalOpts.size();
891       }
892       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
893     }
894     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
895   }
896
897   // PositionalVals - A vector of "positional" arguments we accumulate into
898   // the process at the end.
899   //
900   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
901
902   // If the program has named positional arguments, and the name has been run
903   // across, keep track of which positional argument was named.  Otherwise put
904   // the positional args into the PositionalVals list...
905   Option *ActivePositionalArg = nullptr;
906
907   // Loop over all of the arguments... processing them.
908   bool DashDashFound = false; // Have we read '--'?
909   for (int i = 1; i < argc; ++i) {
910     Option *Handler = nullptr;
911     Option *NearestHandler = nullptr;
912     std::string NearestHandlerString;
913     StringRef Value;
914     StringRef ArgName = "";
915
916     // Check to see if this is a positional argument.  This argument is
917     // considered to be positional if it doesn't start with '-', if it is "-"
918     // itself, or if we have seen "--" already.
919     //
920     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
921       // Positional argument!
922       if (ActivePositionalArg) {
923         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
924         continue; // We are done!
925       }
926
927       if (!PositionalOpts.empty()) {
928         PositionalVals.push_back(std::make_pair(argv[i], i));
929
930         // All of the positional arguments have been fulfulled, give the rest to
931         // the consume after option... if it's specified...
932         //
933         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
934           for (++i; i < argc; ++i)
935             PositionalVals.push_back(std::make_pair(argv[i], i));
936           break; // Handle outside of the argument processing loop...
937         }
938
939         // Delay processing positional arguments until the end...
940         continue;
941       }
942     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
943                !DashDashFound) {
944       DashDashFound = true; // This is the mythical "--"?
945       continue;             // Don't try to process it as an argument itself.
946     } else if (ActivePositionalArg &&
947                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
948       // If there is a positional argument eating options, check to see if this
949       // option is another positional argument.  If so, treat it as an argument,
950       // otherwise feed it to the eating positional.
951       ArgName = argv[i] + 1;
952       // Eat leading dashes.
953       while (!ArgName.empty() && ArgName[0] == '-')
954         ArgName = ArgName.substr(1);
955
956       Handler = LookupOption(ArgName, Value, OptionsMap);
957       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
958         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
959         continue; // We are done!
960       }
961
962     } else { // We start with a '-', must be an argument.
963       ArgName = argv[i] + 1;
964       // Eat leading dashes.
965       while (!ArgName.empty() && ArgName[0] == '-')
966         ArgName = ArgName.substr(1);
967
968       Handler = LookupOption(ArgName, Value, OptionsMap);
969
970       // Check to see if this "option" is really a prefixed or grouped argument.
971       if (!Handler)
972         Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
973                                                 OptionsMap);
974
975       // Otherwise, look for the closest available option to report to the user
976       // in the upcoming error.
977       if (!Handler && SinkOpts.empty())
978         NearestHandler =
979             LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
980     }
981
982     if (!Handler) {
983       if (SinkOpts.empty()) {
984         errs() << ProgramName << ": Unknown command line argument '" << argv[i]
985                << "'.  Try: '" << argv[0] << " -help'\n";
986
987         if (NearestHandler) {
988           // If we know a near match, report it as well.
989           errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
990                  << "'?\n";
991         }
992
993         ErrorParsing = true;
994       } else {
995         for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
996                                                  E = SinkOpts.end();
997              I != E; ++I)
998           (*I)->addOccurrence(i, "", argv[i]);
999       }
1000       continue;
1001     }
1002
1003     // If this is a named positional argument, just remember that it is the
1004     // active one...
1005     if (Handler->getFormattingFlag() == cl::Positional)
1006       ActivePositionalArg = Handler;
1007     else
1008       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1009   }
1010
1011   // Check and handle positional arguments now...
1012   if (NumPositionalRequired > PositionalVals.size()) {
1013     errs() << ProgramName
1014            << ": Not enough positional command line arguments specified!\n"
1015            << "Must specify at least " << NumPositionalRequired
1016            << " positional arguments: See: " << argv[0] << " -help\n";
1017
1018     ErrorParsing = true;
1019   } else if (!HasUnlimitedPositionals &&
1020              PositionalVals.size() > PositionalOpts.size()) {
1021     errs() << ProgramName << ": Too many positional arguments specified!\n"
1022            << "Can specify at most " << PositionalOpts.size()
1023            << " positional arguments: See: " << argv[0] << " -help\n";
1024     ErrorParsing = true;
1025
1026   } else if (!ConsumeAfterOpt) {
1027     // Positional args have already been handled if ConsumeAfter is specified.
1028     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1029     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1030       if (RequiresValue(PositionalOpts[i])) {
1031         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1032                                 PositionalVals[ValNo].second);
1033         ValNo++;
1034         --NumPositionalRequired; // We fulfilled our duty...
1035       }
1036
1037       // If we _can_ give this option more arguments, do so now, as long as we
1038       // do not give it values that others need.  'Done' controls whether the
1039       // option even _WANTS_ any more.
1040       //
1041       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1042       while (NumVals - ValNo > NumPositionalRequired && !Done) {
1043         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1044         case cl::Optional:
1045           Done = true; // Optional arguments want _at most_ one value
1046         // FALL THROUGH
1047         case cl::ZeroOrMore: // Zero or more will take all they can get...
1048         case cl::OneOrMore:  // One or more will take all they can get...
1049           ProvidePositionalOption(PositionalOpts[i],
1050                                   PositionalVals[ValNo].first,
1051                                   PositionalVals[ValNo].second);
1052           ValNo++;
1053           break;
1054         default:
1055           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1056                            "positional argument processing!");
1057         }
1058       }
1059     }
1060   } else {
1061     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1062     unsigned ValNo = 0;
1063     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1064       if (RequiresValue(PositionalOpts[j])) {
1065         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1066                                                 PositionalVals[ValNo].first,
1067                                                 PositionalVals[ValNo].second);
1068         ValNo++;
1069       }
1070
1071     // Handle the case where there is just one positional option, and it's
1072     // optional.  In this case, we want to give JUST THE FIRST option to the
1073     // positional option and keep the rest for the consume after.  The above
1074     // loop would have assigned no values to positional options in this case.
1075     //
1076     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1077       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1078                                               PositionalVals[ValNo].first,
1079                                               PositionalVals[ValNo].second);
1080       ValNo++;
1081     }
1082
1083     // Handle over all of the rest of the arguments to the
1084     // cl::ConsumeAfter command line option...
1085     for (; ValNo != PositionalVals.size(); ++ValNo)
1086       ErrorParsing |=
1087           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1088                                   PositionalVals[ValNo].second);
1089   }
1090
1091   // Loop over args and make sure all required args are specified!
1092   for (const auto &Opt : OptionsMap) {
1093     switch (Opt.second->getNumOccurrencesFlag()) {
1094     case Required:
1095     case OneOrMore:
1096       if (Opt.second->getNumOccurrences() == 0) {
1097         Opt.second->error("must be specified at least once!");
1098         ErrorParsing = true;
1099       }
1100     // Fall through
1101     default:
1102       break;
1103     }
1104   }
1105
1106   // Now that we know if -debug is specified, we can use it.
1107   // Note that if ReadResponseFiles == true, this must be done before the
1108   // memory allocated for the expanded command line is free()d below.
1109   DEBUG(dbgs() << "Args: ";
1110         for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1111         dbgs() << '\n';);
1112
1113   // Free all of the memory allocated to the map.  Command line options may only
1114   // be processed once!
1115   MoreHelp.clear();
1116
1117   // If we had an error processing our arguments, don't let the program execute
1118   if (ErrorParsing)
1119     exit(1);
1120 }
1121
1122 //===----------------------------------------------------------------------===//
1123 // Option Base class implementation
1124 //
1125
1126 bool Option::error(const Twine &Message, StringRef ArgName) {
1127   if (!ArgName.data())
1128     ArgName = ArgStr;
1129   if (ArgName.empty())
1130     errs() << HelpStr; // Be nice for positional arguments
1131   else
1132     errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1133
1134   errs() << " option: " << Message << "\n";
1135   return true;
1136 }
1137
1138 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1139                            bool MultiArg) {
1140   if (!MultiArg)
1141     NumOccurrences++; // Increment the number of times we have been seen
1142
1143   switch (getNumOccurrencesFlag()) {
1144   case Optional:
1145     if (NumOccurrences > 1)
1146       return error("may only occur zero or one times!", ArgName);
1147     break;
1148   case Required:
1149     if (NumOccurrences > 1)
1150       return error("must occur exactly one time!", ArgName);
1151   // Fall through
1152   case OneOrMore:
1153   case ZeroOrMore:
1154   case ConsumeAfter:
1155     break;
1156   }
1157
1158   return handleOccurrence(pos, ArgName, Value);
1159 }
1160
1161 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1162 // has been specified yet.
1163 //
1164 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1165   if (O.ValueStr[0] == 0)
1166     return DefaultMsg;
1167   return O.ValueStr;
1168 }
1169
1170 //===----------------------------------------------------------------------===//
1171 // cl::alias class implementation
1172 //
1173
1174 // Return the width of the option tag for printing...
1175 size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
1176
1177 static void printHelpStr(StringRef HelpStr, size_t Indent,
1178                          size_t FirstLineIndentedBy) {
1179   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1180   outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1181   while (!Split.second.empty()) {
1182     Split = Split.second.split('\n');
1183     outs().indent(Indent) << Split.first << "\n";
1184   }
1185 }
1186
1187 // Print out the option for the alias.
1188 void alias::printOptionInfo(size_t GlobalWidth) const {
1189   outs() << "  -" << ArgStr;
1190   printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1191 }
1192
1193 //===----------------------------------------------------------------------===//
1194 // Parser Implementation code...
1195 //
1196
1197 // basic_parser implementation
1198 //
1199
1200 // Return the width of the option tag for printing...
1201 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1202   size_t Len = std::strlen(O.ArgStr);
1203   if (const char *ValName = getValueName())
1204     Len += std::strlen(getValueStr(O, ValName)) + 3;
1205
1206   return Len + 6;
1207 }
1208
1209 // printOptionInfo - Print out information about this option.  The
1210 // to-be-maintained width is specified.
1211 //
1212 void basic_parser_impl::printOptionInfo(const Option &O,
1213                                         size_t GlobalWidth) const {
1214   outs() << "  -" << O.ArgStr;
1215
1216   if (const char *ValName = getValueName())
1217     outs() << "=<" << getValueStr(O, ValName) << '>';
1218
1219   printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1220 }
1221
1222 void basic_parser_impl::printOptionName(const Option &O,
1223                                         size_t GlobalWidth) const {
1224   outs() << "  -" << O.ArgStr;
1225   outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1226 }
1227
1228 // parser<bool> implementation
1229 //
1230 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1231                          bool &Value) {
1232   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1233       Arg == "1") {
1234     Value = true;
1235     return false;
1236   }
1237
1238   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1239     Value = false;
1240     return false;
1241   }
1242   return O.error("'" + Arg +
1243                  "' is invalid value for boolean argument! Try 0 or 1");
1244 }
1245
1246 // parser<boolOrDefault> implementation
1247 //
1248 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1249                                   boolOrDefault &Value) {
1250   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1251       Arg == "1") {
1252     Value = BOU_TRUE;
1253     return false;
1254   }
1255   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1256     Value = BOU_FALSE;
1257     return false;
1258   }
1259
1260   return O.error("'" + Arg +
1261                  "' is invalid value for boolean argument! Try 0 or 1");
1262 }
1263
1264 // parser<int> implementation
1265 //
1266 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1267                         int &Value) {
1268   if (Arg.getAsInteger(0, Value))
1269     return O.error("'" + Arg + "' value invalid for integer argument!");
1270   return false;
1271 }
1272
1273 // parser<unsigned> implementation
1274 //
1275 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1276                              unsigned &Value) {
1277
1278   if (Arg.getAsInteger(0, Value))
1279     return O.error("'" + Arg + "' value invalid for uint argument!");
1280   return false;
1281 }
1282
1283 // parser<unsigned long long> implementation
1284 //
1285 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1286                                        StringRef Arg,
1287                                        unsigned long long &Value) {
1288
1289   if (Arg.getAsInteger(0, Value))
1290     return O.error("'" + Arg + "' value invalid for uint argument!");
1291   return false;
1292 }
1293
1294 // parser<double>/parser<float> implementation
1295 //
1296 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1297   SmallString<32> TmpStr(Arg.begin(), Arg.end());
1298   const char *ArgStart = TmpStr.c_str();
1299   char *End;
1300   Value = strtod(ArgStart, &End);
1301   if (*End != 0)
1302     return O.error("'" + Arg + "' value invalid for floating point argument!");
1303   return false;
1304 }
1305
1306 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1307                            double &Val) {
1308   return parseDouble(O, Arg, Val);
1309 }
1310
1311 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1312                           float &Val) {
1313   double dVal;
1314   if (parseDouble(O, Arg, dVal))
1315     return true;
1316   Val = (float)dVal;
1317   return false;
1318 }
1319
1320 // generic_parser_base implementation
1321 //
1322
1323 // findOption - Return the option number corresponding to the specified
1324 // argument string.  If the option is not found, getNumOptions() is returned.
1325 //
1326 unsigned generic_parser_base::findOption(const char *Name) {
1327   unsigned e = getNumOptions();
1328
1329   for (unsigned i = 0; i != e; ++i) {
1330     if (strcmp(getOption(i), Name) == 0)
1331       return i;
1332   }
1333   return e;
1334 }
1335
1336 // Return the width of the option tag for printing...
1337 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1338   if (O.hasArgStr()) {
1339     size_t Size = std::strlen(O.ArgStr) + 6;
1340     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1341       Size = std::max(Size, std::strlen(getOption(i)) + 8);
1342     return Size;
1343   } else {
1344     size_t BaseSize = 0;
1345     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1346       BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1347     return BaseSize;
1348   }
1349 }
1350
1351 // printOptionInfo - Print out information about this option.  The
1352 // to-be-maintained width is specified.
1353 //
1354 void generic_parser_base::printOptionInfo(const Option &O,
1355                                           size_t GlobalWidth) const {
1356   if (O.hasArgStr()) {
1357     outs() << "  -" << O.ArgStr;
1358     printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1359
1360     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1361       size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1362       outs() << "    =" << getOption(i);
1363       outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
1364     }
1365   } else {
1366     if (O.HelpStr[0])
1367       outs() << "  " << O.HelpStr << '\n';
1368     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1369       const char *Option = getOption(i);
1370       outs() << "    -" << Option;
1371       printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1372     }
1373   }
1374 }
1375
1376 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1377
1378 // printGenericOptionDiff - Print the value of this option and it's default.
1379 //
1380 // "Generic" options have each value mapped to a name.
1381 void generic_parser_base::printGenericOptionDiff(
1382     const Option &O, const GenericOptionValue &Value,
1383     const GenericOptionValue &Default, size_t GlobalWidth) const {
1384   outs() << "  -" << O.ArgStr;
1385   outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1386
1387   unsigned NumOpts = getNumOptions();
1388   for (unsigned i = 0; i != NumOpts; ++i) {
1389     if (Value.compare(getOptionValue(i)))
1390       continue;
1391
1392     outs() << "= " << getOption(i);
1393     size_t L = std::strlen(getOption(i));
1394     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1395     outs().indent(NumSpaces) << " (default: ";
1396     for (unsigned j = 0; j != NumOpts; ++j) {
1397       if (Default.compare(getOptionValue(j)))
1398         continue;
1399       outs() << getOption(j);
1400       break;
1401     }
1402     outs() << ")\n";
1403     return;
1404   }
1405   outs() << "= *unknown option value*\n";
1406 }
1407
1408 // printOptionDiff - Specializations for printing basic value types.
1409 //
1410 #define PRINT_OPT_DIFF(T)                                                      \
1411   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
1412                                   size_t GlobalWidth) const {                  \
1413     printOptionName(O, GlobalWidth);                                           \
1414     std::string Str;                                                           \
1415     {                                                                          \
1416       raw_string_ostream SS(Str);                                              \
1417       SS << V;                                                                 \
1418     }                                                                          \
1419     outs() << "= " << Str;                                                     \
1420     size_t NumSpaces =                                                         \
1421         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
1422     outs().indent(NumSpaces) << " (default: ";                                 \
1423     if (D.hasValue())                                                          \
1424       outs() << D.getValue();                                                  \
1425     else                                                                       \
1426       outs() << "*no default*";                                                \
1427     outs() << ")\n";                                                           \
1428   }
1429
1430 PRINT_OPT_DIFF(bool)
1431 PRINT_OPT_DIFF(boolOrDefault)
1432 PRINT_OPT_DIFF(int)
1433 PRINT_OPT_DIFF(unsigned)
1434 PRINT_OPT_DIFF(unsigned long long)
1435 PRINT_OPT_DIFF(double)
1436 PRINT_OPT_DIFF(float)
1437 PRINT_OPT_DIFF(char)
1438
1439 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1440                                           OptionValue<std::string> D,
1441                                           size_t GlobalWidth) const {
1442   printOptionName(O, GlobalWidth);
1443   outs() << "= " << V;
1444   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1445   outs().indent(NumSpaces) << " (default: ";
1446   if (D.hasValue())
1447     outs() << D.getValue();
1448   else
1449     outs() << "*no default*";
1450   outs() << ")\n";
1451 }
1452
1453 // Print a placeholder for options that don't yet support printOptionDiff().
1454 void basic_parser_impl::printOptionNoValue(const Option &O,
1455                                            size_t GlobalWidth) const {
1456   printOptionName(O, GlobalWidth);
1457   outs() << "= *cannot print option value*\n";
1458 }
1459
1460 //===----------------------------------------------------------------------===//
1461 // -help and -help-hidden option implementation
1462 //
1463
1464 static int OptNameCompare(const void *LHS, const void *RHS) {
1465   typedef std::pair<const char *, Option *> pair_ty;
1466
1467   return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
1468 }
1469
1470 // Copy Options into a vector so we can sort them as we like.
1471 static void sortOpts(StringMap<Option *> &OptMap,
1472                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1473                      bool ShowHidden) {
1474   SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
1475
1476   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1477        I != E; ++I) {
1478     // Ignore really-hidden options.
1479     if (I->second->getOptionHiddenFlag() == ReallyHidden)
1480       continue;
1481
1482     // Unless showhidden is set, ignore hidden flags.
1483     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1484       continue;
1485
1486     // If we've already seen this option, don't add it to the list again.
1487     if (!OptionSet.insert(I->second).second)
1488       continue;
1489
1490     Opts.push_back(
1491         std::pair<const char *, Option *>(I->getKey().data(), I->second));
1492   }
1493
1494   // Sort the options list alphabetically.
1495   qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1496 }
1497
1498 namespace {
1499
1500 class HelpPrinter {
1501 protected:
1502   const bool ShowHidden;
1503   typedef SmallVector<std::pair<const char *, Option *>, 128>
1504       StrOptionPairVector;
1505   // Print the options. Opts is assumed to be alphabetically sorted.
1506   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1507     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1508       Opts[i].second->printOptionInfo(MaxArgLen);
1509   }
1510
1511 public:
1512   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1513   virtual ~HelpPrinter() {}
1514
1515   // Invoke the printer.
1516   void operator=(bool Value) {
1517     if (Value == false)
1518       return;
1519
1520     StrOptionPairVector Opts;
1521     sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
1522
1523     if (GlobalParser->ProgramOverview)
1524       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1525
1526     outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
1527
1528     for (auto Opt : GlobalParser->PositionalOpts) {
1529       if (Opt->ArgStr[0])
1530         outs() << " --" << Opt->ArgStr;
1531       outs() << " " << Opt->HelpStr;
1532     }
1533
1534     // Print the consume after option info if it exists...
1535     if (GlobalParser->ConsumeAfterOpt)
1536       outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
1537
1538     outs() << "\n\n";
1539
1540     // Compute the maximum argument length...
1541     size_t MaxArgLen = 0;
1542     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1543       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1544
1545     outs() << "OPTIONS:\n";
1546     printOptions(Opts, MaxArgLen);
1547
1548     // Print any extra help the user has declared.
1549     for (auto I : GlobalParser->MoreHelp)
1550       outs() << I;
1551     GlobalParser->MoreHelp.clear();
1552
1553     // Halt the program since help information was printed
1554     exit(0);
1555   }
1556 };
1557
1558 class CategorizedHelpPrinter : public HelpPrinter {
1559 public:
1560   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1561
1562   // Helper function for printOptions().
1563   // It shall return true if A's name should be lexographically
1564   // ordered before B's name. It returns false otherwise.
1565   static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1566     return strcmp(A->getName(), B->getName()) < 0;
1567   }
1568
1569   // Make sure we inherit our base class's operator=()
1570   using HelpPrinter::operator=;
1571
1572 protected:
1573   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1574     std::vector<OptionCategory *> SortedCategories;
1575     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1576
1577     // Collect registered option categories into vector in preparation for
1578     // sorting.
1579     for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1580                                       E = RegisteredOptionCategories->end();
1581          I != E; ++I) {
1582       SortedCategories.push_back(*I);
1583     }
1584
1585     // Sort the different option categories alphabetically.
1586     assert(SortedCategories.size() > 0 && "No option categories registered!");
1587     std::sort(SortedCategories.begin(), SortedCategories.end(),
1588               OptionCategoryCompare);
1589
1590     // Create map to empty vectors.
1591     for (std::vector<OptionCategory *>::const_iterator
1592              I = SortedCategories.begin(),
1593              E = SortedCategories.end();
1594          I != E; ++I)
1595       CategorizedOptions[*I] = std::vector<Option *>();
1596
1597     // Walk through pre-sorted options and assign into categories.
1598     // Because the options are already alphabetically sorted the
1599     // options within categories will also be alphabetically sorted.
1600     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1601       Option *Opt = Opts[I].second;
1602       assert(CategorizedOptions.count(Opt->Category) > 0 &&
1603              "Option has an unregistered category");
1604       CategorizedOptions[Opt->Category].push_back(Opt);
1605     }
1606
1607     // Now do printing.
1608     for (std::vector<OptionCategory *>::const_iterator
1609              Category = SortedCategories.begin(),
1610              E = SortedCategories.end();
1611          Category != E; ++Category) {
1612       // Hide empty categories for -help, but show for -help-hidden.
1613       bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1614       if (!ShowHidden && IsEmptyCategory)
1615         continue;
1616
1617       // Print category information.
1618       outs() << "\n";
1619       outs() << (*Category)->getName() << ":\n";
1620
1621       // Check if description is set.
1622       if ((*Category)->getDescription() != nullptr)
1623         outs() << (*Category)->getDescription() << "\n\n";
1624       else
1625         outs() << "\n";
1626
1627       // When using -help-hidden explicitly state if the category has no
1628       // options associated with it.
1629       if (IsEmptyCategory) {
1630         outs() << "  This option category has no options.\n";
1631         continue;
1632       }
1633       // Loop over the options in the category and print.
1634       for (std::vector<Option *>::const_iterator
1635                Opt = CategorizedOptions[*Category].begin(),
1636                E = CategorizedOptions[*Category].end();
1637            Opt != E; ++Opt)
1638         (*Opt)->printOptionInfo(MaxArgLen);
1639     }
1640   }
1641 };
1642
1643 // This wraps the Uncategorizing and Categorizing printers and decides
1644 // at run time which should be invoked.
1645 class HelpPrinterWrapper {
1646 private:
1647   HelpPrinter &UncategorizedPrinter;
1648   CategorizedHelpPrinter &CategorizedPrinter;
1649
1650 public:
1651   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1652                               CategorizedHelpPrinter &CategorizedPrinter)
1653       : UncategorizedPrinter(UncategorizedPrinter),
1654         CategorizedPrinter(CategorizedPrinter) {}
1655
1656   // Invoke the printer.
1657   void operator=(bool Value);
1658 };
1659
1660 } // End anonymous namespace
1661
1662 // Declare the four HelpPrinter instances that are used to print out help, or
1663 // help-hidden as an uncategorized list or in categories.
1664 static HelpPrinter UncategorizedNormalPrinter(false);
1665 static HelpPrinter UncategorizedHiddenPrinter(true);
1666 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1667 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1668
1669 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1670 // a categorizing help printer
1671 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1672                                                CategorizedNormalPrinter);
1673 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1674                                                CategorizedHiddenPrinter);
1675
1676 // Define a category for generic options that all tools should have.
1677 static cl::OptionCategory GenericCategory("Generic Options");
1678
1679 // Define uncategorized help printers.
1680 // -help-list is hidden by default because if Option categories are being used
1681 // then -help behaves the same as -help-list.
1682 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1683     "help-list",
1684     cl::desc("Display list of available options (-help-list-hidden for more)"),
1685     cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1686     cl::cat(GenericCategory));
1687
1688 static cl::opt<HelpPrinter, true, parser<bool>>
1689     HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1690           cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1691           cl::ValueDisallowed, cl::cat(GenericCategory));
1692
1693 // Define uncategorized/categorized help printers. These printers change their
1694 // behaviour at runtime depending on whether one or more Option categories have
1695 // been declared.
1696 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1697     HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1698         cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1699         cl::cat(GenericCategory));
1700
1701 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1702     HHOp("help-hidden", cl::desc("Display all available options"),
1703          cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1704          cl::cat(GenericCategory));
1705
1706 static cl::opt<bool> PrintOptions(
1707     "print-options",
1708     cl::desc("Print non-default options after command line parsing"),
1709     cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1710
1711 static cl::opt<bool> PrintAllOptions(
1712     "print-all-options",
1713     cl::desc("Print all option values after command line parsing"), cl::Hidden,
1714     cl::init(false), cl::cat(GenericCategory));
1715
1716 void HelpPrinterWrapper::operator=(bool Value) {
1717   if (Value == false)
1718     return;
1719
1720   // Decide which printer to invoke. If more than one option category is
1721   // registered then it is useful to show the categorized help instead of
1722   // uncategorized help.
1723   if (RegisteredOptionCategories->size() > 1) {
1724     // unhide -help-list option so user can have uncategorized output if they
1725     // want it.
1726     HLOp.setHiddenFlag(NotHidden);
1727
1728     CategorizedPrinter = true; // Invoke categorized printer
1729   } else
1730     UncategorizedPrinter = true; // Invoke uncategorized printer
1731 }
1732
1733 // Print the value of each option.
1734 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1735
1736 void CommandLineParser::printOptionValues() {
1737   if (!PrintOptions && !PrintAllOptions)
1738     return;
1739
1740   SmallVector<std::pair<const char *, Option *>, 128> Opts;
1741   sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
1742
1743   // Compute the maximum argument length...
1744   size_t MaxArgLen = 0;
1745   for (size_t i = 0, e = Opts.size(); i != e; ++i)
1746     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1747
1748   for (size_t i = 0, e = Opts.size(); i != e; ++i)
1749     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1750 }
1751
1752 static void (*OverrideVersionPrinter)() = nullptr;
1753
1754 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1755
1756 namespace {
1757 class VersionPrinter {
1758 public:
1759   void print() {
1760     raw_ostream &OS = outs();
1761     OS << "LLVM (http://llvm.org/):\n"
1762        << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1763 #ifdef LLVM_VERSION_INFO
1764     OS << " " << LLVM_VERSION_INFO;
1765 #endif
1766     OS << "\n  ";
1767 #ifndef __OPTIMIZE__
1768     OS << "DEBUG build";
1769 #else
1770     OS << "Optimized build";
1771 #endif
1772 #ifndef NDEBUG
1773     OS << " with assertions";
1774 #endif
1775     std::string CPU = sys::getHostCPUName();
1776     if (CPU == "generic")
1777       CPU = "(unknown)";
1778     OS << ".\n"
1779 #if (ENABLE_TIMESTAMPS == 1)
1780        << "  Built " << __DATE__ << " (" << __TIME__ << ").\n"
1781 #endif
1782        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
1783        << "  Host CPU: " << CPU << '\n';
1784   }
1785   void operator=(bool OptionWasSpecified) {
1786     if (!OptionWasSpecified)
1787       return;
1788
1789     if (OverrideVersionPrinter != nullptr) {
1790       (*OverrideVersionPrinter)();
1791       exit(0);
1792     }
1793     print();
1794
1795     // Iterate over any registered extra printers and call them to add further
1796     // information.
1797     if (ExtraVersionPrinters != nullptr) {
1798       outs() << '\n';
1799       for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1800                                              E = ExtraVersionPrinters->end();
1801            I != E; ++I)
1802         (*I)();
1803     }
1804
1805     exit(0);
1806   }
1807 };
1808 } // End anonymous namespace
1809
1810 // Define the --version option that prints out the LLVM version for the tool
1811 static VersionPrinter VersionPrinterInstance;
1812
1813 static cl::opt<VersionPrinter, true, parser<bool>>
1814     VersOp("version", cl::desc("Display the version of this program"),
1815            cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1816            cl::cat(GenericCategory));
1817
1818 // Utility function for printing the help message.
1819 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1820   // This looks weird, but it actually prints the help message. The Printers are
1821   // types of HelpPrinter and the help gets printed when its operator= is
1822   // invoked. That's because the "normal" usages of the help printer is to be
1823   // assigned true/false depending on whether -help or -help-hidden was given or
1824   // not.  Since we're circumventing that we have to make it look like -help or
1825   // -help-hidden were given, so we assign true.
1826
1827   if (!Hidden && !Categorized)
1828     UncategorizedNormalPrinter = true;
1829   else if (!Hidden && Categorized)
1830     CategorizedNormalPrinter = true;
1831   else if (Hidden && !Categorized)
1832     UncategorizedHiddenPrinter = true;
1833   else
1834     CategorizedHiddenPrinter = true;
1835 }
1836
1837 /// Utility function for printing version number.
1838 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1839
1840 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1841
1842 void cl::AddExtraVersionPrinter(void (*func)()) {
1843   if (!ExtraVersionPrinters)
1844     ExtraVersionPrinters = new std::vector<void (*)()>;
1845
1846   ExtraVersionPrinters->push_back(func);
1847 }
1848
1849 StringMap<Option *> &cl::getRegisteredOptions() {
1850   return GlobalParser->OptionsMap;
1851 }
1852
1853 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1854   for (auto &I : GlobalParser->OptionsMap) {
1855     if (I.second->Category != &Category &&
1856         I.second->Category != &GenericCategory)
1857       I.second->setHiddenFlag(cl::ReallyHidden);
1858   }
1859 }
1860
1861 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
1862   auto CategoriesBegin = Categories.begin();
1863   auto CategoriesEnd = Categories.end();
1864   for (auto &I : GlobalParser->OptionsMap) {
1865     if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1866             CategoriesEnd &&
1867         I.second->Category != &GenericCategory)
1868       I.second->setHiddenFlag(cl::ReallyHidden);
1869   }
1870 }
1871
1872 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1873                                  const char *Overview) {
1874   llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1875 }