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