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