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