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