blob: 9be0daada506fb9f7bdf334924834acf3c00df8b [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) {
Sanjoy Das39c226f2016-06-10 21:18:39 +0000197 assert(count_if(RegisteredOptionCategories,
198 [cat](const OptionCategory *Category) {
199 return cat->getName() == Category->getName();
200 }) == 0 &&
Chris Bieneman67e426a2015-02-13 22:54:32 +0000201 "Duplicate option categories");
202
203 RegisteredOptionCategories.insert(cat);
204 }
205
Chris Bieneman542f56a2015-02-13 22:54:27 +0000206private:
207 Option *LookupOption(StringRef &Arg, StringRef &Value);
Chris Bienemand1d94302015-01-28 19:00:25 +0000208};
209
Benjamin Kramer970eac42015-02-06 17:51:54 +0000210} // namespace
211
Chris Bienemand1d94302015-01-28 19:00:25 +0000212static ManagedStatic<CommandLineParser> GlobalParser;
213
214void cl::AddLiteralOption(Option &O, const char *Name) {
215 GlobalParser->addLiteralOption(O, Name);
216}
Chris Lattner37bcd992004-11-19 17:08:15 +0000217
Chris Bieneman5d232242015-01-13 19:14:20 +0000218extrahelp::extrahelp(const char *Help) : morehelp(Help) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000219 GlobalParser->MoreHelp.push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +0000220}
221
Chris Lattner5247f602007-04-06 21:06:55 +0000222void Option::addArgument() {
Chris Bienemand1d94302015-01-28 19:00:25 +0000223 GlobalParser->addOption(this);
224 FullyInitialized = true;
Chris Lattner5247f602007-04-06 21:06:55 +0000225}
226
Chris Bienemand1d94302015-01-28 19:00:25 +0000227void Option::removeArgument() { GlobalParser->removeOption(this); }
228
David Blaikieff43d692015-11-17 19:00:52 +0000229void Option::setArgStr(StringRef S) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000230 if (FullyInitialized)
231 GlobalParser->updateArgStr(this, S);
232 ArgStr = S;
Jordan Rosec25b0c72014-01-29 18:54:17 +0000233}
234
Andrew Trick0537a982013-05-06 21:56:23 +0000235// Initialise the general option category.
236OptionCategory llvm::cl::GeneralCategory("General options");
237
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000238void OptionCategory::registerCategory() {
Chris Bieneman67e426a2015-02-13 22:54:32 +0000239 GlobalParser->registerCategory(this);
Andrew Trick0537a982013-05-06 21:56:23 +0000240}
Chris Lattneraf039c52007-04-12 00:36:29 +0000241
Chris Lattner5df56c42002-07-22 02:07:59 +0000242//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000243// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000244//
245
Chris Lattner2031b022007-04-05 21:58:17 +0000246/// LookupOption - Lookup the option specified by the specified option on the
247/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000248/// that as well. This assumes that leading dashes have already been stripped.
Chris Bieneman542f56a2015-02-13 22:54:27 +0000249Option *CommandLineParser::LookupOption(StringRef &Arg, StringRef &Value) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000250 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000251 if (Arg.empty())
252 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000253
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000254 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000255
Chris Lattner0a40a972009-09-20 01:53:12 +0000256 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000257 if (EqualPos == StringRef::npos) {
258 // Look up the option.
Chris Bieneman5d232242015-01-13 19:14:20 +0000259 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
Craig Topperc10719f2014-04-07 04:17:22 +0000260 return I != OptionsMap.end() ? I->second : nullptr;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000261 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000262
Chris Lattnere7c1e212009-09-20 05:03:30 +0000263 // If the argument before the = is a valid option name, we match. If not,
264 // return Arg unmolested.
Chris Bieneman5d232242015-01-13 19:14:20 +0000265 StringMap<Option *>::const_iterator I =
266 OptionsMap.find(Arg.substr(0, EqualPos));
267 if (I == OptionsMap.end())
268 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000269
Chris Bieneman5d232242015-01-13 19:14:20 +0000270 Value = Arg.substr(EqualPos + 1);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000271 Arg = Arg.substr(0, EqualPos);
272 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000273}
274
Daniel Dunbarf4132132011-01-18 01:59:24 +0000275/// LookupNearestOption - Lookup the closest match to the option specified by
276/// the specified option on the command line. If there is a value specified
277/// (after an equal sign) return that as well. This assumes that leading dashes
278/// have already been stripped.
279static Option *LookupNearestOption(StringRef Arg,
Chris Bieneman5d232242015-01-13 19:14:20 +0000280 const StringMap<Option *> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000281 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000282 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000283 if (Arg.empty())
284 return nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000285
286 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000287 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
Chris Bieneman5d232242015-01-13 19:14:20 +0000288 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000289 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000290
291 // Find the closest match.
Craig Topperc10719f2014-04-07 04:17:22 +0000292 Option *Best = nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000293 unsigned BestDistance = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000294 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
295 ie = OptionsMap.end();
296 it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000297 Option *O = it->second;
David Blaikieff43d692015-11-17 19:00:52 +0000298 SmallVector<StringRef, 16> OptionNames;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000299 O->getExtraOptionNames(OptionNames);
David Blaikieff43d692015-11-17 19:00:52 +0000300 if (O->hasArgStr())
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000301 OptionNames.push_back(O->ArgStr);
302
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000303 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
304 StringRef Flag = PermitValue ? LHS : Arg;
David Blaikieff43d692015-11-17 19:00:52 +0000305 for (auto Name : OptionNames) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000306 unsigned Distance = StringRef(Name).edit_distance(
Chris Bieneman5d232242015-01-13 19:14:20 +0000307 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000308 if (!Best || Distance < BestDistance) {
309 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000310 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000311 if (RHS.empty() || !PermitValue)
David Blaikieff43d692015-11-17 19:00:52 +0000312 NearestString = Name;
Bill Wendling318f03f2012-07-19 00:15:11 +0000313 else
David Blaikieff43d692015-11-17 19:00:52 +0000314 NearestString = (Twine(Name) + "=" + RHS).str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000315 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000316 }
317 }
318
319 return Best;
320}
321
Alp Tokercb402912014-01-24 17:20:08 +0000322/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
323/// that does special handling of cl::CommaSeparated options.
324static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
325 StringRef ArgName, StringRef Value,
326 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000327 // Check to see if this option accepts a comma separated list of values. If
328 // it does, we have to split up the value into multiple values.
329 if (Handler->getMiscFlags() & CommaSeparated) {
330 StringRef Val(Value);
331 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000332
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000333 while (Pos != StringRef::npos) {
334 // Process the portion before the comma.
335 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
336 return true;
337 // Erase the portion before the comma, AND the comma.
Chris Bieneman5d232242015-01-13 19:14:20 +0000338 Val = Val.substr(Pos + 1);
339 Value.substr(Pos + 1); // Increment the original value pointer as well.
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000340 // Check for another comma.
341 Pos = Val.find(',');
342 }
343
344 Value = Val;
345 }
346
Alexander Kornienko66da20a2015-12-28 15:46:15 +0000347 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000348}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000349
Chris Lattner40fef802009-09-20 01:49:31 +0000350/// ProvideOption - For Value, this differentiates between an empty value ("")
351/// and a null value (StringRef()). The later is accepted for arguments that
352/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000353static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000354 StringRef Value, int argc,
355 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000356 // Is this a multi-argument option?
357 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
358
Chris Lattnere81c4092001-10-27 05:54:17 +0000359 // Enforce value requirements
360 switch (Handler->getValueExpectedFlag()) {
361 case ValueRequired:
Craig Topper8d399f82014-04-09 04:20:00 +0000362 if (!Value.data()) { // No value specified?
Chris Bieneman5d232242015-01-13 19:14:20 +0000363 if (i + 1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000364 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000365 // Steal the next argument, like for '-o filename'
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000366 assert(argv && "null check");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000367 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000368 }
369 break;
370 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000371 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000372 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000373 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000374
Chris Lattner40fef802009-09-20 01:49:31 +0000375 if (Value.data())
Chris Bieneman5d232242015-01-13 19:14:20 +0000376 return Handler->error("does not allow a value! '" + Twine(Value) +
377 "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000378 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000379 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000380 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000381 }
382
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000383 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000384 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000385 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000386
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000387 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000388 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000389
Chris Lattner40fef802009-09-20 01:49:31 +0000390 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000391 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000392 return true;
393 --NumAdditionalVals;
394 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000395 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000396
397 while (NumAdditionalVals > 0) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000398 if (i + 1 >= argc)
Chris Lattneraecd74d2009-09-19 18:55:05 +0000399 return Handler->error("not enough values!");
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000400 assert(argv && "null check");
Chris Lattneraecd74d2009-09-19 18:55:05 +0000401 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000402
Alp Tokercb402912014-01-24 17:20:08 +0000403 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000404 return true;
405 MultiArg = true;
406 --NumAdditionalVals;
407 }
408 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000409}
410
Chris Lattnerca2552d2009-09-20 00:07:40 +0000411static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000412 int Dummy = i;
Craig Topperc10719f2014-04-07 04:17:22 +0000413 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000414}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000415
Chris Lattner5df56c42002-07-22 02:07:59 +0000416// Option predicates...
417static inline bool isGrouping(const Option *O) {
418 return O->getFormattingFlag() == cl::Grouping;
419}
420static inline bool isPrefixedOrGrouping(const Option *O) {
421 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
422}
423
424// getOptionPred - Check to see if there are any options that satisfy the
425// specified predicate with names that are the prefixes in Name. This is
426// checked by progressively stripping characters off of the name, checking to
427// see if there options that satisfy the predicate. If we find one, return it,
428// otherwise return null.
429//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000430static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Bieneman5d232242015-01-13 19:14:20 +0000431 bool (*Pred)(const Option *),
432 const StringMap<Option *> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000433
Chris Bieneman5d232242015-01-13 19:14:20 +0000434 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000435
Chris Lattnere7c1e212009-09-20 05:03:30 +0000436 // Loop while we haven't found an option and Name still has at least two
437 // characters in it (so that the next iteration will not be the empty
438 // string.
439 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000440 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000441 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000442 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000443
Chris Lattner5247f602007-04-06 21:06:55 +0000444 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000445 Length = Name.size();
Chris Bieneman5d232242015-01-13 19:14:20 +0000446 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000447 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000448 return nullptr; // No option found!
Chris Lattner5df56c42002-07-22 02:07:59 +0000449}
450
Chris Lattnere7c1e212009-09-20 05:03:30 +0000451/// HandlePrefixedOrGroupedOption - The specified argument string (which started
452/// with at least one '-') does not fully match an available option. Check to
453/// see if this is a prefix or grouped option. If so, split arg into output an
454/// Arg/Value pair and return the Option to parse it with.
Chris Bieneman5d232242015-01-13 19:14:20 +0000455static Option *
456HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
457 bool &ErrorParsing,
458 const StringMap<Option *> &OptionsMap) {
459 if (Arg.size() == 1)
460 return nullptr;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000461
462 // Do the lookup!
463 size_t Length = 0;
464 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
Chris Bieneman5d232242015-01-13 19:14:20 +0000465 if (!PGOpt)
466 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000467
Chris Lattnere7c1e212009-09-20 05:03:30 +0000468 // If the option is a prefixed option, then the value is simply the
469 // rest of the name... so fall through to later processing, by
470 // setting up the argument name flags and value fields.
471 if (PGOpt->getFormattingFlag() == cl::Prefix) {
472 Value = Arg.substr(Length);
473 Arg = Arg.substr(0, Length);
474 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
475 return PGOpt;
476 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000477
Chris Lattnere7c1e212009-09-20 05:03:30 +0000478 // This must be a grouped option... handle them now. Grouping options can't
479 // have values.
480 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000481
Chris Lattnere7c1e212009-09-20 05:03:30 +0000482 do {
483 // Move current arg name out of Arg into OneArgName.
484 StringRef OneArgName = Arg.substr(0, Length);
485 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000486
Chris Lattnere7c1e212009-09-20 05:03:30 +0000487 // Because ValueRequired is an invalid flag for grouped arguments,
488 // we don't need to pass argc/argv in.
489 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
490 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000491 int Dummy = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000492 ErrorParsing |=
493 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000494
Chris Lattnere7c1e212009-09-20 05:03:30 +0000495 // Get the next grouping option.
496 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
497 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000498
Chris Lattnere7c1e212009-09-20 05:03:30 +0000499 // Return the last option with Arg cut down to just the last one.
500 return PGOpt;
501}
502
Chris Lattner5df56c42002-07-22 02:07:59 +0000503static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000504 return O->getNumOccurrencesFlag() == cl::Required ||
505 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000506}
507
508static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000509 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
510 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000511}
Chris Lattnere81c4092001-10-27 05:54:17 +0000512
Chris Bieneman5d232242015-01-13 19:14:20 +0000513static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
Brian Gaeke497216d2003-08-15 21:05:57 +0000514
Chris Bieneman5d232242015-01-13 19:14:20 +0000515static bool isQuote(char C) { return C == '\"' || C == '\''; }
Reid Klecknera73c7782013-07-18 16:52:05 +0000516
Reid Klecknera73c7782013-07-18 16:52:05 +0000517void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000518 SmallVectorImpl<const char *> &NewArgv,
519 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000520 SmallString<128> Token;
521 for (size_t I = 0, E = Src.size(); I != E; ++I) {
522 // Consume runs of whitespace.
523 if (Token.empty()) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000524 while (I != E && isWhitespace(Src[I])) {
525 // Mark the end of lines in response files
526 if (MarkEOLs && Src[I] == '\n')
527 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000528 ++I;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000529 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000530 if (I == E)
531 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000532 }
533
Nico Weberfa7f4892016-04-26 13:53:56 +0000534 // Backslash escapes the next character.
535 if (I + 1 < E && Src[I] == '\\') {
Chris Bieneman5d232242015-01-13 19:14:20 +0000536 ++I; // Skip the escape.
Reid Klecknera73c7782013-07-18 16:52:05 +0000537 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000538 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000539 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000540
Reid Klecknera73c7782013-07-18 16:52:05 +0000541 // Consume a quoted string.
542 if (isQuote(Src[I])) {
543 char Quote = Src[I++];
544 while (I != E && Src[I] != Quote) {
Nico Weberfa7f4892016-04-26 13:53:56 +0000545 // Backslash escapes the next character.
546 if (Src[I] == '\\' && I + 1 != E)
Reid Klecknera73c7782013-07-18 16:52:05 +0000547 ++I;
548 Token.push_back(Src[I]);
549 ++I;
550 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000551 if (I == E)
552 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000553 continue;
554 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000555
Reid Klecknera73c7782013-07-18 16:52:05 +0000556 // End the token if this is whitespace.
557 if (isWhitespace(Src[I])) {
558 if (!Token.empty())
Rafael Espindola454adf62015-06-13 12:49:52 +0000559 NewArgv.push_back(Saver.save(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000560 Token.clear();
561 continue;
562 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000563
Reid Klecknera73c7782013-07-18 16:52:05 +0000564 // This is a normal character. Append it.
565 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000566 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000567
568 // Append the last token after hitting EOF with no whitespace.
569 if (!Token.empty())
Rafael Espindola454adf62015-06-13 12:49:52 +0000570 NewArgv.push_back(Saver.save(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000571 // Mark the end of response files
572 if (MarkEOLs)
573 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000574}
575
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000576/// Backslashes are interpreted in a rather complicated way in the Windows-style
577/// command line, because backslashes are used both to separate path and to
578/// escape double quote. This method consumes runs of backslashes as well as the
579/// following double quote if it's escaped.
580///
581/// * If an even number of backslashes is followed by a double quote, one
582/// backslash is output for every pair of backslashes, and the last double
583/// quote remains unconsumed. The double quote will later be interpreted as
584/// the start or end of a quoted string in the main loop outside of this
585/// function.
586///
587/// * If an odd number of backslashes is followed by a double quote, one
588/// backslash is output for every pair of backslashes, and a double quote is
589/// output for the last pair of backslash-double quote. The double quote is
590/// consumed in this case.
591///
592/// * Otherwise, backslashes are interpreted literally.
593static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
594 size_t E = Src.size();
595 int BackslashCount = 0;
596 // Skip the backslashes.
597 do {
598 ++I;
599 ++BackslashCount;
600 } while (I != E && Src[I] == '\\');
601
602 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
603 if (FollowedByDoubleQuote) {
604 Token.append(BackslashCount / 2, '\\');
605 if (BackslashCount % 2 == 0)
606 return I - 1;
607 Token.push_back('"');
608 return I;
609 }
610 Token.append(BackslashCount, '\\');
611 return I - 1;
612}
613
Reid Klecknera73c7782013-07-18 16:52:05 +0000614void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000615 SmallVectorImpl<const char *> &NewArgv,
616 bool MarkEOLs) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000617 SmallString<128> Token;
618
619 // This is a small state machine to consume characters until it reaches the
620 // end of the source string.
621 enum { INIT, UNQUOTED, QUOTED } State = INIT;
622 for (size_t I = 0, E = Src.size(); I != E; ++I) {
623 // INIT state indicates that the current input index is at the start of
624 // the string or between tokens.
625 if (State == INIT) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000626 if (isWhitespace(Src[I])) {
627 // Mark the end of lines in response files
628 if (MarkEOLs && Src[I] == '\n')
629 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000630 continue;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000631 }
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000632 if (Src[I] == '"') {
633 State = QUOTED;
634 continue;
635 }
636 if (Src[I] == '\\') {
637 I = parseBackslash(Src, I, Token);
638 State = UNQUOTED;
639 continue;
640 }
641 Token.push_back(Src[I]);
642 State = UNQUOTED;
643 continue;
644 }
645
646 // UNQUOTED state means that it's reading a token not quoted by double
647 // quotes.
648 if (State == UNQUOTED) {
649 // Whitespace means the end of the token.
650 if (isWhitespace(Src[I])) {
Rafael Espindola454adf62015-06-13 12:49:52 +0000651 NewArgv.push_back(Saver.save(Token.c_str()));
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000652 Token.clear();
653 State = INIT;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000654 // Mark the end of lines in response files
655 if (MarkEOLs && Src[I] == '\n')
656 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000657 continue;
658 }
659 if (Src[I] == '"') {
660 State = QUOTED;
661 continue;
662 }
663 if (Src[I] == '\\') {
664 I = parseBackslash(Src, I, Token);
665 continue;
666 }
667 Token.push_back(Src[I]);
668 continue;
669 }
670
671 // QUOTED state means that it's reading a token quoted by double quotes.
672 if (State == QUOTED) {
673 if (Src[I] == '"') {
674 State = UNQUOTED;
675 continue;
676 }
677 if (Src[I] == '\\') {
678 I = parseBackslash(Src, I, Token);
679 continue;
680 }
681 Token.push_back(Src[I]);
682 }
683 }
684 // Append the last token after hitting EOF with no whitespace.
685 if (!Token.empty())
Rafael Espindola454adf62015-06-13 12:49:52 +0000686 NewArgv.push_back(Saver.save(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000687 // Mark the end of response files
688 if (MarkEOLs)
689 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000690}
691
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000692// It is called byte order marker but the UTF-8 BOM is actually not affected
693// by the host system's endianness.
694static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
Chris Bienemanceaf5f62015-02-13 22:54:29 +0000695 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000696}
697
Reid Klecknera73c7782013-07-18 16:52:05 +0000698static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
699 TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000700 SmallVectorImpl<const char *> &NewArgv,
701 bool MarkEOLs = false) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000702 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
703 MemoryBuffer::getFile(FName);
704 if (!MemBufOrErr)
Reid Klecknera73c7782013-07-18 16:52:05 +0000705 return false;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000706 MemoryBuffer &MemBuf = *MemBufOrErr.get();
707 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
Reid Klecknera73c7782013-07-18 16:52:05 +0000708
709 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000710 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
Reid Klecknera73c7782013-07-18 16:52:05 +0000711 std::string UTF8Buf;
712 if (hasUTF16ByteOrderMark(BufRef)) {
713 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
714 return false;
715 Str = StringRef(UTF8Buf);
716 }
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000717 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
718 // these bytes before parsing.
719 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
720 else if (hasUTF8ByteOrderMark(BufRef))
721 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
Reid Klecknera73c7782013-07-18 16:52:05 +0000722
723 // Tokenize the contents into NewArgv.
Reid Klecknere3f146d2014-08-22 19:29:17 +0000724 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
Reid Klecknera73c7782013-07-18 16:52:05 +0000725
726 return true;
727}
728
729/// \brief Expand response files on a command line recursively using the given
730/// StringSaver and tokenization strategy.
731bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000732 SmallVectorImpl<const char *> &Argv,
733 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000734 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000735 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000736
737 // Don't cache Argv.size() because it can change.
Chris Bieneman5d232242015-01-13 19:14:20 +0000738 for (unsigned I = 0; I != Argv.size();) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000739 const char *Arg = Argv[I];
Reid Klecknere3f146d2014-08-22 19:29:17 +0000740 // Check if it is an EOL marker
741 if (Arg == nullptr) {
742 ++I;
743 continue;
744 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000745 if (Arg[0] != '@') {
746 ++I;
747 continue;
748 }
749
750 // If we have too many response files, leave some unexpanded. This avoids
751 // crashing on self-referential response files.
752 if (RspFiles++ > 20)
753 return false;
754
755 // Replace this response file argument with the tokenization of its
756 // contents. Nested response files are expanded in subsequent iterations.
757 // FIXME: If a nested response file uses a relative path, is it relative to
758 // the cwd of the process or the response file?
759 SmallVector<const char *, 0> ExpandedArgv;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000760 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
761 MarkEOLs)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000762 // We couldn't read this file, so we leave it in the argument stream and
763 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000764 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000765 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000766 continue;
767 }
768 Argv.erase(Argv.begin() + I);
769 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
770 }
771 return AllExpanded;
772}
773
Brian Gaekeca782d92003-08-14 22:00:59 +0000774/// ParseEnvironmentOptions - An alternative entry point to the
775/// CommandLine library, which allows you to read the program's name
776/// from the caller (as PROGNAME) and its command-line arguments from
777/// an environment variable (whose name is given in ENVVAR).
778///
Chris Lattnera60f3552004-05-06 22:04:31 +0000779void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000780 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000781 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000782 assert(progName && "Program name not specified");
783 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000784
Brian Gaeke497216d2003-08-15 21:05:57 +0000785 // Get the environment variable they want us to parse options out of.
Marianne Mailhot-Sarrasin7423f402016-03-11 15:59:32 +0000786#ifdef _WIN32
787 std::wstring wenvVar;
788 if (!llvm::ConvertUTF8toWide(envVar, wenvVar)) {
789 assert(false &&
790 "Unicode conversion of environment variable name failed");
791 return;
792 }
793 const wchar_t *wenvValue = _wgetenv(wenvVar.c_str());
794 if (!wenvValue)
795 return;
796 std::string envValueBuffer;
797 if (!llvm::convertWideToUTF8(wenvValue, envValueBuffer)) {
798 assert(false &&
799 "Unicode conversion of environment variable value failed");
800 return;
801 }
802 const char *envValue = envValueBuffer.c_str();
803#else
Chris Lattner2de6e332006-08-27 22:10:29 +0000804 const char *envValue = getenv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000805 if (!envValue)
806 return;
Marianne Mailhot-Sarrasin7423f402016-03-11 15:59:32 +0000807#endif
Brian Gaeke497216d2003-08-15 21:05:57 +0000808
Brian Gaekeca782d92003-08-14 22:00:59 +0000809 // Get program's "name", which we wouldn't know without the caller
810 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000811 SmallVector<const char *, 20> newArgv;
Rafael Espindola454adf62015-06-13 12:49:52 +0000812 BumpPtrAllocator A;
Rafael Espindolab82455d2015-08-13 01:07:02 +0000813 StringSaver Saver(A);
Rafael Espindola454adf62015-06-13 12:49:52 +0000814 newArgv.push_back(Saver.save(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000815
816 // Parse the value of the environment variable into a "command line"
817 // and hand it off to ParseCommandLineOptions().
Reid Klecknera73c7782013-07-18 16:52:05 +0000818 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000819 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000820 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000821}
822
Chris Bieneman5d232242015-01-13 19:14:20 +0000823void cl::ParseCommandLineOptions(int argc, const char *const *argv,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000824 const char *Overview) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000825 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
826}
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000827
Chris Bienemand1d94302015-01-28 19:00:25 +0000828void CommandLineParser::ParseCommandLineOptions(int argc,
829 const char *const *argv,
830 const char *Overview) {
831 assert(hasOptions() && "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000832
833 // Expand response files.
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000834 SmallVector<const char *, 20> newArgv(argv, argv + argc);
Rafael Espindola454adf62015-06-13 12:49:52 +0000835 BumpPtrAllocator A;
Rafael Espindolab82455d2015-08-13 01:07:02 +0000836 StringSaver Saver(A);
Reid Klecknera73c7782013-07-18 16:52:05 +0000837 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000838 argv = &newArgv[0];
839 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000840
Chris Lattner5af1cbc2006-10-13 00:06:24 +0000841 // Copy the program name into ProgName, making sure not to overflow it.
Chris Bienemanb6866422015-01-28 22:25:00 +0000842 ProgramName = sys::path::filename(argv[0]);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000843
Chris Lattner36a57d32001-07-23 17:17:47 +0000844 ProgramOverview = Overview;
845 bool ErrorParsing = false;
846
Chris Lattner5df56c42002-07-22 02:07:59 +0000847 // Check out the positional arguments to collect information about them.
848 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000849
Chris Lattnerd380d842005-08-08 17:25:38 +0000850 // Determine whether or not there are an unlimited number of positionals
851 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000852
Chris Bienemand1d94302015-01-28 19:00:25 +0000853 if (ConsumeAfterOpt) {
854 assert(PositionalOpts.size() > 0 &&
855 "Cannot specify cl::ConsumeAfter without a positional argument!");
856 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000857 if (!PositionalOpts.empty()) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000858
859 // Calculate how many positional values are _required_.
860 bool UnboundedFound = false;
Chris Bienemand1d94302015-01-28 19:00:25 +0000861 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000862 Option *Opt = PositionalOpts[i];
863 if (RequiresValue(Opt))
864 ++NumPositionalRequired;
865 else if (ConsumeAfterOpt) {
866 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +0000867 // unless there is only one positional argument...
Chris Bienemand1d94302015-01-28 19:00:25 +0000868 if (PositionalOpts.size() > 1)
Chris Bieneman5d232242015-01-13 19:14:20 +0000869 ErrorParsing |= Opt->error(
870 "error - this positional option will never be matched, "
871 "because it does not Require a value, and a "
872 "cl::ConsumeAfter option is active!");
David Blaikieff43d692015-11-17 19:00:52 +0000873 } else if (UnboundedFound && !Opt->hasArgStr()) {
Chris Lattner2da046f2003-07-30 17:34:02 +0000874 // This option does not "require" a value... Make sure this option is
875 // not specified after an option that eats all extra arguments, or this
876 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +0000877 //
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000878 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner5df56c42002-07-22 02:07:59 +0000879 "another positional argument will match an "
880 "unbounded number of values, and this option"
881 " does not require a value!");
Chris Bienemand1d94302015-01-28 19:00:25 +0000882 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
883 << "' is all messed up!\n";
884 errs() << PositionalOpts.size();
Chris Lattner5df56c42002-07-22 02:07:59 +0000885 }
886 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
887 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +0000888 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +0000889 }
890
Reid Spencer2027a6f2004-08-13 19:47:30 +0000891 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +0000892 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +0000893 //
Chris Bieneman5d232242015-01-13 19:14:20 +0000894 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +0000895
Chris Lattner2da046f2003-07-30 17:34:02 +0000896 // If the program has named positional arguments, and the name has been run
897 // across, keep track of which positional argument was named. Otherwise put
898 // the positional args into the PositionalVals list...
Craig Topperc10719f2014-04-07 04:17:22 +0000899 Option *ActivePositionalArg = nullptr;
Chris Lattner2da046f2003-07-30 17:34:02 +0000900
Chris Lattner36a57d32001-07-23 17:17:47 +0000901 // Loop over all of the arguments... processing them.
Chris Bieneman5d232242015-01-13 19:14:20 +0000902 bool DashDashFound = false; // Have we read '--'?
Chris Lattner36a57d32001-07-23 17:17:47 +0000903 for (int i = 1; i < argc; ++i) {
Craig Topperc10719f2014-04-07 04:17:22 +0000904 Option *Handler = nullptr;
905 Option *NearestHandler = nullptr;
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000906 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +0000907 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000908 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +0000909
910 // Check to see if this is a positional argument. This argument is
911 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +0000912 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +0000913 //
914 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
915 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +0000916 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000917 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000918 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000919 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000920
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000921 if (!PositionalOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000922 PositionalVals.push_back(std::make_pair(argv[i], i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000923
924 // All of the positional arguments have been fulfulled, give the rest to
925 // the consume after option... if it's specified...
926 //
Craig Topper8d399f82014-04-09 04:20:00 +0000927 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000928 for (++i; i < argc; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +0000929 PositionalVals.push_back(std::make_pair(argv[i], i));
930 break; // Handle outside of the argument processing loop...
Chris Lattner5df56c42002-07-22 02:07:59 +0000931 }
932
933 // Delay processing positional arguments until the end...
934 continue;
935 }
Chris Lattnera60f3552004-05-06 22:04:31 +0000936 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
937 !DashDashFound) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000938 DashDashFound = true; // This is the mythical "--"?
939 continue; // Don't try to process it as an argument itself.
Chris Lattnera60f3552004-05-06 22:04:31 +0000940 } else if (ActivePositionalArg &&
941 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
942 // If there is a positional argument eating options, check to see if this
943 // option is another positional argument. If so, treat it as an argument,
944 // otherwise feed it to the eating positional.
Chris Bieneman5d232242015-01-13 19:14:20 +0000945 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000946 // Eat leading dashes.
947 while (!ArgName.empty() && ArgName[0] == '-')
948 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000949
Chris Bieneman542f56a2015-02-13 22:54:27 +0000950 Handler = LookupOption(ArgName, Value);
Chris Lattnera60f3552004-05-06 22:04:31 +0000951 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000952 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000953 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +0000954 }
955
Chris Bieneman5d232242015-01-13 19:14:20 +0000956 } else { // We start with a '-', must be an argument.
957 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000958 // Eat leading dashes.
959 while (!ArgName.empty() && ArgName[0] == '-')
960 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000961
Chris Bieneman542f56a2015-02-13 22:54:27 +0000962 Handler = LookupOption(ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +0000963
Chris Lattnera60f3552004-05-06 22:04:31 +0000964 // Check to see if this "option" is really a prefixed or grouped argument.
Craig Topper8d399f82014-04-09 04:20:00 +0000965 if (!Handler)
Chris Bienemand1d94302015-01-28 19:00:25 +0000966 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
967 OptionsMap);
Daniel Dunbarf4132132011-01-18 01:59:24 +0000968
969 // Otherwise, look for the closest available option to report to the user
970 // in the upcoming error.
Craig Topper8d399f82014-04-09 04:20:00 +0000971 if (!Handler && SinkOpts.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +0000972 NearestHandler =
Chris Bienemand1d94302015-01-28 19:00:25 +0000973 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +0000974 }
975
Craig Topper8d399f82014-04-09 04:20:00 +0000976 if (!Handler) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000977 if (SinkOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000978 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
979 << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +0000980
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000981 if (NearestHandler) {
982 // If we know a near match, report it as well.
Chris Bieneman5d232242015-01-13 19:14:20 +0000983 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
984 << "'?\n";
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000985 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000986
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000987 ErrorParsing = true;
988 } else {
Chris Bieneman5d232242015-01-13 19:14:20 +0000989 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
990 E = SinkOpts.end();
991 I != E; ++I)
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000992 (*I)->addOccurrence(i, "", argv[i]);
993 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000994 continue;
995 }
996
Chris Lattner2da046f2003-07-30 17:34:02 +0000997 // If this is a named positional argument, just remember that it is the
998 // active one...
999 if (Handler->getFormattingFlag() == cl::Positional)
1000 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +00001001 else
Chris Lattner0a40a972009-09-20 01:53:12 +00001002 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +00001003 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001004
Chris Lattner5df56c42002-07-22 02:07:59 +00001005 // Check and handle positional arguments now...
1006 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001007 errs() << ProgramName
Chris Bieneman5d232242015-01-13 19:14:20 +00001008 << ": Not enough positional command line arguments specified!\n"
1009 << "Must specify at least " << NumPositionalRequired
1010 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001011
Chris Lattner5df56c42002-07-22 02:07:59 +00001012 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001013 } else if (!HasUnlimitedPositionals &&
1014 PositionalVals.size() > PositionalOpts.size()) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001015 errs() << ProgramName << ": Too many positional arguments specified!\n"
1016 << "Can specify at most " << PositionalOpts.size()
1017 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerd380d842005-08-08 17:25:38 +00001018 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +00001019
Craig Topper8d399f82014-04-09 04:20:00 +00001020 } else if (!ConsumeAfterOpt) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001021 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +00001022 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1023 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001024 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +00001025 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001026 PositionalVals[ValNo].second);
1027 ValNo++;
Chris Bieneman5d232242015-01-13 19:14:20 +00001028 --NumPositionalRequired; // We fulfilled our duty...
Chris Lattner5df56c42002-07-22 02:07:59 +00001029 }
1030
1031 // If we _can_ give this option more arguments, do so now, as long as we
1032 // do not give it values that others need. 'Done' controls whether the
1033 // option even _WANTS_ any more.
1034 //
Misha Brukman069e6b52003-07-10 16:49:51 +00001035 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Bieneman5d232242015-01-13 19:14:20 +00001036 while (NumVals - ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +00001037 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001038 case cl::Optional:
Chris Bieneman5d232242015-01-13 19:14:20 +00001039 Done = true; // Optional arguments want _at most_ one value
1040 // FALL THROUGH
1041 case cl::ZeroOrMore: // Zero or more will take all they can get...
1042 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +00001043 ProvidePositionalOption(PositionalOpts[i],
1044 PositionalVals[ValNo].first,
1045 PositionalVals[ValNo].second);
1046 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +00001047 break;
1048 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001049 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Bieneman5d232242015-01-13 19:14:20 +00001050 "positional argument processing!");
Chris Lattner5df56c42002-07-22 02:07:59 +00001051 }
1052 }
Chris Lattnere81c4092001-10-27 05:54:17 +00001053 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001054 } else {
1055 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1056 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001057 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +00001058 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001059 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001060 PositionalVals[ValNo].first,
1061 PositionalVals[ValNo].second);
1062 ValNo++;
1063 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001064
1065 // Handle the case where there is just one positional option, and it's
1066 // optional. In this case, we want to give JUST THE FIRST option to the
1067 // positional option and keep the rest for the consume after. The above
1068 // loop would have assigned no values to positional options in this case.
1069 //
Chris Bienemand1d94302015-01-28 19:00:25 +00001070 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1071 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001072 PositionalVals[ValNo].first,
1073 PositionalVals[ValNo].second);
1074 ValNo++;
1075 }
Misha Brukman10468d82005-04-21 22:55:34 +00001076
Chris Lattner5df56c42002-07-22 02:07:59 +00001077 // Handle over all of the rest of the arguments to the
1078 // cl::ConsumeAfter command line option...
1079 for (; ValNo != PositionalVals.size(); ++ValNo)
Chris Bieneman5d232242015-01-13 19:14:20 +00001080 ErrorParsing |=
1081 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1082 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001083 }
1084
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001085 // Loop over args and make sure all required args are specified!
Chris Bienemand1d94302015-01-28 19:00:25 +00001086 for (const auto &Opt : OptionsMap) {
Justin Bogner973b2ff2014-07-14 19:24:13 +00001087 switch (Opt.second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001088 case Required:
1089 case OneOrMore:
Justin Bogner973b2ff2014-07-14 19:24:13 +00001090 if (Opt.second->getNumOccurrences() == 0) {
1091 Opt.second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001092 ErrorParsing = true;
1093 }
Chris Bieneman5d232242015-01-13 19:14:20 +00001094 // Fall through
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001095 default:
1096 break;
1097 }
1098 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001099
Rafael Espindolacf14a382010-11-19 21:14:29 +00001100 // Now that we know if -debug is specified, we can use it.
1101 // Note that if ReadResponseFiles == true, this must be done before the
1102 // memory allocated for the expanded command line is free()d below.
1103 DEBUG(dbgs() << "Args: ";
Chris Bieneman5d232242015-01-13 19:14:20 +00001104 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1105 dbgs() << '\n';);
Rafael Espindolacf14a382010-11-19 21:14:29 +00001106
Chris Lattner5df56c42002-07-22 02:07:59 +00001107 // Free all of the memory allocated to the map. Command line options may only
1108 // be processed once!
Chris Bienemand1d94302015-01-28 19:00:25 +00001109 MoreHelp.clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001110
1111 // If we had an error processing our arguments, don't let the program execute
Chris Bieneman5d232242015-01-13 19:14:20 +00001112 if (ErrorParsing)
1113 exit(1);
Chris Lattner36a57d32001-07-23 17:17:47 +00001114}
1115
1116//===----------------------------------------------------------------------===//
1117// Option Base class implementation
1118//
Chris Lattner36a57d32001-07-23 17:17:47 +00001119
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001120bool Option::error(const Twine &Message, StringRef ArgName) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001121 if (!ArgName.data())
1122 ArgName = ArgStr;
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001123 if (ArgName.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001124 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001125 else
Chris Bienemand1d94302015-01-28 19:00:25 +00001126 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001127
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001128 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001129 return true;
1130}
1131
Chris Bieneman5d232242015-01-13 19:14:20 +00001132bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1133 bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001134 if (!MultiArg)
Chris Bieneman5d232242015-01-13 19:14:20 +00001135 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001136
Misha Brukman069e6b52003-07-10 16:49:51 +00001137 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001138 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001139 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001140 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001141 break;
1142 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001143 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001144 return error("must occur exactly one time!", ArgName);
Chris Bieneman5d232242015-01-13 19:14:20 +00001145 // Fall through
Chris Lattner36a57d32001-07-23 17:17:47 +00001146 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001147 case ZeroOrMore:
Chris Bieneman5d232242015-01-13 19:14:20 +00001148 case ConsumeAfter:
1149 break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001150 }
1151
Reid Spencer2027a6f2004-08-13 19:47:30 +00001152 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001153}
1154
Chris Lattner5df56c42002-07-22 02:07:59 +00001155// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1156// has been specified yet.
1157//
David Blaikieff43d692015-11-17 19:00:52 +00001158static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1159 if (O.ValueStr.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001160 return DefaultMsg;
Chris Lattner5df56c42002-07-22 02:07:59 +00001161 return O.ValueStr;
1162}
1163
1164//===----------------------------------------------------------------------===//
1165// cl::alias class implementation
1166//
1167
Chris Lattner36a57d32001-07-23 17:17:47 +00001168// Return the width of the option tag for printing...
David Blaikieff43d692015-11-17 19:00:52 +00001169size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
Chris Lattner36a57d32001-07-23 17:17:47 +00001170
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001171static void printHelpStr(StringRef HelpStr, size_t Indent,
1172 size_t FirstLineIndentedBy) {
1173 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1174 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1175 while (!Split.second.empty()) {
1176 Split = Split.second.split('\n');
1177 outs().indent(Indent) << Split.first << "\n";
1178 }
1179}
1180
Chris Lattner1b7a5152006-04-28 05:36:25 +00001181// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001182void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001183 outs() << " -" << ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001184 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001185}
1186
Chris Lattner36a57d32001-07-23 17:17:47 +00001187//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001188// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001189//
1190
Chris Lattnerb4101b12002-08-07 18:36:37 +00001191// basic_parser implementation
1192//
1193
1194// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001195size_t basic_parser_impl::getOptionWidth(const Option &O) const {
David Blaikieff43d692015-11-17 19:00:52 +00001196 size_t Len = O.ArgStr.size();
Chris Lattnerb4101b12002-08-07 18:36:37 +00001197 if (const char *ValName = getValueName())
David Blaikieff43d692015-11-17 19:00:52 +00001198 Len += getValueStr(O, ValName).size() + 3;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001199
1200 return Len + 6;
1201}
1202
Misha Brukman10468d82005-04-21 22:55:34 +00001203// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001204// to-be-maintained width is specified.
1205//
1206void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001207 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001208 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001209
1210 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001211 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001212
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001213 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001214}
1215
Andrew Trick12004012011-04-05 18:54:36 +00001216void basic_parser_impl::printOptionName(const Option &O,
1217 size_t GlobalWidth) const {
1218 outs() << " -" << O.ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001219 outs().indent(GlobalWidth - O.ArgStr.size());
Andrew Trick12004012011-04-05 18:54:36 +00001220}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001221
Chris Lattner5df56c42002-07-22 02:07:59 +00001222// parser<bool> implementation
1223//
Chris Bieneman5d232242015-01-13 19:14:20 +00001224bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1225 bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001226 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001227 Arg == "1") {
1228 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001229 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001230 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001231
Chris Lattneraecd74d2009-09-19 18:55:05 +00001232 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1233 Value = false;
1234 return false;
1235 }
1236 return O.error("'" + Arg +
1237 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001238}
1239
Dale Johannesen82810c82007-05-22 17:14:46 +00001240// parser<boolOrDefault> implementation
1241//
Chris Bieneman5d232242015-01-13 19:14:20 +00001242bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1243 boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001244 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1245 Arg == "1") {
1246 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001247 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001248 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001249 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1250 Value = BOU_FALSE;
1251 return false;
1252 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001253
Chris Lattneraecd74d2009-09-19 18:55:05 +00001254 return O.error("'" + Arg +
1255 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001256}
1257
Chris Lattner5df56c42002-07-22 02:07:59 +00001258// parser<int> implementation
1259//
Chris Bieneman5d232242015-01-13 19:14:20 +00001260bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1261 int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001262 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001263 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001264 return false;
1265}
1266
Chris Lattner719c7152003-06-28 15:47:20 +00001267// parser<unsigned> implementation
1268//
Chris Bieneman5d232242015-01-13 19:14:20 +00001269bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1270 unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001271
1272 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001273 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001274 return false;
1275}
1276
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001277// parser<unsigned long long> implementation
1278//
1279bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
Chris Bieneman5d232242015-01-13 19:14:20 +00001280 StringRef Arg,
1281 unsigned long long &Value) {
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001282
1283 if (Arg.getAsInteger(0, Value))
1284 return O.error("'" + Arg + "' value invalid for uint argument!");
1285 return false;
1286}
1287
Chris Lattnerb4101b12002-08-07 18:36:37 +00001288// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001289//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001290static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001291 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1292 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001293 char *End;
1294 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001295 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001296 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001297 return false;
1298}
1299
Chris Bieneman5d232242015-01-13 19:14:20 +00001300bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1301 double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001302 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001303}
1304
Chris Bieneman5d232242015-01-13 19:14:20 +00001305bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1306 float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001307 double dVal;
1308 if (parseDouble(O, Arg, dVal))
1309 return true;
1310 Val = (float)dVal;
1311 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001312}
1313
Chris Lattner5df56c42002-07-22 02:07:59 +00001314// generic_parser_base implementation
1315//
1316
Chris Lattner494c0b02002-07-23 17:15:12 +00001317// findOption - Return the option number corresponding to the specified
1318// argument string. If the option is not found, getNumOptions() is returned.
1319//
1320unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001321 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001322
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001323 for (unsigned i = 0; i != e; ++i) {
1324 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001325 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001326 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001327 return e;
1328}
1329
Chris Lattner5df56c42002-07-22 02:07:59 +00001330// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001331size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001332 if (O.hasArgStr()) {
David Blaikieff43d692015-11-17 19:00:52 +00001333 size_t Size = O.ArgStr.size() + 6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001334 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001335 Size = std::max(Size, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001336 return Size;
1337 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001338 size_t BaseSize = 0;
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 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001341 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001342 }
1343}
1344
Misha Brukman10468d82005-04-21 22:55:34 +00001345// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001346// to-be-maintained width is specified.
1347//
1348void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001349 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001350 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001351 outs() << " -" << O.ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001352 printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001353
Chris Lattner5df56c42002-07-22 02:07:59 +00001354 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001355 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001356 outs() << " =" << getOption(i);
1357 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001358 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001359 } else {
David Blaikieff43d692015-11-17 19:00:52 +00001360 if (!O.HelpStr.empty())
Chris Lattnere7c1e212009-09-20 05:03:30 +00001361 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001362 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001363 const char *Option = getOption(i);
1364 outs() << " -" << Option;
1365 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001366 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001367 }
1368}
1369
Andrew Trick12004012011-04-05 18:54:36 +00001370static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1371
1372// printGenericOptionDiff - Print the value of this option and it's default.
1373//
1374// "Generic" options have each value mapped to a name.
Chris Bieneman5d232242015-01-13 19:14:20 +00001375void generic_parser_base::printGenericOptionDiff(
1376 const Option &O, const GenericOptionValue &Value,
1377 const GenericOptionValue &Default, size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001378 outs() << " -" << O.ArgStr;
David Blaikieff43d692015-11-17 19:00:52 +00001379 outs().indent(GlobalWidth - O.ArgStr.size());
Andrew Trick12004012011-04-05 18:54:36 +00001380
1381 unsigned NumOpts = getNumOptions();
1382 for (unsigned i = 0; i != NumOpts; ++i) {
1383 if (Value.compare(getOptionValue(i)))
1384 continue;
1385
1386 outs() << "= " << getOption(i);
1387 size_t L = std::strlen(getOption(i));
1388 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1389 outs().indent(NumSpaces) << " (default: ";
1390 for (unsigned j = 0; j != NumOpts; ++j) {
1391 if (Default.compare(getOptionValue(j)))
1392 continue;
1393 outs() << getOption(j);
1394 break;
1395 }
1396 outs() << ")\n";
1397 return;
1398 }
1399 outs() << "= *unknown option value*\n";
1400}
1401
1402// printOptionDiff - Specializations for printing basic value types.
1403//
Chris Bieneman5d232242015-01-13 19:14:20 +00001404#define PRINT_OPT_DIFF(T) \
1405 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1406 size_t GlobalWidth) const { \
1407 printOptionName(O, GlobalWidth); \
1408 std::string Str; \
1409 { \
1410 raw_string_ostream SS(Str); \
1411 SS << V; \
1412 } \
1413 outs() << "= " << Str; \
1414 size_t NumSpaces = \
1415 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1416 outs().indent(NumSpaces) << " (default: "; \
1417 if (D.hasValue()) \
1418 outs() << D.getValue(); \
1419 else \
1420 outs() << "*no default*"; \
1421 outs() << ")\n"; \
1422 }
Andrew Trick12004012011-04-05 18:54:36 +00001423
Frits van Bommel87e33672011-04-06 12:29:56 +00001424PRINT_OPT_DIFF(bool)
1425PRINT_OPT_DIFF(boolOrDefault)
1426PRINT_OPT_DIFF(int)
1427PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001428PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001429PRINT_OPT_DIFF(double)
1430PRINT_OPT_DIFF(float)
1431PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001432
Chris Bieneman5d232242015-01-13 19:14:20 +00001433void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
Benjamin Kramerc321e532016-06-08 19:09:22 +00001434 const OptionValue<std::string> &D,
Chris Bieneman5d232242015-01-13 19:14:20 +00001435 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001436 printOptionName(O, GlobalWidth);
1437 outs() << "= " << V;
1438 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1439 outs().indent(NumSpaces) << " (default: ";
1440 if (D.hasValue())
1441 outs() << D.getValue();
1442 else
1443 outs() << "*no default*";
1444 outs() << ")\n";
1445}
1446
1447// Print a placeholder for options that don't yet support printOptionDiff().
Chris Bieneman5d232242015-01-13 19:14:20 +00001448void basic_parser_impl::printOptionNoValue(const Option &O,
1449 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001450 printOptionName(O, GlobalWidth);
1451 outs() << "= *cannot print option value*\n";
1452}
Chris Lattner36a57d32001-07-23 17:17:47 +00001453
1454//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001455// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001456//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001457
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001458static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1459 const std::pair<const char *, Option *> *RHS) {
1460 return strcmp(LHS->first, RHS->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001461}
1462
Andrew Trick12004012011-04-05 18:54:36 +00001463// Copy Options into a vector so we can sort them as we like.
Chris Bieneman5d232242015-01-13 19:14:20 +00001464static void sortOpts(StringMap<Option *> &OptMap,
1465 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1466 bool ShowHidden) {
Matthias Braunb30f2f512016-01-30 01:24:31 +00001467 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
Andrew Trick12004012011-04-05 18:54:36 +00001468
Chris Bieneman5d232242015-01-13 19:14:20 +00001469 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
Andrew Trick12004012011-04-05 18:54:36 +00001470 I != E; ++I) {
1471 // Ignore really-hidden options.
1472 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1473 continue;
1474
1475 // Unless showhidden is set, ignore hidden flags.
1476 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1477 continue;
1478
1479 // If we've already seen this option, don't add it to the list again.
David Blaikie70573dc2014-11-19 07:49:26 +00001480 if (!OptionSet.insert(I->second).second)
Andrew Trick12004012011-04-05 18:54:36 +00001481 continue;
1482
Chris Bieneman5d232242015-01-13 19:14:20 +00001483 Opts.push_back(
1484 std::pair<const char *, Option *>(I->getKey().data(), I->second));
Andrew Trick12004012011-04-05 18:54:36 +00001485 }
1486
1487 // Sort the options list alphabetically.
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001488 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
Andrew Trick12004012011-04-05 18:54:36 +00001489}
1490
Chris Lattner36a57d32001-07-23 17:17:47 +00001491namespace {
1492
Chris Lattner5df56c42002-07-22 02:07:59 +00001493class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001494protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001495 const bool ShowHidden;
Chris Bieneman5d232242015-01-13 19:14:20 +00001496 typedef SmallVector<std::pair<const char *, Option *>, 128>
1497 StrOptionPairVector;
Andrew Trick0537a982013-05-06 21:56:23 +00001498 // Print the options. Opts is assumed to be alphabetically sorted.
1499 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1500 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1501 Opts[i].second->printOptionInfo(MaxArgLen);
1502 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001503
Chris Lattner5df56c42002-07-22 02:07:59 +00001504public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001505 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001506 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001507
Andrew Trick0537a982013-05-06 21:56:23 +00001508 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001509 void operator=(bool Value) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00001510 if (!Value)
Chris Bieneman5d232242015-01-13 19:14:20 +00001511 return;
Chris Lattner5df56c42002-07-22 02:07:59 +00001512
Andrew Trick0537a982013-05-06 21:56:23 +00001513 StrOptionPairVector Opts;
Chris Bienemand1d94302015-01-28 19:00:25 +00001514 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
Chris Lattner36a57d32001-07-23 17:17:47 +00001515
Chris Bienemand1d94302015-01-28 19:00:25 +00001516 if (GlobalParser->ProgramOverview)
1517 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001518
Chris Bienemand1d94302015-01-28 19:00:25 +00001519 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
Chris Lattner5df56c42002-07-22 02:07:59 +00001520
Chris Bienemand1d94302015-01-28 19:00:25 +00001521 for (auto Opt : GlobalParser->PositionalOpts) {
David Blaikieff43d692015-11-17 19:00:52 +00001522 if (Opt->hasArgStr())
Chris Bienemand1d94302015-01-28 19:00:25 +00001523 outs() << " --" << Opt->ArgStr;
1524 outs() << " " << Opt->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001525 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001526
1527 // Print the consume after option info if it exists...
Chris Bienemand1d94302015-01-28 19:00:25 +00001528 if (GlobalParser->ConsumeAfterOpt)
1529 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
Chris Lattner5df56c42002-07-22 02:07:59 +00001530
Chris Lattner471ba482009-08-23 08:43:55 +00001531 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001532
1533 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001534 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001535 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001536 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001537
Chris Lattner471ba482009-08-23 08:43:55 +00001538 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001539 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001540
Chris Lattner37bcd992004-11-19 17:08:15 +00001541 // Print any extra help the user has declared.
Chris Bienemand1d94302015-01-28 19:00:25 +00001542 for (auto I : GlobalParser->MoreHelp)
1543 outs() << I;
1544 GlobalParser->MoreHelp.clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001545
Reid Spencer5e554702004-11-16 06:11:52 +00001546 // Halt the program since help information was printed
Justin Bogner02b95842014-02-28 19:08:01 +00001547 exit(0);
Chris Lattner36a57d32001-07-23 17:17:47 +00001548 }
1549};
Andrew Trick0537a982013-05-06 21:56:23 +00001550
1551class CategorizedHelpPrinter : public HelpPrinter {
1552public:
1553 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1554
1555 // Helper function for printOptions().
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001556 // It shall return a negative value if A's name should be lexicographically
1557 // ordered before B's name. It returns a value greater equal zero otherwise.
1558 static int OptionCategoryCompare(OptionCategory *const *A,
1559 OptionCategory *const *B) {
1560 return strcmp((*A)->getName(), (*B)->getName());
Andrew Trick0537a982013-05-06 21:56:23 +00001561 }
1562
1563 // Make sure we inherit our base class's operator=()
Chris Bieneman5d232242015-01-13 19:14:20 +00001564 using HelpPrinter::operator=;
Andrew Trick0537a982013-05-06 21:56:23 +00001565
1566protected:
Craig Topper32ea8262014-03-04 06:24:11 +00001567 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
Andrew Trick0537a982013-05-06 21:56:23 +00001568 std::vector<OptionCategory *> SortedCategories;
Chris Bieneman5d232242015-01-13 19:14:20 +00001569 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
Andrew Trick0537a982013-05-06 21:56:23 +00001570
Alp Tokercb402912014-01-24 17:20:08 +00001571 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001572 // sorting.
Chris Bieneman67e426a2015-02-13 22:54:32 +00001573 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1574 E = GlobalParser->RegisteredOptionCategories.end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001575 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001576 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001577 }
Andrew Trick0537a982013-05-06 21:56:23 +00001578
1579 // Sort the different option categories alphabetically.
1580 assert(SortedCategories.size() > 0 && "No option categories registered!");
Benjamin Kramerbd5ee502015-03-14 00:20:13 +00001581 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1582 OptionCategoryCompare);
Andrew Trick0537a982013-05-06 21:56:23 +00001583
1584 // Create map to empty vectors.
1585 for (std::vector<OptionCategory *>::const_iterator
1586 I = SortedCategories.begin(),
1587 E = SortedCategories.end();
1588 I != E; ++I)
1589 CategorizedOptions[*I] = std::vector<Option *>();
1590
1591 // Walk through pre-sorted options and assign into categories.
1592 // Because the options are already alphabetically sorted the
1593 // options within categories will also be alphabetically sorted.
1594 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1595 Option *Opt = Opts[I].second;
1596 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1597 "Option has an unregistered category");
1598 CategorizedOptions[Opt->Category].push_back(Opt);
1599 }
1600
1601 // Now do printing.
1602 for (std::vector<OptionCategory *>::const_iterator
1603 Category = SortedCategories.begin(),
1604 E = SortedCategories.end();
1605 Category != E; ++Category) {
1606 // Hide empty categories for -help, but show for -help-hidden.
1607 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1608 if (!ShowHidden && IsEmptyCategory)
1609 continue;
1610
1611 // Print category information.
1612 outs() << "\n";
1613 outs() << (*Category)->getName() << ":\n";
1614
1615 // Check if description is set.
Craig Topperc10719f2014-04-07 04:17:22 +00001616 if ((*Category)->getDescription() != nullptr)
Andrew Trick0537a982013-05-06 21:56:23 +00001617 outs() << (*Category)->getDescription() << "\n\n";
1618 else
1619 outs() << "\n";
1620
1621 // When using -help-hidden explicitly state if the category has no
1622 // options associated with it.
1623 if (IsEmptyCategory) {
1624 outs() << " This option category has no options.\n";
1625 continue;
1626 }
1627 // Loop over the options in the category and print.
1628 for (std::vector<Option *>::const_iterator
1629 Opt = CategorizedOptions[*Category].begin(),
1630 E = CategorizedOptions[*Category].end();
1631 Opt != E; ++Opt)
1632 (*Opt)->printOptionInfo(MaxArgLen);
1633 }
1634 }
1635};
1636
1637// This wraps the Uncategorizing and Categorizing printers and decides
1638// at run time which should be invoked.
1639class HelpPrinterWrapper {
1640private:
1641 HelpPrinter &UncategorizedPrinter;
1642 CategorizedHelpPrinter &CategorizedPrinter;
1643
1644public:
1645 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
Chris Bieneman5d232242015-01-13 19:14:20 +00001646 CategorizedHelpPrinter &CategorizedPrinter)
1647 : UncategorizedPrinter(UncategorizedPrinter),
1648 CategorizedPrinter(CategorizedPrinter) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001649
1650 // Invoke the printer.
1651 void operator=(bool Value);
1652};
1653
Chris Lattneradb19d62006-10-12 22:09:17 +00001654} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001655
Andrew Trick0537a982013-05-06 21:56:23 +00001656// Declare the four HelpPrinter instances that are used to print out help, or
1657// help-hidden as an uncategorized list or in categories.
1658static HelpPrinter UncategorizedNormalPrinter(false);
1659static HelpPrinter UncategorizedHiddenPrinter(true);
1660static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1661static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1662
Andrew Trick0537a982013-05-06 21:56:23 +00001663// Declare HelpPrinter wrappers that will decide whether or not to invoke
1664// a categorizing help printer
1665static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1666 CategorizedNormalPrinter);
1667static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1668 CategorizedHiddenPrinter);
1669
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001670// Define a category for generic options that all tools should have.
1671static cl::OptionCategory GenericCategory("Generic Options");
1672
Andrew Trick0537a982013-05-06 21:56:23 +00001673// Define uncategorized help printers.
1674// -help-list is hidden by default because if Option categories are being used
1675// then -help behaves the same as -help-list.
Chris Bieneman5d232242015-01-13 19:14:20 +00001676static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1677 "help-list",
1678 cl::desc("Display list of available options (-help-list-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001679 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1680 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001681
Chris Bieneman5d232242015-01-13 19:14:20 +00001682static cl::opt<HelpPrinter, true, parser<bool>>
1683 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1684 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001685 cl::ValueDisallowed, cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001686
1687// Define uncategorized/categorized help printers. These printers change their
1688// behaviour at runtime depending on whether one or more Option categories have
1689// been declared.
Chris Bieneman5d232242015-01-13 19:14:20 +00001690static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1691 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001692 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1693 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001694
Chris Bieneman5d232242015-01-13 19:14:20 +00001695static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1696 HHOp("help-hidden", cl::desc("Display all available options"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001697 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1698 cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001699
Chris Bieneman5d232242015-01-13 19:14:20 +00001700static cl::opt<bool> PrintOptions(
1701 "print-options",
1702 cl::desc("Print non-default options after command line parsing"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001703 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001704
Chris Bieneman5d232242015-01-13 19:14:20 +00001705static cl::opt<bool> PrintAllOptions(
1706 "print-all-options",
1707 cl::desc("Print all option values after command line parsing"), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001708 cl::init(false), cl::cat(GenericCategory));
Andrew Trick12004012011-04-05 18:54:36 +00001709
Andrew Trick0537a982013-05-06 21:56:23 +00001710void HelpPrinterWrapper::operator=(bool Value) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00001711 if (!Value)
Andrew Trick0537a982013-05-06 21:56:23 +00001712 return;
1713
1714 // Decide which printer to invoke. If more than one option category is
1715 // registered then it is useful to show the categorized help instead of
1716 // uncategorized help.
Chris Bieneman67e426a2015-02-13 22:54:32 +00001717 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
Andrew Trick0537a982013-05-06 21:56:23 +00001718 // unhide -help-list option so user can have uncategorized output if they
1719 // want it.
1720 HLOp.setHiddenFlag(NotHidden);
1721
1722 CategorizedPrinter = true; // Invoke categorized printer
Chris Bieneman5d232242015-01-13 19:14:20 +00001723 } else
Andrew Trick0537a982013-05-06 21:56:23 +00001724 UncategorizedPrinter = true; // Invoke uncategorized printer
1725}
1726
Andrew Trick12004012011-04-05 18:54:36 +00001727// Print the value of each option.
Chris Bienemand77bbab2015-01-30 22:16:01 +00001728void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1729
1730void CommandLineParser::printOptionValues() {
Chris Bieneman5d232242015-01-13 19:14:20 +00001731 if (!PrintOptions && !PrintAllOptions)
1732 return;
Andrew Trick12004012011-04-05 18:54:36 +00001733
Chris Bieneman5d232242015-01-13 19:14:20 +00001734 SmallVector<std::pair<const char *, Option *>, 128> Opts;
Chris Bienemand77bbab2015-01-30 22:16:01 +00001735 sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
Andrew Trick12004012011-04-05 18:54:36 +00001736
1737 // Compute the maximum argument length...
1738 size_t MaxArgLen = 0;
1739 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1740 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1741
1742 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1743 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1744}
1745
Craig Topperc10719f2014-04-07 04:17:22 +00001746static void (*OverrideVersionPrinter)() = nullptr;
Reid Spencerb3171672006-06-05 16:22:56 +00001747
Chris Bieneman5d232242015-01-13 19:14:20 +00001748static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
Chandler Carruthea7e5522011-07-22 07:50:40 +00001749
Chris Lattneradb19d62006-10-12 22:09:17 +00001750namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00001751class VersionPrinter {
1752public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00001753 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00001754 raw_ostream &OS = outs();
Chris Bienemanef43d442016-03-15 18:07:46 +00001755#ifdef PACKAGE_VENDOR
1756 OS << PACKAGE_VENDOR << " ";
1757#else
1758 OS << "LLVM (http://llvm.org/):\n ";
1759#endif
1760 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00001761#ifdef LLVM_VERSION_INFO
Justin Bogner581b5922014-06-17 06:52:41 +00001762 OS << " " << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00001763#endif
Chris Lattner131dca92009-09-20 06:18:38 +00001764 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001765#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00001766 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001767#else
Chris Lattner131dca92009-09-20 06:18:38 +00001768 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001769#endif
1770#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00001771 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001772#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00001773 std::string CPU = sys::getHostCPUName();
Chris Bieneman5d232242015-01-13 19:14:20 +00001774 if (CPU == "generic")
1775 CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00001776 OS << ".\n"
Sebastian Pop94441fb2011-11-01 21:32:20 +00001777 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00001778 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00001779 }
1780 void operator=(bool OptionWasSpecified) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001781 if (!OptionWasSpecified)
1782 return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001783
Craig Topperc10719f2014-04-07 04:17:22 +00001784 if (OverrideVersionPrinter != nullptr) {
Chandler Carruthea7e5522011-07-22 07:50:40 +00001785 (*OverrideVersionPrinter)();
Justin Bogner02b95842014-02-28 19:08:01 +00001786 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001787 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001788 print();
1789
1790 // Iterate over any registered extra printers and call them to add further
1791 // information.
Craig Topperc10719f2014-04-07 04:17:22 +00001792 if (ExtraVersionPrinters != nullptr) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00001793 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00001794 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1795 E = ExtraVersionPrinters->end();
1796 I != E; ++I)
1797 (*I)();
1798 }
1799
Justin Bogner02b95842014-02-28 19:08:01 +00001800 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001801 }
1802};
Chris Lattneradb19d62006-10-12 22:09:17 +00001803} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00001804
Reid Spencerff6cc122004-08-04 00:36:06 +00001805// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00001806static VersionPrinter VersionPrinterInstance;
1807
Chris Bieneman5d232242015-01-13 19:14:20 +00001808static cl::opt<VersionPrinter, true, parser<bool>>
1809 VersOp("version", cl::desc("Display the version of this program"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001810 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1811 cl::cat(GenericCategory));
Reid Spencerff6cc122004-08-04 00:36:06 +00001812
Reid Spencer5e554702004-11-16 06:11:52 +00001813// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00001814void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1815 // This looks weird, but it actually prints the help message. The Printers are
1816 // types of HelpPrinter and the help gets printed when its operator= is
1817 // invoked. That's because the "normal" usages of the help printer is to be
1818 // assigned true/false depending on whether -help or -help-hidden was given or
1819 // not. Since we're circumventing that we have to make it look like -help or
1820 // -help-hidden were given, so we assign true.
1821
1822 if (!Hidden && !Categorized)
1823 UncategorizedNormalPrinter = true;
1824 else if (!Hidden && Categorized)
1825 CategorizedNormalPrinter = true;
1826 else if (Hidden && !Categorized)
1827 UncategorizedHiddenPrinter = true;
1828 else
1829 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00001830}
Reid Spencerb3171672006-06-05 16:22:56 +00001831
Devang Patel9eb2caae2007-02-01 01:43:37 +00001832/// Utility function for printing version number.
Chris Bieneman5d232242015-01-13 19:14:20 +00001833void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
Devang Patel9eb2caae2007-02-01 01:43:37 +00001834
Chris Bieneman5d232242015-01-13 19:14:20 +00001835void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001836
1837void cl::AddExtraVersionPrinter(void (*func)()) {
Craig Topper8d399f82014-04-09 04:20:00 +00001838 if (!ExtraVersionPrinters)
Chandler Carruthea7e5522011-07-22 07:50:40 +00001839 ExtraVersionPrinters = new std::vector<void (*)()>;
1840
1841 ExtraVersionPrinters->push_back(func);
1842}
Andrew Trick7cb710d2013-05-06 21:56:35 +00001843
Chris Bienemand1d94302015-01-28 19:00:25 +00001844StringMap<Option *> &cl::getRegisteredOptions() {
1845 return GlobalParser->OptionsMap;
Andrew Trick7cb710d2013-05-06 21:56:35 +00001846}
Peter Collingbournee1863192014-10-16 22:47:52 +00001847
Chris Bieneman9e13af72015-01-21 22:45:52 +00001848void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
Chris Bienemand1d94302015-01-28 19:00:25 +00001849 for (auto &I : GlobalParser->OptionsMap) {
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001850 if (I.second->Category != &Category &&
1851 I.second->Category != &GenericCategory)
Chris Bieneman9e13af72015-01-21 22:45:52 +00001852 I.second->setHiddenFlag(cl::ReallyHidden);
1853 }
1854}
1855
Chris Bieneman68169362015-01-27 22:21:06 +00001856void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
Chris Bieneman01043252015-01-26 21:57:29 +00001857 auto CategoriesBegin = Categories.begin();
1858 auto CategoriesEnd = Categories.end();
Chris Bienemand1d94302015-01-28 19:00:25 +00001859 for (auto &I : GlobalParser->OptionsMap) {
Chris Bieneman01043252015-01-26 21:57:29 +00001860 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1861 CategoriesEnd &&
1862 I.second->Category != &GenericCategory)
1863 I.second->setHiddenFlag(cl::ReallyHidden);
1864 }
1865}
1866
Peter Collingbournee1863192014-10-16 22:47:52 +00001867void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1868 const char *Overview) {
1869 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1870}