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