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