CommandLine.cpp revision 208599
1193323Sed//===-- CommandLine.cpp - Command line parser implementation --------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This class implements a command line argument processor that is useful when
11193323Sed// creating a tool.  It provides a simple, minimalistic interface that is easily
12193323Sed// extensible and supports nonlocal (library) command line options.
13193323Sed//
14193323Sed// Note that rather than trying to figure out what this code does, you could try
15193323Sed// reading the library documentation located in docs/CommandLine.html
16193323Sed//
17193323Sed//===----------------------------------------------------------------------===//
18193323Sed
19193323Sed#include "llvm/Support/CommandLine.h"
20199481Srdivacky#include "llvm/Support/Debug.h"
21198090Srdivacky#include "llvm/Support/ErrorHandling.h"
22193323Sed#include "llvm/Support/MemoryBuffer.h"
23193323Sed#include "llvm/Support/ManagedStatic.h"
24198090Srdivacky#include "llvm/Support/raw_ostream.h"
25198090Srdivacky#include "llvm/Target/TargetRegistry.h"
26198090Srdivacky#include "llvm/System/Host.h"
27193323Sed#include "llvm/System/Path.h"
28198090Srdivacky#include "llvm/ADT/OwningPtr.h"
29198090Srdivacky#include "llvm/ADT/SmallPtrSet.h"
30198090Srdivacky#include "llvm/ADT/SmallString.h"
31198090Srdivacky#include "llvm/ADT/StringMap.h"
32198090Srdivacky#include "llvm/ADT/Twine.h"
33198090Srdivacky#include "llvm/Config/config.h"
34198090Srdivacky#include <cerrno>
35193323Sed#include <cstdlib>
36193323Sedusing namespace llvm;
37193323Sedusing namespace cl;
38193323Sed
39193323Sed//===----------------------------------------------------------------------===//
40193323Sed// Template instantiations and anchors.
41193323Sed//
42199989Srdivackynamespace llvm { namespace cl {
43193323SedTEMPLATE_INSTANTIATION(class basic_parser<bool>);
44193323SedTEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
45193323SedTEMPLATE_INSTANTIATION(class basic_parser<int>);
46193323SedTEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
47193323SedTEMPLATE_INSTANTIATION(class basic_parser<double>);
48193323SedTEMPLATE_INSTANTIATION(class basic_parser<float>);
49193323SedTEMPLATE_INSTANTIATION(class basic_parser<std::string>);
50193323SedTEMPLATE_INSTANTIATION(class basic_parser<char>);
51193323Sed
52193323SedTEMPLATE_INSTANTIATION(class opt<unsigned>);
53193323SedTEMPLATE_INSTANTIATION(class opt<int>);
54193323SedTEMPLATE_INSTANTIATION(class opt<std::string>);
55193323SedTEMPLATE_INSTANTIATION(class opt<char>);
56193323SedTEMPLATE_INSTANTIATION(class opt<bool>);
57199989Srdivacky} } // end namespace llvm::cl
58193323Sed
59193323Sedvoid Option::anchor() {}
60193323Sedvoid basic_parser_impl::anchor() {}
61193323Sedvoid parser<bool>::anchor() {}
62193323Sedvoid parser<boolOrDefault>::anchor() {}
63193323Sedvoid parser<int>::anchor() {}
64193323Sedvoid parser<unsigned>::anchor() {}
65193323Sedvoid parser<double>::anchor() {}
66193323Sedvoid parser<float>::anchor() {}
67193323Sedvoid parser<std::string>::anchor() {}
68193323Sedvoid parser<char>::anchor() {}
69193323Sed
70193323Sed//===----------------------------------------------------------------------===//
71193323Sed
72193323Sed// Globals for name and overview of program.  Program name is not a string to
73193323Sed// avoid static ctor/dtor issues.
74193323Sedstatic char ProgramName[80] = "<premain>";
75193323Sedstatic const char *ProgramOverview = 0;
76193323Sed
77193323Sed// This collects additional help to be printed.
78193323Sedstatic ManagedStatic<std::vector<const char*> > MoreHelp;
79193323Sed
80193323Sedextrahelp::extrahelp(const char *Help)
81193323Sed  : morehelp(Help) {
82193323Sed  MoreHelp->push_back(Help);
83193323Sed}
84193323Sed
85193323Sedstatic bool OptionListChanged = false;
86193323Sed
87193323Sed// MarkOptionsChanged - Internal helper function.
88193323Sedvoid cl::MarkOptionsChanged() {
89193323Sed  OptionListChanged = true;
90193323Sed}
91193323Sed
92193323Sed/// RegisteredOptionList - This is the list of the command line options that
93193323Sed/// have statically constructed themselves.
94193323Sedstatic Option *RegisteredOptionList = 0;
95193323Sed
96193323Sedvoid Option::addArgument() {
97193323Sed  assert(NextRegistered == 0 && "argument multiply registered!");
98193323Sed
99193323Sed  NextRegistered = RegisteredOptionList;
100193323Sed  RegisteredOptionList = this;
101193323Sed  MarkOptionsChanged();
102193323Sed}
103193323Sed
104193323Sed
105193323Sed//===----------------------------------------------------------------------===//
106193323Sed// Basic, shared command line option processing machinery.
107193323Sed//
108193323Sed
109193323Sed/// GetOptionInfo - Scan the list of registered options, turning them into data
110193323Sed/// structures that are easier to handle.
111198090Srdivackystatic void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
112198090Srdivacky                          SmallVectorImpl<Option*> &SinkOpts,
113198090Srdivacky                          StringMap<Option*> &OptionsMap) {
114198090Srdivacky  SmallVector<const char*, 16> OptionNames;
115193323Sed  Option *CAOpt = 0;  // The ConsumeAfter option if it exists.
116193323Sed  for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
117193323Sed    // If this option wants to handle multiple option names, get the full set.
118193323Sed    // This handles enum options like "-O1 -O2" etc.
119193323Sed    O->getExtraOptionNames(OptionNames);
120193323Sed    if (O->ArgStr[0])
121193323Sed      OptionNames.push_back(O->ArgStr);
122193323Sed
123193323Sed    // Handle named options.
124193323Sed    for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
125193323Sed      // Add argument to the argument map!
126198090Srdivacky      if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
127198090Srdivacky        errs() << ProgramName << ": CommandLine Error: Argument '"
128193323Sed             << OptionNames[i] << "' defined more than once!\n";
129193323Sed      }
130193323Sed    }
131193323Sed
132193323Sed    OptionNames.clear();
133193323Sed
134193323Sed    // Remember information about positional options.
135193323Sed    if (O->getFormattingFlag() == cl::Positional)
136193323Sed      PositionalOpts.push_back(O);
137193323Sed    else if (O->getMiscFlags() & cl::Sink) // Remember sink options
138193323Sed      SinkOpts.push_back(O);
139193323Sed    else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
140193323Sed      if (CAOpt)
141193323Sed        O->error("Cannot specify more than one option with cl::ConsumeAfter!");
142193323Sed      CAOpt = O;
143193323Sed    }
144193323Sed  }
145193323Sed
146193323Sed  if (CAOpt)
147193323Sed    PositionalOpts.push_back(CAOpt);
148193323Sed
149193323Sed  // Make sure that they are in order of registration not backwards.
150193323Sed  std::reverse(PositionalOpts.begin(), PositionalOpts.end());
151193323Sed}
152193323Sed
153193323Sed
154193323Sed/// LookupOption - Lookup the option specified by the specified option on the
155193323Sed/// command line.  If there is a value specified (after an equal sign) return
156198090Srdivacky/// that as well.  This assumes that leading dashes have already been stripped.
157198090Srdivackystatic Option *LookupOption(StringRef &Arg, StringRef &Value,
158198090Srdivacky                            const StringMap<Option*> &OptionsMap) {
159198090Srdivacky  // Reject all dashes.
160198090Srdivacky  if (Arg.empty()) return 0;
161199989Srdivacky
162198090Srdivacky  size_t EqualPos = Arg.find('=');
163199989Srdivacky
164198090Srdivacky  // If we have an equals sign, remember the value.
165198090Srdivacky  if (EqualPos == StringRef::npos) {
166198090Srdivacky    // Look up the option.
167198090Srdivacky    StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
168198090Srdivacky    return I != OptionsMap.end() ? I->second : 0;
169198090Srdivacky  }
170193323Sed
171198090Srdivacky  // If the argument before the = is a valid option name, we match.  If not,
172198090Srdivacky  // return Arg unmolested.
173198090Srdivacky  StringMap<Option*>::const_iterator I =
174198090Srdivacky    OptionsMap.find(Arg.substr(0, EqualPos));
175198090Srdivacky  if (I == OptionsMap.end()) return 0;
176199989Srdivacky
177198090Srdivacky  Value = Arg.substr(EqualPos+1);
178198090Srdivacky  Arg = Arg.substr(0, EqualPos);
179198090Srdivacky  return I->second;
180198090Srdivacky}
181193323Sed
182199989Srdivacky/// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
183199989Srdivacky/// does special handling of cl::CommaSeparated options.
184199989Srdivackystatic bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
185199989Srdivacky                                         StringRef ArgName,
186199989Srdivacky                                         StringRef Value, bool MultiArg = false)
187199989Srdivacky{
188199989Srdivacky  // Check to see if this option accepts a comma separated list of values.  If
189199989Srdivacky  // it does, we have to split up the value into multiple values.
190199989Srdivacky  if (Handler->getMiscFlags() & CommaSeparated) {
191199989Srdivacky    StringRef Val(Value);
192199989Srdivacky    StringRef::size_type Pos = Val.find(',');
193193323Sed
194199989Srdivacky    while (Pos != StringRef::npos) {
195199989Srdivacky      // Process the portion before the comma.
196199989Srdivacky      if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
197199989Srdivacky        return true;
198199989Srdivacky      // Erase the portion before the comma, AND the comma.
199199989Srdivacky      Val = Val.substr(Pos+1);
200199989Srdivacky      Value.substr(Pos+1);  // Increment the original value pointer as well.
201199989Srdivacky      // Check for another comma.
202199989Srdivacky      Pos = Val.find(',');
203199989Srdivacky    }
204193323Sed
205199989Srdivacky    Value = Val;
206199989Srdivacky  }
207199989Srdivacky
208199989Srdivacky  if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
209199989Srdivacky    return true;
210199989Srdivacky
211199989Srdivacky  return false;
212199989Srdivacky}
213199989Srdivacky
214198090Srdivacky/// ProvideOption - For Value, this differentiates between an empty value ("")
215198090Srdivacky/// and a null value (StringRef()).  The later is accepted for arguments that
216198090Srdivacky/// don't allow a value (-foo) the former is rejected (-foo=).
217198090Srdivackystatic inline bool ProvideOption(Option *Handler, StringRef ArgName,
218198090Srdivacky                                 StringRef Value, int argc, char **argv,
219193323Sed                                 int &i) {
220193323Sed  // Is this a multi-argument option?
221193323Sed  unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
222193323Sed
223193323Sed  // Enforce value requirements
224193323Sed  switch (Handler->getValueExpectedFlag()) {
225193323Sed  case ValueRequired:
226198090Srdivacky    if (Value.data() == 0) {       // No value specified?
227198090Srdivacky      if (i+1 >= argc)
228198090Srdivacky        return Handler->error("requires a value!");
229198090Srdivacky      // Steal the next argument, like for '-o filename'
230198090Srdivacky      Value = argv[++i];
231193323Sed    }
232193323Sed    break;
233193323Sed  case ValueDisallowed:
234193323Sed    if (NumAdditionalVals > 0)
235198090Srdivacky      return Handler->error("multi-valued option specified"
236198090Srdivacky                            " with ValueDisallowed modifier!");
237193323Sed
238198090Srdivacky    if (Value.data())
239198090Srdivacky      return Handler->error("does not allow a value! '" +
240198090Srdivacky                            Twine(Value) + "' specified.");
241193323Sed    break;
242193323Sed  case ValueOptional:
243193323Sed    break;
244199989Srdivacky
245193323Sed  default:
246198090Srdivacky    errs() << ProgramName
247193323Sed         << ": Bad ValueMask flag! CommandLine usage error:"
248193323Sed         << Handler->getValueExpectedFlag() << "\n";
249198090Srdivacky    llvm_unreachable(0);
250193323Sed  }
251193323Sed
252193323Sed  // If this isn't a multi-arg option, just run the handler.
253198090Srdivacky  if (NumAdditionalVals == 0)
254199989Srdivacky    return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
255198090Srdivacky
256193323Sed  // If it is, run the handle several times.
257198090Srdivacky  bool MultiArg = false;
258193323Sed
259198090Srdivacky  if (Value.data()) {
260199989Srdivacky    if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
261198090Srdivacky      return true;
262198090Srdivacky    --NumAdditionalVals;
263198090Srdivacky    MultiArg = true;
264198090Srdivacky  }
265193323Sed
266198090Srdivacky  while (NumAdditionalVals > 0) {
267198090Srdivacky    if (i+1 >= argc)
268198090Srdivacky      return Handler->error("not enough values!");
269198090Srdivacky    Value = argv[++i];
270199989Srdivacky
271199989Srdivacky    if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
272198090Srdivacky      return true;
273198090Srdivacky    MultiArg = true;
274198090Srdivacky    --NumAdditionalVals;
275193323Sed  }
276198090Srdivacky  return false;
277193323Sed}
278193323Sed
279198090Srdivackystatic bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
280193323Sed  int Dummy = i;
281198090Srdivacky  return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
282193323Sed}
283193323Sed
284193323Sed
285193323Sed// Option predicates...
286193323Sedstatic inline bool isGrouping(const Option *O) {
287193323Sed  return O->getFormattingFlag() == cl::Grouping;
288193323Sed}
289193323Sedstatic inline bool isPrefixedOrGrouping(const Option *O) {
290193323Sed  return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
291193323Sed}
292193323Sed
293193323Sed// getOptionPred - Check to see if there are any options that satisfy the
294193323Sed// specified predicate with names that are the prefixes in Name.  This is
295193323Sed// checked by progressively stripping characters off of the name, checking to
296193323Sed// see if there options that satisfy the predicate.  If we find one, return it,
297193323Sed// otherwise return null.
298193323Sed//
299198090Srdivackystatic Option *getOptionPred(StringRef Name, size_t &Length,
300193323Sed                             bool (*Pred)(const Option*),
301198090Srdivacky                             const StringMap<Option*> &OptionsMap) {
302193323Sed
303198090Srdivacky  StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
304193323Sed
305198090Srdivacky  // Loop while we haven't found an option and Name still has at least two
306198090Srdivacky  // characters in it (so that the next iteration will not be the empty
307198090Srdivacky  // string.
308198090Srdivacky  while (OMI == OptionsMap.end() && Name.size() > 1) {
309198090Srdivacky    Name = Name.substr(0, Name.size()-1);   // Chop off the last character.
310193323Sed    OMI = OptionsMap.find(Name);
311198090Srdivacky  }
312193323Sed
313193323Sed  if (OMI != OptionsMap.end() && Pred(OMI->second)) {
314198090Srdivacky    Length = Name.size();
315193323Sed    return OMI->second;    // Found one!
316193323Sed  }
317193323Sed  return 0;                // No option found!
318193323Sed}
319193323Sed
320198090Srdivacky/// HandlePrefixedOrGroupedOption - The specified argument string (which started
321198090Srdivacky/// with at least one '-') does not fully match an available option.  Check to
322198090Srdivacky/// see if this is a prefix or grouped option.  If so, split arg into output an
323198090Srdivacky/// Arg/Value pair and return the Option to parse it with.
324198090Srdivackystatic Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
325198090Srdivacky                                             bool &ErrorParsing,
326198090Srdivacky                                         const StringMap<Option*> &OptionsMap) {
327198090Srdivacky  if (Arg.size() == 1) return 0;
328198090Srdivacky
329198090Srdivacky  // Do the lookup!
330198090Srdivacky  size_t Length = 0;
331198090Srdivacky  Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
332198090Srdivacky  if (PGOpt == 0) return 0;
333199989Srdivacky
334198090Srdivacky  // If the option is a prefixed option, then the value is simply the
335198090Srdivacky  // rest of the name...  so fall through to later processing, by
336198090Srdivacky  // setting up the argument name flags and value fields.
337198090Srdivacky  if (PGOpt->getFormattingFlag() == cl::Prefix) {
338198090Srdivacky    Value = Arg.substr(Length);
339198090Srdivacky    Arg = Arg.substr(0, Length);
340198090Srdivacky    assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
341198090Srdivacky    return PGOpt;
342198090Srdivacky  }
343199989Srdivacky
344198090Srdivacky  // This must be a grouped option... handle them now.  Grouping options can't
345198090Srdivacky  // have values.
346198090Srdivacky  assert(isGrouping(PGOpt) && "Broken getOptionPred!");
347199989Srdivacky
348198090Srdivacky  do {
349198090Srdivacky    // Move current arg name out of Arg into OneArgName.
350198090Srdivacky    StringRef OneArgName = Arg.substr(0, Length);
351198090Srdivacky    Arg = Arg.substr(Length);
352199989Srdivacky
353198090Srdivacky    // Because ValueRequired is an invalid flag for grouped arguments,
354198090Srdivacky    // we don't need to pass argc/argv in.
355198090Srdivacky    assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
356198090Srdivacky           "Option can not be cl::Grouping AND cl::ValueRequired!");
357202375Srdivacky    int Dummy = 0;
358198090Srdivacky    ErrorParsing |= ProvideOption(PGOpt, OneArgName,
359198090Srdivacky                                  StringRef(), 0, 0, Dummy);
360199989Srdivacky
361198090Srdivacky    // Get the next grouping option.
362198090Srdivacky    PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
363198090Srdivacky  } while (PGOpt && Length != Arg.size());
364199989Srdivacky
365198090Srdivacky  // Return the last option with Arg cut down to just the last one.
366198090Srdivacky  return PGOpt;
367198090Srdivacky}
368198090Srdivacky
369198090Srdivacky
370198090Srdivacky
371193323Sedstatic bool RequiresValue(const Option *O) {
372193323Sed  return O->getNumOccurrencesFlag() == cl::Required ||
373193323Sed         O->getNumOccurrencesFlag() == cl::OneOrMore;
374193323Sed}
375193323Sed
376193323Sedstatic bool EatsUnboundedNumberOfValues(const Option *O) {
377193323Sed  return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
378193323Sed         O->getNumOccurrencesFlag() == cl::OneOrMore;
379193323Sed}
380193323Sed
381193323Sed/// ParseCStringVector - Break INPUT up wherever one or more
382193323Sed/// whitespace characters are found, and store the resulting tokens in
383193323Sed/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
384198090Srdivacky/// using strdup(), so it is the caller's responsibility to free()
385193323Sed/// them later.
386193323Sed///
387198090Srdivackystatic void ParseCStringVector(std::vector<char *> &OutputVector,
388198090Srdivacky                               const char *Input) {
389193323Sed  // Characters which will be treated as token separators:
390198090Srdivacky  StringRef Delims = " \v\f\t\r\n";
391193323Sed
392198090Srdivacky  StringRef WorkStr(Input);
393198090Srdivacky  while (!WorkStr.empty()) {
394198090Srdivacky    // If the first character is a delimiter, strip them off.
395198090Srdivacky    if (Delims.find(WorkStr[0]) != StringRef::npos) {
396198090Srdivacky      size_t Pos = WorkStr.find_first_not_of(Delims);
397198090Srdivacky      if (Pos == StringRef::npos) Pos = WorkStr.size();
398198090Srdivacky      WorkStr = WorkStr.substr(Pos);
399198090Srdivacky      continue;
400193323Sed    }
401199989Srdivacky
402198090Srdivacky    // Find position of first delimiter.
403198090Srdivacky    size_t Pos = WorkStr.find_first_of(Delims);
404198090Srdivacky    if (Pos == StringRef::npos) Pos = WorkStr.size();
405199989Srdivacky
406198090Srdivacky    // Everything from 0 to Pos is the next word to copy.
407198090Srdivacky    char *NewStr = (char*)malloc(Pos+1);
408198090Srdivacky    memcpy(NewStr, WorkStr.data(), Pos);
409198090Srdivacky    NewStr[Pos] = 0;
410198090Srdivacky    OutputVector.push_back(NewStr);
411199989Srdivacky
412198090Srdivacky    WorkStr = WorkStr.substr(Pos);
413193323Sed  }
414193323Sed}
415193323Sed
416193323Sed/// ParseEnvironmentOptions - An alternative entry point to the
417193323Sed/// CommandLine library, which allows you to read the program's name
418193323Sed/// from the caller (as PROGNAME) and its command-line arguments from
419193323Sed/// an environment variable (whose name is given in ENVVAR).
420193323Sed///
421193323Sedvoid cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
422193323Sed                                 const char *Overview, bool ReadResponseFiles) {
423193323Sed  // Check args.
424193323Sed  assert(progName && "Program name not specified");
425193323Sed  assert(envVar && "Environment variable name missing");
426193323Sed
427193323Sed  // Get the environment variable they want us to parse options out of.
428193323Sed  const char *envValue = getenv(envVar);
429193323Sed  if (!envValue)
430193323Sed    return;
431193323Sed
432193323Sed  // Get program's "name", which we wouldn't know without the caller
433193323Sed  // telling us.
434193323Sed  std::vector<char*> newArgv;
435193323Sed  newArgv.push_back(strdup(progName));
436193323Sed
437193323Sed  // Parse the value of the environment variable into a "command line"
438193323Sed  // and hand it off to ParseCommandLineOptions().
439193323Sed  ParseCStringVector(newArgv, envValue);
440193323Sed  int newArgc = static_cast<int>(newArgv.size());
441193323Sed  ParseCommandLineOptions(newArgc, &newArgv[0], Overview, ReadResponseFiles);
442193323Sed
443193323Sed  // Free all the strdup()ed strings.
444193323Sed  for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
445193323Sed       i != e; ++i)
446198090Srdivacky    free(*i);
447193323Sed}
448193323Sed
449193323Sed
450193323Sed/// ExpandResponseFiles - Copy the contents of argv into newArgv,
451193323Sed/// substituting the contents of the response files for the arguments
452193323Sed/// of type @file.
453198090Srdivackystatic void ExpandResponseFiles(unsigned argc, char** argv,
454193323Sed                                std::vector<char*>& newArgv) {
455198090Srdivacky  for (unsigned i = 1; i != argc; ++i) {
456198090Srdivacky    char *arg = argv[i];
457193323Sed
458193323Sed    if (arg[0] == '@') {
459193323Sed      sys::PathWithStatus respFile(++arg);
460193323Sed
461193323Sed      // Check that the response file is not empty (mmap'ing empty
462193323Sed      // files can be problematic).
463193323Sed      const sys::FileStatus *FileStat = respFile.getFileStatus();
464193323Sed      if (FileStat && FileStat->getSize() != 0) {
465193323Sed
466193323Sed        // Mmap the response file into memory.
467193323Sed        OwningPtr<MemoryBuffer>
468193323Sed          respFilePtr(MemoryBuffer::getFile(respFile.c_str()));
469193323Sed
470193323Sed        // If we could open the file, parse its contents, otherwise
471193323Sed        // pass the @file option verbatim.
472193323Sed
473193323Sed        // TODO: we should also support recursive loading of response files,
474193323Sed        // since this is how gcc behaves. (From their man page: "The file may
475193323Sed        // itself contain additional @file options; any such options will be
476193323Sed        // processed recursively.")
477193323Sed
478193323Sed        if (respFilePtr != 0) {
479193323Sed          ParseCStringVector(newArgv, respFilePtr->getBufferStart());
480193323Sed          continue;
481193323Sed        }
482193323Sed      }
483193323Sed    }
484193323Sed    newArgv.push_back(strdup(arg));
485193323Sed  }
486193323Sed}
487193323Sed
488193323Sedvoid cl::ParseCommandLineOptions(int argc, char **argv,
489193323Sed                                 const char *Overview, bool ReadResponseFiles) {
490193323Sed  // Process all registered options.
491198090Srdivacky  SmallVector<Option*, 4> PositionalOpts;
492198090Srdivacky  SmallVector<Option*, 4> SinkOpts;
493198090Srdivacky  StringMap<Option*> Opts;
494193323Sed  GetOptionInfo(PositionalOpts, SinkOpts, Opts);
495193323Sed
496193323Sed  assert((!Opts.empty() || !PositionalOpts.empty()) &&
497193323Sed         "No options specified!");
498193323Sed
499193323Sed  // Expand response files.
500193323Sed  std::vector<char*> newArgv;
501193323Sed  if (ReadResponseFiles) {
502193323Sed    newArgv.push_back(strdup(argv[0]));
503193323Sed    ExpandResponseFiles(argc, argv, newArgv);
504193323Sed    argv = &newArgv[0];
505193323Sed    argc = static_cast<int>(newArgv.size());
506193323Sed  }
507193323Sed
508193323Sed  // Copy the program name into ProgName, making sure not to overflow it.
509193323Sed  std::string ProgName = sys::Path(argv[0]).getLast();
510203954Srdivacky  size_t Len = std::min(ProgName.size(), size_t(79));
511203954Srdivacky  memcpy(ProgramName, ProgName.data(), Len);
512203954Srdivacky  ProgramName[Len] = '\0';
513193323Sed
514193323Sed  ProgramOverview = Overview;
515193323Sed  bool ErrorParsing = false;
516193323Sed
517193323Sed  // Check out the positional arguments to collect information about them.
518193323Sed  unsigned NumPositionalRequired = 0;
519193323Sed
520193323Sed  // Determine whether or not there are an unlimited number of positionals
521193323Sed  bool HasUnlimitedPositionals = false;
522193323Sed
523193323Sed  Option *ConsumeAfterOpt = 0;
524193323Sed  if (!PositionalOpts.empty()) {
525193323Sed    if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
526193323Sed      assert(PositionalOpts.size() > 1 &&
527193323Sed             "Cannot specify cl::ConsumeAfter without a positional argument!");
528193323Sed      ConsumeAfterOpt = PositionalOpts[0];
529193323Sed    }
530193323Sed
531193323Sed    // Calculate how many positional values are _required_.
532193323Sed    bool UnboundedFound = false;
533193323Sed    for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
534193323Sed         i != e; ++i) {
535193323Sed      Option *Opt = PositionalOpts[i];
536193323Sed      if (RequiresValue(Opt))
537193323Sed        ++NumPositionalRequired;
538193323Sed      else if (ConsumeAfterOpt) {
539193323Sed        // ConsumeAfter cannot be combined with "optional" positional options
540193323Sed        // unless there is only one positional argument...
541193323Sed        if (PositionalOpts.size() > 2)
542193323Sed          ErrorParsing |=
543198090Srdivacky            Opt->error("error - this positional option will never be matched, "
544193323Sed                       "because it does not Require a value, and a "
545193323Sed                       "cl::ConsumeAfter option is active!");
546193323Sed      } else if (UnboundedFound && !Opt->ArgStr[0]) {
547193323Sed        // This option does not "require" a value...  Make sure this option is
548193323Sed        // not specified after an option that eats all extra arguments, or this
549193323Sed        // one will never get any!
550193323Sed        //
551198090Srdivacky        ErrorParsing |= Opt->error("error - option can never match, because "
552193323Sed                                   "another positional argument will match an "
553193323Sed                                   "unbounded number of values, and this option"
554193323Sed                                   " does not require a value!");
555193323Sed      }
556193323Sed      UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
557193323Sed    }
558193323Sed    HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
559193323Sed  }
560193323Sed
561193323Sed  // PositionalVals - A vector of "positional" arguments we accumulate into
562198090Srdivacky  // the process at the end.
563193323Sed  //
564198090Srdivacky  SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
565193323Sed
566193323Sed  // If the program has named positional arguments, and the name has been run
567193323Sed  // across, keep track of which positional argument was named.  Otherwise put
568193323Sed  // the positional args into the PositionalVals list...
569193323Sed  Option *ActivePositionalArg = 0;
570193323Sed
571193323Sed  // Loop over all of the arguments... processing them.
572193323Sed  bool DashDashFound = false;  // Have we read '--'?
573193323Sed  for (int i = 1; i < argc; ++i) {
574193323Sed    Option *Handler = 0;
575198090Srdivacky    StringRef Value;
576198090Srdivacky    StringRef ArgName = "";
577193323Sed
578193323Sed    // If the option list changed, this means that some command line
579193323Sed    // option has just been registered or deregistered.  This can occur in
580193323Sed    // response to things like -load, etc.  If this happens, rescan the options.
581193323Sed    if (OptionListChanged) {
582193323Sed      PositionalOpts.clear();
583193323Sed      SinkOpts.clear();
584193323Sed      Opts.clear();
585193323Sed      GetOptionInfo(PositionalOpts, SinkOpts, Opts);
586193323Sed      OptionListChanged = false;
587193323Sed    }
588193323Sed
589193323Sed    // Check to see if this is a positional argument.  This argument is
590193323Sed    // considered to be positional if it doesn't start with '-', if it is "-"
591193323Sed    // itself, or if we have seen "--" already.
592193323Sed    //
593193323Sed    if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
594193323Sed      // Positional argument!
595193323Sed      if (ActivePositionalArg) {
596193323Sed        ProvidePositionalOption(ActivePositionalArg, argv[i], i);
597193323Sed        continue;  // We are done!
598198090Srdivacky      }
599199989Srdivacky
600198090Srdivacky      if (!PositionalOpts.empty()) {
601193323Sed        PositionalVals.push_back(std::make_pair(argv[i],i));
602193323Sed
603193323Sed        // All of the positional arguments have been fulfulled, give the rest to
604193323Sed        // the consume after option... if it's specified...
605193323Sed        //
606193323Sed        if (PositionalVals.size() >= NumPositionalRequired &&
607193323Sed            ConsumeAfterOpt != 0) {
608193323Sed          for (++i; i < argc; ++i)
609193323Sed            PositionalVals.push_back(std::make_pair(argv[i],i));
610193323Sed          break;   // Handle outside of the argument processing loop...
611193323Sed        }
612193323Sed
613193323Sed        // Delay processing positional arguments until the end...
614193323Sed        continue;
615193323Sed      }
616193323Sed    } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
617193323Sed               !DashDashFound) {
618193323Sed      DashDashFound = true;  // This is the mythical "--"?
619193323Sed      continue;              // Don't try to process it as an argument itself.
620193323Sed    } else if (ActivePositionalArg &&
621193323Sed               (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
622193323Sed      // If there is a positional argument eating options, check to see if this
623193323Sed      // option is another positional argument.  If so, treat it as an argument,
624193323Sed      // otherwise feed it to the eating positional.
625193323Sed      ArgName = argv[i]+1;
626198090Srdivacky      // Eat leading dashes.
627198090Srdivacky      while (!ArgName.empty() && ArgName[0] == '-')
628198090Srdivacky        ArgName = ArgName.substr(1);
629199989Srdivacky
630193323Sed      Handler = LookupOption(ArgName, Value, Opts);
631193323Sed      if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
632193323Sed        ProvidePositionalOption(ActivePositionalArg, argv[i], i);
633193323Sed        continue;  // We are done!
634193323Sed      }
635193323Sed
636198090Srdivacky    } else {     // We start with a '-', must be an argument.
637193323Sed      ArgName = argv[i]+1;
638198090Srdivacky      // Eat leading dashes.
639198090Srdivacky      while (!ArgName.empty() && ArgName[0] == '-')
640198090Srdivacky        ArgName = ArgName.substr(1);
641199989Srdivacky
642193323Sed      Handler = LookupOption(ArgName, Value, Opts);
643193323Sed
644193323Sed      // Check to see if this "option" is really a prefixed or grouped argument.
645198090Srdivacky      if (Handler == 0)
646198090Srdivacky        Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
647198090Srdivacky                                                ErrorParsing, Opts);
648193323Sed    }
649193323Sed
650193323Sed    if (Handler == 0) {
651193323Sed      if (SinkOpts.empty()) {
652198090Srdivacky        errs() << ProgramName << ": Unknown command line argument '"
653204642Srdivacky             << argv[i] << "'.  Try: '" << argv[0] << " -help'\n";
654193323Sed        ErrorParsing = true;
655193323Sed      } else {
656198090Srdivacky        for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
657193323Sed               E = SinkOpts.end(); I != E ; ++I)
658193323Sed          (*I)->addOccurrence(i, "", argv[i]);
659193323Sed      }
660193323Sed      continue;
661193323Sed    }
662193323Sed
663193323Sed    // If this is a named positional argument, just remember that it is the
664193323Sed    // active one...
665193323Sed    if (Handler->getFormattingFlag() == cl::Positional)
666193323Sed      ActivePositionalArg = Handler;
667193323Sed    else
668193323Sed      ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
669193323Sed  }
670193323Sed
671193323Sed  // Check and handle positional arguments now...
672193323Sed  if (NumPositionalRequired > PositionalVals.size()) {
673198090Srdivacky    errs() << ProgramName
674193323Sed         << ": Not enough positional command line arguments specified!\n"
675193323Sed         << "Must specify at least " << NumPositionalRequired
676204642Srdivacky         << " positional arguments: See: " << argv[0] << " -help\n";
677193323Sed
678193323Sed    ErrorParsing = true;
679206083Srdivacky  } else if (!HasUnlimitedPositionals &&
680206083Srdivacky             PositionalVals.size() > PositionalOpts.size()) {
681198090Srdivacky    errs() << ProgramName
682193323Sed         << ": Too many positional arguments specified!\n"
683193323Sed         << "Can specify at most " << PositionalOpts.size()
684204642Srdivacky         << " positional arguments: See: " << argv[0] << " -help\n";
685193323Sed    ErrorParsing = true;
686193323Sed
687193323Sed  } else if (ConsumeAfterOpt == 0) {
688198090Srdivacky    // Positional args have already been handled if ConsumeAfter is specified.
689193323Sed    unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
690193323Sed    for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
691193323Sed      if (RequiresValue(PositionalOpts[i])) {
692193323Sed        ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
693193323Sed                                PositionalVals[ValNo].second);
694193323Sed        ValNo++;
695193323Sed        --NumPositionalRequired;  // We fulfilled our duty...
696193323Sed      }
697193323Sed
698193323Sed      // If we _can_ give this option more arguments, do so now, as long as we
699193323Sed      // do not give it values that others need.  'Done' controls whether the
700193323Sed      // option even _WANTS_ any more.
701193323Sed      //
702193323Sed      bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
703193323Sed      while (NumVals-ValNo > NumPositionalRequired && !Done) {
704193323Sed        switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
705193323Sed        case cl::Optional:
706193323Sed          Done = true;          // Optional arguments want _at most_ one value
707193323Sed          // FALL THROUGH
708193323Sed        case cl::ZeroOrMore:    // Zero or more will take all they can get...
709193323Sed        case cl::OneOrMore:     // One or more will take all they can get...
710193323Sed          ProvidePositionalOption(PositionalOpts[i],
711193323Sed                                  PositionalVals[ValNo].first,
712193323Sed                                  PositionalVals[ValNo].second);
713193323Sed          ValNo++;
714193323Sed          break;
715193323Sed        default:
716198090Srdivacky          llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
717193323Sed                 "positional argument processing!");
718193323Sed        }
719193323Sed      }
720193323Sed    }
721193323Sed  } else {
722193323Sed    assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
723193323Sed    unsigned ValNo = 0;
724193323Sed    for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
725193323Sed      if (RequiresValue(PositionalOpts[j])) {
726193323Sed        ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
727193323Sed                                                PositionalVals[ValNo].first,
728193323Sed                                                PositionalVals[ValNo].second);
729193323Sed        ValNo++;
730193323Sed      }
731193323Sed
732193323Sed    // Handle the case where there is just one positional option, and it's
733193323Sed    // optional.  In this case, we want to give JUST THE FIRST option to the
734193323Sed    // positional option and keep the rest for the consume after.  The above
735193323Sed    // loop would have assigned no values to positional options in this case.
736193323Sed    //
737193323Sed    if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
738193323Sed      ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
739193323Sed                                              PositionalVals[ValNo].first,
740193323Sed                                              PositionalVals[ValNo].second);
741193323Sed      ValNo++;
742193323Sed    }
743193323Sed
744193323Sed    // Handle over all of the rest of the arguments to the
745193323Sed    // cl::ConsumeAfter command line option...
746193323Sed    for (; ValNo != PositionalVals.size(); ++ValNo)
747193323Sed      ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
748193323Sed                                              PositionalVals[ValNo].first,
749193323Sed                                              PositionalVals[ValNo].second);
750193323Sed  }
751193323Sed
752193323Sed  // Loop over args and make sure all required args are specified!
753198090Srdivacky  for (StringMap<Option*>::iterator I = Opts.begin(),
754193323Sed         E = Opts.end(); I != E; ++I) {
755193323Sed    switch (I->second->getNumOccurrencesFlag()) {
756193323Sed    case Required:
757193323Sed    case OneOrMore:
758193323Sed      if (I->second->getNumOccurrences() == 0) {
759198090Srdivacky        I->second->error("must be specified at least once!");
760193323Sed        ErrorParsing = true;
761193323Sed      }
762193323Sed      // Fall through
763193323Sed    default:
764193323Sed      break;
765193323Sed    }
766193323Sed  }
767193323Sed
768193323Sed  // Free all of the memory allocated to the map.  Command line options may only
769193323Sed  // be processed once!
770193323Sed  Opts.clear();
771193323Sed  PositionalOpts.clear();
772193323Sed  MoreHelp->clear();
773193323Sed
774193323Sed  // Free the memory allocated by ExpandResponseFiles.
775193323Sed  if (ReadResponseFiles) {
776193323Sed    // Free all the strdup()ed strings.
777193323Sed    for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
778193323Sed         i != e; ++i)
779198090Srdivacky      free(*i);
780193323Sed  }
781193323Sed
782202375Srdivacky  DEBUG(dbgs() << "Args: ";
783199481Srdivacky        for (int i = 0; i < argc; ++i)
784202375Srdivacky          dbgs() << argv[i] << ' ';
785202375Srdivacky        dbgs() << '\n';
786199481Srdivacky       );
787199481Srdivacky
788193323Sed  // If we had an error processing our arguments, don't let the program execute
789193323Sed  if (ErrorParsing) exit(1);
790193323Sed}
791193323Sed
792193323Sed//===----------------------------------------------------------------------===//
793193323Sed// Option Base class implementation
794193323Sed//
795193323Sed
796198090Srdivackybool Option::error(const Twine &Message, StringRef ArgName) {
797198090Srdivacky  if (ArgName.data() == 0) ArgName = ArgStr;
798198090Srdivacky  if (ArgName.empty())
799198090Srdivacky    errs() << HelpStr;  // Be nice for positional arguments
800193323Sed  else
801198090Srdivacky    errs() << ProgramName << ": for the -" << ArgName;
802193323Sed
803198090Srdivacky  errs() << " option: " << Message << "\n";
804193323Sed  return true;
805193323Sed}
806193323Sed
807198090Srdivackybool Option::addOccurrence(unsigned pos, StringRef ArgName,
808198090Srdivacky                           StringRef Value, bool MultiArg) {
809193323Sed  if (!MultiArg)
810193323Sed    NumOccurrences++;   // Increment the number of times we have been seen
811193323Sed
812193323Sed  switch (getNumOccurrencesFlag()) {
813193323Sed  case Optional:
814193323Sed    if (NumOccurrences > 1)
815198090Srdivacky      return error("may only occur zero or one times!", ArgName);
816193323Sed    break;
817193323Sed  case Required:
818193323Sed    if (NumOccurrences > 1)
819198090Srdivacky      return error("must occur exactly one time!", ArgName);
820193323Sed    // Fall through
821193323Sed  case OneOrMore:
822193323Sed  case ZeroOrMore:
823193323Sed  case ConsumeAfter: break;
824198090Srdivacky  default: return error("bad num occurrences flag value!");
825193323Sed  }
826193323Sed
827193323Sed  return handleOccurrence(pos, ArgName, Value);
828193323Sed}
829193323Sed
830193323Sed
831193323Sed// getValueStr - Get the value description string, using "DefaultMsg" if nothing
832193323Sed// has been specified yet.
833193323Sed//
834193323Sedstatic const char *getValueStr(const Option &O, const char *DefaultMsg) {
835193323Sed  if (O.ValueStr[0] == 0) return DefaultMsg;
836193323Sed  return O.ValueStr;
837193323Sed}
838193323Sed
839193323Sed//===----------------------------------------------------------------------===//
840193323Sed// cl::alias class implementation
841193323Sed//
842193323Sed
843193323Sed// Return the width of the option tag for printing...
844193323Sedsize_t alias::getOptionWidth() const {
845193323Sed  return std::strlen(ArgStr)+6;
846193323Sed}
847193323Sed
848193323Sed// Print out the option for the alias.
849193323Sedvoid alias::printOptionInfo(size_t GlobalWidth) const {
850193323Sed  size_t L = std::strlen(ArgStr);
851198090Srdivacky  errs() << "  -" << ArgStr;
852198090Srdivacky  errs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n";
853193323Sed}
854193323Sed
855193323Sed
856193323Sed
857193323Sed//===----------------------------------------------------------------------===//
858193323Sed// Parser Implementation code...
859193323Sed//
860193323Sed
861193323Sed// basic_parser implementation
862193323Sed//
863193323Sed
864193323Sed// Return the width of the option tag for printing...
865193323Sedsize_t basic_parser_impl::getOptionWidth(const Option &O) const {
866193323Sed  size_t Len = std::strlen(O.ArgStr);
867193323Sed  if (const char *ValName = getValueName())
868193323Sed    Len += std::strlen(getValueStr(O, ValName))+3;
869193323Sed
870193323Sed  return Len + 6;
871193323Sed}
872193323Sed
873193323Sed// printOptionInfo - Print out information about this option.  The
874193323Sed// to-be-maintained width is specified.
875193323Sed//
876193323Sedvoid basic_parser_impl::printOptionInfo(const Option &O,
877193323Sed                                        size_t GlobalWidth) const {
878198090Srdivacky  outs() << "  -" << O.ArgStr;
879193323Sed
880193323Sed  if (const char *ValName = getValueName())
881198090Srdivacky    outs() << "=<" << getValueStr(O, ValName) << '>';
882193323Sed
883198090Srdivacky  outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n';
884193323Sed}
885193323Sed
886193323Sed
887193323Sed
888193323Sed
889193323Sed// parser<bool> implementation
890193323Sed//
891198090Srdivackybool parser<bool>::parse(Option &O, StringRef ArgName,
892198090Srdivacky                         StringRef Arg, bool &Value) {
893193323Sed  if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
894193323Sed      Arg == "1") {
895193323Sed    Value = true;
896198090Srdivacky    return false;
897198090Srdivacky  }
898199989Srdivacky
899198090Srdivacky  if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
900193323Sed    Value = false;
901198090Srdivacky    return false;
902193323Sed  }
903198090Srdivacky  return O.error("'" + Arg +
904198090Srdivacky                 "' is invalid value for boolean argument! Try 0 or 1");
905193323Sed}
906193323Sed
907193323Sed// parser<boolOrDefault> implementation
908193323Sed//
909198090Srdivackybool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
910198090Srdivacky                                  StringRef Arg, boolOrDefault &Value) {
911193323Sed  if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
912193323Sed      Arg == "1") {
913193323Sed    Value = BOU_TRUE;
914198090Srdivacky    return false;
915198090Srdivacky  }
916198090Srdivacky  if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
917193323Sed    Value = BOU_FALSE;
918198090Srdivacky    return false;
919193323Sed  }
920199989Srdivacky
921198090Srdivacky  return O.error("'" + Arg +
922198090Srdivacky                 "' is invalid value for boolean argument! Try 0 or 1");
923193323Sed}
924193323Sed
925193323Sed// parser<int> implementation
926193323Sed//
927198090Srdivackybool parser<int>::parse(Option &O, StringRef ArgName,
928198090Srdivacky                        StringRef Arg, int &Value) {
929198090Srdivacky  if (Arg.getAsInteger(0, Value))
930198090Srdivacky    return O.error("'" + Arg + "' value invalid for integer argument!");
931193323Sed  return false;
932193323Sed}
933193323Sed
934193323Sed// parser<unsigned> implementation
935193323Sed//
936198090Srdivackybool parser<unsigned>::parse(Option &O, StringRef ArgName,
937198090Srdivacky                             StringRef Arg, unsigned &Value) {
938198090Srdivacky
939198090Srdivacky  if (Arg.getAsInteger(0, Value))
940198090Srdivacky    return O.error("'" + Arg + "' value invalid for uint argument!");
941193323Sed  return false;
942193323Sed}
943193323Sed
944193323Sed// parser<double>/parser<float> implementation
945193323Sed//
946198090Srdivackystatic bool parseDouble(Option &O, StringRef Arg, double &Value) {
947198090Srdivacky  SmallString<32> TmpStr(Arg.begin(), Arg.end());
948198090Srdivacky  const char *ArgStart = TmpStr.c_str();
949193323Sed  char *End;
950193323Sed  Value = strtod(ArgStart, &End);
951193323Sed  if (*End != 0)
952198090Srdivacky    return O.error("'" + Arg + "' value invalid for floating point argument!");
953193323Sed  return false;
954193323Sed}
955193323Sed
956198090Srdivackybool parser<double>::parse(Option &O, StringRef ArgName,
957198090Srdivacky                           StringRef Arg, double &Val) {
958193323Sed  return parseDouble(O, Arg, Val);
959193323Sed}
960193323Sed
961198090Srdivackybool parser<float>::parse(Option &O, StringRef ArgName,
962198090Srdivacky                          StringRef Arg, float &Val) {
963193323Sed  double dVal;
964193323Sed  if (parseDouble(O, Arg, dVal))
965193323Sed    return true;
966193323Sed  Val = (float)dVal;
967193323Sed  return false;
968193323Sed}
969193323Sed
970193323Sed
971193323Sed
972193323Sed// generic_parser_base implementation
973193323Sed//
974193323Sed
975193323Sed// findOption - Return the option number corresponding to the specified
976193323Sed// argument string.  If the option is not found, getNumOptions() is returned.
977193323Sed//
978193323Sedunsigned generic_parser_base::findOption(const char *Name) {
979198090Srdivacky  unsigned e = getNumOptions();
980193323Sed
981198090Srdivacky  for (unsigned i = 0; i != e; ++i) {
982198090Srdivacky    if (strcmp(getOption(i), Name) == 0)
983193323Sed      return i;
984198090Srdivacky  }
985193323Sed  return e;
986193323Sed}
987193323Sed
988193323Sed
989193323Sed// Return the width of the option tag for printing...
990193323Sedsize_t generic_parser_base::getOptionWidth(const Option &O) const {
991193323Sed  if (O.hasArgStr()) {
992193323Sed    size_t Size = std::strlen(O.ArgStr)+6;
993193323Sed    for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
994193323Sed      Size = std::max(Size, std::strlen(getOption(i))+8);
995193323Sed    return Size;
996193323Sed  } else {
997193323Sed    size_t BaseSize = 0;
998193323Sed    for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
999193323Sed      BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1000193323Sed    return BaseSize;
1001193323Sed  }
1002193323Sed}
1003193323Sed
1004193323Sed// printOptionInfo - Print out information about this option.  The
1005193323Sed// to-be-maintained width is specified.
1006193323Sed//
1007193323Sedvoid generic_parser_base::printOptionInfo(const Option &O,
1008193323Sed                                          size_t GlobalWidth) const {
1009193323Sed  if (O.hasArgStr()) {
1010193323Sed    size_t L = std::strlen(O.ArgStr);
1011198090Srdivacky    outs() << "  -" << O.ArgStr;
1012198090Srdivacky    outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n';
1013193323Sed
1014193323Sed    for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1015193323Sed      size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1016198090Srdivacky      outs() << "    =" << getOption(i);
1017198090Srdivacky      outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
1018193323Sed    }
1019193323Sed  } else {
1020193323Sed    if (O.HelpStr[0])
1021198090Srdivacky      outs() << "  " << O.HelpStr << '\n';
1022193323Sed    for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1023193323Sed      size_t L = std::strlen(getOption(i));
1024198090Srdivacky      outs() << "    -" << getOption(i);
1025198090Srdivacky      outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n';
1026193323Sed    }
1027193323Sed  }
1028193323Sed}
1029193323Sed
1030193323Sed
1031193323Sed//===----------------------------------------------------------------------===//
1032204642Srdivacky// -help and -help-hidden option implementation
1033193323Sed//
1034193323Sed
1035198090Srdivackystatic int OptNameCompare(const void *LHS, const void *RHS) {
1036198090Srdivacky  typedef std::pair<const char *, Option*> pair_ty;
1037199989Srdivacky
1038198090Srdivacky  return strcmp(((pair_ty*)LHS)->first, ((pair_ty*)RHS)->first);
1039198090Srdivacky}
1040198090Srdivacky
1041193323Sednamespace {
1042193323Sed
1043193323Sedclass HelpPrinter {
1044193323Sed  size_t MaxArgLen;
1045193323Sed  const Option *EmptyArg;
1046193323Sed  const bool ShowHidden;
1047193323Sed
1048193323Sedpublic:
1049193323Sed  explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
1050193323Sed    EmptyArg = 0;
1051193323Sed  }
1052193323Sed
1053193323Sed  void operator=(bool Value) {
1054193323Sed    if (Value == false) return;
1055193323Sed
1056193323Sed    // Get all the options.
1057198090Srdivacky    SmallVector<Option*, 4> PositionalOpts;
1058198090Srdivacky    SmallVector<Option*, 4> SinkOpts;
1059198090Srdivacky    StringMap<Option*> OptMap;
1060193323Sed    GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1061193323Sed
1062198090Srdivacky    // Copy Options into a vector so we can sort them as we like.
1063198090Srdivacky    SmallVector<std::pair<const char *, Option*>, 128> Opts;
1064198090Srdivacky    SmallPtrSet<Option*, 128> OptionSet;  // Duplicate option detection.
1065193323Sed
1066198090Srdivacky    for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1067198090Srdivacky         I != E; ++I) {
1068198090Srdivacky      // Ignore really-hidden options.
1069198090Srdivacky      if (I->second->getOptionHiddenFlag() == ReallyHidden)
1070198090Srdivacky        continue;
1071199989Srdivacky
1072198090Srdivacky      // Unless showhidden is set, ignore hidden flags.
1073198090Srdivacky      if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1074198090Srdivacky        continue;
1075199989Srdivacky
1076198090Srdivacky      // If we've already seen this option, don't add it to the list again.
1077198090Srdivacky      if (!OptionSet.insert(I->second))
1078198090Srdivacky        continue;
1079193323Sed
1080198090Srdivacky      Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1081198090Srdivacky                                                      I->second));
1082193323Sed    }
1083199989Srdivacky
1084198090Srdivacky    // Sort the options list alphabetically.
1085198090Srdivacky    qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1086193323Sed
1087193323Sed    if (ProgramOverview)
1088198090Srdivacky      outs() << "OVERVIEW: " << ProgramOverview << "\n";
1089193323Sed
1090198090Srdivacky    outs() << "USAGE: " << ProgramName << " [options]";
1091193323Sed
1092193323Sed    // Print out the positional options.
1093193323Sed    Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
1094193323Sed    if (!PositionalOpts.empty() &&
1095193323Sed        PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1096193323Sed      CAOpt = PositionalOpts[0];
1097193323Sed
1098193323Sed    for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1099193323Sed      if (PositionalOpts[i]->ArgStr[0])
1100198090Srdivacky        outs() << " --" << PositionalOpts[i]->ArgStr;
1101198090Srdivacky      outs() << " " << PositionalOpts[i]->HelpStr;
1102193323Sed    }
1103193323Sed
1104193323Sed    // Print the consume after option info if it exists...
1105198090Srdivacky    if (CAOpt) outs() << " " << CAOpt->HelpStr;
1106193323Sed
1107198090Srdivacky    outs() << "\n\n";
1108193323Sed
1109193323Sed    // Compute the maximum argument length...
1110193323Sed    MaxArgLen = 0;
1111193323Sed    for (size_t i = 0, e = Opts.size(); i != e; ++i)
1112193323Sed      MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1113193323Sed
1114198090Srdivacky    outs() << "OPTIONS:\n";
1115193323Sed    for (size_t i = 0, e = Opts.size(); i != e; ++i)
1116193323Sed      Opts[i].second->printOptionInfo(MaxArgLen);
1117193323Sed
1118193323Sed    // Print any extra help the user has declared.
1119193323Sed    for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1120193323Sed          E = MoreHelp->end(); I != E; ++I)
1121198090Srdivacky      outs() << *I;
1122193323Sed    MoreHelp->clear();
1123193323Sed
1124193323Sed    // Halt the program since help information was printed
1125193323Sed    exit(1);
1126193323Sed  }
1127193323Sed};
1128193323Sed} // End anonymous namespace
1129193323Sed
1130193323Sed// Define the two HelpPrinter instances that are used to print out help, or
1131193323Sed// help-hidden...
1132193323Sed//
1133193323Sedstatic HelpPrinter NormalPrinter(false);
1134193323Sedstatic HelpPrinter HiddenPrinter(true);
1135193323Sed
1136193323Sedstatic cl::opt<HelpPrinter, true, parser<bool> >
1137204642SrdivackyHOp("help", cl::desc("Display available options (-help-hidden for more)"),
1138193323Sed    cl::location(NormalPrinter), cl::ValueDisallowed);
1139193323Sed
1140193323Sedstatic cl::opt<HelpPrinter, true, parser<bool> >
1141193323SedHHOp("help-hidden", cl::desc("Display all available options"),
1142193323Sed     cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1143193323Sed
1144193323Sedstatic void (*OverrideVersionPrinter)() = 0;
1145193323Sed
1146198090Srdivackystatic int TargetArraySortFn(const void *LHS, const void *RHS) {
1147198090Srdivacky  typedef std::pair<const char *, const Target*> pair_ty;
1148198090Srdivacky  return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1149198090Srdivacky}
1150198090Srdivacky
1151193323Sednamespace {
1152193323Sedclass VersionPrinter {
1153193323Sedpublic:
1154193323Sed  void print() {
1155198090Srdivacky    raw_ostream &OS = outs();
1156198090Srdivacky    OS << "Low Level Virtual Machine (http://llvm.org/):\n"
1157198090Srdivacky       << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1158193323Sed#ifdef LLVM_VERSION_INFO
1159198090Srdivacky    OS << LLVM_VERSION_INFO;
1160193323Sed#endif
1161198090Srdivacky    OS << "\n  ";
1162193323Sed#ifndef __OPTIMIZE__
1163198090Srdivacky    OS << "DEBUG build";
1164193323Sed#else
1165198090Srdivacky    OS << "Optimized build";
1166193323Sed#endif
1167193323Sed#ifndef NDEBUG
1168198090Srdivacky    OS << " with assertions";
1169193323Sed#endif
1170199481Srdivacky    std::string CPU = sys::getHostCPUName();
1171199481Srdivacky    if (CPU == "generic") CPU = "(unknown)";
1172198090Srdivacky    OS << ".\n"
1173208599Srdivacky#if (ENABLE_TIMESTAMPS == 1)
1174198090Srdivacky       << "  Built " << __DATE__ << " (" << __TIME__ << ").\n"
1175208599Srdivacky#endif
1176198090Srdivacky       << "  Host: " << sys::getHostTriple() << '\n'
1177199481Srdivacky       << "  Host CPU: " << CPU << '\n'
1178198090Srdivacky       << '\n'
1179198090Srdivacky       << "  Registered Targets:\n";
1180198090Srdivacky
1181198090Srdivacky    std::vector<std::pair<const char *, const Target*> > Targets;
1182198090Srdivacky    size_t Width = 0;
1183199989Srdivacky    for (TargetRegistry::iterator it = TargetRegistry::begin(),
1184198090Srdivacky           ie = TargetRegistry::end(); it != ie; ++it) {
1185198090Srdivacky      Targets.push_back(std::make_pair(it->getName(), &*it));
1186198090Srdivacky      Width = std::max(Width, strlen(Targets.back().first));
1187198090Srdivacky    }
1188198090Srdivacky    if (!Targets.empty())
1189198090Srdivacky      qsort(&Targets[0], Targets.size(), sizeof(Targets[0]),
1190198090Srdivacky            TargetArraySortFn);
1191198090Srdivacky
1192198090Srdivacky    for (unsigned i = 0, e = Targets.size(); i != e; ++i) {
1193198090Srdivacky      OS << "    " << Targets[i].first;
1194198090Srdivacky      OS.indent(Width - strlen(Targets[i].first)) << " - "
1195198090Srdivacky             << Targets[i].second->getShortDescription() << '\n';
1196198090Srdivacky    }
1197198090Srdivacky    if (Targets.empty())
1198198090Srdivacky      OS << "    (none)\n";
1199193323Sed  }
1200193323Sed  void operator=(bool OptionWasSpecified) {
1201198090Srdivacky    if (!OptionWasSpecified) return;
1202199989Srdivacky
1203198090Srdivacky    if (OverrideVersionPrinter == 0) {
1204198090Srdivacky      print();
1205198090Srdivacky      exit(1);
1206193323Sed    }
1207198090Srdivacky    (*OverrideVersionPrinter)();
1208198090Srdivacky    exit(1);
1209193323Sed  }
1210193323Sed};
1211193323Sed} // End anonymous namespace
1212193323Sed
1213193323Sed
1214193323Sed// Define the --version option that prints out the LLVM version for the tool
1215193323Sedstatic VersionPrinter VersionPrinterInstance;
1216193323Sed
1217193323Sedstatic cl::opt<VersionPrinter, true, parser<bool> >
1218193323SedVersOp("version", cl::desc("Display the version of this program"),
1219193323Sed    cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1220193323Sed
1221193323Sed// Utility function for printing the help message.
1222193323Sedvoid cl::PrintHelpMessage() {
1223193323Sed  // This looks weird, but it actually prints the help message. The
1224193323Sed  // NormalPrinter variable is a HelpPrinter and the help gets printed when
1225193323Sed  // its operator= is invoked. That's because the "normal" usages of the
1226193323Sed  // help printer is to be assigned true/false depending on whether the
1227204642Srdivacky  // -help option was given or not. Since we're circumventing that we have
1228204642Srdivacky  // to make it look like -help was given, so we assign true.
1229193323Sed  NormalPrinter = true;
1230193323Sed}
1231193323Sed
1232193323Sed/// Utility function for printing version number.
1233193323Sedvoid cl::PrintVersionMessage() {
1234193323Sed  VersionPrinterInstance.print();
1235193323Sed}
1236193323Sed
1237193323Sedvoid cl::SetVersionPrinter(void (*func)()) {
1238193323Sed  OverrideVersionPrinter = func;
1239193323Sed}
1240