blob: 4cd6f0c5f0a398fd398bca744b06f61201044174 [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"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerfa9c6f42009-09-19 23:59:02 +000023#include "llvm/ADT/SmallString.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000024#include "llvm/ADT/StringMap.h"
Chris Lattneraecd74d2009-09-19 18:55:05 +000025#include "llvm/ADT/Twine.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000026#include "llvm/Config/config.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000027#include "llvm/Support/ConvertUTF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/Host.h"
31#include "llvm/Support/ManagedStatic.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/raw_ostream.h"
Brian Gaekee5e53222003-10-10 17:01:36 +000035#include <cerrno>
Chris Lattner36b3caf2009-08-23 18:09:02 +000036#include <cstdlib>
Andrew Trick0537a982013-05-06 21:56:23 +000037#include <map>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000038#include <system_error>
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 {
Chris Lattner3e5d60f2006-08-27 12:45:47 +000049TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen82810c82007-05-22 17:14:46 +000050TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000051TEMPLATE_INSTANTIATION(class basic_parser<int>);
52TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000053TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000054TEMPLATE_INSTANTIATION(class basic_parser<double>);
55TEMPLATE_INSTANTIATION(class basic_parser<float>);
56TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000057TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000058
59TEMPLATE_INSTANTIATION(class opt<unsigned>);
60TEMPLATE_INSTANTIATION(class opt<int>);
61TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000062TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000063TEMPLATE_INSTANTIATION(class opt<bool>);
Chris Bieneman5d232242015-01-13 19:14:20 +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() {}
Sean Silvadb794842014-08-15 23:39:01 +000082void StringSaver::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000083
84//===----------------------------------------------------------------------===//
85
Chris Lattner5af1cbc2006-10-13 00:06:24 +000086// Globals for name and overview of program. Program name is not a string to
87// avoid static ctor/dtor issues.
88static char ProgramName[80] = "<premain>";
Craig Topperc10719f2014-04-07 04:17:22 +000089static const char *ProgramOverview = nullptr;
Reid Spencer9501b9b2004-09-01 04:41:28 +000090
Chris Lattner37bcd992004-11-19 17:08:15 +000091// This collects additional help to be printed.
Chris Bieneman5d232242015-01-13 19:14:20 +000092static ManagedStatic<std::vector<const char *>> MoreHelp;
Chris Lattner37bcd992004-11-19 17:08:15 +000093
Chris Bieneman5d232242015-01-13 19:14:20 +000094extrahelp::extrahelp(const char *Help) : morehelp(Help) {
Chris Lattner8111c592006-10-04 21:52:35 +000095 MoreHelp->push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +000096}
97
Chris Lattneraf039c52007-04-12 00:36:29 +000098static bool OptionListChanged = false;
99
100// MarkOptionsChanged - Internal helper function.
Chris Bieneman5d232242015-01-13 19:14:20 +0000101void cl::MarkOptionsChanged() { OptionListChanged = true; }
Chris Lattneraf039c52007-04-12 00:36:29 +0000102
Chris Lattner5247f602007-04-06 21:06:55 +0000103/// RegisteredOptionList - This is the list of the command line options that
104/// have statically constructed themselves.
Craig Topperc10719f2014-04-07 04:17:22 +0000105static Option *RegisteredOptionList = nullptr;
Chris Lattner5247f602007-04-06 21:06:55 +0000106
107void Option::addArgument() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000108 assert(!NextRegistered && "argument multiply registered!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000109
Chris Lattner5247f602007-04-06 21:06:55 +0000110 NextRegistered = RegisteredOptionList;
111 RegisteredOptionList = this;
Chris Lattneraf039c52007-04-12 00:36:29 +0000112 MarkOptionsChanged();
Chris Lattner5247f602007-04-06 21:06:55 +0000113}
114
Jordan Rosec25b0c72014-01-29 18:54:17 +0000115void Option::removeArgument() {
Chris Bieneman732e0aa2014-10-15 21:54:35 +0000116 if (RegisteredOptionList == this) {
117 RegisteredOptionList = NextRegistered;
118 MarkOptionsChanged();
119 return;
120 }
121 Option *O = RegisteredOptionList;
122 for (; O->NextRegistered != this; O = O->NextRegistered)
123 ;
124 O->NextRegistered = NextRegistered;
Jordan Rosec25b0c72014-01-29 18:54:17 +0000125 MarkOptionsChanged();
126}
127
Andrew Trick0537a982013-05-06 21:56:23 +0000128// This collects the different option categories that have been registered.
Chris Bieneman5d232242015-01-13 19:14:20 +0000129typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet;
Andrew Trick0537a982013-05-06 21:56:23 +0000130static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
131
132// Initialise the general option category.
133OptionCategory llvm::cl::GeneralCategory("General options");
134
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000135void OptionCategory::registerCategory() {
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000136 assert(std::count_if(RegisteredOptionCategories->begin(),
137 RegisteredOptionCategories->end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000138 [this](const OptionCategory *Category) {
139 return getName() == Category->getName();
Chris Bieneman5d232242015-01-13 19:14:20 +0000140 }) == 0 &&
141 "Duplicate option categories");
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000142
Andrew Trick0537a982013-05-06 21:56:23 +0000143 RegisteredOptionCategories->insert(this);
144}
Chris Lattneraf039c52007-04-12 00:36:29 +0000145
Chris Lattner5df56c42002-07-22 02:07:59 +0000146//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000147// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000148//
149
Chris Lattner5247f602007-04-06 21:06:55 +0000150/// GetOptionInfo - Scan the list of registered options, turning them into data
151/// structures that are easier to handle.
Chris Bieneman5d232242015-01-13 19:14:20 +0000152static void GetOptionInfo(SmallVectorImpl<Option *> &PositionalOpts,
153 SmallVectorImpl<Option *> &SinkOpts,
154 StringMap<Option *> &OptionsMap) {
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000155 bool HadErrors = false;
Chris Bieneman5d232242015-01-13 19:14:20 +0000156 SmallVector<const char *, 16> OptionNames;
157 Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
Chris Lattner5247f602007-04-06 21:06:55 +0000158 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
159 // If this option wants to handle multiple option names, get the full set.
160 // This handles enum options like "-O1 -O2" etc.
161 O->getExtraOptionNames(OptionNames);
162 if (O->ArgStr[0])
163 OptionNames.push_back(O->ArgStr);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000164
Chris Lattner5247f602007-04-06 21:06:55 +0000165 // Handle named options.
Evan Cheng86cb3182008-05-05 18:30:58 +0000166 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +0000167 // Add argument to the argument map!
David Blaikie5106ce72014-11-19 05:49:42 +0000168 if (!OptionsMap.insert(std::make_pair(OptionNames[i], O)).second) {
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000169 errs() << ProgramName << ": CommandLine Error: Option '"
170 << OptionNames[i] << "' registered more than once!\n";
171 HadErrors = true;
Chris Lattner5247f602007-04-06 21:06:55 +0000172 }
173 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000174
Chris Lattner5247f602007-04-06 21:06:55 +0000175 OptionNames.clear();
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000176
Chris Lattner5247f602007-04-06 21:06:55 +0000177 // Remember information about positional options.
178 if (O->getFormattingFlag() == cl::Positional)
179 PositionalOpts.push_back(O);
Dan Gohman63d2d1f2008-02-23 01:55:25 +0000180 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000181 SinkOpts.push_back(O);
Chris Lattner5247f602007-04-06 21:06:55 +0000182 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000183 if (CAOpt) {
Chris Lattner5247f602007-04-06 21:06:55 +0000184 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000185 HadErrors = true;
186 }
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000187 CAOpt = O;
Chris Lattner5247f602007-04-06 21:06:55 +0000188 }
Chris Lattner1f790af2002-07-29 20:58:42 +0000189 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000190
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000191 if (CAOpt)
192 PositionalOpts.push_back(CAOpt);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000193
Chris Lattner0e1c1d42007-04-07 05:38:53 +0000194 // Make sure that they are in order of registration not backwards.
195 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
Alp Tokerfb39de3b2014-06-19 07:25:25 +0000196
197 // Fail hard if there were errors. These are strictly unrecoverable and
198 // indicate serious issues such as conflicting option names or an incorrectly
199 // linked LLVM distribution.
200 if (HadErrors)
201 report_fatal_error("inconsistency in registered CommandLine options");
Chris Lattner1f790af2002-07-29 20:58:42 +0000202}
203
Chris Lattner2031b022007-04-05 21:58:17 +0000204/// LookupOption - Lookup the option specified by the specified option on the
205/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000206/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000207static Option *LookupOption(StringRef &Arg, StringRef &Value,
Chris Bieneman5d232242015-01-13 19:14:20 +0000208 const StringMap<Option *> &OptionsMap) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000209 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000210 if (Arg.empty())
211 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000212
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000213 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000214
Chris Lattner0a40a972009-09-20 01:53:12 +0000215 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000216 if (EqualPos == StringRef::npos) {
217 // Look up the option.
Chris Bieneman5d232242015-01-13 19:14:20 +0000218 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
Craig Topperc10719f2014-04-07 04:17:22 +0000219 return I != OptionsMap.end() ? I->second : nullptr;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000220 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000221
Chris Lattnere7c1e212009-09-20 05:03:30 +0000222 // If the argument before the = is a valid option name, we match. If not,
223 // return Arg unmolested.
Chris Bieneman5d232242015-01-13 19:14:20 +0000224 StringMap<Option *>::const_iterator I =
225 OptionsMap.find(Arg.substr(0, EqualPos));
226 if (I == OptionsMap.end())
227 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000228
Chris Bieneman5d232242015-01-13 19:14:20 +0000229 Value = Arg.substr(EqualPos + 1);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000230 Arg = Arg.substr(0, EqualPos);
231 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000232}
233
Daniel Dunbarf4132132011-01-18 01:59:24 +0000234/// LookupNearestOption - Lookup the closest match to the option specified by
235/// the specified option on the command line. If there is a value specified
236/// (after an equal sign) return that as well. This assumes that leading dashes
237/// have already been stripped.
238static Option *LookupNearestOption(StringRef Arg,
Chris Bieneman5d232242015-01-13 19:14:20 +0000239 const StringMap<Option *> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000240 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000241 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000242 if (Arg.empty())
243 return nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000244
245 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000246 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
Chris Bieneman5d232242015-01-13 19:14:20 +0000247 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000248 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000249
250 // Find the closest match.
Craig Topperc10719f2014-04-07 04:17:22 +0000251 Option *Best = nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000252 unsigned BestDistance = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000253 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
254 ie = OptionsMap.end();
255 it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000256 Option *O = it->second;
Chris Bieneman5d232242015-01-13 19:14:20 +0000257 SmallVector<const char *, 16> OptionNames;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000258 O->getExtraOptionNames(OptionNames);
259 if (O->ArgStr[0])
260 OptionNames.push_back(O->ArgStr);
261
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000262 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
263 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000264 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
265 StringRef Name = OptionNames[i];
266 unsigned Distance = StringRef(Name).edit_distance(
Chris Bieneman5d232242015-01-13 19:14:20 +0000267 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000268 if (!Best || Distance < BestDistance) {
269 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000270 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000271 if (RHS.empty() || !PermitValue)
272 NearestString = OptionNames[i];
273 else
274 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000275 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000276 }
277 }
278
279 return Best;
280}
281
Alp Tokercb402912014-01-24 17:20:08 +0000282/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
283/// that does special handling of cl::CommaSeparated options.
284static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
285 StringRef ArgName, StringRef Value,
286 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000287 // Check to see if this option accepts a comma separated list of values. If
288 // it does, we have to split up the value into multiple values.
289 if (Handler->getMiscFlags() & CommaSeparated) {
290 StringRef Val(Value);
291 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000292
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000293 while (Pos != StringRef::npos) {
294 // Process the portion before the comma.
295 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
296 return true;
297 // Erase the portion before the comma, AND the comma.
Chris Bieneman5d232242015-01-13 19:14:20 +0000298 Val = Val.substr(Pos + 1);
299 Value.substr(Pos + 1); // Increment the original value pointer as well.
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000300 // Check for another comma.
301 Pos = Val.find(',');
302 }
303
304 Value = Val;
305 }
306
307 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
308 return true;
309
310 return false;
311}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000312
Chris Lattner40fef802009-09-20 01:49:31 +0000313/// ProvideOption - For Value, this differentiates between an empty value ("")
314/// and a null value (StringRef()). The later is accepted for arguments that
315/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000316static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000317 StringRef Value, int argc,
318 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000319 // Is this a multi-argument option?
320 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
321
Chris Lattnere81c4092001-10-27 05:54:17 +0000322 // Enforce value requirements
323 switch (Handler->getValueExpectedFlag()) {
324 case ValueRequired:
Craig Topper8d399f82014-04-09 04:20:00 +0000325 if (!Value.data()) { // No value specified?
Chris Bieneman5d232242015-01-13 19:14:20 +0000326 if (i + 1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000327 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000328 // Steal the next argument, like for '-o filename'
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000329 assert(argv && "null check");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000330 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000331 }
332 break;
333 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000334 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000335 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000336 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000337
Chris Lattner40fef802009-09-20 01:49:31 +0000338 if (Value.data())
Chris Bieneman5d232242015-01-13 19:14:20 +0000339 return Handler->error("does not allow a value! '" + Twine(Value) +
340 "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000341 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000342 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000343 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000344 }
345
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000346 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000347 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000348 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000349
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000350 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000351 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000352
Chris Lattner40fef802009-09-20 01:49:31 +0000353 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000354 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000355 return true;
356 --NumAdditionalVals;
357 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000358 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000359
360 while (NumAdditionalVals > 0) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000361 if (i + 1 >= argc)
Chris Lattneraecd74d2009-09-19 18:55:05 +0000362 return Handler->error("not enough values!");
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000363 assert(argv && "null check");
Chris Lattneraecd74d2009-09-19 18:55:05 +0000364 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000365
Alp Tokercb402912014-01-24 17:20:08 +0000366 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000367 return true;
368 MultiArg = true;
369 --NumAdditionalVals;
370 }
371 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000372}
373
Chris Lattnerca2552d2009-09-20 00:07:40 +0000374static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000375 int Dummy = i;
Craig Topperc10719f2014-04-07 04:17:22 +0000376 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000377}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000378
Chris Lattner5df56c42002-07-22 02:07:59 +0000379// Option predicates...
380static inline bool isGrouping(const Option *O) {
381 return O->getFormattingFlag() == cl::Grouping;
382}
383static inline bool isPrefixedOrGrouping(const Option *O) {
384 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
385}
386
387// getOptionPred - Check to see if there are any options that satisfy the
388// specified predicate with names that are the prefixes in Name. This is
389// checked by progressively stripping characters off of the name, checking to
390// see if there options that satisfy the predicate. If we find one, return it,
391// otherwise return null.
392//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000393static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Bieneman5d232242015-01-13 19:14:20 +0000394 bool (*Pred)(const Option *),
395 const StringMap<Option *> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000396
Chris Bieneman5d232242015-01-13 19:14:20 +0000397 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000398
Chris Lattnere7c1e212009-09-20 05:03:30 +0000399 // Loop while we haven't found an option and Name still has at least two
400 // characters in it (so that the next iteration will not be the empty
401 // string.
402 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000403 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000404 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000405 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000406
Chris Lattner5247f602007-04-06 21:06:55 +0000407 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000408 Length = Name.size();
Chris Bieneman5d232242015-01-13 19:14:20 +0000409 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000410 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000411 return nullptr; // No option found!
Chris Lattner5df56c42002-07-22 02:07:59 +0000412}
413
Chris Lattnere7c1e212009-09-20 05:03:30 +0000414/// HandlePrefixedOrGroupedOption - The specified argument string (which started
415/// with at least one '-') does not fully match an available option. Check to
416/// see if this is a prefix or grouped option. If so, split arg into output an
417/// Arg/Value pair and return the Option to parse it with.
Chris Bieneman5d232242015-01-13 19:14:20 +0000418static Option *
419HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
420 bool &ErrorParsing,
421 const StringMap<Option *> &OptionsMap) {
422 if (Arg.size() == 1)
423 return nullptr;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000424
425 // Do the lookup!
426 size_t Length = 0;
427 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
Chris Bieneman5d232242015-01-13 19:14:20 +0000428 if (!PGOpt)
429 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000430
Chris Lattnere7c1e212009-09-20 05:03:30 +0000431 // If the option is a prefixed option, then the value is simply the
432 // rest of the name... so fall through to later processing, by
433 // setting up the argument name flags and value fields.
434 if (PGOpt->getFormattingFlag() == cl::Prefix) {
435 Value = Arg.substr(Length);
436 Arg = Arg.substr(0, Length);
437 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
438 return PGOpt;
439 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000440
Chris Lattnere7c1e212009-09-20 05:03:30 +0000441 // This must be a grouped option... handle them now. Grouping options can't
442 // have values.
443 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000444
Chris Lattnere7c1e212009-09-20 05:03:30 +0000445 do {
446 // Move current arg name out of Arg into OneArgName.
447 StringRef OneArgName = Arg.substr(0, Length);
448 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000449
Chris Lattnere7c1e212009-09-20 05:03:30 +0000450 // Because ValueRequired is an invalid flag for grouped arguments,
451 // we don't need to pass argc/argv in.
452 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
453 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000454 int Dummy = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000455 ErrorParsing |=
456 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000457
Chris Lattnere7c1e212009-09-20 05:03:30 +0000458 // Get the next grouping option.
459 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
460 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000461
Chris Lattnere7c1e212009-09-20 05:03:30 +0000462 // Return the last option with Arg cut down to just the last one.
463 return PGOpt;
464}
465
Chris Lattner5df56c42002-07-22 02:07:59 +0000466static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000467 return O->getNumOccurrencesFlag() == cl::Required ||
468 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000469}
470
471static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000472 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
473 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000474}
Chris Lattnere81c4092001-10-27 05:54:17 +0000475
Chris Bieneman5d232242015-01-13 19:14:20 +0000476static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
Brian Gaeke497216d2003-08-15 21:05:57 +0000477
Chris Bieneman5d232242015-01-13 19:14:20 +0000478static bool isQuote(char C) { return C == '\"' || C == '\''; }
Reid Klecknera73c7782013-07-18 16:52:05 +0000479
Chris Bieneman5d232242015-01-13 19:14:20 +0000480static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
Reid Klecknera73c7782013-07-18 16:52:05 +0000481
482void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000483 SmallVectorImpl<const char *> &NewArgv,
484 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000485 SmallString<128> Token;
486 for (size_t I = 0, E = Src.size(); I != E; ++I) {
487 // Consume runs of whitespace.
488 if (Token.empty()) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000489 while (I != E && isWhitespace(Src[I])) {
490 // Mark the end of lines in response files
491 if (MarkEOLs && Src[I] == '\n')
492 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000493 ++I;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000494 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000495 if (I == E)
496 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000497 }
498
499 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
500 // they are literal. This makes it much easier to read Windows file paths.
501 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000502 ++I; // Skip the escape.
Reid Klecknera73c7782013-07-18 16:52:05 +0000503 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000504 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000505 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000506
Reid Klecknera73c7782013-07-18 16:52:05 +0000507 // Consume a quoted string.
508 if (isQuote(Src[I])) {
509 char Quote = Src[I++];
510 while (I != E && Src[I] != Quote) {
511 // Backslashes are literal, unless they escape a special character.
512 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
513 ++I;
514 Token.push_back(Src[I]);
515 ++I;
516 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000517 if (I == E)
518 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000519 continue;
520 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000521
Reid Klecknera73c7782013-07-18 16:52:05 +0000522 // End the token if this is whitespace.
523 if (isWhitespace(Src[I])) {
524 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000525 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000526 Token.clear();
527 continue;
528 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000529
Reid Klecknera73c7782013-07-18 16:52:05 +0000530 // This is a normal character. Append it.
531 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000532 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000533
534 // Append the last token after hitting EOF with no whitespace.
535 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000536 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000537 // Mark the end of response files
538 if (MarkEOLs)
539 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000540}
541
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000542/// Backslashes are interpreted in a rather complicated way in the Windows-style
543/// command line, because backslashes are used both to separate path and to
544/// escape double quote. This method consumes runs of backslashes as well as the
545/// following double quote if it's escaped.
546///
547/// * If an even number of backslashes is followed by a double quote, one
548/// backslash is output for every pair of backslashes, and the last double
549/// quote remains unconsumed. The double quote will later be interpreted as
550/// the start or end of a quoted string in the main loop outside of this
551/// function.
552///
553/// * If an odd number of backslashes is followed by a double quote, one
554/// backslash is output for every pair of backslashes, and a double quote is
555/// output for the last pair of backslash-double quote. The double quote is
556/// consumed in this case.
557///
558/// * Otherwise, backslashes are interpreted literally.
559static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
560 size_t E = Src.size();
561 int BackslashCount = 0;
562 // Skip the backslashes.
563 do {
564 ++I;
565 ++BackslashCount;
566 } while (I != E && Src[I] == '\\');
567
568 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
569 if (FollowedByDoubleQuote) {
570 Token.append(BackslashCount / 2, '\\');
571 if (BackslashCount % 2 == 0)
572 return I - 1;
573 Token.push_back('"');
574 return I;
575 }
576 Token.append(BackslashCount, '\\');
577 return I - 1;
578}
579
Reid Klecknera73c7782013-07-18 16:52:05 +0000580void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000581 SmallVectorImpl<const char *> &NewArgv,
582 bool MarkEOLs) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000583 SmallString<128> Token;
584
585 // This is a small state machine to consume characters until it reaches the
586 // end of the source string.
587 enum { INIT, UNQUOTED, QUOTED } State = INIT;
588 for (size_t I = 0, E = Src.size(); I != E; ++I) {
589 // INIT state indicates that the current input index is at the start of
590 // the string or between tokens.
591 if (State == INIT) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000592 if (isWhitespace(Src[I])) {
593 // Mark the end of lines in response files
594 if (MarkEOLs && Src[I] == '\n')
595 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000596 continue;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000597 }
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000598 if (Src[I] == '"') {
599 State = QUOTED;
600 continue;
601 }
602 if (Src[I] == '\\') {
603 I = parseBackslash(Src, I, Token);
604 State = UNQUOTED;
605 continue;
606 }
607 Token.push_back(Src[I]);
608 State = UNQUOTED;
609 continue;
610 }
611
612 // UNQUOTED state means that it's reading a token not quoted by double
613 // quotes.
614 if (State == UNQUOTED) {
615 // Whitespace means the end of the token.
616 if (isWhitespace(Src[I])) {
Sean Silvadb794842014-08-15 23:39:01 +0000617 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000618 Token.clear();
619 State = INIT;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000620 // Mark the end of lines in response files
621 if (MarkEOLs && Src[I] == '\n')
622 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000623 continue;
624 }
625 if (Src[I] == '"') {
626 State = QUOTED;
627 continue;
628 }
629 if (Src[I] == '\\') {
630 I = parseBackslash(Src, I, Token);
631 continue;
632 }
633 Token.push_back(Src[I]);
634 continue;
635 }
636
637 // QUOTED state means that it's reading a token quoted by double quotes.
638 if (State == QUOTED) {
639 if (Src[I] == '"') {
640 State = UNQUOTED;
641 continue;
642 }
643 if (Src[I] == '\\') {
644 I = parseBackslash(Src, I, Token);
645 continue;
646 }
647 Token.push_back(Src[I]);
648 }
649 }
650 // Append the last token after hitting EOF with no whitespace.
651 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000652 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000653 // Mark the end of response files
654 if (MarkEOLs)
655 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000656}
657
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000658// It is called byte order marker but the UTF-8 BOM is actually not affected
659// by the host system's endianness.
660static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
661 return (S.size() >= 3 &&
662 S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
663}
664
Reid Klecknera73c7782013-07-18 16:52:05 +0000665static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
666 TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000667 SmallVectorImpl<const char *> &NewArgv,
668 bool MarkEOLs = false) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000669 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
670 MemoryBuffer::getFile(FName);
671 if (!MemBufOrErr)
Reid Klecknera73c7782013-07-18 16:52:05 +0000672 return false;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000673 MemoryBuffer &MemBuf = *MemBufOrErr.get();
674 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
Reid Klecknera73c7782013-07-18 16:52:05 +0000675
676 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000677 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
Reid Klecknera73c7782013-07-18 16:52:05 +0000678 std::string UTF8Buf;
679 if (hasUTF16ByteOrderMark(BufRef)) {
680 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
681 return false;
682 Str = StringRef(UTF8Buf);
683 }
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000684 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
685 // these bytes before parsing.
686 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
687 else if (hasUTF8ByteOrderMark(BufRef))
688 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
Reid Klecknera73c7782013-07-18 16:52:05 +0000689
690 // Tokenize the contents into NewArgv.
Reid Klecknere3f146d2014-08-22 19:29:17 +0000691 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
Reid Klecknera73c7782013-07-18 16:52:05 +0000692
693 return true;
694}
695
696/// \brief Expand response files on a command line recursively using the given
697/// StringSaver and tokenization strategy.
698bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000699 SmallVectorImpl<const char *> &Argv,
700 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000701 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000702 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000703
704 // Don't cache Argv.size() because it can change.
Chris Bieneman5d232242015-01-13 19:14:20 +0000705 for (unsigned I = 0; I != Argv.size();) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000706 const char *Arg = Argv[I];
Reid Klecknere3f146d2014-08-22 19:29:17 +0000707 // Check if it is an EOL marker
708 if (Arg == nullptr) {
709 ++I;
710 continue;
711 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000712 if (Arg[0] != '@') {
713 ++I;
714 continue;
715 }
716
717 // If we have too many response files, leave some unexpanded. This avoids
718 // crashing on self-referential response files.
719 if (RspFiles++ > 20)
720 return false;
721
722 // Replace this response file argument with the tokenization of its
723 // contents. Nested response files are expanded in subsequent iterations.
724 // FIXME: If a nested response file uses a relative path, is it relative to
725 // the cwd of the process or the response file?
726 SmallVector<const char *, 0> ExpandedArgv;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000727 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
728 MarkEOLs)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000729 // We couldn't read this file, so we leave it in the argument stream and
730 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000731 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000732 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000733 continue;
734 }
735 Argv.erase(Argv.begin() + I);
736 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
737 }
738 return AllExpanded;
739}
740
Sean Silvadb794842014-08-15 23:39:01 +0000741namespace {
Chris Bieneman5d232242015-01-13 19:14:20 +0000742class StrDupSaver : public StringSaver {
743 std::vector<char *> Dups;
744
745public:
746 ~StrDupSaver() {
747 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
748 ++I) {
749 char *Dup = *I;
750 free(Dup);
Sean Silvadb794842014-08-15 23:39:01 +0000751 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000752 }
753 const char *SaveString(const char *Str) override {
754 char *Dup = strdup(Str);
755 Dups.push_back(Dup);
756 return Dup;
757 }
758};
Sean Silvadb794842014-08-15 23:39:01 +0000759}
760
Brian Gaekeca782d92003-08-14 22:00:59 +0000761/// ParseEnvironmentOptions - An alternative entry point to the
762/// CommandLine library, which allows you to read the program's name
763/// from the caller (as PROGNAME) and its command-line arguments from
764/// an environment variable (whose name is given in ENVVAR).
765///
Chris Lattnera60f3552004-05-06 22:04:31 +0000766void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000767 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000768 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000769 assert(progName && "Program name not specified");
770 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000771
Brian Gaeke497216d2003-08-15 21:05:57 +0000772 // Get the environment variable they want us to parse options out of.
Chris Lattner2de6e332006-08-27 22:10:29 +0000773 const char *envValue = getenv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000774 if (!envValue)
775 return;
776
Brian Gaekeca782d92003-08-14 22:00:59 +0000777 // Get program's "name", which we wouldn't know without the caller
778 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000779 SmallVector<const char *, 20> newArgv;
Sean Silvadb794842014-08-15 23:39:01 +0000780 StrDupSaver Saver;
781 newArgv.push_back(Saver.SaveString(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000782
783 // Parse the value of the environment variable into a "command line"
784 // and hand it off to ParseCommandLineOptions().
Reid Klecknera73c7782013-07-18 16:52:05 +0000785 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000786 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000787 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000788}
789
Chris Bieneman5d232242015-01-13 19:14:20 +0000790void cl::ParseCommandLineOptions(int argc, const char *const *argv,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000791 const char *Overview) {
Chris Lattner5247f602007-04-06 21:06:55 +0000792 // Process all registered options.
Chris Bieneman5d232242015-01-13 19:14:20 +0000793 SmallVector<Option *, 4> PositionalOpts;
794 SmallVector<Option *, 4> SinkOpts;
795 StringMap<Option *> Opts;
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000796 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000797
Chris Bieneman5d232242015-01-13 19:14:20 +0000798 assert((!Opts.empty() || !PositionalOpts.empty()) && "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000799
800 // Expand response files.
Reid Klecknera73c7782013-07-18 16:52:05 +0000801 SmallVector<const char *, 20> newArgv;
802 for (int i = 0; i != argc; ++i)
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000803 newArgv.push_back(argv[i]);
Sean Silvadb794842014-08-15 23:39:01 +0000804 StrDupSaver Saver;
Reid Klecknera73c7782013-07-18 16:52:05 +0000805 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000806 argv = &newArgv[0];
807 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000808
Chris Lattner5af1cbc2006-10-13 00:06:24 +0000809 // Copy the program name into ProgName, making sure not to overflow it.
NAKAMURA Takumic2c66492014-04-23 14:51:23 +0000810 StringRef ProgName = sys::path::filename(argv[0]);
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000811 size_t Len = std::min(ProgName.size(), size_t(79));
812 memcpy(ProgramName, ProgName.data(), Len);
813 ProgramName[Len] = '\0';
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000814
Chris Lattner36a57d32001-07-23 17:17:47 +0000815 ProgramOverview = Overview;
816 bool ErrorParsing = false;
817
Chris Lattner5df56c42002-07-22 02:07:59 +0000818 // Check out the positional arguments to collect information about them.
819 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000820
Chris Lattnerd380d842005-08-08 17:25:38 +0000821 // Determine whether or not there are an unlimited number of positionals
822 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000823
Craig Topperc10719f2014-04-07 04:17:22 +0000824 Option *ConsumeAfterOpt = nullptr;
Chris Lattner5df56c42002-07-22 02:07:59 +0000825 if (!PositionalOpts.empty()) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000826 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000827 assert(PositionalOpts.size() > 1 &&
828 "Cannot specify cl::ConsumeAfter without a positional argument!");
829 ConsumeAfterOpt = PositionalOpts[0];
830 }
831
832 // Calculate how many positional values are _required_.
833 bool UnboundedFound = false;
Chris Bieneman5d232242015-01-13 19:14:20 +0000834 for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size(); i != e;
835 ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000836 Option *Opt = PositionalOpts[i];
837 if (RequiresValue(Opt))
838 ++NumPositionalRequired;
839 else if (ConsumeAfterOpt) {
840 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +0000841 // unless there is only one positional argument...
842 if (PositionalOpts.size() > 2)
Chris Bieneman5d232242015-01-13 19:14:20 +0000843 ErrorParsing |= Opt->error(
844 "error - this positional option will never be matched, "
845 "because it does not Require a value, and a "
846 "cl::ConsumeAfter option is active!");
Chris Lattner2da046f2003-07-30 17:34:02 +0000847 } else if (UnboundedFound && !Opt->ArgStr[0]) {
848 // This option does not "require" a value... Make sure this option is
849 // not specified after an option that eats all extra arguments, or this
850 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +0000851 //
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000852 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner5df56c42002-07-22 02:07:59 +0000853 "another positional argument will match an "
854 "unbounded number of values, and this option"
855 " does not require a value!");
856 }
857 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
858 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +0000859 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +0000860 }
861
Reid Spencer2027a6f2004-08-13 19:47:30 +0000862 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +0000863 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +0000864 //
Chris Bieneman5d232242015-01-13 19:14:20 +0000865 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +0000866
Chris Lattner2da046f2003-07-30 17:34:02 +0000867 // If the program has named positional arguments, and the name has been run
868 // across, keep track of which positional argument was named. Otherwise put
869 // the positional args into the PositionalVals list...
Craig Topperc10719f2014-04-07 04:17:22 +0000870 Option *ActivePositionalArg = nullptr;
Chris Lattner2da046f2003-07-30 17:34:02 +0000871
Chris Lattner36a57d32001-07-23 17:17:47 +0000872 // Loop over all of the arguments... processing them.
Chris Bieneman5d232242015-01-13 19:14:20 +0000873 bool DashDashFound = false; // Have we read '--'?
Chris Lattner36a57d32001-07-23 17:17:47 +0000874 for (int i = 1; i < argc; ++i) {
Craig Topperc10719f2014-04-07 04:17:22 +0000875 Option *Handler = nullptr;
876 Option *NearestHandler = nullptr;
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000877 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +0000878 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000879 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +0000880
Chris Lattneraf039c52007-04-12 00:36:29 +0000881 // If the option list changed, this means that some command line
Chris Lattner83b53a52007-04-11 15:35:18 +0000882 // option has just been registered or deregistered. This can occur in
883 // response to things like -load, etc. If this happens, rescan the options.
Chris Lattneraf039c52007-04-12 00:36:29 +0000884 if (OptionListChanged) {
Chris Lattner83b53a52007-04-11 15:35:18 +0000885 PositionalOpts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000886 SinkOpts.clear();
Chris Lattner83b53a52007-04-11 15:35:18 +0000887 Opts.clear();
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000888 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
Chris Lattneraf039c52007-04-12 00:36:29 +0000889 OptionListChanged = false;
Chris Lattner83b53a52007-04-11 15:35:18 +0000890 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000891
Chris Lattner5df56c42002-07-22 02:07:59 +0000892 // Check to see if this is a positional argument. This argument is
893 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +0000894 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +0000895 //
896 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
897 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +0000898 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000899 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000900 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000901 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000902
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000903 if (!PositionalOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000904 PositionalVals.push_back(std::make_pair(argv[i], i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000905
906 // All of the positional arguments have been fulfulled, give the rest to
907 // the consume after option... if it's specified...
908 //
Craig Topper8d399f82014-04-09 04:20:00 +0000909 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000910 for (++i; i < argc; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +0000911 PositionalVals.push_back(std::make_pair(argv[i], i));
912 break; // Handle outside of the argument processing loop...
Chris Lattner5df56c42002-07-22 02:07:59 +0000913 }
914
915 // Delay processing positional arguments until the end...
916 continue;
917 }
Chris Lattnera60f3552004-05-06 22:04:31 +0000918 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
919 !DashDashFound) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000920 DashDashFound = true; // This is the mythical "--"?
921 continue; // Don't try to process it as an argument itself.
Chris Lattnera60f3552004-05-06 22:04:31 +0000922 } else if (ActivePositionalArg &&
923 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
924 // If there is a positional argument eating options, check to see if this
925 // option is another positional argument. If so, treat it as an argument,
926 // otherwise feed it to the eating positional.
Chris Bieneman5d232242015-01-13 19:14:20 +0000927 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000928 // Eat leading dashes.
929 while (!ArgName.empty() && ArgName[0] == '-')
930 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000931
Chris Lattner5247f602007-04-06 21:06:55 +0000932 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattnera60f3552004-05-06 22:04:31 +0000933 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000934 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000935 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +0000936 }
937
Chris Bieneman5d232242015-01-13 19:14:20 +0000938 } else { // We start with a '-', must be an argument.
939 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000940 // Eat leading dashes.
941 while (!ArgName.empty() && ArgName[0] == '-')
942 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000943
Chris Lattner5247f602007-04-06 21:06:55 +0000944 Handler = LookupOption(ArgName, Value, Opts);
Chris Lattner36a57d32001-07-23 17:17:47 +0000945
Chris Lattnera60f3552004-05-06 22:04:31 +0000946 // Check to see if this "option" is really a prefixed or grouped argument.
Craig Topper8d399f82014-04-09 04:20:00 +0000947 if (!Handler)
Chris Bieneman5d232242015-01-13 19:14:20 +0000948 Handler =
949 HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, Opts);
Daniel Dunbarf4132132011-01-18 01:59:24 +0000950
951 // Otherwise, look for the closest available option to report to the user
952 // in the upcoming error.
Craig Topper8d399f82014-04-09 04:20:00 +0000953 if (!Handler && SinkOpts.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +0000954 NearestHandler =
955 LookupNearestOption(ArgName, Opts, NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +0000956 }
957
Craig Topper8d399f82014-04-09 04:20:00 +0000958 if (!Handler) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000959 if (SinkOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000960 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
961 << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +0000962
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000963 if (NearestHandler) {
964 // If we know a near match, report it as well.
Chris Bieneman5d232242015-01-13 19:14:20 +0000965 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
966 << "'?\n";
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000967 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000968
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000969 ErrorParsing = true;
970 } else {
Chris Bieneman5d232242015-01-13 19:14:20 +0000971 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
972 E = SinkOpts.end();
973 I != E; ++I)
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000974 (*I)->addOccurrence(i, "", argv[i]);
975 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000976 continue;
977 }
978
Chris Lattner2da046f2003-07-30 17:34:02 +0000979 // If this is a named positional argument, just remember that it is the
980 // active one...
981 if (Handler->getFormattingFlag() == cl::Positional)
982 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +0000983 else
Chris Lattner0a40a972009-09-20 01:53:12 +0000984 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +0000985 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000986
Chris Lattner5df56c42002-07-22 02:07:59 +0000987 // Check and handle positional arguments now...
988 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +0000989 errs() << ProgramName
Chris Bieneman5d232242015-01-13 19:14:20 +0000990 << ": Not enough positional command line arguments specified!\n"
991 << "Must specify at least " << NumPositionalRequired
992 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000993
Chris Lattner5df56c42002-07-22 02:07:59 +0000994 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000995 } else if (!HasUnlimitedPositionals &&
996 PositionalVals.size() > PositionalOpts.size()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000997 errs() << ProgramName << ": Too many positional arguments specified!\n"
998 << "Can specify at most " << PositionalOpts.size()
999 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerd380d842005-08-08 17:25:38 +00001000 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +00001001
Craig Topper8d399f82014-04-09 04:20:00 +00001002 } else if (!ConsumeAfterOpt) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001003 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +00001004 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1005 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001006 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +00001007 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001008 PositionalVals[ValNo].second);
1009 ValNo++;
Chris Bieneman5d232242015-01-13 19:14:20 +00001010 --NumPositionalRequired; // We fulfilled our duty...
Chris Lattner5df56c42002-07-22 02:07:59 +00001011 }
1012
1013 // If we _can_ give this option more arguments, do so now, as long as we
1014 // do not give it values that others need. 'Done' controls whether the
1015 // option even _WANTS_ any more.
1016 //
Misha Brukman069e6b52003-07-10 16:49:51 +00001017 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Bieneman5d232242015-01-13 19:14:20 +00001018 while (NumVals - ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +00001019 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001020 case cl::Optional:
Chris Bieneman5d232242015-01-13 19:14:20 +00001021 Done = true; // Optional arguments want _at most_ one value
1022 // FALL THROUGH
1023 case cl::ZeroOrMore: // Zero or more will take all they can get...
1024 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +00001025 ProvidePositionalOption(PositionalOpts[i],
1026 PositionalVals[ValNo].first,
1027 PositionalVals[ValNo].second);
1028 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +00001029 break;
1030 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001031 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Bieneman5d232242015-01-13 19:14:20 +00001032 "positional argument processing!");
Chris Lattner5df56c42002-07-22 02:07:59 +00001033 }
1034 }
Chris Lattnere81c4092001-10-27 05:54:17 +00001035 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001036 } else {
1037 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1038 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001039 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +00001040 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001041 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001042 PositionalVals[ValNo].first,
1043 PositionalVals[ValNo].second);
1044 ValNo++;
1045 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001046
1047 // Handle the case where there is just one positional option, and it's
1048 // optional. In this case, we want to give JUST THE FIRST option to the
1049 // positional option and keep the rest for the consume after. The above
1050 // loop would have assigned no values to positional options in this case.
1051 //
Reid Spencer2027a6f2004-08-13 19:47:30 +00001052 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001053 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001054 PositionalVals[ValNo].first,
1055 PositionalVals[ValNo].second);
1056 ValNo++;
1057 }
Misha Brukman10468d82005-04-21 22:55:34 +00001058
Chris Lattner5df56c42002-07-22 02:07:59 +00001059 // Handle over all of the rest of the arguments to the
1060 // cl::ConsumeAfter command line option...
1061 for (; ValNo != PositionalVals.size(); ++ValNo)
Chris Bieneman5d232242015-01-13 19:14:20 +00001062 ErrorParsing |=
1063 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1064 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001065 }
1066
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001067 // Loop over args and make sure all required args are specified!
Justin Bogner973b2ff2014-07-14 19:24:13 +00001068 for (const auto &Opt : Opts) {
1069 switch (Opt.second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001070 case Required:
1071 case OneOrMore:
Justin Bogner973b2ff2014-07-14 19:24:13 +00001072 if (Opt.second->getNumOccurrences() == 0) {
1073 Opt.second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001074 ErrorParsing = true;
1075 }
Chris Bieneman5d232242015-01-13 19:14:20 +00001076 // Fall through
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001077 default:
1078 break;
1079 }
1080 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001081
Rafael Espindolacf14a382010-11-19 21:14:29 +00001082 // Now that we know if -debug is specified, we can use it.
1083 // Note that if ReadResponseFiles == true, this must be done before the
1084 // memory allocated for the expanded command line is free()d below.
1085 DEBUG(dbgs() << "Args: ";
Chris Bieneman5d232242015-01-13 19:14:20 +00001086 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1087 dbgs() << '\n';);
Rafael Espindolacf14a382010-11-19 21:14:29 +00001088
Chris Lattner5df56c42002-07-22 02:07:59 +00001089 // Free all of the memory allocated to the map. Command line options may only
1090 // be processed once!
Chris Lattner8111c592006-10-04 21:52:35 +00001091 Opts.clear();
Chris Lattner5df56c42002-07-22 02:07:59 +00001092 PositionalOpts.clear();
Chris Lattner8111c592006-10-04 21:52:35 +00001093 MoreHelp->clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001094
1095 // If we had an error processing our arguments, don't let the program execute
Chris Bieneman5d232242015-01-13 19:14:20 +00001096 if (ErrorParsing)
1097 exit(1);
Chris Lattner36a57d32001-07-23 17:17:47 +00001098}
1099
1100//===----------------------------------------------------------------------===//
1101// Option Base class implementation
1102//
Chris Lattner36a57d32001-07-23 17:17:47 +00001103
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001104bool Option::error(const Twine &Message, StringRef ArgName) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001105 if (!ArgName.data())
1106 ArgName = ArgStr;
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001107 if (ArgName.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001108 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001109 else
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001110 errs() << ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001111
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001112 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001113 return true;
1114}
1115
Chris Bieneman5d232242015-01-13 19:14:20 +00001116bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1117 bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001118 if (!MultiArg)
Chris Bieneman5d232242015-01-13 19:14:20 +00001119 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001120
Misha Brukman069e6b52003-07-10 16:49:51 +00001121 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001122 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001123 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001124 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001125 break;
1126 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001127 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001128 return error("must occur exactly one time!", ArgName);
Chris Bieneman5d232242015-01-13 19:14:20 +00001129 // Fall through
Chris Lattner36a57d32001-07-23 17:17:47 +00001130 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001131 case ZeroOrMore:
Chris Bieneman5d232242015-01-13 19:14:20 +00001132 case ConsumeAfter:
1133 break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001134 }
1135
Reid Spencer2027a6f2004-08-13 19:47:30 +00001136 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001137}
1138
Chris Lattner5df56c42002-07-22 02:07:59 +00001139// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1140// has been specified yet.
1141//
1142static const char *getValueStr(const Option &O, const char *DefaultMsg) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001143 if (O.ValueStr[0] == 0)
1144 return DefaultMsg;
Chris Lattner5df56c42002-07-22 02:07:59 +00001145 return O.ValueStr;
1146}
1147
1148//===----------------------------------------------------------------------===//
1149// cl::alias class implementation
1150//
1151
Chris Lattner36a57d32001-07-23 17:17:47 +00001152// Return the width of the option tag for printing...
Chris Bieneman5d232242015-01-13 19:14:20 +00001153size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
Chris Lattner36a57d32001-07-23 17:17:47 +00001154
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001155static void printHelpStr(StringRef HelpStr, size_t Indent,
1156 size_t FirstLineIndentedBy) {
1157 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1158 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1159 while (!Split.second.empty()) {
1160 Split = Split.second.split('\n');
1161 outs().indent(Indent) << Split.first << "\n";
1162 }
1163}
1164
Chris Lattner1b7a5152006-04-28 05:36:25 +00001165// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001166void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001167 outs() << " -" << ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001168 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001169}
1170
Chris Lattner36a57d32001-07-23 17:17:47 +00001171//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001172// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001173//
1174
Chris Lattnerb4101b12002-08-07 18:36:37 +00001175// basic_parser implementation
1176//
1177
1178// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001179size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1180 size_t Len = std::strlen(O.ArgStr);
Chris Lattnerb4101b12002-08-07 18:36:37 +00001181 if (const char *ValName = getValueName())
Chris Bieneman5d232242015-01-13 19:14:20 +00001182 Len += std::strlen(getValueStr(O, ValName)) + 3;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001183
1184 return Len + 6;
1185}
1186
Misha Brukman10468d82005-04-21 22:55:34 +00001187// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001188// to-be-maintained width is specified.
1189//
1190void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001191 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001192 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001193
1194 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001195 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001196
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001197 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001198}
1199
Andrew Trick12004012011-04-05 18:54:36 +00001200void basic_parser_impl::printOptionName(const Option &O,
1201 size_t GlobalWidth) const {
1202 outs() << " -" << O.ArgStr;
Chris Bieneman5d232242015-01-13 19:14:20 +00001203 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
Andrew Trick12004012011-04-05 18:54:36 +00001204}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001205
Chris Lattner5df56c42002-07-22 02:07:59 +00001206// parser<bool> implementation
1207//
Chris Bieneman5d232242015-01-13 19:14:20 +00001208bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1209 bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001210 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001211 Arg == "1") {
1212 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001213 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001214 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001215
Chris Lattneraecd74d2009-09-19 18:55:05 +00001216 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1217 Value = false;
1218 return false;
1219 }
1220 return O.error("'" + Arg +
1221 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001222}
1223
Dale Johannesen82810c82007-05-22 17:14:46 +00001224// parser<boolOrDefault> implementation
1225//
Chris Bieneman5d232242015-01-13 19:14:20 +00001226bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1227 boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001228 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1229 Arg == "1") {
1230 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001231 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001232 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001233 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1234 Value = BOU_FALSE;
1235 return false;
1236 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001237
Chris Lattneraecd74d2009-09-19 18:55:05 +00001238 return O.error("'" + Arg +
1239 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001240}
1241
Chris Lattner5df56c42002-07-22 02:07:59 +00001242// parser<int> implementation
1243//
Chris Bieneman5d232242015-01-13 19:14:20 +00001244bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1245 int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001246 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001247 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001248 return false;
1249}
1250
Chris Lattner719c7152003-06-28 15:47:20 +00001251// parser<unsigned> implementation
1252//
Chris Bieneman5d232242015-01-13 19:14:20 +00001253bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1254 unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001255
1256 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001257 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001258 return false;
1259}
1260
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001261// parser<unsigned long long> implementation
1262//
1263bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
Chris Bieneman5d232242015-01-13 19:14:20 +00001264 StringRef Arg,
1265 unsigned long long &Value) {
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001266
1267 if (Arg.getAsInteger(0, Value))
1268 return O.error("'" + Arg + "' value invalid for uint argument!");
1269 return false;
1270}
1271
Chris Lattnerb4101b12002-08-07 18:36:37 +00001272// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001273//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001274static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001275 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1276 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001277 char *End;
1278 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001279 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001280 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001281 return false;
1282}
1283
Chris Bieneman5d232242015-01-13 19:14:20 +00001284bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1285 double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001286 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001287}
1288
Chris Bieneman5d232242015-01-13 19:14:20 +00001289bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1290 float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001291 double dVal;
1292 if (parseDouble(O, Arg, dVal))
1293 return true;
1294 Val = (float)dVal;
1295 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001296}
1297
Chris Lattner5df56c42002-07-22 02:07:59 +00001298// generic_parser_base implementation
1299//
1300
Chris Lattner494c0b02002-07-23 17:15:12 +00001301// findOption - Return the option number corresponding to the specified
1302// argument string. If the option is not found, getNumOptions() is returned.
1303//
1304unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001305 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001306
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001307 for (unsigned i = 0; i != e; ++i) {
1308 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001309 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001310 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001311 return e;
1312}
1313
Chris Lattner5df56c42002-07-22 02:07:59 +00001314// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001315size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001316 if (O.hasArgStr()) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001317 size_t Size = std::strlen(O.ArgStr) + 6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001318 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001319 Size = std::max(Size, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001320 return Size;
1321 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001322 size_t BaseSize = 0;
Chris Lattner5df56c42002-07-22 02:07:59 +00001323 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001324 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001325 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001326 }
1327}
1328
Misha Brukman10468d82005-04-21 22:55:34 +00001329// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001330// to-be-maintained width is specified.
1331//
1332void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001333 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001334 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001335 outs() << " -" << O.ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001336 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001337
Chris Lattner5df56c42002-07-22 02:07:59 +00001338 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001339 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001340 outs() << " =" << getOption(i);
1341 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001342 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001343 } else {
1344 if (O.HelpStr[0])
Chris Lattnere7c1e212009-09-20 05:03:30 +00001345 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001346 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001347 const char *Option = getOption(i);
1348 outs() << " -" << Option;
1349 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001350 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001351 }
1352}
1353
Andrew Trick12004012011-04-05 18:54:36 +00001354static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1355
1356// printGenericOptionDiff - Print the value of this option and it's default.
1357//
1358// "Generic" options have each value mapped to a name.
Chris Bieneman5d232242015-01-13 19:14:20 +00001359void generic_parser_base::printGenericOptionDiff(
1360 const Option &O, const GenericOptionValue &Value,
1361 const GenericOptionValue &Default, size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001362 outs() << " -" << O.ArgStr;
Chris Bieneman5d232242015-01-13 19:14:20 +00001363 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
Andrew Trick12004012011-04-05 18:54:36 +00001364
1365 unsigned NumOpts = getNumOptions();
1366 for (unsigned i = 0; i != NumOpts; ++i) {
1367 if (Value.compare(getOptionValue(i)))
1368 continue;
1369
1370 outs() << "= " << getOption(i);
1371 size_t L = std::strlen(getOption(i));
1372 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1373 outs().indent(NumSpaces) << " (default: ";
1374 for (unsigned j = 0; j != NumOpts; ++j) {
1375 if (Default.compare(getOptionValue(j)))
1376 continue;
1377 outs() << getOption(j);
1378 break;
1379 }
1380 outs() << ")\n";
1381 return;
1382 }
1383 outs() << "= *unknown option value*\n";
1384}
1385
1386// printOptionDiff - Specializations for printing basic value types.
1387//
Chris Bieneman5d232242015-01-13 19:14:20 +00001388#define PRINT_OPT_DIFF(T) \
1389 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1390 size_t GlobalWidth) const { \
1391 printOptionName(O, GlobalWidth); \
1392 std::string Str; \
1393 { \
1394 raw_string_ostream SS(Str); \
1395 SS << V; \
1396 } \
1397 outs() << "= " << Str; \
1398 size_t NumSpaces = \
1399 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1400 outs().indent(NumSpaces) << " (default: "; \
1401 if (D.hasValue()) \
1402 outs() << D.getValue(); \
1403 else \
1404 outs() << "*no default*"; \
1405 outs() << ")\n"; \
1406 }
Andrew Trick12004012011-04-05 18:54:36 +00001407
Frits van Bommel87e33672011-04-06 12:29:56 +00001408PRINT_OPT_DIFF(bool)
1409PRINT_OPT_DIFF(boolOrDefault)
1410PRINT_OPT_DIFF(int)
1411PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001412PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001413PRINT_OPT_DIFF(double)
1414PRINT_OPT_DIFF(float)
1415PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001416
Chris Bieneman5d232242015-01-13 19:14:20 +00001417void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1418 OptionValue<std::string> D,
1419 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001420 printOptionName(O, GlobalWidth);
1421 outs() << "= " << V;
1422 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1423 outs().indent(NumSpaces) << " (default: ";
1424 if (D.hasValue())
1425 outs() << D.getValue();
1426 else
1427 outs() << "*no default*";
1428 outs() << ")\n";
1429}
1430
1431// Print a placeholder for options that don't yet support printOptionDiff().
Chris Bieneman5d232242015-01-13 19:14:20 +00001432void basic_parser_impl::printOptionNoValue(const Option &O,
1433 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001434 printOptionName(O, GlobalWidth);
1435 outs() << "= *cannot print option value*\n";
1436}
Chris Lattner36a57d32001-07-23 17:17:47 +00001437
1438//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001439// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001440//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001441
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001442static int OptNameCompare(const void *LHS, const void *RHS) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001443 typedef std::pair<const char *, Option *> pair_ty;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001444
Chris Bieneman5d232242015-01-13 19:14:20 +00001445 return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001446}
1447
Andrew Trick12004012011-04-05 18:54:36 +00001448// Copy Options into a vector so we can sort them as we like.
Chris Bieneman5d232242015-01-13 19:14:20 +00001449static void sortOpts(StringMap<Option *> &OptMap,
1450 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1451 bool ShowHidden) {
1452 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
Andrew Trick12004012011-04-05 18:54:36 +00001453
Chris Bieneman5d232242015-01-13 19:14:20 +00001454 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
Andrew Trick12004012011-04-05 18:54:36 +00001455 I != E; ++I) {
1456 // Ignore really-hidden options.
1457 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1458 continue;
1459
1460 // Unless showhidden is set, ignore hidden flags.
1461 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1462 continue;
1463
1464 // If we've already seen this option, don't add it to the list again.
David Blaikie70573dc2014-11-19 07:49:26 +00001465 if (!OptionSet.insert(I->second).second)
Andrew Trick12004012011-04-05 18:54:36 +00001466 continue;
1467
Chris Bieneman5d232242015-01-13 19:14:20 +00001468 Opts.push_back(
1469 std::pair<const char *, Option *>(I->getKey().data(), I->second));
Andrew Trick12004012011-04-05 18:54:36 +00001470 }
1471
1472 // Sort the options list alphabetically.
1473 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1474}
1475
Chris Lattner36a57d32001-07-23 17:17:47 +00001476namespace {
1477
Chris Lattner5df56c42002-07-22 02:07:59 +00001478class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001479protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001480 const bool ShowHidden;
Chris Bieneman5d232242015-01-13 19:14:20 +00001481 typedef SmallVector<std::pair<const char *, Option *>, 128>
1482 StrOptionPairVector;
Andrew Trick0537a982013-05-06 21:56:23 +00001483 // Print the options. Opts is assumed to be alphabetically sorted.
1484 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1485 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1486 Opts[i].second->printOptionInfo(MaxArgLen);
1487 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001488
Chris Lattner5df56c42002-07-22 02:07:59 +00001489public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001490 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001491 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001492
Andrew Trick0537a982013-05-06 21:56:23 +00001493 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001494 void operator=(bool Value) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001495 if (Value == false)
1496 return;
Chris Lattner5df56c42002-07-22 02:07:59 +00001497
Chris Lattner5247f602007-04-06 21:06:55 +00001498 // Get all the options.
Chris Bieneman5d232242015-01-13 19:14:20 +00001499 SmallVector<Option *, 4> PositionalOpts;
1500 SmallVector<Option *, 4> SinkOpts;
1501 StringMap<Option *> OptMap;
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001502 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001503
Andrew Trick0537a982013-05-06 21:56:23 +00001504 StrOptionPairVector Opts;
Andrew Trick12004012011-04-05 18:54:36 +00001505 sortOpts(OptMap, Opts, ShowHidden);
Chris Lattner36a57d32001-07-23 17:17:47 +00001506
1507 if (ProgramOverview)
Chris Lattner471ba482009-08-23 08:43:55 +00001508 outs() << "OVERVIEW: " << ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001509
Chris Lattner471ba482009-08-23 08:43:55 +00001510 outs() << "USAGE: " << ProgramName << " [options]";
Chris Lattner5df56c42002-07-22 02:07:59 +00001511
Chris Lattner8111c592006-10-04 21:52:35 +00001512 // Print out the positional options.
Chris Bieneman5d232242015-01-13 19:14:20 +00001513 Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001514 if (!PositionalOpts.empty() &&
Chris Lattner5247f602007-04-06 21:06:55 +00001515 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1516 CAOpt = PositionalOpts[0];
Chris Lattner5df56c42002-07-22 02:07:59 +00001517
Craig Topperc10719f2014-04-07 04:17:22 +00001518 for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5247f602007-04-06 21:06:55 +00001519 if (PositionalOpts[i]->ArgStr[0])
Chris Lattner471ba482009-08-23 08:43:55 +00001520 outs() << " --" << PositionalOpts[i]->ArgStr;
1521 outs() << " " << PositionalOpts[i]->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001522 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001523
1524 // Print the consume after option info if it exists...
Chris Bieneman5d232242015-01-13 19:14:20 +00001525 if (CAOpt)
1526 outs() << " " << CAOpt->HelpStr;
Chris Lattner5df56c42002-07-22 02:07:59 +00001527
Chris Lattner471ba482009-08-23 08:43:55 +00001528 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001529
1530 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001531 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001532 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001533 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001534
Chris Lattner471ba482009-08-23 08:43:55 +00001535 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001536 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001537
Chris Lattner37bcd992004-11-19 17:08:15 +00001538 // Print any extra help the user has declared.
Chris Lattner8111c592006-10-04 21:52:35 +00001539 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
Andrew Trick0537a982013-05-06 21:56:23 +00001540 E = MoreHelp->end();
1541 I != E; ++I)
Chris Lattner471ba482009-08-23 08:43:55 +00001542 outs() << *I;
Chris Lattner8111c592006-10-04 21:52:35 +00001543 MoreHelp->clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001544
Reid Spencer5e554702004-11-16 06:11:52 +00001545 // Halt the program since help information was printed
Justin Bogner02b95842014-02-28 19:08:01 +00001546 exit(0);
Chris Lattner36a57d32001-07-23 17:17:47 +00001547 }
1548};
Andrew Trick0537a982013-05-06 21:56:23 +00001549
1550class CategorizedHelpPrinter : public HelpPrinter {
1551public:
1552 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1553
1554 // Helper function for printOptions().
1555 // It shall return true if A's name should be lexographically
1556 // ordered before B's name. It returns false otherwise.
1557 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
Alexander Kornienkod772d722014-02-07 17:42:30 +00001558 return strcmp(A->getName(), B->getName()) < 0;
Andrew Trick0537a982013-05-06 21:56:23 +00001559 }
1560
1561 // Make sure we inherit our base class's operator=()
Chris Bieneman5d232242015-01-13 19:14:20 +00001562 using HelpPrinter::operator=;
Andrew Trick0537a982013-05-06 21:56:23 +00001563
1564protected:
Craig Topper32ea8262014-03-04 06:24:11 +00001565 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
Andrew Trick0537a982013-05-06 21:56:23 +00001566 std::vector<OptionCategory *> SortedCategories;
Chris Bieneman5d232242015-01-13 19:14:20 +00001567 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
Andrew Trick0537a982013-05-06 21:56:23 +00001568
Alp Tokercb402912014-01-24 17:20:08 +00001569 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001570 // sorting.
1571 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1572 E = RegisteredOptionCategories->end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001573 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001574 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001575 }
Andrew Trick0537a982013-05-06 21:56:23 +00001576
1577 // Sort the different option categories alphabetically.
1578 assert(SortedCategories.size() > 0 && "No option categories registered!");
1579 std::sort(SortedCategories.begin(), SortedCategories.end(),
1580 OptionCategoryCompare);
1581
1582 // Create map to empty vectors.
1583 for (std::vector<OptionCategory *>::const_iterator
1584 I = SortedCategories.begin(),
1585 E = SortedCategories.end();
1586 I != E; ++I)
1587 CategorizedOptions[*I] = std::vector<Option *>();
1588
1589 // Walk through pre-sorted options and assign into categories.
1590 // Because the options are already alphabetically sorted the
1591 // options within categories will also be alphabetically sorted.
1592 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1593 Option *Opt = Opts[I].second;
1594 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1595 "Option has an unregistered category");
1596 CategorizedOptions[Opt->Category].push_back(Opt);
1597 }
1598
1599 // Now do printing.
1600 for (std::vector<OptionCategory *>::const_iterator
1601 Category = SortedCategories.begin(),
1602 E = SortedCategories.end();
1603 Category != E; ++Category) {
1604 // Hide empty categories for -help, but show for -help-hidden.
1605 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1606 if (!ShowHidden && IsEmptyCategory)
1607 continue;
1608
1609 // Print category information.
1610 outs() << "\n";
1611 outs() << (*Category)->getName() << ":\n";
1612
1613 // Check if description is set.
Craig Topperc10719f2014-04-07 04:17:22 +00001614 if ((*Category)->getDescription() != nullptr)
Andrew Trick0537a982013-05-06 21:56:23 +00001615 outs() << (*Category)->getDescription() << "\n\n";
1616 else
1617 outs() << "\n";
1618
1619 // When using -help-hidden explicitly state if the category has no
1620 // options associated with it.
1621 if (IsEmptyCategory) {
1622 outs() << " This option category has no options.\n";
1623 continue;
1624 }
1625 // Loop over the options in the category and print.
1626 for (std::vector<Option *>::const_iterator
1627 Opt = CategorizedOptions[*Category].begin(),
1628 E = CategorizedOptions[*Category].end();
1629 Opt != E; ++Opt)
1630 (*Opt)->printOptionInfo(MaxArgLen);
1631 }
1632 }
1633};
1634
1635// This wraps the Uncategorizing and Categorizing printers and decides
1636// at run time which should be invoked.
1637class HelpPrinterWrapper {
1638private:
1639 HelpPrinter &UncategorizedPrinter;
1640 CategorizedHelpPrinter &CategorizedPrinter;
1641
1642public:
1643 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
Chris Bieneman5d232242015-01-13 19:14:20 +00001644 CategorizedHelpPrinter &CategorizedPrinter)
1645 : UncategorizedPrinter(UncategorizedPrinter),
1646 CategorizedPrinter(CategorizedPrinter) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001647
1648 // Invoke the printer.
1649 void operator=(bool Value);
1650};
1651
Chris Lattneradb19d62006-10-12 22:09:17 +00001652} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001653
Andrew Trick0537a982013-05-06 21:56:23 +00001654// Declare the four HelpPrinter instances that are used to print out help, or
1655// help-hidden as an uncategorized list or in categories.
1656static HelpPrinter UncategorizedNormalPrinter(false);
1657static HelpPrinter UncategorizedHiddenPrinter(true);
1658static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1659static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1660
Andrew Trick0537a982013-05-06 21:56:23 +00001661// Declare HelpPrinter wrappers that will decide whether or not to invoke
1662// a categorizing help printer
1663static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1664 CategorizedNormalPrinter);
1665static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1666 CategorizedHiddenPrinter);
1667
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001668// Define a category for generic options that all tools should have.
1669static cl::OptionCategory GenericCategory("Generic Options");
1670
Andrew Trick0537a982013-05-06 21:56:23 +00001671// Define uncategorized help printers.
1672// -help-list is hidden by default because if Option categories are being used
1673// then -help behaves the same as -help-list.
Chris Bieneman5d232242015-01-13 19:14:20 +00001674static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1675 "help-list",
1676 cl::desc("Display list of available options (-help-list-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001677 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1678 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001679
Chris Bieneman5d232242015-01-13 19:14:20 +00001680static cl::opt<HelpPrinter, true, parser<bool>>
1681 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1682 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001683 cl::ValueDisallowed, cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001684
1685// Define uncategorized/categorized help printers. These printers change their
1686// behaviour at runtime depending on whether one or more Option categories have
1687// been declared.
Chris Bieneman5d232242015-01-13 19:14:20 +00001688static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1689 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001690 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1691 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001692
Chris Bieneman5d232242015-01-13 19:14:20 +00001693static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1694 HHOp("help-hidden", cl::desc("Display all available options"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001695 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1696 cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001697
Chris Bieneman5d232242015-01-13 19:14:20 +00001698static cl::opt<bool> PrintOptions(
1699 "print-options",
1700 cl::desc("Print non-default options after command line parsing"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001701 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001702
Chris Bieneman5d232242015-01-13 19:14:20 +00001703static cl::opt<bool> PrintAllOptions(
1704 "print-all-options",
1705 cl::desc("Print all option values after command line parsing"), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001706 cl::init(false), cl::cat(GenericCategory));
Andrew Trick12004012011-04-05 18:54:36 +00001707
Andrew Trick0537a982013-05-06 21:56:23 +00001708void HelpPrinterWrapper::operator=(bool Value) {
1709 if (Value == false)
1710 return;
1711
1712 // Decide which printer to invoke. If more than one option category is
1713 // registered then it is useful to show the categorized help instead of
1714 // uncategorized help.
1715 if (RegisteredOptionCategories->size() > 1) {
1716 // unhide -help-list option so user can have uncategorized output if they
1717 // want it.
1718 HLOp.setHiddenFlag(NotHidden);
1719
1720 CategorizedPrinter = true; // Invoke categorized printer
Chris Bieneman5d232242015-01-13 19:14:20 +00001721 } else
Andrew Trick0537a982013-05-06 21:56:23 +00001722 UncategorizedPrinter = true; // Invoke uncategorized printer
1723}
1724
Andrew Trick12004012011-04-05 18:54:36 +00001725// Print the value of each option.
1726void cl::PrintOptionValues() {
Chris Bieneman5d232242015-01-13 19:14:20 +00001727 if (!PrintOptions && !PrintAllOptions)
1728 return;
Andrew Trick12004012011-04-05 18:54:36 +00001729
1730 // Get all the options.
Chris Bieneman5d232242015-01-13 19:14:20 +00001731 SmallVector<Option *, 4> PositionalOpts;
1732 SmallVector<Option *, 4> SinkOpts;
1733 StringMap<Option *> OptMap;
Andrew Trick12004012011-04-05 18:54:36 +00001734 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1735
Chris Bieneman5d232242015-01-13 19:14:20 +00001736 SmallVector<std::pair<const char *, Option *>, 128> Opts;
1737 sortOpts(OptMap, Opts, /*ShowHidden*/ true);
Andrew Trick12004012011-04-05 18:54:36 +00001738
1739 // Compute the maximum argument length...
1740 size_t MaxArgLen = 0;
1741 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1742 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1743
1744 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1745 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1746}
1747
Craig Topperc10719f2014-04-07 04:17:22 +00001748static void (*OverrideVersionPrinter)() = nullptr;
Reid Spencerb3171672006-06-05 16:22:56 +00001749
Chris Bieneman5d232242015-01-13 19:14:20 +00001750static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
Chandler Carruthea7e5522011-07-22 07:50:40 +00001751
Chris Lattneradb19d62006-10-12 22:09:17 +00001752namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00001753class VersionPrinter {
1754public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00001755 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00001756 raw_ostream &OS = outs();
Jim Grosbach65e24652012-01-25 22:00:23 +00001757 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner131dca92009-09-20 06:18:38 +00001758 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00001759#ifdef LLVM_VERSION_INFO
Justin Bogner581b5922014-06-17 06:52:41 +00001760 OS << " " << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00001761#endif
Chris Lattner131dca92009-09-20 06:18:38 +00001762 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001763#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00001764 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001765#else
Chris Lattner131dca92009-09-20 06:18:38 +00001766 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001767#endif
1768#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00001769 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001770#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00001771 std::string CPU = sys::getHostCPUName();
Chris Bieneman5d232242015-01-13 19:14:20 +00001772 if (CPU == "generic")
1773 CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00001774 OS << ".\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001775#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner131dca92009-09-20 06:18:38 +00001776 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001777#endif
Sebastian Pop94441fb2011-11-01 21:32:20 +00001778 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00001779 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00001780 }
1781 void operator=(bool OptionWasSpecified) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001782 if (!OptionWasSpecified)
1783 return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001784
Craig Topperc10719f2014-04-07 04:17:22 +00001785 if (OverrideVersionPrinter != nullptr) {
Chandler Carruthea7e5522011-07-22 07:50:40 +00001786 (*OverrideVersionPrinter)();
Justin Bogner02b95842014-02-28 19:08:01 +00001787 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001788 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001789 print();
1790
1791 // Iterate over any registered extra printers and call them to add further
1792 // information.
Craig Topperc10719f2014-04-07 04:17:22 +00001793 if (ExtraVersionPrinters != nullptr) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00001794 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00001795 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1796 E = ExtraVersionPrinters->end();
1797 I != E; ++I)
1798 (*I)();
1799 }
1800
Justin Bogner02b95842014-02-28 19:08:01 +00001801 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001802 }
1803};
Chris Lattneradb19d62006-10-12 22:09:17 +00001804} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00001805
Reid Spencerff6cc122004-08-04 00:36:06 +00001806// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00001807static VersionPrinter VersionPrinterInstance;
1808
Chris Bieneman5d232242015-01-13 19:14:20 +00001809static cl::opt<VersionPrinter, true, parser<bool>>
1810 VersOp("version", cl::desc("Display the version of this program"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001811 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1812 cl::cat(GenericCategory));
Reid Spencerff6cc122004-08-04 00:36:06 +00001813
Reid Spencer5e554702004-11-16 06:11:52 +00001814// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00001815void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1816 // This looks weird, but it actually prints the help message. The Printers are
1817 // types of HelpPrinter and the help gets printed when its operator= is
1818 // invoked. That's because the "normal" usages of the help printer is to be
1819 // assigned true/false depending on whether -help or -help-hidden was given or
1820 // not. Since we're circumventing that we have to make it look like -help or
1821 // -help-hidden were given, so we assign true.
1822
1823 if (!Hidden && !Categorized)
1824 UncategorizedNormalPrinter = true;
1825 else if (!Hidden && Categorized)
1826 CategorizedNormalPrinter = true;
1827 else if (Hidden && !Categorized)
1828 UncategorizedHiddenPrinter = true;
1829 else
1830 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00001831}
Reid Spencerb3171672006-06-05 16:22:56 +00001832
Devang Patel9eb2caae2007-02-01 01:43:37 +00001833/// Utility function for printing version number.
Chris Bieneman5d232242015-01-13 19:14:20 +00001834void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
Devang Patel9eb2caae2007-02-01 01:43:37 +00001835
Chris Bieneman5d232242015-01-13 19:14:20 +00001836void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001837
1838void cl::AddExtraVersionPrinter(void (*func)()) {
Craig Topper8d399f82014-04-09 04:20:00 +00001839 if (!ExtraVersionPrinters)
Chandler Carruthea7e5522011-07-22 07:50:40 +00001840 ExtraVersionPrinters = new std::vector<void (*)()>;
1841
1842 ExtraVersionPrinters->push_back(func);
1843}
Andrew Trick7cb710d2013-05-06 21:56:35 +00001844
Chris Bieneman5d232242015-01-13 19:14:20 +00001845void cl::getRegisteredOptions(StringMap<Option *> &Map) {
Andrew Trick7cb710d2013-05-06 21:56:35 +00001846 // Get all the options.
Chris Bieneman5d232242015-01-13 19:14:20 +00001847 SmallVector<Option *, 4> PositionalOpts; // NOT USED
Chris Bieneman9e13af72015-01-21 22:45:52 +00001848 SmallVector<Option *, 4> SinkOpts; // NOT USED
Andrew Trick7cb710d2013-05-06 21:56:35 +00001849 assert(Map.size() == 0 && "StringMap must be empty");
1850 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1851 return;
1852}
Peter Collingbournee1863192014-10-16 22:47:52 +00001853
Chris Bieneman9e13af72015-01-21 22:45:52 +00001854void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1855 StringMap<cl::Option *> Options;
1856 cl::getRegisteredOptions(Options);
1857 for (auto &I : Options) {
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001858 if (I.second->Category != &Category &&
1859 I.second->Category != &GenericCategory)
Chris Bieneman9e13af72015-01-21 22:45:52 +00001860 I.second->setHiddenFlag(cl::ReallyHidden);
1861 }
1862}
1863
Chris Bieneman01043252015-01-26 21:57:29 +00001864void cl::HideUnrelatedOptions(
1865 SmallVectorImpl<cl::OptionCategory *> &Categories) {
1866 auto CategoriesBegin = Categories.begin();
1867 auto CategoriesEnd = Categories.end();
1868 StringMap<cl::Option *> Options;
1869 cl::getRegisteredOptions(Options);
1870 for (auto &I : Options) {
1871 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1872 CategoriesEnd &&
1873 I.second->Category != &GenericCategory)
1874 I.second->setHiddenFlag(cl::ReallyHidden);
1875 }
1876}
1877
Peter Collingbournee1863192014-10-16 22:47:52 +00001878void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1879 const char *Overview) {
1880 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1881}