blob: c1615a0a68309b1c301f7029f4b945f1c94e7871 [file] [log] [blame]
Chris Lattner36a57d32001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner36a57d32001-07-23 17:17:47 +00009//
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//
Chris Lattner81cc83d2001-07-23 23:04:07 +000014// 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//
Chris Lattner36a57d32001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer7c16caa2004-09-01 22:55:40 +000019#include "llvm/Support/CommandLine.h"
Peter Collingbournee1863192014-10-16 22:47:52 +000020#include "llvm-c/Support.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000021#include "llvm/ADT/ArrayRef.h"
Benjamin Kramerbd5ee502015-03-14 00:20:13 +000022#include "llvm/ADT/STLExtras.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerfa9c6f42009-09-19 23:59:02 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000025#include "llvm/ADT/StringMap.h"
Chris Lattneraecd74d2009-09-19 18:55:05 +000026#include "llvm/ADT/Twine.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000027#include "llvm/Config/config.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000028#include "llvm/Support/ConvertUTF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Support/Debug.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/Host.h"
32#include "llvm/Support/ManagedStatic.h"
33#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/Path.h"
Rafael Espindola454adf62015-06-13 12:49:52 +000035#include "llvm/Support/StringSaver.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/raw_ostream.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000037#include <cstdlib>
Andrew Trick0537a982013-05-06 21:56:23 +000038#include <map>
Chris Lattnerc9499b62003-12-14 21:35:53 +000039using namespace llvm;
Chris Lattner36a57d32001-07-23 17:17:47 +000040using namespace cl;
41
Chandler Carruthe96dd892014-04-21 22:55:11 +000042#define DEBUG_TYPE "commandline"
43
Chris Lattner3e5d60f2006-08-27 12:45:47 +000044//===----------------------------------------------------------------------===//
45// Template instantiations and anchors.
46//
Chris Bieneman5d232242015-01-13 19:14:20 +000047namespace llvm {
48namespace cl {
Benjamin Kramera667d1a2015-07-13 17:21:31 +000049template class basic_parser<bool>;
50template class basic_parser<boolOrDefault>;
51template class basic_parser<int>;
52template class basic_parser<unsigned>;
53template class basic_parser<unsigned long long>;
54template class basic_parser<double>;
55template class basic_parser<float>;
56template class basic_parser<std::string>;
57template class basic_parser<char>;
Chris Lattner3e5d60f2006-08-27 12:45:47 +000058
Benjamin Kramera667d1a2015-07-13 17:21:31 +000059template class opt<unsigned>;
60template class opt<int>;
61template class opt<std::string>;
62template class opt<char>;
63template class opt<bool>;
Alexander Kornienkof00654e2015-06-23 09:49:53 +000064}
65} // end namespace llvm::cl
Chris Lattner3e5d60f2006-08-27 12:45:47 +000066
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000067// Pin the vtables to this file.
68void GenericOptionValue::anchor() {}
David Blaikie3a15e142011-12-01 08:00:17 +000069void OptionValue<boolOrDefault>::anchor() {}
70void OptionValue<std::string>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000071void Option::anchor() {}
72void basic_parser_impl::anchor() {}
73void parser<bool>::anchor() {}
Dale Johannesen82810c82007-05-22 17:14:46 +000074void parser<boolOrDefault>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000075void parser<int>::anchor() {}
76void parser<unsigned>::anchor() {}
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000077void parser<unsigned long long>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000078void parser<double>::anchor() {}
79void parser<float>::anchor() {}
80void parser<std::string>::anchor() {}
Bill Wendlingdb59fda2009-04-29 23:26:16 +000081void parser<char>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000082
83//===----------------------------------------------------------------------===//
84
Benjamin Kramer970eac42015-02-06 17:51:54 +000085namespace {
86
Chris Bienemand1d94302015-01-28 19:00:25 +000087class CommandLineParser {
88public:
89 // Globals for name and overview of program. Program name is not a string to
90 // avoid static ctor/dtor issues.
Chris Bienemanb6866422015-01-28 22:25:00 +000091 std::string ProgramName;
NAKAMURA Takumi81828182015-01-29 11:06:59 +000092 const char *ProgramOverview;
Reid Spencer9501b9b2004-09-01 04:41:28 +000093
Chris Bienemand1d94302015-01-28 19:00:25 +000094 // This collects additional help to be printed.
95 std::vector<const char *> MoreHelp;
96
97 SmallVector<Option *, 4> PositionalOpts;
98 SmallVector<Option *, 4> SinkOpts;
99 StringMap<Option *> OptionsMap;
100
NAKAMURA Takumi81828182015-01-29 11:06:59 +0000101 Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists.
102
Chris Bieneman67e426a2015-02-13 22:54:32 +0000103 // This collects the different option categories that have been registered.
104 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
105
NAKAMURA Takumi81828182015-01-29 11:06:59 +0000106 CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
Chris Bienemand1d94302015-01-28 19:00:25 +0000107
108 void ParseCommandLineOptions(int argc, const char *const *argv,
109 const char *Overview);
110
111 void addLiteralOption(Option &Opt, const char *Name) {
112 if (!Opt.hasArgStr()) {
113 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
114 errs() << ProgramName << ": CommandLine Error: Option '" << Name
115 << "' registered more than once!\n";
116 report_fatal_error("inconsistency in registered CommandLine options");
117 }
118 }
119 }
120
121 void addOption(Option *O) {
122 bool HadErrors = false;
David Blaikieff43d692015-11-17 19:00:52 +0000123 if (O->hasArgStr()) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000124 // Add argument to the argument map!
125 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
126 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
127 << "' registered more than once!\n";
128 HadErrors = true;
129 }
130 }
131
132 // Remember information about positional options.
133 if (O->getFormattingFlag() == cl::Positional)
134 PositionalOpts.push_back(O);
135 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
136 SinkOpts.push_back(O);
137 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
138 if (ConsumeAfterOpt) {
139 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
140 HadErrors = true;
141 }
142 ConsumeAfterOpt = O;
143 }
144
145 // Fail hard if there were errors. These are strictly unrecoverable and
146 // indicate serious issues such as conflicting option names or an
147 // incorrectly
148 // linked LLVM distribution.
149 if (HadErrors)
150 report_fatal_error("inconsistency in registered CommandLine options");
151 }
152
153 void removeOption(Option *O) {
David Blaikieff43d692015-11-17 19:00:52 +0000154 SmallVector<StringRef, 16> OptionNames;
Chris Bienemand1d94302015-01-28 19:00:25 +0000155 O->getExtraOptionNames(OptionNames);
David Blaikieff43d692015-11-17 19:00:52 +0000156 if (O->hasArgStr())
Chris Bienemand1d94302015-01-28 19:00:25 +0000157 OptionNames.push_back(O->ArgStr);
158 for (auto Name : OptionNames)
David Blaikieff43d692015-11-17 19:00:52 +0000159 OptionsMap.erase(Name);
Chris Bienemand1d94302015-01-28 19:00:25 +0000160
161 if (O->getFormattingFlag() == cl::Positional)
162 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
163 ++Opt) {
164 if (*Opt == O) {
165 PositionalOpts.erase(Opt);
166 break;
167 }
168 }
169 else if (O->getMiscFlags() & cl::Sink)
170 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
171 if (*Opt == O) {
172 SinkOpts.erase(Opt);
173 break;
174 }
175 }
176 else if (O == ConsumeAfterOpt)
177 ConsumeAfterOpt = nullptr;
178 }
179
180 bool hasOptions() {
181 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
182 nullptr != ConsumeAfterOpt);
183 }
184
David Blaikieff43d692015-11-17 19:00:52 +0000185 void updateArgStr(Option *O, StringRef NewName) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000186 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
187 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
188 << "' registered more than once!\n";
189 report_fatal_error("inconsistency in registered CommandLine options");
190 }
David Blaikieff43d692015-11-17 19:00:52 +0000191 OptionsMap.erase(O->ArgStr);
Chris Bienemand1d94302015-01-28 19:00:25 +0000192 }
Chris Bienemand77bbab2015-01-30 22:16:01 +0000193
194 void printOptionValues();
Chris Bieneman542f56a2015-02-13 22:54:27 +0000195
Chris Bieneman67e426a2015-02-13 22:54:32 +0000196 void registerCategory(OptionCategory *cat) {
197 assert(std::count_if(RegisteredOptionCategories.begin(),
198 RegisteredOptionCategories.end(),
199 [cat](const OptionCategory *Category) {
Chris Bienemanf942c0c2015-02-13 23:10:31 +0000200 return cat->getName() == Category->getName();
Chris Bieneman67e426a2015-02-13 22:54:32 +0000201 }) == 0 &&
202 "Duplicate option categories");
203
204 RegisteredOptionCategories.insert(cat);
205 }
206
Chris Bieneman542f56a2015-02-13 22:54:27 +0000207private:
208 Option *LookupOption(StringRef &Arg, StringRef &Value);
Chris Bienemand1d94302015-01-28 19:00:25 +0000209};
210
Benjamin Kramer970eac42015-02-06 17:51:54 +0000211} // namespace
212
Chris Bienemand1d94302015-01-28 19:00:25 +0000213static ManagedStatic<CommandLineParser> GlobalParser;
214
215void cl::AddLiteralOption(Option &O, const char *Name) {
216 GlobalParser->addLiteralOption(O, Name);
217}
Chris Lattner37bcd992004-11-19 17:08:15 +0000218
Chris Bieneman5d232242015-01-13 19:14:20 +0000219extrahelp::extrahelp(const char *Help) : morehelp(Help) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000220 GlobalParser->MoreHelp.push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +0000221}
222
Chris Lattner5247f602007-04-06 21:06:55 +0000223void Option::addArgument() {
Chris Bienemand1d94302015-01-28 19:00:25 +0000224 GlobalParser->addOption(this);
225 FullyInitialized = true;
Chris Lattner5247f602007-04-06 21:06:55 +0000226}
227
Chris Bienemand1d94302015-01-28 19:00:25 +0000228void Option::removeArgument() { GlobalParser->removeOption(this); }
229
David Blaikieff43d692015-11-17 19:00:52 +0000230void Option::setArgStr(StringRef S) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000231 if (FullyInitialized)
232 GlobalParser->updateArgStr(this, S);
233 ArgStr = S;
Jordan Rosec25b0c72014-01-29 18:54:17 +0000234}
235
Andrew Trick0537a982013-05-06 21:56:23 +0000236// Initialise the general option category.
237OptionCategory llvm::cl::GeneralCategory("General options");
238
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000239void OptionCategory::registerCategory() {
Chris Bieneman67e426a2015-02-13 22:54:32 +0000240 GlobalParser->registerCategory(this);
Andrew Trick0537a982013-05-06 21:56:23 +0000241}
Chris Lattneraf039c52007-04-12 00:36:29 +0000242
Chris Lattner5df56c42002-07-22 02:07:59 +0000243//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000244// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000245//
246
Chris Lattner2031b022007-04-05 21:58:17 +0000247/// LookupOption - Lookup the option specified by the specified option on the
248/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000249/// that as well. This assumes that leading dashes have already been stripped.
Chris Bieneman542f56a2015-02-13 22:54:27 +0000250Option *CommandLineParser::LookupOption(StringRef &Arg, StringRef &Value) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000251 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000252 if (Arg.empty())
253 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000254
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000255 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000256
Chris Lattner0a40a972009-09-20 01:53:12 +0000257 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000258 if (EqualPos == StringRef::npos) {
259 // Look up the option.
Chris Bieneman5d232242015-01-13 19:14:20 +0000260 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
Craig Topperc10719f2014-04-07 04:17:22 +0000261 return I != OptionsMap.end() ? I->second : nullptr;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000262 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000263
Chris Lattnere7c1e212009-09-20 05:03:30 +0000264 // If the argument before the = is a valid option name, we match. If not,
265 // return Arg unmolested.
Chris Bieneman5d232242015-01-13 19:14:20 +0000266 StringMap<Option *>::const_iterator I =
267 OptionsMap.find(Arg.substr(0, EqualPos));
268 if (I == OptionsMap.end())
269 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000270
Chris Bieneman5d232242015-01-13 19:14:20 +0000271 Value = Arg.substr(EqualPos + 1);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000272 Arg = Arg.substr(0, EqualPos);
273 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000274}
275
Daniel Dunbarf4132132011-01-18 01:59:24 +0000276/// LookupNearestOption - Lookup the closest match to the option specified by
277/// the specified option on the command line. If there is a value specified
278/// (after an equal sign) return that as well. This assumes that leading dashes
279/// have already been stripped.
280static Option *LookupNearestOption(StringRef Arg,
Chris Bieneman5d232242015-01-13 19:14:20 +0000281 const StringMap<Option *> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000282 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000283 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000284 if (Arg.empty())
285 return nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000286
287 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000288 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
Chris Bieneman5d232242015-01-13 19:14:20 +0000289 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000290 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000291
292 // Find the closest match.
Craig Topperc10719f2014-04-07 04:17:22 +0000293 Option *Best = nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000294 unsigned BestDistance = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000295 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
296 ie = OptionsMap.end();
297 it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000298 Option *O = it->second;
David Blaikieff43d692015-11-17 19:00:52 +0000299 SmallVector<StringRef, 16> OptionNames;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000300 O->getExtraOptionNames(OptionNames);
David Blaikieff43d692015-11-17 19:00:52 +0000301 if (O->hasArgStr())
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000302 OptionNames.push_back(O->ArgStr);
303
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000304 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
305 StringRef Flag = PermitValue ? LHS : Arg;
David Blaikieff43d692015-11-17 19:00:52 +0000306 for (auto Name : OptionNames) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000307 unsigned Distance = StringRef(Name).edit_distance(
Chris Bieneman5d232242015-01-13 19:14:20 +0000308 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000309 if (!Best || Distance < BestDistance) {
310 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000311 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000312 if (RHS.empty() || !PermitValue)
David Blaikieff43d692015-11-17 19:00:52 +0000313 NearestString = Name;
Bill Wendling318f03f2012-07-19 00:15:11 +0000314 else
David Blaikieff43d692015-11-17 19:00:52 +0000315 NearestString = (Twine(Name) + "=" + RHS).str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000316 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000317 }
318 }
319
320 return Best;
321}
322
Alp Tokercb402912014-01-24 17:20:08 +0000323/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
324/// that does special handling of cl::CommaSeparated options.
325static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
326 StringRef ArgName, StringRef Value,
327 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000328 // Check to see if this option accepts a comma separated list of values. If
329 // it does, we have to split up the value into multiple values.
330 if (Handler->getMiscFlags() & CommaSeparated) {
331 StringRef Val(Value);
332 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000333
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000334 while (Pos != StringRef::npos) {
335 // Process the portion before the comma.
336 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
337 return true;
338 // Erase the portion before the comma, AND the comma.
Chris Bieneman5d232242015-01-13 19:14:20 +0000339 Val = Val.substr(Pos + 1);
340 Value.substr(Pos + 1); // Increment the original value pointer as well.
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000341 // Check for another comma.
342 Pos = Val.find(',');
343 }
344
345 Value = Val;
346 }
347
Alexander Kornienko66da20a2015-12-28 15:46:15 +0000348 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000349}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000350
Chris Lattner40fef802009-09-20 01:49:31 +0000351/// ProvideOption - For Value, this differentiates between an empty value ("")
352/// and a null value (StringRef()). The later is accepted for arguments that
353/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000354static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000355 StringRef Value, int argc,
356 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000357 // Is this a multi-argument option?
358 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
359
Chris Lattnere81c4092001-10-27 05:54:17 +0000360 // Enforce value requirements
361 switch (Handler->getValueExpectedFlag()) {
362 case ValueRequired:
Craig Topper8d399f82014-04-09 04:20:00 +0000363 if (!Value.data()) { // No value specified?
Chris Bieneman5d232242015-01-13 19:14:20 +0000364 if (i + 1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000365 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000366 // Steal the next argument, like for '-o filename'
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000367 assert(argv && "null check");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000368 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000369 }
370 break;
371 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000372 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000373 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000374 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000375
Chris Lattner40fef802009-09-20 01:49:31 +0000376 if (Value.data())
Chris Bieneman5d232242015-01-13 19:14:20 +0000377 return Handler->error("does not allow a value! '" + Twine(Value) +
378 "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000379 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000380 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000381 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000382 }
383
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000384 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000385 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000386 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000387
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000388 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000389 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000390
Chris Lattner40fef802009-09-20 01:49:31 +0000391 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000392 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000393 return true;
394 --NumAdditionalVals;
395 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000396 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000397
398 while (NumAdditionalVals > 0) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000399 if (i + 1 >= argc)
Chris Lattneraecd74d2009-09-19 18:55:05 +0000400 return Handler->error("not enough values!");
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000401 assert(argv && "null check");
Chris Lattneraecd74d2009-09-19 18:55:05 +0000402 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000403
Alp Tokercb402912014-01-24 17:20:08 +0000404 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000405 return true;
406 MultiArg = true;
407 --NumAdditionalVals;
408 }
409 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000410}
411
Chris Lattnerca2552d2009-09-20 00:07:40 +0000412static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000413 int Dummy = i;
Craig Topperc10719f2014-04-07 04:17:22 +0000414 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000415}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000416
Chris Lattner5df56c42002-07-22 02:07:59 +0000417// Option predicates...
418static inline bool isGrouping(const Option *O) {
419 return O->getFormattingFlag() == cl::Grouping;
420}
421static inline bool isPrefixedOrGrouping(const Option *O) {
422 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
423}
424
425// getOptionPred - Check to see if there are any options that satisfy the
426// specified predicate with names that are the prefixes in Name. This is
427// checked by progressively stripping characters off of the name, checking to
428// see if there options that satisfy the predicate. If we find one, return it,
429// otherwise return null.
430//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000431static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Bieneman5d232242015-01-13 19:14:20 +0000432 bool (*Pred)(const Option *),
433 const StringMap<Option *> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000434
Chris Bieneman5d232242015-01-13 19:14:20 +0000435 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000436
Chris Lattnere7c1e212009-09-20 05:03:30 +0000437 // Loop while we haven't found an option and Name still has at least two
438 // characters in it (so that the next iteration will not be the empty
439 // string.
440 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000441 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000442 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000443 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000444
Chris Lattner5247f602007-04-06 21:06:55 +0000445 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000446 Length = Name.size();
Chris Bieneman5d232242015-01-13 19:14:20 +0000447 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000448 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000449 return nullptr; // No option found!
Chris Lattner5df56c42002-07-22 02:07:59 +0000450}
451
Chris Lattnere7c1e212009-09-20 05:03:30 +0000452/// HandlePrefixedOrGroupedOption - The specified argument string (which started
453/// with at least one '-') does not fully match an available option. Check to
454/// see if this is a prefix or grouped option. If so, split arg into output an
455/// Arg/Value pair and return the Option to parse it with.
Chris Bieneman5d232242015-01-13 19:14:20 +0000456static Option *
457HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
458 bool &ErrorParsing,
459 const StringMap<Option *> &OptionsMap) {
460 if (Arg.size() == 1)
461 return nullptr;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000462
463 // Do the lookup!
464 size_t Length = 0;
465 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
Chris Bieneman5d232242015-01-13 19:14:20 +0000466 if (!PGOpt)
467 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000468
Chris Lattnere7c1e212009-09-20 05:03:30 +0000469 // If the option is a prefixed option, then the value is simply the
470 // rest of the name... so fall through to later processing, by
471 // setting up the argument name flags and value fields.
472 if (PGOpt->getFormattingFlag() == cl::Prefix) {
473 Value = Arg.substr(Length);
474 Arg = Arg.substr(0, Length);
475 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
476 return PGOpt;
477 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000478
Chris Lattnere7c1e212009-09-20 05:03:30 +0000479 // This must be a grouped option... handle them now. Grouping options can't
480 // have values.
481 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000482
Chris Lattnere7c1e212009-09-20 05:03:30 +0000483 do {
484 // Move current arg name out of Arg into OneArgName.
485 StringRef OneArgName = Arg.substr(0, Length);
486 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000487
Chris Lattnere7c1e212009-09-20 05:03:30 +0000488 // Because ValueRequired is an invalid flag for grouped arguments,
489 // we don't need to pass argc/argv in.
490 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
491 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000492 int Dummy = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000493 ErrorParsing |=
494 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000495
Chris Lattnere7c1e212009-09-20 05:03:30 +0000496 // Get the next grouping option.
497 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
498 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000499
Chris Lattnere7c1e212009-09-20 05:03:30 +0000500 // Return the last option with Arg cut down to just the last one.
501 return PGOpt;
502}
503
Chris Lattner5df56c42002-07-22 02:07:59 +0000504static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000505 return O->getNumOccurrencesFlag() == cl::Required ||
506 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000507}
508
509static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000510 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
511 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000512}
Chris Lattnere81c4092001-10-27 05:54:17 +0000513
Chris Bieneman5d232242015-01-13 19:14:20 +0000514static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
Brian Gaeke497216d2003-08-15 21:05:57 +0000515
Chris Bieneman5d232242015-01-13 19:14:20 +0000516static bool isQuote(char C) { return C == '\"' || C == '\''; }
Reid Klecknera73c7782013-07-18 16:52:05 +0000517
Chris Bieneman5d232242015-01-13 19:14:20 +0000518static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
Reid Klecknera73c7782013-07-18 16:52:05 +0000519
520void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000521 SmallVectorImpl<const char *> &NewArgv,
522 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000523 SmallString<128> Token;
524 for (size_t I = 0, E = Src.size(); I != E; ++I) {
525 // Consume runs of whitespace.
526 if (Token.empty()) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000527 while (I != E && isWhitespace(Src[I])) {
528 // Mark the end of lines in response files
529 if (MarkEOLs && Src[I] == '\n')
530 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000531 ++I;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000532 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000533 if (I == E)
534 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000535 }
536
537 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
538 // they are literal. This makes it much easier to read Windows file paths.
539 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000540 ++I; // Skip the escape.
Reid Klecknera73c7782013-07-18 16:52:05 +0000541 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000542 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000543 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000544
Reid Klecknera73c7782013-07-18 16:52:05 +0000545 // Consume a quoted string.
546 if (isQuote(Src[I])) {
547 char Quote = Src[I++];
548 while (I != E && Src[I] != Quote) {
549 // Backslashes are literal, unless they escape a special character.
550 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
551 ++I;
552 Token.push_back(Src[I]);
553 ++I;
554 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000555 if (I == E)
556 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000557 continue;
558 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000559
Reid Klecknera73c7782013-07-18 16:52:05 +0000560 // End the token if this is whitespace.
561 if (isWhitespace(Src[I])) {
562 if (!Token.empty())
Rafael Espindola454adf62015-06-13 12:49:52 +0000563 NewArgv.push_back(Saver.save(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000564 Token.clear();
565 continue;
566 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000567
Reid Klecknera73c7782013-07-18 16:52:05 +0000568 // This is a normal character. Append it.
569 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000570 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000571
572 // Append the last token after hitting EOF with no whitespace.
573 if (!Token.empty())
Rafael Espindola454adf62015-06-13 12:49:52 +0000574 NewArgv.push_back(Saver.save(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000575 // Mark the end of response files
576 if (MarkEOLs)
577 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000578}
579
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000580/// Backslashes are interpreted in a rather complicated way in the Windows-style
581/// command line, because backslashes are used both to separate path and to
582/// escape double quote. This method consumes runs of backslashes as well as the
583/// following double quote if it's escaped.
584///
585/// * If an even number of backslashes is followed by a double quote, one
586/// backslash is output for every pair of backslashes, and the last double
587/// quote remains unconsumed. The double quote will later be interpreted as
588/// the start or end of a quoted string in the main loop outside of this
589/// function.
590///
591/// * If an odd number of backslashes is followed by a double quote, one
592/// backslash is output for every pair of backslashes, and a double quote is
593/// output for the last pair of backslash-double quote. The double quote is
594/// consumed in this case.
595///
596/// * Otherwise, backslashes are interpreted literally.
597static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
598 size_t E = Src.size();
599 int BackslashCount = 0;
600 // Skip the backslashes.
601 do {
602 ++I;
603 ++BackslashCount;
604 } while (I != E && Src[I] == '\\');
605
606 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
607 if (FollowedByDoubleQuote) {
608 Token.append(BackslashCount / 2, '\\');
609 if (BackslashCount % 2 == 0)
610 return I - 1;
611 Token.push_back('"');
612 return I;
613 }
614 Token.append(BackslashCount, '\\');
615 return I - 1;
616}
617
Reid Klecknera73c7782013-07-18 16:52:05 +0000618void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000619 SmallVectorImpl<const char *> &NewArgv,
620 bool MarkEOLs) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000621 SmallString<128> Token;
622
623 // This is a small state machine to consume characters until it reaches the
624 // end of the source string.
625 enum { INIT, UNQUOTED, QUOTED } State = INIT;
626 for (size_t I = 0, E = Src.size(); I != E; ++I) {
627 // INIT state indicates that the current input index is at the start of
628 // the string or between tokens.
629 if (State == INIT) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000630 if (isWhitespace(Src[I])) {
631 // Mark the end of lines in response files
632 if (MarkEOLs && Src[I] == '\n')
633 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000634 continue;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000635 }
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000636 if (Src[I] == '"') {
637 State = QUOTED;
638 continue;
639 }
640 if (Src[I] == '\\') {
641 I = parseBackslash(Src, I, Token);
642 State = UNQUOTED;
643 continue;
644 }
645 Token.push_back(Src[I]);
646 State = UNQUOTED;
647 continue;
648 }
649
650 // UNQUOTED state means that it's reading a token not quoted by double
651 // quotes.
652 if (State == UNQUOTED) {
653 // Whitespace means the end of the token.
654 if (isWhitespace(Src[I])) {
Rafael Espindola454adf62015-06-13 12:49:52 +0000655 NewArgv.push_back(Saver.save(Token.c_str()));
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000656 Token.clear();
657 State = INIT;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000658 // Mark the end of lines in response files
659 if (MarkEOLs && Src[I] == '\n')
660 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000661 continue;
662 }
663 if (Src[I] == '"') {
664 State = QUOTED;
665 continue;
666 }
667 if (Src[I] == '\\') {
668 I = parseBackslash(Src, I, Token);
669 continue;
670 }
671 Token.push_back(Src[I]);
672 continue;
673 }
674
675 // QUOTED state means that it's reading a token quoted by double quotes.
676 if (State == QUOTED) {
677 if (Src[I] == '"') {
678 State = UNQUOTED;
679 continue;
680 }
681 if (Src[I] == '\\') {
682 I = parseBackslash(Src, I, Token);
683 continue;
684 }
685 Token.push_back(Src[I]);
686 }
687 }
688 // Append the last token after hitting EOF with no whitespace.
689 if (!Token.empty())
Rafael Espindola454adf62015-06-13 12:49:52 +0000690 NewArgv.push_back(Saver.save(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000691 // Mark the end of response files
692 if (MarkEOLs)
693 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000694}
695
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000696// It is called byte order marker but the UTF-8 BOM is actually not affected
697// by the host system's endianness.
698static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
Chris Bienemanceaf5f62015-02-13 22:54:29 +0000699 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000700}
701
Reid Klecknera73c7782013-07-18 16:52:05 +0000702static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
703 TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000704 SmallVectorImpl<const char *> &NewArgv,
705 bool MarkEOLs = false) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000706 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
707 MemoryBuffer::getFile(FName);
708 if (!MemBufOrErr)
Reid Klecknera73c7782013-07-18 16:52:05 +0000709 return false;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000710 MemoryBuffer &MemBuf = *MemBufOrErr.get();
711 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
Reid Klecknera73c7782013-07-18 16:52:05 +0000712
713 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000714 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
Reid Klecknera73c7782013-07-18 16:52:05 +0000715 std::string UTF8Buf;
716 if (hasUTF16ByteOrderMark(BufRef)) {
717 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
718 return false;
719 Str = StringRef(UTF8Buf);
720 }
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000721 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
722 // these bytes before parsing.
723 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
724 else if (hasUTF8ByteOrderMark(BufRef))
725 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
Reid Klecknera73c7782013-07-18 16:52:05 +0000726
727 // Tokenize the contents into NewArgv.
Reid Klecknere3f146d2014-08-22 19:29:17 +0000728 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
Reid Klecknera73c7782013-07-18 16:52:05 +0000729
730 return true;
731}
732
733/// \brief Expand response files on a command line recursively using the given
734/// StringSaver and tokenization strategy.
735bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000736 SmallVectorImpl<const char *> &Argv,
737 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000738 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000739 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000740
741 // Don't cache Argv.size() because it can change.
Chris Bieneman5d232242015-01-13 19:14:20 +0000742 for (unsigned I = 0; I != Argv.size();) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000743 const char *Arg = Argv[I];
Reid Klecknere3f146d2014-08-22 19:29:17 +0000744 // Check if it is an EOL marker
745 if (Arg == nullptr) {
746 ++I;
747 continue;
748 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000749 if (Arg[0] != '@') {
750 ++I;
751 continue;
752 }
753
754 // If we have too many response files, leave some unexpanded. This avoids
755 // crashing on self-referential response files.
756 if (RspFiles++ > 20)
757 return false;
758
759 // Replace this response file argument with the tokenization of its
760 // contents. Nested response files are expanded in subsequent iterations.
761 // FIXME: If a nested response file uses a relative path, is it relative to
762 // the cwd of the process or the response file?
763 SmallVector<const char *, 0> ExpandedArgv;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000764 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
765 MarkEOLs)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000766 // We couldn't read this file, so we leave it in the argument stream and
767 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000768 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000769 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000770 continue;
771 }
772 Argv.erase(Argv.begin() + I);
773 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
774 }
775 return AllExpanded;
776}
777
Brian Gaekeca782d92003-08-14 22:00:59 +0000778/// ParseEnvironmentOptions - An alternative entry point to the
779/// CommandLine library, which allows you to read the program's name
780/// from the caller (as PROGNAME) and its command-line arguments from
781/// an environment variable (whose name is given in ENVVAR).
782///
Chris Lattnera60f3552004-05-06 22:04:31 +0000783void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000784 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000785 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000786 assert(progName && "Program name not specified");
787 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000788
Brian Gaeke497216d2003-08-15 21:05:57 +0000789 // Get the environment variable they want us to parse options out of.
Chris Lattner2de6e332006-08-27 22:10:29 +0000790 const char *envValue = getenv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000791 if (!envValue)
792 return;
793
Brian Gaekeca782d92003-08-14 22:00:59 +0000794 // Get program's "name", which we wouldn't know without the caller
795 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000796 SmallVector<const char *, 20> newArgv;
Rafael Espindola454adf62015-06-13 12:49:52 +0000797 BumpPtrAllocator A;
Rafael Espindolab82455d2015-08-13 01:07:02 +0000798 StringSaver Saver(A);
Rafael Espindola454adf62015-06-13 12:49:52 +0000799 newArgv.push_back(Saver.save(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000800
801 // Parse the value of the environment variable into a "command line"
802 // and hand it off to ParseCommandLineOptions().
Reid Klecknera73c7782013-07-18 16:52:05 +0000803 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000804 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000805 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000806}
807
Chris Bieneman5d232242015-01-13 19:14:20 +0000808void cl::ParseCommandLineOptions(int argc, const char *const *argv,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000809 const char *Overview) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000810 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
811}
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000812
Chris Bienemand1d94302015-01-28 19:00:25 +0000813void CommandLineParser::ParseCommandLineOptions(int argc,
814 const char *const *argv,
815 const char *Overview) {
816 assert(hasOptions() && "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000817
818 // Expand response files.
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000819 SmallVector<const char *, 20> newArgv(argv, argv + argc);
Rafael Espindola454adf62015-06-13 12:49:52 +0000820 BumpPtrAllocator A;
Rafael Espindolab82455d2015-08-13 01:07:02 +0000821 StringSaver Saver(A);
Reid Klecknera73c7782013-07-18 16:52:05 +0000822 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000823 argv = &newArgv[0];
824 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000825
Chris Lattner5af1cbc2006-10-13 00:06:24 +0000826 // Copy the program name into ProgName, making sure not to overflow it.
Chris Bienemanb6866422015-01-28 22:25:00 +0000827 ProgramName = sys::path::filename(argv[0]);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000828
Chris Lattner36a57d32001-07-23 17:17:47 +0000829 ProgramOverview = Overview;
830 bool ErrorParsing = false;
831
Chris Lattner5df56c42002-07-22 02:07:59 +0000832 // Check out the positional arguments to collect information about them.
833 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000834
Chris Lattnerd380d842005-08-08 17:25:38 +0000835 // Determine whether or not there are an unlimited number of positionals
836 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000837
Chris Bienemand1d94302015-01-28 19:00:25 +0000838 if (ConsumeAfterOpt) {
839 assert(PositionalOpts.size() > 0 &&
840 "Cannot specify cl::ConsumeAfter without a positional argument!");
841 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000842 if (!PositionalOpts.empty()) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000843
844 // Calculate how many positional values are _required_.
845 bool UnboundedFound = false;
Chris Bienemand1d94302015-01-28 19:00:25 +0000846 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000847 Option *Opt = PositionalOpts[i];
848 if (RequiresValue(Opt))
849 ++NumPositionalRequired;
850 else if (ConsumeAfterOpt) {
851 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +0000852 // unless there is only one positional argument...
Chris Bienemand1d94302015-01-28 19:00:25 +0000853 if (PositionalOpts.size() > 1)
Chris Bieneman5d232242015-01-13 19:14:20 +0000854 ErrorParsing |= Opt->error(
855 "error - this positional option will never be matched, "
856 "because it does not Require a value, and a "
857 "cl::ConsumeAfter option is active!");
David Blaikieff43d692015-11-17 19:00:52 +0000858 } else if (UnboundedFound && !Opt->hasArgStr()) {
Chris Lattner2da046f2003-07-30 17:34:02 +0000859 // This option does not "require" a value... Make sure this option is
860 // not specified after an option that eats all extra arguments, or this
861 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +0000862 //
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000863 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner5df56c42002-07-22 02:07:59 +0000864 "another positional argument will match an "
865 "unbounded number of values, and this option"
866 " does not require a value!");
Chris Bienemand1d94302015-01-28 19:00:25 +0000867 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
868 << "' is all messed up!\n";
869 errs() << PositionalOpts.size();
Chris Lattner5df56c42002-07-22 02:07:59 +0000870 }
871 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
872 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +0000873 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +0000874 }
875
Reid Spencer2027a6f2004-08-13 19:47:30 +0000876 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +0000877 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +0000878 //
Chris Bieneman5d232242015-01-13 19:14:20 +0000879 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +0000880
Chris Lattner2da046f2003-07-30 17:34:02 +0000881 // If the program has named positional arguments, and the name has been run
882 // across, keep track of which positional argument was named. Otherwise put
883 // the positional args into the PositionalVals list...
Craig Topperc10719f2014-04-07 04:17:22 +0000884 Option *ActivePositionalArg = nullptr;
Chris Lattner2da046f2003-07-30 17:34:02 +0000885
Chris Lattner36a57d32001-07-23 17:17:47 +0000886 // Loop over all of the arguments... processing them.
Chris Bieneman5d232242015-01-13 19:14:20 +0000887 bool DashDashFound = false; // Have we read '--'?
Chris Lattner36a57d32001-07-23 17:17:47 +0000888 for (int i = 1; i < argc; ++i) {
Craig Topperc10719f2014-04-07 04:17:22 +0000889 Option *Handler = nullptr;
890 Option *NearestHandler = nullptr;
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000891 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +0000892 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000893 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +0000894
895 // Check to see if this is a positional argument. This argument is
896 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +0000897 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +0000898 //
899 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
900 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +0000901 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000902 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000903 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000904 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000905
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000906 if (!PositionalOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000907 PositionalVals.push_back(std::make_pair(argv[i], i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000908
909 // All of the positional arguments have been fulfulled, give the rest to
910 // the consume after option... if it's specified...
911 //
Craig Topper8d399f82014-04-09 04:20:00 +0000912 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000913 for (++i; i < argc; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +0000914 PositionalVals.push_back(std::make_pair(argv[i], i));
915 break; // Handle outside of the argument processing loop...
Chris Lattner5df56c42002-07-22 02:07:59 +0000916 }
917
918 // Delay processing positional arguments until the end...
919 continue;
920 }
Chris Lattnera60f3552004-05-06 22:04:31 +0000921 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
922 !DashDashFound) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000923 DashDashFound = true; // This is the mythical "--"?
924 continue; // Don't try to process it as an argument itself.
Chris Lattnera60f3552004-05-06 22:04:31 +0000925 } else if (ActivePositionalArg &&
926 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
927 // If there is a positional argument eating options, check to see if this
928 // option is another positional argument. If so, treat it as an argument,
929 // otherwise feed it to the eating positional.
Chris Bieneman5d232242015-01-13 19:14:20 +0000930 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000931 // Eat leading dashes.
932 while (!ArgName.empty() && ArgName[0] == '-')
933 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000934
Chris Bieneman542f56a2015-02-13 22:54:27 +0000935 Handler = LookupOption(ArgName, Value);
Chris Lattnera60f3552004-05-06 22:04:31 +0000936 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000937 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000938 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +0000939 }
940
Chris Bieneman5d232242015-01-13 19:14:20 +0000941 } else { // We start with a '-', must be an argument.
942 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000943 // Eat leading dashes.
944 while (!ArgName.empty() && ArgName[0] == '-')
945 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000946
Chris Bieneman542f56a2015-02-13 22:54:27 +0000947 Handler = LookupOption(ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +0000948
Chris Lattnera60f3552004-05-06 22:04:31 +0000949 // Check to see if this "option" is really a prefixed or grouped argument.
Craig Topper8d399f82014-04-09 04:20:00 +0000950 if (!Handler)
Chris Bienemand1d94302015-01-28 19:00:25 +0000951 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
952 OptionsMap);
Daniel Dunbarf4132132011-01-18 01:59:24 +0000953
954 // Otherwise, look for the closest available option to report to the user
955 // in the upcoming error.
Craig Topper8d399f82014-04-09 04:20:00 +0000956 if (!Handler && SinkOpts.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +0000957 NearestHandler =
Chris Bienemand1d94302015-01-28 19:00:25 +0000958 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +0000959 }
960
Craig Topper8d399f82014-04-09 04:20:00 +0000961 if (!Handler) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000962 if (SinkOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000963 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
964 << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +0000965
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000966 if (NearestHandler) {
967 // If we know a near match, report it as well.
Chris Bieneman5d232242015-01-13 19:14:20 +0000968 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
969 << "'?\n";
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000970 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000971
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000972 ErrorParsing = true;
973 } else {
Chris Bieneman5d232242015-01-13 19:14:20 +0000974 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
975 E = SinkOpts.end();
976 I != E; ++I)
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000977 (*I)->addOccurrence(i, "", argv[i]);
978 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000979 continue;
980 }
981
Chris Lattner2da046f2003-07-30 17:34:02 +0000982 // If this is a named positional argument, just remember that it is the
983 // active one...
984 if (Handler->getFormattingFlag() == cl::Positional)
985 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +0000986 else
Chris Lattner0a40a972009-09-20 01:53:12 +0000987 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +0000988 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000989
Chris Lattner5df56c42002-07-22 02:07:59 +0000990 // Check and handle positional arguments now...
991 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000992 errs() << ProgramName
Chris Bieneman5d232242015-01-13 19:14:20 +0000993 << ": Not enough positional command line arguments specified!\n"
994 << "Must specify at least " << NumPositionalRequired
995 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000996
Chris Lattner5df56c42002-07-22 02:07:59 +0000997 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000998 } else if (!HasUnlimitedPositionals &&
999 PositionalVals.size() > PositionalOpts.size()) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001000 errs() << ProgramName << ": Too many positional arguments specified!\n"
1001 << "Can specify at most " << PositionalOpts.size()
1002 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerd380d842005-08-08 17:25:38 +00001003 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +00001004
Craig Topper8d399f82014-04-09 04:20:00 +00001005 } else if (!ConsumeAfterOpt) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001006 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +00001007 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1008 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001009 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +00001010 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001011 PositionalVals[ValNo].second);
1012 ValNo++;
Chris Bieneman5d232242015-01-13 19:14:20 +00001013 --NumPositionalRequired; // We fulfilled our duty...
Chris Lattner5df56c42002-07-22 02:07:59 +00001014 }
1015
1016 // If we _can_ give this option more arguments, do so now, as long as we
1017 // do not give it values that others need. 'Done' controls whether the
1018 // option even _WANTS_ any more.
1019 //
Misha Brukman069e6b52003-07-10 16:49:51 +00001020 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Bieneman5d232242015-01-13 19:14:20 +00001021 while (NumVals - ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +00001022 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001023 case cl::Optional:
Chris Bieneman5d232242015-01-13 19:14:20 +00001024 Done = true; // Optional arguments want _at most_ one value
1025 // FALL THROUGH
1026 case cl::ZeroOrMore: // Zero or more will take all they can get...
1027 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +00001028 ProvidePositionalOption(PositionalOpts[i],
1029 PositionalVals[ValNo].first,
1030 PositionalVals[ValNo].second);
1031 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +00001032 break;
1033 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001034 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Bieneman5d232242015-01-13 19:14:20 +00001035 "positional argument processing!");
Chris Lattner5df56c42002-07-22 02:07:59 +00001036 }
1037 }
Chris Lattnere81c4092001-10-27 05:54:17 +00001038 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001039 } else {
1040 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1041 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001042 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +00001043 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001044 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001045 PositionalVals[ValNo].first,
1046 PositionalVals[ValNo].second);
1047 ValNo++;
1048 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001049
1050 // Handle the case where there is just one positional option, and it's
1051 // optional. In this case, we want to give JUST THE FIRST option to the
1052 // positional option and keep the rest for the consume after. The above
1053 // loop would have assigned no values to positional options in this case.
1054 //
Chris Bienemand1d94302015-01-28 19:00:25 +00001055 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1056 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001057 PositionalVals[ValNo].first,
1058 PositionalVals[ValNo].second);
1059 ValNo++;
1060 }
Misha Brukman10468d82005-04-21 22:55:34 +00001061
Chris Lattner5df56c42002-07-22 02:07:59 +00001062 // Handle over all of the rest of the arguments to the
1063 // cl::ConsumeAfter command line option...
1064 for (; ValNo != PositionalVals.size(); ++ValNo)
Chris Bieneman5d232242015-01-13 19:14:20 +00001065 ErrorParsing |=
1066 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1067 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001068 }
1069
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001070 // Loop over args and make sure all required args are specified!
Chris Bienemand1d94302015-01-28 19:00:25 +00001071 for (const auto &Opt : OptionsMap) {
Justin Bogner973b2ff2014-07-14 19:24:13 +00001072 switch (Opt.second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001073 case Required:
1074 case OneOrMore:
Justin Bogner973b2ff2014-07-14 19:24:13 +00001075 if (Opt.second->getNumOccurrences() == 0) {
1076 Opt.second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001077 ErrorParsing = true;
1078 }
Chris Bieneman5d232242015-01-13 19:14:20 +00001079 // Fall through
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001080 default:
1081 break;
1082 }
1083 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001084
Rafael Espindolacf14a382010-11-19 21:14:29 +00001085 // Now that we know if -debug is specified, we can use it.
1086 // Note that if ReadResponseFiles == true, this must be done before the
1087 // memory allocated for the expanded command line is free()d below.
1088 DEBUG(dbgs() << "Args: ";
Chris Bieneman5d232242015-01-13 19:14:20 +00001089 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1090 dbgs() << '\n';);
Rafael Espindolacf14a382010-11-19 21:14:29 +00001091
Chris Lattner5df56c42002-07-22 02:07:59 +00001092 // Free all of the memory allocated to the map. Command line options may only
1093 // be processed once!
Chris Bienemand1d94302015-01-28 19:00:25 +00001094 MoreHelp.clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001095
1096 // If we had an error processing our arguments, don't let the program execute
Chris Bieneman5d232242015-01-13 19:14:20 +00001097 if (ErrorParsing)
1098 exit(1);
Chris Lattner36a57d32001-07-23 17:17:47 +00001099}
1100
1101//===----------------------------------------------------------------------===//
1102// Option Base class implementation
1103//
Chris Lattner36a57d32001-07-23 17:17:47 +00001104
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001105bool Option::error(const Twine &Message, StringRef ArgName) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001106 if (!ArgName.data())
1107 ArgName = ArgStr;
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001108 if (ArgName.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001109 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001110 else
Chris Bienemand1d94302015-01-28 19:00:25 +00001111 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001112
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001113 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001114 return true;
1115}
1116
Chris Bieneman5d232242015-01-13 19:14:20 +00001117bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1118 bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001119 if (!MultiArg)
Chris Bieneman5d232242015-01-13 19:14:20 +00001120 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001121
Misha Brukman069e6b52003-07-10 16:49:51 +00001122 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001123 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001124 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001125 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001126 break;
1127 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001128 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001129 return error("must occur exactly one time!", ArgName);
Chris Bieneman5d232242015-01-13 19:14:20 +00001130 // Fall through
Chris Lattner36a57d32001-07-23 17:17:47 +00001131 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001132 case ZeroOrMore:
Chris Bieneman5d232242015-01-13 19:14:20 +00001133 case ConsumeAfter:
1134 break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001135 }
1136
Reid Spencer2027a6f2004-08-13 19:47:30 +00001137 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001138}
1139
Chris Lattner5df56c42002-07-22 02:07:59 +00001140// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1141// has been specified yet.
1142//
David Blaikieff43d692015-11-17 19:00:52 +00001143static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1144 if (O.ValueStr.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001145 return DefaultMsg;
Chris Lattner5df56c42002-07-22 02:07:59 +00001146 return O.ValueStr;
1147}
1148
1149//===----------------------------------------------------------------------===//
1150// cl::alias class implementation
1151//
1152
Chris Lattner36a57d32001-07-23 17:17:47 +00001153// Return the width of the option tag for printing...
David Blaikieff43d692015-11-17 19:00:52 +00001154size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
Chris Lattner36a57d32001-07-23 17:17:47 +00001155
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001156static void printHelpStr(StringRef HelpStr, size_t Indent,
1157 size_t FirstLineIndentedBy) {
1158 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1159 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1160 while (!Split.second.empty()) {
1161 Split = Split.second.split('\n');
1162 outs().indent(Indent) << Split.first << "\n";
1163 }
1164}
1165
Chris Lattner1b7a5152006-04-28 05:36:25 +00001166// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001167void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001168 outs() << " -" << ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001169 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001170}
1171
Chris Lattner36a57d32001-07-23 17:17:47 +00001172//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001173// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001174//
1175
Chris Lattnerb4101b12002-08-07 18:36:37 +00001176// basic_parser implementation
1177//
1178
1179// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001180size_t basic_parser_impl::getOptionWidth(const Option &O) const {
David Blaikieff43d692015-11-17 19:00:52 +00001181 size_t Len = O.ArgStr.size();
Chris Lattnerb4101b12002-08-07 18:36:37 +00001182 if (const char *ValName = getValueName())
David Blaikieff43d692015-11-17 19:00:52 +00001183 Len += getValueStr(O, ValName).size() + 3;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001184
1185 return Len + 6;
1186}
1187
Misha Brukman10468d82005-04-21 22:55:34 +00001188// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001189// to-be-maintained width is specified.
1190//
1191void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001192 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001193 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001194
1195 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001196 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001197
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001198 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001199}
1200
Andrew Trick12004012011-04-05 18:54:36 +00001201void basic_parser_impl::printOptionName(const Option &O,
1202 size_t GlobalWidth) const {
1203 outs() << " -" << O.ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001204 outs().indent(GlobalWidth - O.ArgStr.size());
Andrew Trick12004012011-04-05 18:54:36 +00001205}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001206
Chris Lattner5df56c42002-07-22 02:07:59 +00001207// parser<bool> implementation
1208//
Chris Bieneman5d232242015-01-13 19:14:20 +00001209bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1210 bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001211 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001212 Arg == "1") {
1213 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001214 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001215 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001216
Chris Lattneraecd74d2009-09-19 18:55:05 +00001217 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1218 Value = false;
1219 return false;
1220 }
1221 return O.error("'" + Arg +
1222 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001223}
1224
Dale Johannesen82810c82007-05-22 17:14:46 +00001225// parser<boolOrDefault> implementation
1226//
Chris Bieneman5d232242015-01-13 19:14:20 +00001227bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1228 boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001229 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1230 Arg == "1") {
1231 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001232 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001233 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001234 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1235 Value = BOU_FALSE;
1236 return false;
1237 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001238
Chris Lattneraecd74d2009-09-19 18:55:05 +00001239 return O.error("'" + Arg +
1240 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001241}
1242
Chris Lattner5df56c42002-07-22 02:07:59 +00001243// parser<int> implementation
1244//
Chris Bieneman5d232242015-01-13 19:14:20 +00001245bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1246 int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001247 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001248 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001249 return false;
1250}
1251
Chris Lattner719c7152003-06-28 15:47:20 +00001252// parser<unsigned> implementation
1253//
Chris Bieneman5d232242015-01-13 19:14:20 +00001254bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1255 unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001256
1257 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001258 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001259 return false;
1260}
1261
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001262// parser<unsigned long long> implementation
1263//
1264bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
Chris Bieneman5d232242015-01-13 19:14:20 +00001265 StringRef Arg,
1266 unsigned long long &Value) {
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001267
1268 if (Arg.getAsInteger(0, Value))
1269 return O.error("'" + Arg + "' value invalid for uint argument!");
1270 return false;
1271}
1272
Chris Lattnerb4101b12002-08-07 18:36:37 +00001273// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001274//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001275static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001276 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1277 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001278 char *End;
1279 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001280 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001281 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001282 return false;
1283}
1284
Chris Bieneman5d232242015-01-13 19:14:20 +00001285bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1286 double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001287 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001288}
1289
Chris Bieneman5d232242015-01-13 19:14:20 +00001290bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1291 float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001292 double dVal;
1293 if (parseDouble(O, Arg, dVal))
1294 return true;
1295 Val = (float)dVal;
1296 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001297}
1298
Chris Lattner5df56c42002-07-22 02:07:59 +00001299// generic_parser_base implementation
1300//
1301
Chris Lattner494c0b02002-07-23 17:15:12 +00001302// findOption - Return the option number corresponding to the specified
1303// argument string. If the option is not found, getNumOptions() is returned.
1304//
1305unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001306 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001307
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001308 for (unsigned i = 0; i != e; ++i) {
1309 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001310 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001311 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001312 return e;
1313}
1314
Chris Lattner5df56c42002-07-22 02:07:59 +00001315// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001316size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001317 if (O.hasArgStr()) {
David Blaikieff43d692015-11-17 19:00:52 +00001318 size_t Size = O.ArgStr.size() + 6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001319 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001320 Size = std::max(Size, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001321 return Size;
1322 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001323 size_t BaseSize = 0;
Chris Lattner5df56c42002-07-22 02:07:59 +00001324 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001325 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001326 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001327 }
1328}
1329
Misha Brukman10468d82005-04-21 22:55:34 +00001330// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001331// to-be-maintained width is specified.
1332//
1333void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001334 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001335 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001336 outs() << " -" << O.ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001337 printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001338
Chris Lattner5df56c42002-07-22 02:07:59 +00001339 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001340 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001341 outs() << " =" << getOption(i);
1342 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001343 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001344 } else {
David Blaikieff43d692015-11-17 19:00:52 +00001345 if (!O.HelpStr.empty())
Chris Lattnere7c1e212009-09-20 05:03:30 +00001346 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001347 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001348 const char *Option = getOption(i);
1349 outs() << " -" << Option;
1350 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001351 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001352 }
1353}
1354
Andrew Trick12004012011-04-05 18:54:36 +00001355static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1356
1357// printGenericOptionDiff - Print the value of this option and it's default.
1358//
1359// "Generic" options have each value mapped to a name.
Chris Bieneman5d232242015-01-13 19:14:20 +00001360void generic_parser_base::printGenericOptionDiff(
1361 const Option &O, const GenericOptionValue &Value,
1362 const GenericOptionValue &Default, size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001363 outs() << " -" << O.ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001364 outs().indent(GlobalWidth - O.ArgStr.size());
Andrew Trick12004012011-04-05 18:54:36 +00001365
1366 unsigned NumOpts = getNumOptions();
1367 for (unsigned i = 0; i != NumOpts; ++i) {
1368 if (Value.compare(getOptionValue(i)))
1369 continue;
1370
1371 outs() << "= " << getOption(i);
1372 size_t L = std::strlen(getOption(i));
1373 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1374 outs().indent(NumSpaces) << " (default: ";
1375 for (unsigned j = 0; j != NumOpts; ++j) {
1376 if (Default.compare(getOptionValue(j)))
1377 continue;
1378 outs() << getOption(j);
1379 break;
1380 }
1381 outs() << ")\n";
1382 return;
1383 }
1384 outs() << "= *unknown option value*\n";
1385}
1386
1387// printOptionDiff - Specializations for printing basic value types.
1388//
Chris Bieneman5d232242015-01-13 19:14:20 +00001389#define PRINT_OPT_DIFF(T) \
1390 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1391 size_t GlobalWidth) const { \
1392 printOptionName(O, GlobalWidth); \
1393 std::string Str; \
1394 { \
1395 raw_string_ostream SS(Str); \
1396 SS << V; \
1397 } \
1398 outs() << "= " << Str; \
1399 size_t NumSpaces = \
1400 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1401 outs().indent(NumSpaces) << " (default: "; \
1402 if (D.hasValue()) \
1403 outs() << D.getValue(); \
1404 else \
1405 outs() << "*no default*"; \
1406 outs() << ")\n"; \
1407 }
Andrew Trick12004012011-04-05 18:54:36 +00001408
Frits van Bommel87e33672011-04-06 12:29:56 +00001409PRINT_OPT_DIFF(bool)
1410PRINT_OPT_DIFF(boolOrDefault)
1411PRINT_OPT_DIFF(int)
1412PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001413PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001414PRINT_OPT_DIFF(double)
1415PRINT_OPT_DIFF(float)
1416PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001417
Chris Bieneman5d232242015-01-13 19:14:20 +00001418void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1419 OptionValue<std::string> D,
1420 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001421 printOptionName(O, GlobalWidth);
1422 outs() << "= " << V;
1423 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1424 outs().indent(NumSpaces) << " (default: ";
1425 if (D.hasValue())
1426 outs() << D.getValue();
1427 else
1428 outs() << "*no default*";
1429 outs() << ")\n";
1430}
1431
1432// Print a placeholder for options that don't yet support printOptionDiff().
Chris Bieneman5d232242015-01-13 19:14:20 +00001433void basic_parser_impl::printOptionNoValue(const Option &O,
1434 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001435 printOptionName(O, GlobalWidth);
1436 outs() << "= *cannot print option value*\n";
1437}
Chris Lattner36a57d32001-07-23 17:17:47 +00001438
1439//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001440// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001441//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001442
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001443static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1444 const std::pair<const char *, Option *> *RHS) {
1445 return strcmp(LHS->first, RHS->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001446}
1447
Andrew Trick12004012011-04-05 18:54:36 +00001448// Copy Options into a vector so we can sort them as we like.
Chris Bieneman5d232242015-01-13 19:14:20 +00001449static void sortOpts(StringMap<Option *> &OptMap,
1450 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1451 bool ShowHidden) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00001452 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
Andrew Trick12004012011-04-05 18:54:36 +00001453
Chris Bieneman5d232242015-01-13 19:14:20 +00001454 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
Andrew Trick12004012011-04-05 18:54:36 +00001455 I != E; ++I) {
1456 // Ignore really-hidden options.
1457 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1458 continue;
1459
1460 // Unless showhidden is set, ignore hidden flags.
1461 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1462 continue;
1463
1464 // If we've already seen this option, don't add it to the list again.
David Blaikie70573dc2014-11-19 07:49:26 +00001465 if (!OptionSet.insert(I->second).second)
Andrew Trick12004012011-04-05 18:54:36 +00001466 continue;
1467
Chris Bieneman5d232242015-01-13 19:14:20 +00001468 Opts.push_back(
1469 std::pair<const char *, Option *>(I->getKey().data(), I->second));
Andrew Trick12004012011-04-05 18:54:36 +00001470 }
1471
1472 // Sort the options list alphabetically.
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001473 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
Andrew Trick12004012011-04-05 18:54:36 +00001474}
1475
Chris Lattner36a57d32001-07-23 17:17:47 +00001476namespace {
1477
Chris Lattner5df56c42002-07-22 02:07:59 +00001478class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001479protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001480 const bool ShowHidden;
Chris Bieneman5d232242015-01-13 19:14:20 +00001481 typedef SmallVector<std::pair<const char *, Option *>, 128>
1482 StrOptionPairVector;
Andrew Trick0537a982013-05-06 21:56:23 +00001483 // Print the options. Opts is assumed to be alphabetically sorted.
1484 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1485 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1486 Opts[i].second->printOptionInfo(MaxArgLen);
1487 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001488
Chris Lattner5df56c42002-07-22 02:07:59 +00001489public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001490 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001491 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001492
Andrew Trick0537a982013-05-06 21:56:23 +00001493 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001494 void operator=(bool Value) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00001495 if (!Value)
Chris Bieneman5d232242015-01-13 19:14:20 +00001496 return;
Chris Lattner5df56c42002-07-22 02:07:59 +00001497
Andrew Trick0537a982013-05-06 21:56:23 +00001498 StrOptionPairVector Opts;
Chris Bienemand1d94302015-01-28 19:00:25 +00001499 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
Chris Lattner36a57d32001-07-23 17:17:47 +00001500
Chris Bienemand1d94302015-01-28 19:00:25 +00001501 if (GlobalParser->ProgramOverview)
1502 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001503
Chris Bienemand1d94302015-01-28 19:00:25 +00001504 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
Chris Lattner5df56c42002-07-22 02:07:59 +00001505
Chris Bienemand1d94302015-01-28 19:00:25 +00001506 for (auto Opt : GlobalParser->PositionalOpts) {
David Blaikieff43d692015-11-17 19:00:52 +00001507 if (Opt->hasArgStr())
Chris Bienemand1d94302015-01-28 19:00:25 +00001508 outs() << " --" << Opt->ArgStr;
1509 outs() << " " << Opt->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001510 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001511
1512 // Print the consume after option info if it exists...
Chris Bienemand1d94302015-01-28 19:00:25 +00001513 if (GlobalParser->ConsumeAfterOpt)
1514 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
Chris Lattner5df56c42002-07-22 02:07:59 +00001515
Chris Lattner471ba482009-08-23 08:43:55 +00001516 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001517
1518 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001519 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001520 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001521 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001522
Chris Lattner471ba482009-08-23 08:43:55 +00001523 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001524 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001525
Chris Lattner37bcd992004-11-19 17:08:15 +00001526 // Print any extra help the user has declared.
Chris Bienemand1d94302015-01-28 19:00:25 +00001527 for (auto I : GlobalParser->MoreHelp)
1528 outs() << I;
1529 GlobalParser->MoreHelp.clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001530
Reid Spencer5e554702004-11-16 06:11:52 +00001531 // Halt the program since help information was printed
Justin Bogner02b95842014-02-28 19:08:01 +00001532 exit(0);
Chris Lattner36a57d32001-07-23 17:17:47 +00001533 }
1534};
Andrew Trick0537a982013-05-06 21:56:23 +00001535
1536class CategorizedHelpPrinter : public HelpPrinter {
1537public:
1538 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1539
1540 // Helper function for printOptions().
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001541 // It shall return a negative value if A's name should be lexicographically
1542 // ordered before B's name. It returns a value greater equal zero otherwise.
1543 static int OptionCategoryCompare(OptionCategory *const *A,
1544 OptionCategory *const *B) {
1545 return strcmp((*A)->getName(), (*B)->getName());
Andrew Trick0537a982013-05-06 21:56:23 +00001546 }
1547
1548 // Make sure we inherit our base class's operator=()
Chris Bieneman5d232242015-01-13 19:14:20 +00001549 using HelpPrinter::operator=;
Andrew Trick0537a982013-05-06 21:56:23 +00001550
1551protected:
Craig Topper32ea8262014-03-04 06:24:11 +00001552 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
Andrew Trick0537a982013-05-06 21:56:23 +00001553 std::vector<OptionCategory *> SortedCategories;
Chris Bieneman5d232242015-01-13 19:14:20 +00001554 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
Andrew Trick0537a982013-05-06 21:56:23 +00001555
Alp Tokercb402912014-01-24 17:20:08 +00001556 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001557 // sorting.
Chris Bieneman67e426a2015-02-13 22:54:32 +00001558 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1559 E = GlobalParser->RegisteredOptionCategories.end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001560 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001561 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001562 }
Andrew Trick0537a982013-05-06 21:56:23 +00001563
1564 // Sort the different option categories alphabetically.
1565 assert(SortedCategories.size() > 0 && "No option categories registered!");
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001566 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1567 OptionCategoryCompare);
Andrew Trick0537a982013-05-06 21:56:23 +00001568
1569 // Create map to empty vectors.
1570 for (std::vector<OptionCategory *>::const_iterator
1571 I = SortedCategories.begin(),
1572 E = SortedCategories.end();
1573 I != E; ++I)
1574 CategorizedOptions[*I] = std::vector<Option *>();
1575
1576 // Walk through pre-sorted options and assign into categories.
1577 // Because the options are already alphabetically sorted the
1578 // options within categories will also be alphabetically sorted.
1579 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1580 Option *Opt = Opts[I].second;
1581 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1582 "Option has an unregistered category");
1583 CategorizedOptions[Opt->Category].push_back(Opt);
1584 }
1585
1586 // Now do printing.
1587 for (std::vector<OptionCategory *>::const_iterator
1588 Category = SortedCategories.begin(),
1589 E = SortedCategories.end();
1590 Category != E; ++Category) {
1591 // Hide empty categories for -help, but show for -help-hidden.
1592 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1593 if (!ShowHidden && IsEmptyCategory)
1594 continue;
1595
1596 // Print category information.
1597 outs() << "\n";
1598 outs() << (*Category)->getName() << ":\n";
1599
1600 // Check if description is set.
Craig Topperc10719f2014-04-07 04:17:22 +00001601 if ((*Category)->getDescription() != nullptr)
Andrew Trick0537a982013-05-06 21:56:23 +00001602 outs() << (*Category)->getDescription() << "\n\n";
1603 else
1604 outs() << "\n";
1605
1606 // When using -help-hidden explicitly state if the category has no
1607 // options associated with it.
1608 if (IsEmptyCategory) {
1609 outs() << " This option category has no options.\n";
1610 continue;
1611 }
1612 // Loop over the options in the category and print.
1613 for (std::vector<Option *>::const_iterator
1614 Opt = CategorizedOptions[*Category].begin(),
1615 E = CategorizedOptions[*Category].end();
1616 Opt != E; ++Opt)
1617 (*Opt)->printOptionInfo(MaxArgLen);
1618 }
1619 }
1620};
1621
1622// This wraps the Uncategorizing and Categorizing printers and decides
1623// at run time which should be invoked.
1624class HelpPrinterWrapper {
1625private:
1626 HelpPrinter &UncategorizedPrinter;
1627 CategorizedHelpPrinter &CategorizedPrinter;
1628
1629public:
1630 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
Chris Bieneman5d232242015-01-13 19:14:20 +00001631 CategorizedHelpPrinter &CategorizedPrinter)
1632 : UncategorizedPrinter(UncategorizedPrinter),
1633 CategorizedPrinter(CategorizedPrinter) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001634
1635 // Invoke the printer.
1636 void operator=(bool Value);
1637};
1638
Chris Lattneradb19d62006-10-12 22:09:17 +00001639} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001640
Andrew Trick0537a982013-05-06 21:56:23 +00001641// Declare the four HelpPrinter instances that are used to print out help, or
1642// help-hidden as an uncategorized list or in categories.
1643static HelpPrinter UncategorizedNormalPrinter(false);
1644static HelpPrinter UncategorizedHiddenPrinter(true);
1645static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1646static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1647
Andrew Trick0537a982013-05-06 21:56:23 +00001648// Declare HelpPrinter wrappers that will decide whether or not to invoke
1649// a categorizing help printer
1650static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1651 CategorizedNormalPrinter);
1652static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1653 CategorizedHiddenPrinter);
1654
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001655// Define a category for generic options that all tools should have.
1656static cl::OptionCategory GenericCategory("Generic Options");
1657
Andrew Trick0537a982013-05-06 21:56:23 +00001658// Define uncategorized help printers.
1659// -help-list is hidden by default because if Option categories are being used
1660// then -help behaves the same as -help-list.
Chris Bieneman5d232242015-01-13 19:14:20 +00001661static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1662 "help-list",
1663 cl::desc("Display list of available options (-help-list-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001664 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1665 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001666
Chris Bieneman5d232242015-01-13 19:14:20 +00001667static cl::opt<HelpPrinter, true, parser<bool>>
1668 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1669 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001670 cl::ValueDisallowed, cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001671
1672// Define uncategorized/categorized help printers. These printers change their
1673// behaviour at runtime depending on whether one or more Option categories have
1674// been declared.
Chris Bieneman5d232242015-01-13 19:14:20 +00001675static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1676 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001677 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1678 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001679
Chris Bieneman5d232242015-01-13 19:14:20 +00001680static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1681 HHOp("help-hidden", cl::desc("Display all available options"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001682 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1683 cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001684
Chris Bieneman5d232242015-01-13 19:14:20 +00001685static cl::opt<bool> PrintOptions(
1686 "print-options",
1687 cl::desc("Print non-default options after command line parsing"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001688 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001689
Chris Bieneman5d232242015-01-13 19:14:20 +00001690static cl::opt<bool> PrintAllOptions(
1691 "print-all-options",
1692 cl::desc("Print all option values after command line parsing"), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001693 cl::init(false), cl::cat(GenericCategory));
Andrew Trick12004012011-04-05 18:54:36 +00001694
Andrew Trick0537a982013-05-06 21:56:23 +00001695void HelpPrinterWrapper::operator=(bool Value) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00001696 if (!Value)
Andrew Trick0537a982013-05-06 21:56:23 +00001697 return;
1698
1699 // Decide which printer to invoke. If more than one option category is
1700 // registered then it is useful to show the categorized help instead of
1701 // uncategorized help.
Chris Bieneman67e426a2015-02-13 22:54:32 +00001702 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
Andrew Trick0537a982013-05-06 21:56:23 +00001703 // unhide -help-list option so user can have uncategorized output if they
1704 // want it.
1705 HLOp.setHiddenFlag(NotHidden);
1706
1707 CategorizedPrinter = true; // Invoke categorized printer
Chris Bieneman5d232242015-01-13 19:14:20 +00001708 } else
Andrew Trick0537a982013-05-06 21:56:23 +00001709 UncategorizedPrinter = true; // Invoke uncategorized printer
1710}
1711
Andrew Trick12004012011-04-05 18:54:36 +00001712// Print the value of each option.
Chris Bienemand77bbab2015-01-30 22:16:01 +00001713void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1714
1715void CommandLineParser::printOptionValues() {
Chris Bieneman5d232242015-01-13 19:14:20 +00001716 if (!PrintOptions && !PrintAllOptions)
1717 return;
Andrew Trick12004012011-04-05 18:54:36 +00001718
Chris Bieneman5d232242015-01-13 19:14:20 +00001719 SmallVector<std::pair<const char *, Option *>, 128> Opts;
Chris Bienemand77bbab2015-01-30 22:16:01 +00001720 sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
Andrew Trick12004012011-04-05 18:54:36 +00001721
1722 // Compute the maximum argument length...
1723 size_t MaxArgLen = 0;
1724 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1725 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1726
1727 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1728 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1729}
1730
Craig Topperc10719f2014-04-07 04:17:22 +00001731static void (*OverrideVersionPrinter)() = nullptr;
Reid Spencerb3171672006-06-05 16:22:56 +00001732
Chris Bieneman5d232242015-01-13 19:14:20 +00001733static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
Chandler Carruthea7e5522011-07-22 07:50:40 +00001734
Chris Lattneradb19d62006-10-12 22:09:17 +00001735namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00001736class VersionPrinter {
1737public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00001738 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00001739 raw_ostream &OS = outs();
Jim Grosbach65e24652012-01-25 22:00:23 +00001740 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner131dca92009-09-20 06:18:38 +00001741 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00001742#ifdef LLVM_VERSION_INFO
Justin Bogner581b5922014-06-17 06:52:41 +00001743 OS << " " << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00001744#endif
Chris Lattner131dca92009-09-20 06:18:38 +00001745 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001746#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00001747 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001748#else
Chris Lattner131dca92009-09-20 06:18:38 +00001749 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001750#endif
1751#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00001752 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001753#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00001754 std::string CPU = sys::getHostCPUName();
Chris Bieneman5d232242015-01-13 19:14:20 +00001755 if (CPU == "generic")
1756 CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00001757 OS << ".\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001758#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner131dca92009-09-20 06:18:38 +00001759 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001760#endif
Sebastian Pop94441fb2011-11-01 21:32:20 +00001761 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00001762 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00001763 }
1764 void operator=(bool OptionWasSpecified) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001765 if (!OptionWasSpecified)
1766 return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001767
Craig Topperc10719f2014-04-07 04:17:22 +00001768 if (OverrideVersionPrinter != nullptr) {
Chandler Carruthea7e5522011-07-22 07:50:40 +00001769 (*OverrideVersionPrinter)();
Justin Bogner02b95842014-02-28 19:08:01 +00001770 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001771 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001772 print();
1773
1774 // Iterate over any registered extra printers and call them to add further
1775 // information.
Craig Topperc10719f2014-04-07 04:17:22 +00001776 if (ExtraVersionPrinters != nullptr) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00001777 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00001778 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1779 E = ExtraVersionPrinters->end();
1780 I != E; ++I)
1781 (*I)();
1782 }
1783
Justin Bogner02b95842014-02-28 19:08:01 +00001784 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001785 }
1786};
Chris Lattneradb19d62006-10-12 22:09:17 +00001787} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00001788
Reid Spencerff6cc122004-08-04 00:36:06 +00001789// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00001790static VersionPrinter VersionPrinterInstance;
1791
Chris Bieneman5d232242015-01-13 19:14:20 +00001792static cl::opt<VersionPrinter, true, parser<bool>>
1793 VersOp("version", cl::desc("Display the version of this program"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001794 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1795 cl::cat(GenericCategory));
Reid Spencerff6cc122004-08-04 00:36:06 +00001796
Reid Spencer5e554702004-11-16 06:11:52 +00001797// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00001798void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1799 // This looks weird, but it actually prints the help message. The Printers are
1800 // types of HelpPrinter and the help gets printed when its operator= is
1801 // invoked. That's because the "normal" usages of the help printer is to be
1802 // assigned true/false depending on whether -help or -help-hidden was given or
1803 // not. Since we're circumventing that we have to make it look like -help or
1804 // -help-hidden were given, so we assign true.
1805
1806 if (!Hidden && !Categorized)
1807 UncategorizedNormalPrinter = true;
1808 else if (!Hidden && Categorized)
1809 CategorizedNormalPrinter = true;
1810 else if (Hidden && !Categorized)
1811 UncategorizedHiddenPrinter = true;
1812 else
1813 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00001814}
Reid Spencerb3171672006-06-05 16:22:56 +00001815
Devang Patel9eb2caae2007-02-01 01:43:37 +00001816/// Utility function for printing version number.
Chris Bieneman5d232242015-01-13 19:14:20 +00001817void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
Devang Patel9eb2caae2007-02-01 01:43:37 +00001818
Chris Bieneman5d232242015-01-13 19:14:20 +00001819void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001820
1821void cl::AddExtraVersionPrinter(void (*func)()) {
Craig Topper8d399f82014-04-09 04:20:00 +00001822 if (!ExtraVersionPrinters)
Chandler Carruthea7e5522011-07-22 07:50:40 +00001823 ExtraVersionPrinters = new std::vector<void (*)()>;
1824
1825 ExtraVersionPrinters->push_back(func);
1826}
Andrew Trick7cb710d2013-05-06 21:56:35 +00001827
Chris Bienemand1d94302015-01-28 19:00:25 +00001828StringMap<Option *> &cl::getRegisteredOptions() {
1829 return GlobalParser->OptionsMap;
Andrew Trick7cb710d2013-05-06 21:56:35 +00001830}
Peter Collingbournee1863192014-10-16 22:47:52 +00001831
Chris Bieneman9e13af72015-01-21 22:45:52 +00001832void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
Chris Bienemand1d94302015-01-28 19:00:25 +00001833 for (auto &I : GlobalParser->OptionsMap) {
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001834 if (I.second->Category != &Category &&
1835 I.second->Category != &GenericCategory)
Chris Bieneman9e13af72015-01-21 22:45:52 +00001836 I.second->setHiddenFlag(cl::ReallyHidden);
1837 }
1838}
1839
Chris Bieneman68169362015-01-27 22:21:06 +00001840void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
Chris Bieneman01043252015-01-26 21:57:29 +00001841 auto CategoriesBegin = Categories.begin();
1842 auto CategoriesEnd = Categories.end();
Chris Bienemand1d94302015-01-28 19:00:25 +00001843 for (auto &I : GlobalParser->OptionsMap) {
Chris Bieneman01043252015-01-26 21:57:29 +00001844 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1845 CategoriesEnd &&
1846 I.second->Category != &GenericCategory)
1847 I.second->setHiddenFlag(cl::ReallyHidden);
1848 }
1849}
1850
Peter Collingbournee1863192014-10-16 22:47:52 +00001851void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1852 const char *Overview) {
1853 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1854}