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