Work around GCC PR19958, which causes programs to sometimes crash after
[oota-llvm.git] / lib / Support / CommandLine.cpp
1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Config/config.h"
20 #include "llvm/Support/CommandLine.h"
21 #include <algorithm>
22 #include <map>
23 #include <set>
24 #include <iostream>
25 #include <cstdlib>
26 #include <cerrno>
27 #include <cstring>
28 using namespace llvm;
29
30 using namespace cl;
31
32 // Globals for name and overview of program
33 static const char *ProgramName = "<unknown>";
34 static const char *ProgramOverview = 0;
35
36 // This collects additional help to be printed.
37 static std::vector<const char*> &MoreHelp() {
38   static std::vector<const char*> moreHelp;
39   return moreHelp;
40 }
41
42 extrahelp::extrahelp(const char* Help)
43   : morehelp(Help) {
44   MoreHelp().push_back(Help);
45 }
46
47 //===----------------------------------------------------------------------===//
48 // Basic, shared command line option processing machinery...
49 //
50
51 // Return the global command line option vector.  Making it a function scoped
52 // static ensures that it will be initialized correctly before its first use.
53 //
54 static std::map<std::string, Option*> &getOpts() {
55   static std::map<std::string, Option*> CommandLineOptions;
56   return CommandLineOptions;
57 }
58
59 static Option *getOption(const std::string &Str) {
60   std::map<std::string,Option*>::iterator I = getOpts().find(Str);
61   return I != getOpts().end() ? I->second : 0;
62 }
63
64 static std::vector<Option*> &getPositionalOpts() {
65   static std::vector<Option*> Positional;
66   return Positional;
67 }
68
69 static void AddArgument(const char *ArgName, Option *Opt) {
70   if (getOption(ArgName)) {
71     std::cerr << ProgramName << ": CommandLine Error: Argument '" 
72               << ArgName << "' defined more than once!\n";
73   } else {
74     // Add argument to the argument map!
75     getOpts()[ArgName] = Opt;
76   }
77 }
78
79 // RemoveArgument - It's possible that the argument is no longer in the map if
80 // options have already been processed and the map has been deleted!
81 // 
82 static void RemoveArgument(const char *ArgName, Option *Opt) {
83   if(getOpts().empty()) return;
84
85 #ifndef NDEBUG
86   // This disgusting HACK is brought to you courtesy of GCC 3.3.2, which ICE's
87   // If we pass ArgName directly into getOption here.
88   std::string Tmp = ArgName;
89   assert(getOption(Tmp) == Opt && "Arg not in map!");
90 #endif
91   getOpts().erase(ArgName);
92 }
93
94 static inline bool ProvideOption(Option *Handler, const char *ArgName,
95                                  const char *Value, int argc, char **argv,
96                                  int &i) {
97   // Enforce value requirements
98   switch (Handler->getValueExpectedFlag()) {
99   case ValueRequired:
100     if (Value == 0 || *Value == 0) {  // No value specified?
101       if (i+1 < argc) {     // Steal the next argument, like for '-o filename'
102         Value = argv[++i];
103       } else {
104         return Handler->error(" requires a value!");
105       }
106     }
107     break;
108   case ValueDisallowed:
109     if (*Value != 0)
110       return Handler->error(" does not allow a value! '" + 
111                             std::string(Value) + "' specified.");
112     break;
113   case ValueOptional: 
114     break;
115   default: 
116     std::cerr << ProgramName 
117               << ": Bad ValueMask flag! CommandLine usage error:" 
118               << Handler->getValueExpectedFlag() << "\n"; 
119     abort();
120     break;
121   }
122
123   // Run the handler now!
124   return Handler->addOccurrence(i, ArgName, Value);
125 }
126
127 static bool ProvidePositionalOption(Option *Handler, const std::string &Arg, 
128                                     int i) {
129   int Dummy = i;
130   return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
131 }
132
133
134 // Option predicates...
135 static inline bool isGrouping(const Option *O) {
136   return O->getFormattingFlag() == cl::Grouping;
137 }
138 static inline bool isPrefixedOrGrouping(const Option *O) {
139   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
140 }
141
142 // getOptionPred - Check to see if there are any options that satisfy the
143 // specified predicate with names that are the prefixes in Name.  This is
144 // checked by progressively stripping characters off of the name, checking to
145 // see if there options that satisfy the predicate.  If we find one, return it,
146 // otherwise return null.
147 //
148 static Option *getOptionPred(std::string Name, unsigned &Length,
149                              bool (*Pred)(const Option*)) {
150   
151   Option *Op = getOption(Name);
152   if (Op && Pred(Op)) {
153     Length = Name.length();
154     return Op;
155   }
156
157   if (Name.size() == 1) return 0;
158   do {
159     Name.erase(Name.end()-1, Name.end());   // Chop off the last character...
160     Op = getOption(Name);
161
162     // Loop while we haven't found an option and Name still has at least two
163     // characters in it (so that the next iteration will not be the empty
164     // string...
165   } while ((Op == 0 || !Pred(Op)) && Name.size() > 1);
166
167   if (Op && Pred(Op)) {
168     Length = Name.length();
169     return Op;             // Found one!
170   }
171   return 0;                // No option found!
172 }
173
174 static bool RequiresValue(const Option *O) {
175   return O->getNumOccurrencesFlag() == cl::Required ||
176          O->getNumOccurrencesFlag() == cl::OneOrMore;
177 }
178
179 static bool EatsUnboundedNumberOfValues(const Option *O) {
180   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
181          O->getNumOccurrencesFlag() == cl::OneOrMore;
182 }
183
184 /// ParseCStringVector - Break INPUT up wherever one or more
185 /// whitespace characters are found, and store the resulting tokens in
186 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
187 /// using strdup (), so it is the caller's responsibility to free ()
188 /// them later.
189 ///
190 static void ParseCStringVector (std::vector<char *> &output,
191                                 const char *input) {
192   // Characters which will be treated as token separators:
193   static const char *delims = " \v\f\t\r\n";
194
195   std::string work (input);
196   // Skip past any delims at head of input string.
197   size_t pos = work.find_first_not_of (delims);
198   // If the string consists entirely of delims, then exit early.
199   if (pos == std::string::npos) return;
200   // Otherwise, jump forward to beginning of first word.
201   work = work.substr (pos);
202   // Find position of first delimiter.
203   pos = work.find_first_of (delims);
204
205   while (!work.empty() && pos != std::string::npos) {
206     // Everything from 0 to POS is the next word to copy.
207     output.push_back (strdup (work.substr (0,pos).c_str ()));
208     // Is there another word in the string?
209     size_t nextpos = work.find_first_not_of (delims, pos + 1);
210     if (nextpos != std::string::npos) {
211       // Yes? Then remove delims from beginning ...
212       work = work.substr (work.find_first_not_of (delims, pos + 1));
213       // and find the end of the word.
214       pos = work.find_first_of (delims);
215     } else {
216       // No? (Remainder of string is delims.) End the loop.
217       work = "";
218       pos = std::string::npos;
219     }
220   }
221
222   // If `input' ended with non-delim char, then we'll get here with
223   // the last word of `input' in `work'; copy it now.
224   if (!work.empty ()) {
225     output.push_back (strdup (work.c_str ()));
226   }
227 }
228
229 /// ParseEnvironmentOptions - An alternative entry point to the
230 /// CommandLine library, which allows you to read the program's name
231 /// from the caller (as PROGNAME) and its command-line arguments from
232 /// an environment variable (whose name is given in ENVVAR).
233 ///
234 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
235                                  const char *Overview) {
236   // Check args.
237   assert(progName && "Program name not specified");
238   assert(envVar && "Environment variable name missing");
239   
240   // Get the environment variable they want us to parse options out of.
241   const char *envValue = getenv (envVar);
242   if (!envValue)
243     return;
244
245   // Get program's "name", which we wouldn't know without the caller
246   // telling us.
247   std::vector<char *> newArgv;
248   newArgv.push_back (strdup (progName));
249
250   // Parse the value of the environment variable into a "command line"
251   // and hand it off to ParseCommandLineOptions().
252   ParseCStringVector (newArgv, envValue);
253   int newArgc = newArgv.size ();
254   ParseCommandLineOptions (newArgc, &newArgv[0], Overview);
255
256   // Free all the strdup()ed strings.
257   for (std::vector<char *>::iterator i = newArgv.begin (), e = newArgv.end ();
258        i != e; ++i) {
259     free (*i);
260   }
261 }
262
263 /// LookupOption - Lookup the option specified by the specified option on the
264 /// command line.  If there is a value specified (after an equal sign) return
265 /// that as well.
266 static Option *LookupOption(const char *&Arg, const char *&Value) {
267   while (*Arg == '-') ++Arg;  // Eat leading dashes
268   
269   const char *ArgEnd = Arg;
270   while (*ArgEnd && *ArgEnd != '=')
271     ++ArgEnd; // Scan till end of argument name...
272
273   Value = ArgEnd;
274   if (*Value)           // If we have an equals sign...
275     ++Value;            // Advance to value...
276   
277   if (*Arg == 0) return 0;
278
279   // Look up the option.
280   std::map<std::string, Option*> &Opts = getOpts();
281   std::map<std::string, Option*>::iterator I =
282     Opts.find(std::string(Arg, ArgEnd));
283   return (I != Opts.end()) ? I->second : 0;
284 }
285
286 void cl::ParseCommandLineOptions(int &argc, char **argv,
287                                  const char *Overview) {
288   assert((!getOpts().empty() || !getPositionalOpts().empty()) &&
289          "No options specified, or ParseCommandLineOptions called more"
290          " than once!");
291   ProgramName = argv[0];  // Save this away safe and snug
292   ProgramOverview = Overview;
293   bool ErrorParsing = false;
294
295   std::map<std::string, Option*> &Opts = getOpts();
296   std::vector<Option*> &PositionalOpts = getPositionalOpts();
297
298   // Check out the positional arguments to collect information about them.
299   unsigned NumPositionalRequired = 0;
300   Option *ConsumeAfterOpt = 0;
301   if (!PositionalOpts.empty()) {
302     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
303       assert(PositionalOpts.size() > 1 &&
304              "Cannot specify cl::ConsumeAfter without a positional argument!");
305       ConsumeAfterOpt = PositionalOpts[0];
306     }
307
308     // Calculate how many positional values are _required_.
309     bool UnboundedFound = false;
310     for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
311          i != e; ++i) {
312       Option *Opt = PositionalOpts[i];
313       if (RequiresValue(Opt))
314         ++NumPositionalRequired;
315       else if (ConsumeAfterOpt) {
316         // ConsumeAfter cannot be combined with "optional" positional options
317         // unless there is only one positional argument...
318         if (PositionalOpts.size() > 2)
319           ErrorParsing |=
320             Opt->error(" error - this positional option will never be matched, "
321                        "because it does not Require a value, and a "
322                        "cl::ConsumeAfter option is active!");
323       } else if (UnboundedFound && !Opt->ArgStr[0]) {
324         // This option does not "require" a value...  Make sure this option is
325         // not specified after an option that eats all extra arguments, or this
326         // one will never get any!
327         //
328         ErrorParsing |= Opt->error(" error - option can never match, because "
329                                    "another positional argument will match an "
330                                    "unbounded number of values, and this option"
331                                    " does not require a value!");
332       }
333       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
334     }
335   }
336
337   // PositionalVals - A vector of "positional" arguments we accumulate into
338   // the process at the end...
339   //
340   std::vector<std::pair<std::string,unsigned> > PositionalVals;
341
342   // If the program has named positional arguments, and the name has been run
343   // across, keep track of which positional argument was named.  Otherwise put
344   // the positional args into the PositionalVals list...
345   Option *ActivePositionalArg = 0;
346
347   // Loop over all of the arguments... processing them.
348   bool DashDashFound = false;  // Have we read '--'?
349   for (int i = 1; i < argc; ++i) {
350     Option *Handler = 0;
351     const char *Value = "";
352     const char *ArgName = "";
353
354     // Check to see if this is a positional argument.  This argument is
355     // considered to be positional if it doesn't start with '-', if it is "-"
356     // itself, or if we have seen "--" already.
357     //
358     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
359       // Positional argument!
360       if (ActivePositionalArg) {
361         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
362         continue;  // We are done!
363       } else if (!PositionalOpts.empty()) {
364         PositionalVals.push_back(std::make_pair(argv[i],i));
365
366         // All of the positional arguments have been fulfulled, give the rest to
367         // the consume after option... if it's specified...
368         //
369         if (PositionalVals.size() >= NumPositionalRequired && 
370             ConsumeAfterOpt != 0) {
371           for (++i; i < argc; ++i)
372             PositionalVals.push_back(std::make_pair(argv[i],i));
373           break;   // Handle outside of the argument processing loop...
374         }
375
376         // Delay processing positional arguments until the end...
377         continue;
378       }
379     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
380                !DashDashFound) {
381       DashDashFound = true;  // This is the mythical "--"?
382       continue;              // Don't try to process it as an argument itself.
383     } else if (ActivePositionalArg &&
384                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
385       // If there is a positional argument eating options, check to see if this
386       // option is another positional argument.  If so, treat it as an argument,
387       // otherwise feed it to the eating positional.
388       ArgName = argv[i]+1;
389       Handler = LookupOption(ArgName, Value);
390       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
391         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
392         continue;  // We are done!
393       }
394
395     } else {     // We start with a '-', must be an argument...
396       ArgName = argv[i]+1;
397       Handler = LookupOption(ArgName, Value);
398
399       // Check to see if this "option" is really a prefixed or grouped argument.
400       if (Handler == 0) {
401         std::string RealName(ArgName);
402         if (RealName.size() > 1) {
403           unsigned Length = 0;
404           Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping);
405   
406           // If the option is a prefixed option, then the value is simply the
407           // rest of the name...  so fall through to later processing, by
408           // setting up the argument name flags and value fields.
409           //
410           if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
411             Value = ArgName+Length;
412             assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
413                    Opts.find(std::string(ArgName, Value))->second == PGOpt);
414             Handler = PGOpt;
415           } else if (PGOpt) {
416             // This must be a grouped option... handle them now.
417             assert(isGrouping(PGOpt) && "Broken getOptionPred!");
418             
419             do {
420               // Move current arg name out of RealName into RealArgName...
421               std::string RealArgName(RealName.begin(),
422                                       RealName.begin() + Length);
423               RealName.erase(RealName.begin(), RealName.begin() + Length);
424               
425               // Because ValueRequired is an invalid flag for grouped arguments,
426               // we don't need to pass argc/argv in...
427               //
428               assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
429                      "Option can not be cl::Grouping AND cl::ValueRequired!");
430               int Dummy;
431               ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
432                                             "", 0, 0, Dummy);
433               
434               // Get the next grouping option...
435               PGOpt = getOptionPred(RealName, Length, isGrouping);
436             } while (PGOpt && Length != RealName.size());
437             
438             Handler = PGOpt; // Ate all of the options.
439           }
440         }
441       }
442     }
443
444     if (Handler == 0) {
445       std::cerr << ProgramName << ": Unknown command line argument '" << argv[i]
446                 << "'.  Try: '" << argv[0] << " --help'\n";
447       ErrorParsing = true;
448       continue;
449     }
450
451     // Check to see if this option accepts a comma separated list of values.  If
452     // it does, we have to split up the value into multiple values...
453     if (Handler->getMiscFlags() & CommaSeparated) {
454       std::string Val(Value);
455       std::string::size_type Pos = Val.find(',');
456
457       while (Pos != std::string::npos) {
458         // Process the portion before the comma...
459         ErrorParsing |= ProvideOption(Handler, ArgName,
460                                       std::string(Val.begin(),
461                                                   Val.begin()+Pos).c_str(),
462                                       argc, argv, i);
463         // Erase the portion before the comma, AND the comma...
464         Val.erase(Val.begin(), Val.begin()+Pos+1);
465         Value += Pos+1;  // Increment the original value pointer as well...
466
467         // Check for another comma...
468         Pos = Val.find(',');
469       }
470     }
471
472     // If this is a named positional argument, just remember that it is the
473     // active one...
474     if (Handler->getFormattingFlag() == cl::Positional)
475       ActivePositionalArg = Handler;
476     else 
477       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
478   }
479
480   // Check and handle positional arguments now...
481   if (NumPositionalRequired > PositionalVals.size()) {
482     std::cerr << ProgramName 
483               << ": Not enough positional command line arguments specified!\n"
484               << "Must specify at least " << NumPositionalRequired
485               << " positional arguments: See: " << argv[0] << " --help\n";
486     ErrorParsing = true;
487
488
489   } else if (ConsumeAfterOpt == 0) {
490     // Positional args have already been handled if ConsumeAfter is specified...
491     unsigned ValNo = 0, NumVals = PositionalVals.size();
492     for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
493       if (RequiresValue(PositionalOpts[i])) {
494         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 
495                                 PositionalVals[ValNo].second);
496         ValNo++;
497         --NumPositionalRequired;  // We fulfilled our duty...
498       }
499
500       // If we _can_ give this option more arguments, do so now, as long as we
501       // do not give it values that others need.  'Done' controls whether the
502       // option even _WANTS_ any more.
503       //
504       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
505       while (NumVals-ValNo > NumPositionalRequired && !Done) {
506         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
507         case cl::Optional:
508           Done = true;          // Optional arguments want _at most_ one value
509           // FALL THROUGH
510         case cl::ZeroOrMore:    // Zero or more will take all they can get...
511         case cl::OneOrMore:     // One or more will take all they can get...
512           ProvidePositionalOption(PositionalOpts[i],
513                                   PositionalVals[ValNo].first,
514                                   PositionalVals[ValNo].second);
515           ValNo++;
516           break;
517         default:
518           assert(0 && "Internal error, unexpected NumOccurrences flag in "
519                  "positional argument processing!");
520         }
521       }
522     }
523   } else {
524     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
525     unsigned ValNo = 0;
526     for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
527       if (RequiresValue(PositionalOpts[j])) {
528         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
529                                                 PositionalVals[ValNo].first,
530                                                 PositionalVals[ValNo].second);
531         ValNo++;
532       }
533
534     // Handle the case where there is just one positional option, and it's
535     // optional.  In this case, we want to give JUST THE FIRST option to the
536     // positional option and keep the rest for the consume after.  The above
537     // loop would have assigned no values to positional options in this case.
538     //
539     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
540       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
541                                               PositionalVals[ValNo].first,
542                                               PositionalVals[ValNo].second);
543       ValNo++;
544     }
545     
546     // Handle over all of the rest of the arguments to the
547     // cl::ConsumeAfter command line option...
548     for (; ValNo != PositionalVals.size(); ++ValNo)
549       ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
550                                               PositionalVals[ValNo].first,
551                                               PositionalVals[ValNo].second);
552   }
553
554   // Loop over args and make sure all required args are specified!
555   for (std::map<std::string, Option*>::iterator I = Opts.begin(), 
556          E = Opts.end(); I != E; ++I) {
557     switch (I->second->getNumOccurrencesFlag()) {
558     case Required:
559     case OneOrMore:
560       if (I->second->getNumOccurrences() == 0) {
561         I->second->error(" must be specified at least once!");
562         ErrorParsing = true;
563       }
564       // Fall through
565     default:
566       break;
567     }
568   }
569
570   // Free all of the memory allocated to the map.  Command line options may only
571   // be processed once!
572   getOpts().clear();
573   PositionalOpts.clear();
574   MoreHelp().clear();
575
576   // If we had an error processing our arguments, don't let the program execute
577   if (ErrorParsing) exit(1);
578 }
579
580 //===----------------------------------------------------------------------===//
581 // Option Base class implementation
582 //
583
584 bool Option::error(std::string Message, const char *ArgName) {
585   if (ArgName == 0) ArgName = ArgStr;
586   if (ArgName[0] == 0)
587     std::cerr << HelpStr;  // Be nice for positional arguments
588   else
589     std::cerr << ProgramName << ": for the -" << ArgName;
590   std::cerr << " option: " << Message << "\n";
591   return true;
592 }
593
594 bool Option::addOccurrence(unsigned pos, const char *ArgName, const std::string &Value) {
595   NumOccurrences++;   // Increment the number of times we have been seen
596
597   switch (getNumOccurrencesFlag()) {
598   case Optional:
599     if (NumOccurrences > 1)
600       return error(": may only occur zero or one times!", ArgName);
601     break;
602   case Required:
603     if (NumOccurrences > 1)
604       return error(": must occur exactly one time!", ArgName);
605     // Fall through
606   case OneOrMore:
607   case ZeroOrMore:
608   case ConsumeAfter: break;
609   default: return error(": bad num occurrences flag value!");
610   }
611
612   return handleOccurrence(pos, ArgName, Value);
613 }
614
615 // addArgument - Tell the system that this Option subclass will handle all
616 // occurrences of -ArgStr on the command line.
617 //
618 void Option::addArgument(const char *ArgStr) {
619   if (ArgStr[0])
620     AddArgument(ArgStr, this);
621
622   if (getFormattingFlag() == Positional)
623     getPositionalOpts().push_back(this);
624   else if (getNumOccurrencesFlag() == ConsumeAfter) {
625     if (!getPositionalOpts().empty() &&
626         getPositionalOpts().front()->getNumOccurrencesFlag() == ConsumeAfter)
627       error("Cannot specify more than one option with cl::ConsumeAfter!");
628     getPositionalOpts().insert(getPositionalOpts().begin(), this);
629   }
630 }
631
632 void Option::removeArgument(const char *ArgStr) {
633   if (ArgStr[0])
634     RemoveArgument(ArgStr, this);
635
636   if (getFormattingFlag() == Positional) {
637     std::vector<Option*>::iterator I =
638       std::find(getPositionalOpts().begin(), getPositionalOpts().end(), this);
639     assert(I != getPositionalOpts().end() && "Arg not registered!");
640     getPositionalOpts().erase(I);
641   } else if (getNumOccurrencesFlag() == ConsumeAfter) {
642     assert(!getPositionalOpts().empty() && getPositionalOpts()[0] == this &&
643            "Arg not registered correctly!");
644     getPositionalOpts().erase(getPositionalOpts().begin());
645   }
646 }
647
648
649 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
650 // has been specified yet.
651 //
652 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
653   if (O.ValueStr[0] == 0) return DefaultMsg;
654   return O.ValueStr;
655 }
656
657 //===----------------------------------------------------------------------===//
658 // cl::alias class implementation
659 //
660
661 // Return the width of the option tag for printing...
662 unsigned alias::getOptionWidth() const {
663   return std::strlen(ArgStr)+6;
664 }
665
666 // Print out the option for the alias...
667 void alias::printOptionInfo(unsigned GlobalWidth) const {
668   unsigned L = std::strlen(ArgStr);
669   std::cerr << "  -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
670             << HelpStr << "\n";
671 }
672
673
674
675 //===----------------------------------------------------------------------===//
676 // Parser Implementation code...
677 //
678
679 // basic_parser implementation
680 //
681
682 // Return the width of the option tag for printing...
683 unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
684   unsigned Len = std::strlen(O.ArgStr);
685   if (const char *ValName = getValueName())
686     Len += std::strlen(getValueStr(O, ValName))+3;
687
688   return Len + 6;
689 }
690
691 // printOptionInfo - Print out information about this option.  The 
692 // to-be-maintained width is specified.
693 //
694 void basic_parser_impl::printOptionInfo(const Option &O,
695                                         unsigned GlobalWidth) const {
696   std::cerr << "  -" << O.ArgStr;
697
698   if (const char *ValName = getValueName())
699     std::cerr << "=<" << getValueStr(O, ValName) << ">";
700
701   std::cerr << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
702             << O.HelpStr << "\n";
703 }
704
705
706
707
708 // parser<bool> implementation
709 //
710 bool parser<bool>::parse(Option &O, const char *ArgName,
711                          const std::string &Arg, bool &Value) {
712   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 
713       Arg == "1") {
714     Value = true;
715   } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
716     Value = false;
717   } else {
718     return O.error(": '" + Arg +
719                    "' is invalid value for boolean argument! Try 0 or 1");
720   }
721   return false;
722 }
723
724 // parser<int> implementation
725 //
726 bool parser<int>::parse(Option &O, const char *ArgName,
727                         const std::string &Arg, int &Value) {
728   char *End;
729   Value = (int)strtol(Arg.c_str(), &End, 0);
730   if (*End != 0) 
731     return O.error(": '" + Arg + "' value invalid for integer argument!");
732   return false;
733 }
734
735 // parser<unsigned> implementation
736 //
737 bool parser<unsigned>::parse(Option &O, const char *ArgName,
738                              const std::string &Arg, unsigned &Value) {
739   char *End;
740   errno = 0;
741   unsigned long V = strtoul(Arg.c_str(), &End, 0);
742   Value = (unsigned)V;
743   if (((V == ULONG_MAX) && (errno == ERANGE))
744       || (*End != 0)
745       || (Value != V))
746     return O.error(": '" + Arg + "' value invalid for uint argument!");
747   return false;
748 }
749
750 // parser<double>/parser<float> implementation
751 //
752 static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
753   const char *ArgStart = Arg.c_str();
754   char *End;
755   Value = strtod(ArgStart, &End);
756   if (*End != 0) 
757     return O.error(": '" +Arg+ "' value invalid for floating point argument!");
758   return false;
759 }
760
761 bool parser<double>::parse(Option &O, const char *AN,
762                            const std::string &Arg, double &Val) {
763   return parseDouble(O, Arg, Val);
764 }
765
766 bool parser<float>::parse(Option &O, const char *AN,
767                           const std::string &Arg, float &Val) {
768   double dVal;
769   if (parseDouble(O, Arg, dVal))
770     return true;
771   Val = (float)dVal;
772   return false;
773 }
774
775
776
777 // generic_parser_base implementation
778 //
779
780 // findOption - Return the option number corresponding to the specified
781 // argument string.  If the option is not found, getNumOptions() is returned.
782 //
783 unsigned generic_parser_base::findOption(const char *Name) {
784   unsigned i = 0, e = getNumOptions();
785   std::string N(Name);
786
787   while (i != e)
788     if (getOption(i) == N)
789       return i;
790     else
791       ++i;
792   return e;
793 }
794
795
796 // Return the width of the option tag for printing...
797 unsigned generic_parser_base::getOptionWidth(const Option &O) const {
798   if (O.hasArgStr()) {
799     unsigned Size = std::strlen(O.ArgStr)+6;
800     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
801       Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
802     return Size;
803   } else {
804     unsigned BaseSize = 0;
805     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
806       BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
807     return BaseSize;
808   }
809 }
810
811 // printOptionInfo - Print out information about this option.  The 
812 // to-be-maintained width is specified.
813 //
814 void generic_parser_base::printOptionInfo(const Option &O,
815                                           unsigned GlobalWidth) const {
816   if (O.hasArgStr()) {
817     unsigned L = std::strlen(O.ArgStr);
818     std::cerr << "  -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
819               << " - " << O.HelpStr << "\n";
820
821     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
822       unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
823       std::cerr << "    =" << getOption(i) << std::string(NumSpaces, ' ')
824                 << " - " << getDescription(i) << "\n";
825     }
826   } else {
827     if (O.HelpStr[0])
828       std::cerr << "  " << O.HelpStr << "\n"; 
829     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
830       unsigned L = std::strlen(getOption(i));
831       std::cerr << "    -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
832                 << " - " << getDescription(i) << "\n";
833     }
834   }
835 }
836
837
838 //===----------------------------------------------------------------------===//
839 // --help and --help-hidden option implementation
840 //
841
842 namespace {
843
844 class HelpPrinter {
845   unsigned MaxArgLen;
846   const Option *EmptyArg;
847   const bool ShowHidden;
848
849   // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
850   inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
851     return OptPair.second->getOptionHiddenFlag() >= Hidden;
852   }
853   inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
854     return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
855   }
856
857 public:
858   HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
859     EmptyArg = 0;
860   }
861
862   void operator=(bool Value) {
863     if (Value == false) return;
864
865     // Copy Options into a vector so we can sort them as we like...
866     std::vector<std::pair<std::string, Option*> > Options;
867     copy(getOpts().begin(), getOpts().end(), std::back_inserter(Options));
868
869     // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
870     Options.erase(std::remove_if(Options.begin(), Options.end(), 
871                          std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
872                   Options.end());
873
874     // Eliminate duplicate entries in table (from enum flags options, f.e.)
875     {  // Give OptionSet a scope
876       std::set<Option*> OptionSet;
877       for (unsigned i = 0; i != Options.size(); ++i)
878         if (OptionSet.count(Options[i].second) == 0)
879           OptionSet.insert(Options[i].second);   // Add new entry to set
880         else
881           Options.erase(Options.begin()+i--);    // Erase duplicate
882     }
883
884     if (ProgramOverview)
885       std::cerr << "OVERVIEW:" << ProgramOverview << "\n";
886
887     std::cerr << "USAGE: " << ProgramName << " [options]";
888
889     // Print out the positional options...
890     std::vector<Option*> &PosOpts = getPositionalOpts();
891     Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
892     if (!PosOpts.empty() && PosOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
893       CAOpt = PosOpts[0];
894
895     for (unsigned i = CAOpt != 0, e = PosOpts.size(); i != e; ++i) {
896       if (PosOpts[i]->ArgStr[0])
897         std::cerr << " --" << PosOpts[i]->ArgStr;
898       std::cerr << " " << PosOpts[i]->HelpStr;
899     }
900
901     // Print the consume after option info if it exists...
902     if (CAOpt) std::cerr << " " << CAOpt->HelpStr;
903
904     std::cerr << "\n\n";
905
906     // Compute the maximum argument length...
907     MaxArgLen = 0;
908     for (unsigned i = 0, e = Options.size(); i != e; ++i)
909       MaxArgLen = std::max(MaxArgLen, Options[i].second->getOptionWidth());
910
911     std::cerr << "OPTIONS:\n";
912     for (unsigned i = 0, e = Options.size(); i != e; ++i)
913       Options[i].second->printOptionInfo(MaxArgLen);
914
915     // Print any extra help the user has declared.
916     for (std::vector<const char *>::iterator I = MoreHelp().begin(),
917           E = MoreHelp().end(); I != E; ++I)
918       std::cerr << *I;
919     MoreHelp().clear();
920
921     // Halt the program since help information was printed
922     getOpts().clear();  // Don't bother making option dtors remove from map.
923     exit(1);
924   }
925 };
926
927 class VersionPrinter {
928 public:
929   void operator=(bool OptionWasSpecified) {
930     if (OptionWasSpecified) {
931       std::cerr << "Low Level Virtual Machine (" << PACKAGE_NAME << ") " 
932                 << PACKAGE_VERSION << " (see http://llvm.cs.uiuc.edu/)\n";
933       getOpts().clear();  // Don't bother making option dtors remove from map.
934       exit(1);
935     }
936   }
937 };
938
939
940 // Define the two HelpPrinter instances that are used to print out help, or
941 // help-hidden...
942 //
943 HelpPrinter NormalPrinter(false);
944 HelpPrinter HiddenPrinter(true);
945
946 cl::opt<HelpPrinter, true, parser<bool> > 
947 HOp("help", cl::desc("display available options (--help-hidden for more)"),
948     cl::location(NormalPrinter), cl::ValueDisallowed);
949
950 cl::opt<HelpPrinter, true, parser<bool> >
951 HHOp("help-hidden", cl::desc("display all available options"),
952      cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
953
954 // Define the --version option that prints out the LLVM version for the tool
955 VersionPrinter VersionPrinterInstance;
956 cl::opt<VersionPrinter, true, parser<bool> >
957 VersOp("version", cl::desc("display the version"), 
958     cl::location(VersionPrinterInstance), cl::ValueDisallowed);
959
960
961 } // End anonymous namespace
962
963 // Utility function for printing the help message.
964 void cl::PrintHelpMessage() {
965   // This looks weird, but it actually prints the help message. The 
966   // NormalPrinter variable is a HelpPrinter and the help gets printed when
967   // its operator= is invoked. That's because the "normal" usages of the
968   // help printer is to be assigned true/false depending on whether the 
969   // --help option was given or not. Since we're circumventing that we have
970   // to make it look like --help was given, so we assign true.
971   NormalPrinter = true;
972 }