blob: 961dc1fef9238cce3bc96ac6814df5d5e89fbc1d [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "llvm/Support/CommandLine.h"
Sandeep Patel8e51aeb2009-11-11 03:23:46 +000020#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000021#include "llvm/Support/ErrorHandling.h"
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +000022#include "llvm/Support/MemoryBuffer.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/Support/ManagedStatic.h"
Chris Lattner9cb435b2009-08-23 18:09:02 +000024#include "llvm/Support/raw_ostream.h"
Daniel Dunbar9b3edb62009-07-16 02:06:09 +000025#include "llvm/Target/TargetRegistry.h"
Daniel Dunbar401011e2009-09-02 23:52:38 +000026#include "llvm/System/Host.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/System/Path.h"
Chris Lattner9cb435b2009-08-23 18:09:02 +000028#include "llvm/ADT/OwningPtr.h"
Chris Lattner97be18f2009-09-20 05:12:14 +000029#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner717f7732009-09-19 23:59:02 +000030#include "llvm/ADT/SmallString.h"
Chris Lattner97be18f2009-09-20 05:12:14 +000031#include "llvm/ADT/StringMap.h"
Chris Lattner47d05cb2009-09-19 18:55:05 +000032#include "llvm/ADT/Twine.h"
Chris Lattner9cb435b2009-08-23 18:09:02 +000033#include "llvm/Config/config.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#include <cerrno>
Chris Lattner9cb435b2009-08-23 18:09:02 +000035#include <cstdlib>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036using namespace llvm;
37using namespace cl;
38
39//===----------------------------------------------------------------------===//
40// Template instantiations and anchors.
41//
Douglas Gregor58f610e2009-11-25 06:04:18 +000042namespace llvm { namespace cl {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000043TEMPLATE_INSTANTIATION(class basic_parser<bool>);
44TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
45TEMPLATE_INSTANTIATION(class basic_parser<int>);
46TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
47TEMPLATE_INSTANTIATION(class basic_parser<double>);
48TEMPLATE_INSTANTIATION(class basic_parser<float>);
49TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingf0d2d952009-04-29 23:26:16 +000050TEMPLATE_INSTANTIATION(class basic_parser<char>);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051
52TEMPLATE_INSTANTIATION(class opt<unsigned>);
53TEMPLATE_INSTANTIATION(class opt<int>);
54TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingf0d2d952009-04-29 23:26:16 +000055TEMPLATE_INSTANTIATION(class opt<char>);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056TEMPLATE_INSTANTIATION(class opt<bool>);
Douglas Gregor58f610e2009-11-25 06:04:18 +000057} } // end namespace llvm::cl
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058
59void Option::anchor() {}
60void basic_parser_impl::anchor() {}
61void parser<bool>::anchor() {}
62void parser<boolOrDefault>::anchor() {}
63void parser<int>::anchor() {}
64void parser<unsigned>::anchor() {}
65void parser<double>::anchor() {}
66void parser<float>::anchor() {}
67void parser<std::string>::anchor() {}
Bill Wendlingf0d2d952009-04-29 23:26:16 +000068void parser<char>::anchor() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069
70//===----------------------------------------------------------------------===//
71
72// Globals for name and overview of program. Program name is not a string to
73// avoid static ctor/dtor issues.
74static char ProgramName[80] = "<premain>";
75static const char *ProgramOverview = 0;
76
77// This collects additional help to be printed.
78static ManagedStatic<std::vector<const char*> > MoreHelp;
79
80extrahelp::extrahelp(const char *Help)
81 : morehelp(Help) {
82 MoreHelp->push_back(Help);
83}
84
85static bool OptionListChanged = false;
86
87// MarkOptionsChanged - Internal helper function.
88void cl::MarkOptionsChanged() {
89 OptionListChanged = true;
90}
91
92/// RegisteredOptionList - This is the list of the command line options that
93/// have statically constructed themselves.
94static Option *RegisteredOptionList = 0;
95
96void Option::addArgument() {
97 assert(NextRegistered == 0 && "argument multiply registered!");
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +000098
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099 NextRegistered = RegisteredOptionList;
100 RegisteredOptionList = this;
101 MarkOptionsChanged();
102}
103
104
105//===----------------------------------------------------------------------===//
106// Basic, shared command line option processing machinery.
107//
108
109/// GetOptionInfo - Scan the list of registered options, turning them into data
110/// structures that are easier to handle.
Chris Lattner3d211b22009-09-20 06:18:38 +0000111static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
112 SmallVectorImpl<Option*> &SinkOpts,
Benjamin Kramer48086602009-09-19 10:01:45 +0000113 StringMap<Option*> &OptionsMap) {
Chris Lattnere4a6ac92009-09-20 06:21:43 +0000114 SmallVector<const char*, 16> OptionNames;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115 Option *CAOpt = 0; // The ConsumeAfter option if it exists.
116 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
117 // If this option wants to handle multiple option names, get the full set.
118 // This handles enum options like "-O1 -O2" etc.
119 O->getExtraOptionNames(OptionNames);
120 if (O->ArgStr[0])
121 OptionNames.push_back(O->ArgStr);
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000122
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 // Handle named options.
Evan Cheng591bfc82008-05-05 18:30:58 +0000124 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125 // Add argument to the argument map!
Benjamin Kramer48086602009-09-19 10:01:45 +0000126 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
Benjamin Kramer32dd0232009-08-23 10:01:13 +0000127 errs() << ProgramName << ": CommandLine Error: Argument '"
Matthijs Kooijman5e270092008-05-30 13:26:11 +0000128 << OptionNames[i] << "' defined more than once!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129 }
130 }
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000131
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 OptionNames.clear();
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000133
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134 // Remember information about positional options.
135 if (O->getFormattingFlag() == cl::Positional)
136 PositionalOpts.push_back(O);
Dan Gohmane411a2d2008-02-23 01:55:25 +0000137 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Anton Korobeynikov6288e922008-02-20 12:38:07 +0000138 SinkOpts.push_back(O);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
140 if (CAOpt)
141 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
142 CAOpt = O;
143 }
144 }
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000145
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 if (CAOpt)
147 PositionalOpts.push_back(CAOpt);
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000148
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149 // Make sure that they are in order of registration not backwards.
150 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
151}
152
153
154/// LookupOption - Lookup the option specified by the specified option on the
155/// command line. If there is a value specified (after an equal sign) return
Chris Lattnerd516d022009-09-20 05:03:30 +0000156/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner0a5bcfc2009-09-20 02:02:24 +0000157static Option *LookupOption(StringRef &Arg, StringRef &Value,
158 const StringMap<Option*> &OptionsMap) {
Chris Lattner0a5bcfc2009-09-20 02:02:24 +0000159 // Reject all dashes.
160 if (Arg.empty()) return 0;
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000161
Chris Lattner0a5bcfc2009-09-20 02:02:24 +0000162 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000163
Chris Lattnerd8168dd2009-09-20 01:53:12 +0000164 // If we have an equals sign, remember the value.
Chris Lattnerd516d022009-09-20 05:03:30 +0000165 if (EqualPos == StringRef::npos) {
166 // Look up the option.
167 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
168 return I != OptionsMap.end() ? I->second : 0;
Chris Lattner0a5bcfc2009-09-20 02:02:24 +0000169 }
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000170
Chris Lattnerd516d022009-09-20 05:03:30 +0000171 // If the argument before the = is a valid option name, we match. If not,
172 // return Arg unmolested.
173 StringMap<Option*>::const_iterator I =
174 OptionsMap.find(Arg.substr(0, EqualPos));
175 if (I == OptionsMap.end()) return 0;
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000176
Chris Lattnerd516d022009-09-20 05:03:30 +0000177 Value = Arg.substr(EqualPos+1);
178 Arg = Arg.substr(0, EqualPos);
179 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180}
181
Mikhail Glushenkovc8cb0d92009-11-20 17:23:17 +0000182/// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
183/// does special handling of cl::CommaSeparated options.
184static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
185 StringRef ArgName,
186 StringRef Value, bool MultiArg = false)
187{
188 // Check to see if this option accepts a comma separated list of values. If
189 // it does, we have to split up the value into multiple values.
190 if (Handler->getMiscFlags() & CommaSeparated) {
191 StringRef Val(Value);
192 StringRef::size_type Pos = Val.find(',');
Chris Lattnerd516d022009-09-20 05:03:30 +0000193
Mikhail Glushenkovc8cb0d92009-11-20 17:23:17 +0000194 while (Pos != StringRef::npos) {
195 // Process the portion before the comma.
196 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
197 return true;
198 // Erase the portion before the comma, AND the comma.
199 Val = Val.substr(Pos+1);
200 Value.substr(Pos+1); // Increment the original value pointer as well.
201 // Check for another comma.
202 Pos = Val.find(',');
203 }
204
205 Value = Val;
206 }
207
208 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
209 return true;
210
211 return false;
212}
Chris Lattnerd516d022009-09-20 05:03:30 +0000213
Chris Lattner4627c682009-09-20 01:49:31 +0000214/// ProvideOption - For Value, this differentiates between an empty value ("")
215/// and a null value (StringRef()). The later is accepted for arguments that
216/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner157229d2009-09-20 00:40:49 +0000217static inline bool ProvideOption(Option *Handler, StringRef ArgName,
Chris Lattner4627c682009-09-20 01:49:31 +0000218 StringRef Value, int argc, char **argv,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 int &i) {
Mikhail Glushenkovad6fc7f2009-01-16 22:54:19 +0000220 // Is this a multi-argument option?
221 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
222
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 // Enforce value requirements
224 switch (Handler->getValueExpectedFlag()) {
225 case ValueRequired:
Chris Lattner4627c682009-09-20 01:49:31 +0000226 if (Value.data() == 0) { // No value specified?
Chris Lattner747e01e2009-09-20 00:07:40 +0000227 if (i+1 >= argc)
Benjamin Kramer9164c672009-08-02 12:13:02 +0000228 return Handler->error("requires a value!");
Chris Lattner747e01e2009-09-20 00:07:40 +0000229 // Steal the next argument, like for '-o filename'
230 Value = argv[++i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 }
232 break;
233 case ValueDisallowed:
Mikhail Glushenkovad6fc7f2009-01-16 22:54:19 +0000234 if (NumAdditionalVals > 0)
Benjamin Kramer9164c672009-08-02 12:13:02 +0000235 return Handler->error("multi-valued option specified"
Chris Lattner747e01e2009-09-20 00:07:40 +0000236 " with ValueDisallowed modifier!");
Mikhail Glushenkovad6fc7f2009-01-16 22:54:19 +0000237
Chris Lattner4627c682009-09-20 01:49:31 +0000238 if (Value.data())
Benjamin Kramer9164c672009-08-02 12:13:02 +0000239 return Handler->error("does not allow a value! '" +
Chris Lattner47d05cb2009-09-19 18:55:05 +0000240 Twine(Value) + "' specified.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241 break;
242 case ValueOptional:
243 break;
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000244
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 default:
Benjamin Kramer32dd0232009-08-23 10:01:13 +0000246 errs() << ProgramName
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 << ": Bad ValueMask flag! CommandLine usage error:"
248 << Handler->getValueExpectedFlag() << "\n";
Edwin Törökbd448e32009-07-14 16:55:14 +0000249 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 }
251
Mikhail Glushenkovad6fc7f2009-01-16 22:54:19 +0000252 // If this isn't a multi-arg option, just run the handler.
Chris Lattner47d05cb2009-09-19 18:55:05 +0000253 if (NumAdditionalVals == 0)
Mikhail Glushenkovc8cb0d92009-11-20 17:23:17 +0000254 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
Chris Lattner47d05cb2009-09-19 18:55:05 +0000255
Mikhail Glushenkovad6fc7f2009-01-16 22:54:19 +0000256 // If it is, run the handle several times.
Chris Lattner47d05cb2009-09-19 18:55:05 +0000257 bool MultiArg = false;
Mikhail Glushenkovad6fc7f2009-01-16 22:54:19 +0000258
Chris Lattner4627c682009-09-20 01:49:31 +0000259 if (Value.data()) {
Mikhail Glushenkovc8cb0d92009-11-20 17:23:17 +0000260 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
Chris Lattner47d05cb2009-09-19 18:55:05 +0000261 return true;
262 --NumAdditionalVals;
263 MultiArg = true;
Mikhail Glushenkovad6fc7f2009-01-16 22:54:19 +0000264 }
Chris Lattner47d05cb2009-09-19 18:55:05 +0000265
266 while (NumAdditionalVals > 0) {
Chris Lattner47d05cb2009-09-19 18:55:05 +0000267 if (i+1 >= argc)
268 return Handler->error("not enough values!");
269 Value = argv[++i];
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000270
Mikhail Glushenkovc8cb0d92009-11-20 17:23:17 +0000271 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
Chris Lattner47d05cb2009-09-19 18:55:05 +0000272 return true;
273 MultiArg = true;
274 --NumAdditionalVals;
275 }
276 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277}
278
Chris Lattner747e01e2009-09-20 00:07:40 +0000279static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 int Dummy = i;
Chris Lattner4627c682009-09-20 01:49:31 +0000281 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282}
283
284
285// Option predicates...
286static inline bool isGrouping(const Option *O) {
287 return O->getFormattingFlag() == cl::Grouping;
288}
289static inline bool isPrefixedOrGrouping(const Option *O) {
290 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
291}
292
293// getOptionPred - Check to see if there are any options that satisfy the
294// specified predicate with names that are the prefixes in Name. This is
295// checked by progressively stripping characters off of the name, checking to
296// see if there options that satisfy the predicate. If we find one, return it,
297// otherwise return null.
298//
Chris Lattner157229d2009-09-20 00:40:49 +0000299static Option *getOptionPred(StringRef Name, size_t &Length,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300 bool (*Pred)(const Option*),
Chris Lattnerd516d022009-09-20 05:03:30 +0000301 const StringMap<Option*> &OptionsMap) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302
Chris Lattnerd516d022009-09-20 05:03:30 +0000303 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304
Chris Lattnerd516d022009-09-20 05:03:30 +0000305 // Loop while we haven't found an option and Name still has at least two
306 // characters in it (so that the next iteration will not be the empty
307 // string.
308 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Lattner157229d2009-09-20 00:40:49 +0000309 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310 OMI = OptionsMap.find(Name);
Chris Lattnerd516d022009-09-20 05:03:30 +0000311 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312
313 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner157229d2009-09-20 00:40:49 +0000314 Length = Name.size();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 return OMI->second; // Found one!
316 }
317 return 0; // No option found!
318}
319
Chris Lattnerd516d022009-09-20 05:03:30 +0000320/// HandlePrefixedOrGroupedOption - The specified argument string (which started
321/// with at least one '-') does not fully match an available option. Check to
322/// see if this is a prefix or grouped option. If so, split arg into output an
323/// Arg/Value pair and return the Option to parse it with.
324static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
325 bool &ErrorParsing,
326 const StringMap<Option*> &OptionsMap) {
327 if (Arg.size() == 1) return 0;
328
329 // Do the lookup!
330 size_t Length = 0;
331 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
332 if (PGOpt == 0) return 0;
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000333
Chris Lattnerd516d022009-09-20 05:03:30 +0000334 // If the option is a prefixed option, then the value is simply the
335 // rest of the name... so fall through to later processing, by
336 // setting up the argument name flags and value fields.
337 if (PGOpt->getFormattingFlag() == cl::Prefix) {
338 Value = Arg.substr(Length);
339 Arg = Arg.substr(0, Length);
340 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
341 return PGOpt;
342 }
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000343
Chris Lattnerd516d022009-09-20 05:03:30 +0000344 // This must be a grouped option... handle them now. Grouping options can't
345 // have values.
346 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000347
Chris Lattnerd516d022009-09-20 05:03:30 +0000348 do {
349 // Move current arg name out of Arg into OneArgName.
350 StringRef OneArgName = Arg.substr(0, Length);
351 Arg = Arg.substr(Length);
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000352
Chris Lattnerd516d022009-09-20 05:03:30 +0000353 // Because ValueRequired is an invalid flag for grouped arguments,
354 // we don't need to pass argc/argv in.
355 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
356 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsbc576902010-01-09 08:30:33 +0000357 int Dummy = 0;
Chris Lattnerd516d022009-09-20 05:03:30 +0000358 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
359 StringRef(), 0, 0, Dummy);
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000360
Chris Lattnerd516d022009-09-20 05:03:30 +0000361 // Get the next grouping option.
362 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
363 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000364
Chris Lattnerd516d022009-09-20 05:03:30 +0000365 // Return the last option with Arg cut down to just the last one.
366 return PGOpt;
367}
368
369
370
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371static bool RequiresValue(const Option *O) {
372 return O->getNumOccurrencesFlag() == cl::Required ||
373 O->getNumOccurrencesFlag() == cl::OneOrMore;
374}
375
376static bool EatsUnboundedNumberOfValues(const Option *O) {
377 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
378 O->getNumOccurrencesFlag() == cl::OneOrMore;
379}
380
381/// ParseCStringVector - Break INPUT up wherever one or more
382/// whitespace characters are found, and store the resulting tokens in
383/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
Chris Lattner2ee921e2009-09-20 01:11:23 +0000384/// using strdup(), so it is the caller's responsibility to free()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385/// them later.
386///
Chris Lattnerc8b70662009-09-24 05:38:36 +0000387static void ParseCStringVector(std::vector<char *> &OutputVector,
388 const char *Input) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389 // Characters which will be treated as token separators:
Chris Lattnerc8b70662009-09-24 05:38:36 +0000390 StringRef Delims = " \v\f\t\r\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000391
Chris Lattnerc8b70662009-09-24 05:38:36 +0000392 StringRef WorkStr(Input);
393 while (!WorkStr.empty()) {
394 // If the first character is a delimiter, strip them off.
395 if (Delims.find(WorkStr[0]) != StringRef::npos) {
396 size_t Pos = WorkStr.find_first_not_of(Delims);
397 if (Pos == StringRef::npos) Pos = WorkStr.size();
398 WorkStr = WorkStr.substr(Pos);
399 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400 }
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000401
Chris Lattnerc8b70662009-09-24 05:38:36 +0000402 // Find position of first delimiter.
403 size_t Pos = WorkStr.find_first_of(Delims);
404 if (Pos == StringRef::npos) Pos = WorkStr.size();
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000405
Chris Lattnerc8b70662009-09-24 05:38:36 +0000406 // Everything from 0 to Pos is the next word to copy.
407 char *NewStr = (char*)malloc(Pos+1);
408 memcpy(NewStr, WorkStr.data(), Pos);
409 NewStr[Pos] = 0;
410 OutputVector.push_back(NewStr);
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000411
Chris Lattnerc8b70662009-09-24 05:38:36 +0000412 WorkStr = WorkStr.substr(Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414}
415
416/// ParseEnvironmentOptions - An alternative entry point to the
417/// CommandLine library, which allows you to read the program's name
418/// from the caller (as PROGNAME) and its command-line arguments from
419/// an environment variable (whose name is given in ENVVAR).
420///
421void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000422 const char *Overview, bool ReadResponseFiles) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 // Check args.
424 assert(progName && "Program name not specified");
425 assert(envVar && "Environment variable name missing");
426
427 // Get the environment variable they want us to parse options out of.
428 const char *envValue = getenv(envVar);
429 if (!envValue)
430 return;
431
432 // Get program's "name", which we wouldn't know without the caller
433 // telling us.
434 std::vector<char*> newArgv;
435 newArgv.push_back(strdup(progName));
436
437 // Parse the value of the environment variable into a "command line"
438 // and hand it off to ParseCommandLineOptions().
439 ParseCStringVector(newArgv, envValue);
Evan Cheng591bfc82008-05-05 18:30:58 +0000440 int newArgc = static_cast<int>(newArgv.size());
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000441 ParseCommandLineOptions(newArgc, &newArgv[0], Overview, ReadResponseFiles);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442
443 // Free all the strdup()ed strings.
444 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
445 i != e; ++i)
Chris Lattner2ee921e2009-09-20 01:11:23 +0000446 free(*i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000447}
448
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000449
450/// ExpandResponseFiles - Copy the contents of argv into newArgv,
451/// substituting the contents of the response files for the arguments
452/// of type @file.
Chris Lattnerd516d022009-09-20 05:03:30 +0000453static void ExpandResponseFiles(unsigned argc, char** argv,
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000454 std::vector<char*>& newArgv) {
Chris Lattnerd516d022009-09-20 05:03:30 +0000455 for (unsigned i = 1; i != argc; ++i) {
456 char *arg = argv[i];
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000457
458 if (arg[0] == '@') {
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000459 sys::PathWithStatus respFile(++arg);
460
461 // Check that the response file is not empty (mmap'ing empty
462 // files can be problematic).
463 const sys::FileStatus *FileStat = respFile.getFileStatus();
Mikhail Glushenkov0215ec22009-01-21 13:14:02 +0000464 if (FileStat && FileStat->getSize() != 0) {
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000465
Mikhail Glushenkov0215ec22009-01-21 13:14:02 +0000466 // Mmap the response file into memory.
467 OwningPtr<MemoryBuffer>
468 respFilePtr(MemoryBuffer::getFile(respFile.c_str()));
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000469
Mikhail Glushenkov0215ec22009-01-21 13:14:02 +0000470 // If we could open the file, parse its contents, otherwise
471 // pass the @file option verbatim.
Mikhail Glushenkovc591ed142009-01-28 03:46:22 +0000472
473 // TODO: we should also support recursive loading of response files,
474 // since this is how gcc behaves. (From their man page: "The file may
475 // itself contain additional @file options; any such options will be
476 // processed recursively.")
477
Mikhail Glushenkov0215ec22009-01-21 13:14:02 +0000478 if (respFilePtr != 0) {
479 ParseCStringVector(newArgv, respFilePtr->getBufferStart());
480 continue;
481 }
482 }
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000483 }
Mikhail Glushenkov0215ec22009-01-21 13:14:02 +0000484 newArgv.push_back(strdup(arg));
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000485 }
486}
487
Dan Gohman61db06b2007-10-09 16:04:57 +0000488void cl::ParseCommandLineOptions(int argc, char **argv,
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000489 const char *Overview, bool ReadResponseFiles) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000490 // Process all registered options.
Chris Lattner3d211b22009-09-20 06:18:38 +0000491 SmallVector<Option*, 4> PositionalOpts;
492 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer48086602009-09-19 10:01:45 +0000493 StringMap<Option*> Opts;
Anton Korobeynikov6288e922008-02-20 12:38:07 +0000494 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000495
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496 assert((!Opts.empty() || !PositionalOpts.empty()) &&
497 "No options specified!");
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000498
499 // Expand response files.
500 std::vector<char*> newArgv;
501 if (ReadResponseFiles) {
502 newArgv.push_back(strdup(argv[0]));
503 ExpandResponseFiles(argc, argv, newArgv);
504 argv = &newArgv[0];
Evan Cheng591bfc82008-05-05 18:30:58 +0000505 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000506 }
507
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000508 // Copy the program name into ProgName, making sure not to overflow it.
509 std::string ProgName = sys::Path(argv[0]).getLast();
Benjamin Kramerd65ad3c62010-01-28 18:04:38 +0000510 size_t Len = std::min(ProgName.size(), size_t(79));
511 memcpy(ProgramName, ProgName.data(), Len);
512 ProgramName[Len] = '\0';
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000513
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 ProgramOverview = Overview;
515 bool ErrorParsing = false;
516
517 // Check out the positional arguments to collect information about them.
518 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000519
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520 // Determine whether or not there are an unlimited number of positionals
521 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000522
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523 Option *ConsumeAfterOpt = 0;
524 if (!PositionalOpts.empty()) {
525 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
526 assert(PositionalOpts.size() > 1 &&
527 "Cannot specify cl::ConsumeAfter without a positional argument!");
528 ConsumeAfterOpt = PositionalOpts[0];
529 }
530
531 // Calculate how many positional values are _required_.
532 bool UnboundedFound = false;
Evan Cheng591bfc82008-05-05 18:30:58 +0000533 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 i != e; ++i) {
535 Option *Opt = PositionalOpts[i];
536 if (RequiresValue(Opt))
537 ++NumPositionalRequired;
538 else if (ConsumeAfterOpt) {
539 // ConsumeAfter cannot be combined with "optional" positional options
540 // unless there is only one positional argument...
541 if (PositionalOpts.size() > 2)
542 ErrorParsing |=
Benjamin Kramer9164c672009-08-02 12:13:02 +0000543 Opt->error("error - this positional option will never be matched, "
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544 "because it does not Require a value, and a "
545 "cl::ConsumeAfter option is active!");
546 } else if (UnboundedFound && !Opt->ArgStr[0]) {
547 // This option does not "require" a value... Make sure this option is
548 // not specified after an option that eats all extra arguments, or this
549 // one will never get any!
550 //
Benjamin Kramer9164c672009-08-02 12:13:02 +0000551 ErrorParsing |= Opt->error("error - option can never match, because "
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552 "another positional argument will match an "
553 "unbounded number of values, and this option"
554 " does not require a value!");
555 }
556 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
557 }
558 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
559 }
560
561 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattner747e01e2009-09-20 00:07:40 +0000562 // the process at the end.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000563 //
Chris Lattner747e01e2009-09-20 00:07:40 +0000564 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565
566 // If the program has named positional arguments, and the name has been run
567 // across, keep track of which positional argument was named. Otherwise put
568 // the positional args into the PositionalVals list...
569 Option *ActivePositionalArg = 0;
570
571 // Loop over all of the arguments... processing them.
572 bool DashDashFound = false; // Have we read '--'?
573 for (int i = 1; i < argc; ++i) {
574 Option *Handler = 0;
Chris Lattnerd8168dd2009-09-20 01:53:12 +0000575 StringRef Value;
Chris Lattner0a5bcfc2009-09-20 02:02:24 +0000576 StringRef ArgName = "";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577
578 // If the option list changed, this means that some command line
579 // option has just been registered or deregistered. This can occur in
580 // response to things like -load, etc. If this happens, rescan the options.
581 if (OptionListChanged) {
582 PositionalOpts.clear();
Anton Korobeynikov6288e922008-02-20 12:38:07 +0000583 SinkOpts.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000584 Opts.clear();
Anton Korobeynikov6288e922008-02-20 12:38:07 +0000585 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 OptionListChanged = false;
587 }
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000588
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 // Check to see if this is a positional argument. This argument is
590 // considered to be positional if it doesn't start with '-', if it is "-"
591 // itself, or if we have seen "--" already.
592 //
593 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
594 // Positional argument!
595 if (ActivePositionalArg) {
596 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
597 continue; // We are done!
Chris Lattner157229d2009-09-20 00:40:49 +0000598 }
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000599
Chris Lattner157229d2009-09-20 00:40:49 +0000600 if (!PositionalOpts.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601 PositionalVals.push_back(std::make_pair(argv[i],i));
602
603 // All of the positional arguments have been fulfulled, give the rest to
604 // the consume after option... if it's specified...
605 //
606 if (PositionalVals.size() >= NumPositionalRequired &&
607 ConsumeAfterOpt != 0) {
608 for (++i; i < argc; ++i)
609 PositionalVals.push_back(std::make_pair(argv[i],i));
610 break; // Handle outside of the argument processing loop...
611 }
612
613 // Delay processing positional arguments until the end...
614 continue;
615 }
616 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
617 !DashDashFound) {
618 DashDashFound = true; // This is the mythical "--"?
619 continue; // Don't try to process it as an argument itself.
620 } else if (ActivePositionalArg &&
621 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
622 // If there is a positional argument eating options, check to see if this
623 // option is another positional argument. If so, treat it as an argument,
624 // otherwise feed it to the eating positional.
625 ArgName = argv[i]+1;
Chris Lattnerd516d022009-09-20 05:03:30 +0000626 // Eat leading dashes.
627 while (!ArgName.empty() && ArgName[0] == '-')
628 ArgName = ArgName.substr(1);
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000629
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 Handler = LookupOption(ArgName, Value, Opts);
631 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
632 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
633 continue; // We are done!
634 }
635
Chris Lattner157229d2009-09-20 00:40:49 +0000636 } else { // We start with a '-', must be an argument.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637 ArgName = argv[i]+1;
Chris Lattnerd516d022009-09-20 05:03:30 +0000638 // Eat leading dashes.
639 while (!ArgName.empty() && ArgName[0] == '-')
640 ArgName = ArgName.substr(1);
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000641
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 Handler = LookupOption(ArgName, Value, Opts);
643
644 // Check to see if this "option" is really a prefixed or grouped argument.
Chris Lattnerd516d022009-09-20 05:03:30 +0000645 if (Handler == 0)
646 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
647 ErrorParsing, Opts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 }
649
650 if (Handler == 0) {
Anton Korobeynikov6288e922008-02-20 12:38:07 +0000651 if (SinkOpts.empty()) {
Benjamin Kramer32dd0232009-08-23 10:01:13 +0000652 errs() << ProgramName << ": Unknown command line argument '"
Anton Korobeynikov6288e922008-02-20 12:38:07 +0000653 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
654 ErrorParsing = true;
655 } else {
Chris Lattner3d211b22009-09-20 06:18:38 +0000656 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
Anton Korobeynikov6288e922008-02-20 12:38:07 +0000657 E = SinkOpts.end(); I != E ; ++I)
658 (*I)->addOccurrence(i, "", argv[i]);
659 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660 continue;
661 }
662
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663 // If this is a named positional argument, just remember that it is the
664 // active one...
665 if (Handler->getFormattingFlag() == cl::Positional)
666 ActivePositionalArg = Handler;
Chris Lattner4627c682009-09-20 01:49:31 +0000667 else
Chris Lattnerd8168dd2009-09-20 01:53:12 +0000668 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 }
670
671 // Check and handle positional arguments now...
672 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramer32dd0232009-08-23 10:01:13 +0000673 errs() << ProgramName
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000674 << ": Not enough positional command line arguments specified!\n"
675 << "Must specify at least " << NumPositionalRequired
676 << " positional arguments: See: " << argv[0] << " --help\n";
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000677
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678 ErrorParsing = true;
679 } else if (!HasUnlimitedPositionals
680 && PositionalVals.size() > PositionalOpts.size()) {
Benjamin Kramer32dd0232009-08-23 10:01:13 +0000681 errs() << ProgramName
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 << ": Too many positional arguments specified!\n"
683 << "Can specify at most " << PositionalOpts.size()
684 << " positional arguments: See: " << argv[0] << " --help\n";
685 ErrorParsing = true;
686
687 } else if (ConsumeAfterOpt == 0) {
Chris Lattnerd516d022009-09-20 05:03:30 +0000688 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng591bfc82008-05-05 18:30:58 +0000689 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
690 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691 if (RequiresValue(PositionalOpts[i])) {
692 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
693 PositionalVals[ValNo].second);
694 ValNo++;
695 --NumPositionalRequired; // We fulfilled our duty...
696 }
697
698 // If we _can_ give this option more arguments, do so now, as long as we
699 // do not give it values that others need. 'Done' controls whether the
700 // option even _WANTS_ any more.
701 //
702 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
703 while (NumVals-ValNo > NumPositionalRequired && !Done) {
704 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
705 case cl::Optional:
706 Done = true; // Optional arguments want _at most_ one value
707 // FALL THROUGH
708 case cl::ZeroOrMore: // Zero or more will take all they can get...
709 case cl::OneOrMore: // One or more will take all they can get...
710 ProvidePositionalOption(PositionalOpts[i],
711 PositionalVals[ValNo].first,
712 PositionalVals[ValNo].second);
713 ValNo++;
714 break;
715 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000716 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 "positional argument processing!");
718 }
719 }
720 }
721 } else {
722 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
723 unsigned ValNo = 0;
Evan Cheng591bfc82008-05-05 18:30:58 +0000724 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 if (RequiresValue(PositionalOpts[j])) {
726 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
727 PositionalVals[ValNo].first,
728 PositionalVals[ValNo].second);
729 ValNo++;
730 }
731
732 // Handle the case where there is just one positional option, and it's
733 // optional. In this case, we want to give JUST THE FIRST option to the
734 // positional option and keep the rest for the consume after. The above
735 // loop would have assigned no values to positional options in this case.
736 //
737 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
738 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
739 PositionalVals[ValNo].first,
740 PositionalVals[ValNo].second);
741 ValNo++;
742 }
743
744 // Handle over all of the rest of the arguments to the
745 // cl::ConsumeAfter command line option...
746 for (; ValNo != PositionalVals.size(); ++ValNo)
747 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
748 PositionalVals[ValNo].first,
749 PositionalVals[ValNo].second);
750 }
751
752 // Loop over args and make sure all required args are specified!
Benjamin Kramer48086602009-09-19 10:01:45 +0000753 for (StringMap<Option*>::iterator I = Opts.begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 E = Opts.end(); I != E; ++I) {
755 switch (I->second->getNumOccurrencesFlag()) {
756 case Required:
757 case OneOrMore:
758 if (I->second->getNumOccurrences() == 0) {
Benjamin Kramer9164c672009-08-02 12:13:02 +0000759 I->second->error("must be specified at least once!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760 ErrorParsing = true;
761 }
762 // Fall through
763 default:
764 break;
765 }
766 }
767
768 // Free all of the memory allocated to the map. Command line options may only
769 // be processed once!
770 Opts.clear();
771 PositionalOpts.clear();
772 MoreHelp->clear();
773
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000774 // Free the memory allocated by ExpandResponseFiles.
775 if (ReadResponseFiles) {
776 // Free all the strdup()ed strings.
777 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
778 i != e; ++i)
Chris Lattnera77caae2009-09-20 07:16:54 +0000779 free(*i);
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000780 }
781
David Greene67c70252010-01-05 01:29:03 +0000782 DEBUG(dbgs() << "Args: ";
Sandeep Patel8e51aeb2009-11-11 03:23:46 +0000783 for (int i = 0; i < argc; ++i)
David Greene67c70252010-01-05 01:29:03 +0000784 dbgs() << argv[i] << ' ';
785 dbgs() << '\n';
Sandeep Patel8e51aeb2009-11-11 03:23:46 +0000786 );
787
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 // If we had an error processing our arguments, don't let the program execute
789 if (ErrorParsing) exit(1);
790}
791
792//===----------------------------------------------------------------------===//
793// Option Base class implementation
794//
795
Chris Lattner157229d2009-09-20 00:40:49 +0000796bool Option::error(const Twine &Message, StringRef ArgName) {
797 if (ArgName.data() == 0) ArgName = ArgStr;
798 if (ArgName.empty())
Benjamin Kramer32dd0232009-08-23 10:01:13 +0000799 errs() << HelpStr; // Be nice for positional arguments
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 else
Benjamin Kramer32dd0232009-08-23 10:01:13 +0000801 errs() << ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +0000802
Benjamin Kramer32dd0232009-08-23 10:01:13 +0000803 errs() << " option: " << Message << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804 return true;
805}
806
Chris Lattner157229d2009-09-20 00:40:49 +0000807bool Option::addOccurrence(unsigned pos, StringRef ArgName,
Chris Lattner47d05cb2009-09-19 18:55:05 +0000808 StringRef Value, bool MultiArg) {
Mikhail Glushenkovad6fc7f2009-01-16 22:54:19 +0000809 if (!MultiArg)
810 NumOccurrences++; // Increment the number of times we have been seen
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811
812 switch (getNumOccurrencesFlag()) {
813 case Optional:
814 if (NumOccurrences > 1)
Benjamin Kramer9164c672009-08-02 12:13:02 +0000815 return error("may only occur zero or one times!", ArgName);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 break;
817 case Required:
818 if (NumOccurrences > 1)
Benjamin Kramer9164c672009-08-02 12:13:02 +0000819 return error("must occur exactly one time!", ArgName);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 // Fall through
821 case OneOrMore:
822 case ZeroOrMore:
823 case ConsumeAfter: break;
Benjamin Kramer9164c672009-08-02 12:13:02 +0000824 default: return error("bad num occurrences flag value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 }
826
827 return handleOccurrence(pos, ArgName, Value);
828}
829
830
831// getValueStr - Get the value description string, using "DefaultMsg" if nothing
832// has been specified yet.
833//
834static const char *getValueStr(const Option &O, const char *DefaultMsg) {
835 if (O.ValueStr[0] == 0) return DefaultMsg;
836 return O.ValueStr;
837}
838
839//===----------------------------------------------------------------------===//
840// cl::alias class implementation
841//
842
843// Return the width of the option tag for printing...
Evan Cheng591bfc82008-05-05 18:30:58 +0000844size_t alias::getOptionWidth() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845 return std::strlen(ArgStr)+6;
846}
847
848// Print out the option for the alias.
Evan Cheng591bfc82008-05-05 18:30:58 +0000849void alias::printOptionInfo(size_t GlobalWidth) const {
850 size_t L = std::strlen(ArgStr);
Chris Lattnerd516d022009-09-20 05:03:30 +0000851 errs() << " -" << ArgStr;
852 errs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000853}
854
855
856
857//===----------------------------------------------------------------------===//
858// Parser Implementation code...
859//
860
861// basic_parser implementation
862//
863
864// Return the width of the option tag for printing...
Evan Cheng591bfc82008-05-05 18:30:58 +0000865size_t basic_parser_impl::getOptionWidth(const Option &O) const {
866 size_t Len = std::strlen(O.ArgStr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867 if (const char *ValName = getValueName())
868 Len += std::strlen(getValueStr(O, ValName))+3;
869
870 return Len + 6;
871}
872
873// printOptionInfo - Print out information about this option. The
874// to-be-maintained width is specified.
875//
876void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng591bfc82008-05-05 18:30:58 +0000877 size_t GlobalWidth) const {
Chris Lattner5febcae2009-08-23 08:43:55 +0000878 outs() << " -" << O.ArgStr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000879
880 if (const char *ValName = getValueName())
Chris Lattner5febcae2009-08-23 08:43:55 +0000881 outs() << "=<" << getValueStr(O, ValName) << '>';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000882
Chris Lattner5febcae2009-08-23 08:43:55 +0000883 outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884}
885
886
887
888
889// parser<bool> implementation
890//
Chris Lattner157229d2009-09-20 00:40:49 +0000891bool parser<bool>::parse(Option &O, StringRef ArgName,
Chris Lattner47d05cb2009-09-19 18:55:05 +0000892 StringRef Arg, bool &Value) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
894 Arg == "1") {
895 Value = true;
Chris Lattner47d05cb2009-09-19 18:55:05 +0000896 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 }
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000898
Chris Lattner47d05cb2009-09-19 18:55:05 +0000899 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
900 Value = false;
901 return false;
902 }
903 return O.error("'" + Arg +
904 "' is invalid value for boolean argument! Try 0 or 1");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905}
906
907// parser<boolOrDefault> implementation
908//
Chris Lattner157229d2009-09-20 00:40:49 +0000909bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
Chris Lattner47d05cb2009-09-19 18:55:05 +0000910 StringRef Arg, boolOrDefault &Value) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000911 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
912 Arg == "1") {
913 Value = BOU_TRUE;
Chris Lattner47d05cb2009-09-19 18:55:05 +0000914 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915 }
Chris Lattner47d05cb2009-09-19 18:55:05 +0000916 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
917 Value = BOU_FALSE;
918 return false;
919 }
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +0000920
Chris Lattner47d05cb2009-09-19 18:55:05 +0000921 return O.error("'" + Arg +
922 "' is invalid value for boolean argument! Try 0 or 1");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923}
924
925// parser<int> implementation
926//
Chris Lattner157229d2009-09-20 00:40:49 +0000927bool parser<int>::parse(Option &O, StringRef ArgName,
Chris Lattner47d05cb2009-09-19 18:55:05 +0000928 StringRef Arg, int &Value) {
Chris Lattner717f7732009-09-19 23:59:02 +0000929 if (Arg.getAsInteger(0, Value))
Benjamin Kramer9164c672009-08-02 12:13:02 +0000930 return O.error("'" + Arg + "' value invalid for integer argument!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931 return false;
932}
933
934// parser<unsigned> implementation
935//
Chris Lattner157229d2009-09-20 00:40:49 +0000936bool parser<unsigned>::parse(Option &O, StringRef ArgName,
Chris Lattner47d05cb2009-09-19 18:55:05 +0000937 StringRef Arg, unsigned &Value) {
Chris Lattner717f7732009-09-19 23:59:02 +0000938
939 if (Arg.getAsInteger(0, Value))
Benjamin Kramer9164c672009-08-02 12:13:02 +0000940 return O.error("'" + Arg + "' value invalid for uint argument!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941 return false;
942}
943
944// parser<double>/parser<float> implementation
945//
Chris Lattner47d05cb2009-09-19 18:55:05 +0000946static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattner717f7732009-09-19 23:59:02 +0000947 SmallString<32> TmpStr(Arg.begin(), Arg.end());
948 const char *ArgStart = TmpStr.c_str();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949 char *End;
950 Value = strtod(ArgStart, &End);
951 if (*End != 0)
Benjamin Kramer9164c672009-08-02 12:13:02 +0000952 return O.error("'" + Arg + "' value invalid for floating point argument!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953 return false;
954}
955
Chris Lattner157229d2009-09-20 00:40:49 +0000956bool parser<double>::parse(Option &O, StringRef ArgName,
Chris Lattner47d05cb2009-09-19 18:55:05 +0000957 StringRef Arg, double &Val) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958 return parseDouble(O, Arg, Val);
959}
960
Chris Lattner157229d2009-09-20 00:40:49 +0000961bool parser<float>::parse(Option &O, StringRef ArgName,
Chris Lattner47d05cb2009-09-19 18:55:05 +0000962 StringRef Arg, float &Val) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963 double dVal;
964 if (parseDouble(O, Arg, dVal))
965 return true;
966 Val = (float)dVal;
967 return false;
968}
969
970
971
972// generic_parser_base implementation
973//
974
975// findOption - Return the option number corresponding to the specified
976// argument string. If the option is not found, getNumOptions() is returned.
977//
978unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer48086602009-09-19 10:01:45 +0000979 unsigned e = getNumOptions();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980
Benjamin Kramer48086602009-09-19 10:01:45 +0000981 for (unsigned i = 0; i != e; ++i) {
982 if (strcmp(getOption(i), Name) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983 return i;
Benjamin Kramer48086602009-09-19 10:01:45 +0000984 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985 return e;
986}
987
988
989// Return the width of the option tag for printing...
Evan Cheng591bfc82008-05-05 18:30:58 +0000990size_t generic_parser_base::getOptionWidth(const Option &O) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991 if (O.hasArgStr()) {
Evan Cheng591bfc82008-05-05 18:30:58 +0000992 size_t Size = std::strlen(O.ArgStr)+6;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng591bfc82008-05-05 18:30:58 +0000994 Size = std::max(Size, std::strlen(getOption(i))+8);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000995 return Size;
996 } else {
Evan Cheng591bfc82008-05-05 18:30:58 +0000997 size_t BaseSize = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000998 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Evan Cheng591bfc82008-05-05 18:30:58 +0000999 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000 return BaseSize;
1001 }
1002}
1003
1004// printOptionInfo - Print out information about this option. The
1005// to-be-maintained width is specified.
1006//
1007void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng591bfc82008-05-05 18:30:58 +00001008 size_t GlobalWidth) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 if (O.hasArgStr()) {
Evan Cheng591bfc82008-05-05 18:30:58 +00001010 size_t L = std::strlen(O.ArgStr);
Chris Lattnerd516d022009-09-20 05:03:30 +00001011 outs() << " -" << O.ArgStr;
1012 outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013
1014 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng591bfc82008-05-05 18:30:58 +00001015 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
Chris Lattnerd516d022009-09-20 05:03:30 +00001016 outs() << " =" << getOption(i);
1017 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001018 }
1019 } else {
1020 if (O.HelpStr[0])
Chris Lattnerd516d022009-09-20 05:03:30 +00001021 outs() << " " << O.HelpStr << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Evan Cheng591bfc82008-05-05 18:30:58 +00001023 size_t L = std::strlen(getOption(i));
Chris Lattnerd516d022009-09-20 05:03:30 +00001024 outs() << " -" << getOption(i);
1025 outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001026 }
1027 }
1028}
1029
1030
1031//===----------------------------------------------------------------------===//
1032// --help and --help-hidden option implementation
1033//
1034
Chris Lattner0d9aff42009-09-20 05:37:24 +00001035static int OptNameCompare(const void *LHS, const void *RHS) {
1036 typedef std::pair<const char *, Option*> pair_ty;
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +00001037
Chris Lattner0d9aff42009-09-20 05:37:24 +00001038 return strcmp(((pair_ty*)LHS)->first, ((pair_ty*)RHS)->first);
1039}
1040
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041namespace {
1042
1043class HelpPrinter {
Evan Cheng591bfc82008-05-05 18:30:58 +00001044 size_t MaxArgLen;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 const Option *EmptyArg;
1046 const bool ShowHidden;
1047
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048public:
Dan Gohman40bd38e2008-03-25 22:06:05 +00001049 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050 EmptyArg = 0;
1051 }
1052
1053 void operator=(bool Value) {
1054 if (Value == false) return;
1055
1056 // Get all the options.
Chris Lattner3d211b22009-09-20 06:18:38 +00001057 SmallVector<Option*, 4> PositionalOpts;
1058 SmallVector<Option*, 4> SinkOpts;
Benjamin Kramer48086602009-09-19 10:01:45 +00001059 StringMap<Option*> OptMap;
Anton Korobeynikov6288e922008-02-20 12:38:07 +00001060 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +00001061
Chris Lattner97be18f2009-09-20 05:12:14 +00001062 // Copy Options into a vector so we can sort them as we like.
Chris Lattner0d9aff42009-09-20 05:37:24 +00001063 SmallVector<std::pair<const char *, Option*>, 128> Opts;
Chris Lattnerc8240962009-09-20 05:22:52 +00001064 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1065
Benjamin Kramer48086602009-09-19 10:01:45 +00001066 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1067 I != E; ++I) {
Chris Lattner34bbc242009-09-20 05:18:28 +00001068 // Ignore really-hidden options.
1069 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1070 continue;
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +00001071
Chris Lattner34bbc242009-09-20 05:18:28 +00001072 // Unless showhidden is set, ignore hidden flags.
1073 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1074 continue;
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +00001075
Chris Lattnerc8240962009-09-20 05:22:52 +00001076 // If we've already seen this option, don't add it to the list again.
Chris Lattner0d9aff42009-09-20 05:37:24 +00001077 if (!OptionSet.insert(I->second))
Chris Lattnerc8240962009-09-20 05:22:52 +00001078 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079
Chris Lattner0d9aff42009-09-20 05:37:24 +00001080 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1081 I->second));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 }
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +00001083
Chris Lattner0d9aff42009-09-20 05:37:24 +00001084 // Sort the options list alphabetically.
1085 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086
1087 if (ProgramOverview)
Chris Lattner5febcae2009-08-23 08:43:55 +00001088 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089
Chris Lattner5febcae2009-08-23 08:43:55 +00001090 outs() << "USAGE: " << ProgramName << " [options]";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091
1092 // Print out the positional options.
1093 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkov7015ef82008-04-28 16:44:25 +00001094 if (!PositionalOpts.empty() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1096 CAOpt = PositionalOpts[0];
1097
Evan Cheng591bfc82008-05-05 18:30:58 +00001098 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 if (PositionalOpts[i]->ArgStr[0])
Chris Lattner5febcae2009-08-23 08:43:55 +00001100 outs() << " --" << PositionalOpts[i]->ArgStr;
1101 outs() << " " << PositionalOpts[i]->HelpStr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102 }
1103
1104 // Print the consume after option info if it exists...
Chris Lattner5febcae2009-08-23 08:43:55 +00001105 if (CAOpt) outs() << " " << CAOpt->HelpStr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106
Chris Lattner5febcae2009-08-23 08:43:55 +00001107 outs() << "\n\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108
1109 // Compute the maximum argument length...
1110 MaxArgLen = 0;
Evan Cheng591bfc82008-05-05 18:30:58 +00001111 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner0d9aff42009-09-20 05:37:24 +00001112 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113
Chris Lattner5febcae2009-08-23 08:43:55 +00001114 outs() << "OPTIONS:\n";
Evan Cheng591bfc82008-05-05 18:30:58 +00001115 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner0d9aff42009-09-20 05:37:24 +00001116 Opts[i].second->printOptionInfo(MaxArgLen);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117
1118 // Print any extra help the user has declared.
1119 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1120 E = MoreHelp->end(); I != E; ++I)
Chris Lattner5febcae2009-08-23 08:43:55 +00001121 outs() << *I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001122 MoreHelp->clear();
1123
1124 // Halt the program since help information was printed
1125 exit(1);
1126 }
1127};
1128} // End anonymous namespace
1129
1130// Define the two HelpPrinter instances that are used to print out help, or
1131// help-hidden...
1132//
1133static HelpPrinter NormalPrinter(false);
1134static HelpPrinter HiddenPrinter(true);
1135
1136static cl::opt<HelpPrinter, true, parser<bool> >
1137HOp("help", cl::desc("Display available options (--help-hidden for more)"),
1138 cl::location(NormalPrinter), cl::ValueDisallowed);
1139
1140static cl::opt<HelpPrinter, true, parser<bool> >
1141HHOp("help-hidden", cl::desc("Display all available options"),
1142 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1143
1144static void (*OverrideVersionPrinter)() = 0;
1145
Chris Lattner8748d232009-09-20 05:53:47 +00001146static int TargetArraySortFn(const void *LHS, const void *RHS) {
1147 typedef std::pair<const char *, const Target*> pair_ty;
1148 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1149}
1150
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151namespace {
1152class VersionPrinter {
1153public:
1154 void print() {
Chris Lattner3d211b22009-09-20 06:18:38 +00001155 raw_ostream &OS = outs();
1156 OS << "Low Level Virtual Machine (http://llvm.org/):\n"
1157 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158#ifdef LLVM_VERSION_INFO
Chris Lattner3d211b22009-09-20 06:18:38 +00001159 OS << LLVM_VERSION_INFO;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160#endif
Chris Lattner3d211b22009-09-20 06:18:38 +00001161 OS << "\n ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162#ifndef __OPTIMIZE__
Chris Lattner3d211b22009-09-20 06:18:38 +00001163 OS << "DEBUG build";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164#else
Chris Lattner3d211b22009-09-20 06:18:38 +00001165 OS << "Optimized build";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001166#endif
1167#ifndef NDEBUG
Chris Lattner3d211b22009-09-20 06:18:38 +00001168 OS << " with assertions";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001169#endif
Daniel Dunbard31559c2009-11-14 21:36:07 +00001170 std::string CPU = sys::getHostCPUName();
Benjamin Kramerc77d9a42009-11-17 17:57:04 +00001171 if (CPU == "generic") CPU = "(unknown)";
Chris Lattner3d211b22009-09-20 06:18:38 +00001172 OS << ".\n"
1173 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1174 << " Host: " << sys::getHostTriple() << '\n'
Daniel Dunbard31559c2009-11-14 21:36:07 +00001175 << " Host CPU: " << CPU << '\n'
Chris Lattner3d211b22009-09-20 06:18:38 +00001176 << '\n'
1177 << " Registered Targets:\n";
Daniel Dunbar9b3edb62009-07-16 02:06:09 +00001178
Chris Lattner8748d232009-09-20 05:53:47 +00001179 std::vector<std::pair<const char *, const Target*> > Targets;
Benjamin Kramer32dd0232009-08-23 10:01:13 +00001180 size_t Width = 0;
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +00001181 for (TargetRegistry::iterator it = TargetRegistry::begin(),
Benjamin Kramer32dd0232009-08-23 10:01:13 +00001182 ie = TargetRegistry::end(); it != ie; ++it) {
1183 Targets.push_back(std::make_pair(it->getName(), &*it));
Chris Lattner8748d232009-09-20 05:53:47 +00001184 Width = std::max(Width, strlen(Targets.back().first));
Benjamin Kramer32dd0232009-08-23 10:01:13 +00001185 }
Chris Lattner8748d232009-09-20 05:53:47 +00001186 if (!Targets.empty())
1187 qsort(&Targets[0], Targets.size(), sizeof(Targets[0]),
1188 TargetArraySortFn);
Daniel Dunbar80329932009-07-26 05:09:50 +00001189
Benjamin Kramer32dd0232009-08-23 10:01:13 +00001190 for (unsigned i = 0, e = Targets.size(); i != e; ++i) {
Chris Lattner3d211b22009-09-20 06:18:38 +00001191 OS << " " << Targets[i].first;
1192 OS.indent(Width - strlen(Targets[i].first)) << " - "
Chris Lattnerd516d022009-09-20 05:03:30 +00001193 << Targets[i].second->getShortDescription() << '\n';
Benjamin Kramer32dd0232009-08-23 10:01:13 +00001194 }
1195 if (Targets.empty())
Chris Lattner3d211b22009-09-20 06:18:38 +00001196 OS << " (none)\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001197 }
1198 void operator=(bool OptionWasSpecified) {
Chris Lattnera8165362009-09-20 05:48:01 +00001199 if (!OptionWasSpecified) return;
Mikhail Glushenkov766a36d2009-11-19 17:29:36 +00001200
Chris Lattnera8165362009-09-20 05:48:01 +00001201 if (OverrideVersionPrinter == 0) {
1202 print();
1203 exit(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 }
Chris Lattnera8165362009-09-20 05:48:01 +00001205 (*OverrideVersionPrinter)();
1206 exit(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001207 }
1208};
1209} // End anonymous namespace
1210
1211
1212// Define the --version option that prints out the LLVM version for the tool
1213static VersionPrinter VersionPrinterInstance;
1214
1215static cl::opt<VersionPrinter, true, parser<bool> >
1216VersOp("version", cl::desc("Display the version of this program"),
1217 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1218
1219// Utility function for printing the help message.
1220void cl::PrintHelpMessage() {
1221 // This looks weird, but it actually prints the help message. The
1222 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1223 // its operator= is invoked. That's because the "normal" usages of the
1224 // help printer is to be assigned true/false depending on whether the
1225 // --help option was given or not. Since we're circumventing that we have
1226 // to make it look like --help was given, so we assign true.
1227 NormalPrinter = true;
1228}
1229
1230/// Utility function for printing version number.
1231void cl::PrintVersionMessage() {
1232 VersionPrinterInstance.print();
1233}
1234
1235void cl::SetVersionPrinter(void (*func)()) {
1236 OverrideVersionPrinter = func;
1237}