1//===-- CommandLine.cpp - Command line parser implementation --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This class implements a command line argument processor that is useful when
10// creating a tool. It provides a simple, minimalistic interface that is easily
11// extensible and supports nonlocal (library) command line options.
12//
13// Note that rather than trying to figure out what this code does, you could try
14// reading the library documentation located in docs/CommandLine.html
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Support/CommandLine.h"
19
20#include "DebugOptions.h"
21
22#include "llvm-c/Support.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/STLFunctionalExtras.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/ADT/StringMap.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/ADT/Twine.h"
31#include "llvm/Config/config.h"
32#include "llvm/Support/Compiler.h"
33#include "llvm/Support/ConvertUTF.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/Error.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/FileSystem.h"
38#include "llvm/Support/ManagedStatic.h"
39#include "llvm/Support/MemoryBuffer.h"
40#include "llvm/Support/Path.h"
41#include "llvm/Support/Process.h"
42#include "llvm/Support/StringSaver.h"
43#include "llvm/Support/TypeSize.h"
44#include "llvm/Support/VirtualFileSystem.h"
45#include "llvm/Support/raw_ostream.h"
46#include <cstdlib>
47#include <optional>
48#include <string>
49using namespace llvm;
50using namespace cl;
51
52#define DEBUG_TYPE "commandline"
53
54//===----------------------------------------------------------------------===//
55// Template instantiations and anchors.
56//
57namespace llvm {
58namespace cl {
59template class LLVM_EXPORT_TEMPLATE basic_parser<bool>;
60template class LLVM_EXPORT_TEMPLATE basic_parser<boolOrDefault>;
61template class LLVM_EXPORT_TEMPLATE basic_parser<int>;
62template class LLVM_EXPORT_TEMPLATE basic_parser<long>;
63template class LLVM_EXPORT_TEMPLATE basic_parser<long long>;
64template class LLVM_EXPORT_TEMPLATE basic_parser<unsigned>;
65template class LLVM_EXPORT_TEMPLATE basic_parser<unsigned long>;
66template class LLVM_EXPORT_TEMPLATE basic_parser<unsigned long long>;
67template class LLVM_EXPORT_TEMPLATE basic_parser<double>;
68template class LLVM_EXPORT_TEMPLATE basic_parser<float>;
69template class LLVM_EXPORT_TEMPLATE basic_parser<std::string>;
70template class LLVM_EXPORT_TEMPLATE basic_parser<char>;
71template class LLVM_EXPORT_TEMPLATE basic_parser<ElementCount>;
72
73#if !(defined(LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS) && defined(_MSC_VER))
74// Only instantiate opt<std::string> when not building a Windows DLL. When
75// exporting opt<std::string>, MSVC implicitly exports symbols for
76// std::basic_string through transitive inheritance via std::string. These
77// symbols may appear in clients, leading to duplicate symbol conflicts.
78template class LLVM_EXPORT_TEMPLATE opt<std::string>;
79#endif
80
81template class LLVM_EXPORT_TEMPLATE opt<bool>;
82template class LLVM_EXPORT_TEMPLATE opt<char>;
83template class LLVM_EXPORT_TEMPLATE opt<int>;
84template class LLVM_EXPORT_TEMPLATE opt<unsigned>;
85
86} // namespace cl
87} // namespace llvm
88
89// Pin the vtables to this file.
90void GenericOptionValue::anchor() {}
91void OptionValue<boolOrDefault>::anchor() {}
92void OptionValue<std::string>::anchor() {}
93void Option::anchor() {}
94void basic_parser_impl::anchor() {}
95void parser<bool>::anchor() {}
96void parser<boolOrDefault>::anchor() {}
97void parser<int>::anchor() {}
98void parser<long>::anchor() {}
99void parser<long long>::anchor() {}
100void parser<unsigned>::anchor() {}
101void parser<unsigned long>::anchor() {}
102void parser<unsigned long long>::anchor() {}
103void parser<double>::anchor() {}
104void parser<float>::anchor() {}
105void parser<std::string>::anchor() {}
106void parser<std::optional<std::string>>::anchor() {}
107void parser<char>::anchor() {}
108void parser<ElementCount>::anchor() {}
109
110// These anchor functions instantiate opt<T> and reference its virtual
111// destructor to ensure MSVC exports the corresponding vtable and typeinfo when
112// building a Windows DLL. Without an explicit reference, MSVC may omit the
113// instantiation at link time even if it is marked DLL-export.
114void opt_bool_anchor() { opt<bool> anchor{""}; }
115void opt_char_anchor() { opt<char> anchor{""}; }
116void opt_int_anchor() { opt<int> anchor{""}; }
117void opt_unsigned_anchor() { opt<unsigned> anchor{""}; }
118
119//===----------------------------------------------------------------------===//
120
121const static size_t DefaultPad = 2;
122
123static StringRef ArgPrefix = "-";
124static StringRef ArgPrefixLong = "--";
125static StringRef ArgHelpPrefix = " - ";
126
127static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
128 size_t Len = ArgName.size();
129 if (Len == 1)
130 return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
131 return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
132}
133
134static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
135 SmallString<8> Prefix;
136 for (size_t I = 0; I < Pad; ++I) {
137 Prefix.push_back(Elt: ' ');
138 }
139 Prefix.append(RHS: ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
140 return Prefix;
141}
142
143// Option predicates...
144static inline bool isGrouping(const Option *O) {
145 return O->getMiscFlags() & cl::Grouping;
146}
147static inline bool isPrefixedOrGrouping(const Option *O) {
148 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
149 O->getFormattingFlag() == cl::AlwaysPrefix;
150}
151
152using OptionsMapTy = DenseMap<StringRef, Option *>;
153
154namespace {
155
156class PrintArg {
157 StringRef ArgName;
158 size_t Pad;
159public:
160 PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
161 friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
162};
163
164raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
165 OS << argPrefix(ArgName: Arg.ArgName, Pad: Arg.Pad) << Arg.ArgName;
166 return OS;
167}
168
169class CommandLineParser {
170public:
171 // Globals for name and overview of program. Program name is not a string to
172 // avoid static ctor/dtor issues.
173 std::string ProgramName;
174 StringRef ProgramOverview;
175
176 // This collects additional help to be printed.
177 std::vector<StringRef> MoreHelp;
178
179 // This collects Options added with the cl::DefaultOption flag. Since they can
180 // be overridden, they are not added to the appropriate SubCommands until
181 // ParseCommandLineOptions actually runs.
182 SmallVector<Option*, 4> DefaultOptions;
183
184 // This collects the different option categories that have been registered.
185 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
186
187 // This collects the different subcommands that have been registered.
188 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
189
190 CommandLineParser() { registerSubCommand(sub: &SubCommand::getTopLevel()); }
191
192 void ResetAllOptionOccurrences();
193
194 bool ParseCommandLineOptions(int argc, const char *const *argv,
195 StringRef Overview, raw_ostream *Errs = nullptr,
196 vfs::FileSystem *VFS = nullptr,
197 bool LongOptionsUseDoubleDash = false);
198
199 void forEachSubCommand(Option &Opt, function_ref<void(SubCommand &)> Action) {
200 if (Opt.Subs.empty()) {
201 Action(SubCommand::getTopLevel());
202 return;
203 }
204 if (Opt.Subs.size() == 1 && *Opt.Subs.begin() == &SubCommand::getAll()) {
205 for (auto *SC : RegisteredSubCommands)
206 Action(*SC);
207 Action(SubCommand::getAll());
208 return;
209 }
210 for (auto *SC : Opt.Subs) {
211 assert(SC != &SubCommand::getAll() &&
212 "SubCommand::getAll() should not be used with other subcommands");
213 Action(*SC);
214 }
215 }
216
217 void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
218 if (Opt.hasArgStr())
219 return;
220 if (!SC->OptionsMap.insert(KV: std::make_pair(x&: Name, y: &Opt)).second) {
221 errs() << ProgramName << ": CommandLine Error: Option '" << Name
222 << "' registered more than once!\n";
223 report_fatal_error(reason: "inconsistency in registered CommandLine options");
224 }
225 }
226
227 void addLiteralOption(Option &Opt, StringRef Name) {
228 forEachSubCommand(
229 Opt, Action: [&](SubCommand &SC) { addLiteralOption(Opt, SC: &SC, Name); });
230 }
231
232 void addOption(Option *O, SubCommand *SC) {
233 bool HadErrors = false;
234 if (O->hasArgStr()) {
235 // If it's a DefaultOption, check to make sure it isn't already there.
236 if (O->isDefaultOption() && SC->OptionsMap.contains(Val: O->ArgStr))
237 return;
238
239 // Add argument to the argument map!
240 if (!SC->OptionsMap.insert(KV: std::make_pair(x&: O->ArgStr, y&: O)).second) {
241 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
242 << "' registered more than once!\n";
243 HadErrors = true;
244 }
245 }
246
247 // Remember information about positional options.
248 if (O->getFormattingFlag() == cl::Positional)
249 SC->PositionalOpts.push_back(Elt: O);
250 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
251 SC->SinkOpts.push_back(Elt: O);
252 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
253 if (SC->ConsumeAfterOpt) {
254 O->error(Message: "Cannot specify more than one option with cl::ConsumeAfter!");
255 HadErrors = true;
256 }
257 SC->ConsumeAfterOpt = O;
258 }
259
260 // Fail hard if there were errors. These are strictly unrecoverable and
261 // indicate serious issues such as conflicting option names or an
262 // incorrectly
263 // linked LLVM distribution.
264 if (HadErrors)
265 report_fatal_error(reason: "inconsistency in registered CommandLine options");
266 }
267
268 void addOption(Option *O, bool ProcessDefaultOption = false) {
269 if (!ProcessDefaultOption && O->isDefaultOption()) {
270 DefaultOptions.push_back(Elt: O);
271 return;
272 }
273 forEachSubCommand(Opt&: *O, Action: [&](SubCommand &SC) { addOption(O, SC: &SC); });
274 }
275
276 void removeOption(Option *O, SubCommand *SC) {
277 SmallVector<StringRef, 16> OptionNames;
278 O->getExtraOptionNames(OptionNames);
279 if (O->hasArgStr())
280 OptionNames.push_back(Elt: O->ArgStr);
281
282 SubCommand &Sub = *SC;
283 for (auto Name : OptionNames) {
284 auto I = Sub.OptionsMap.find(Val: Name);
285 // Re-query end() each iteration: a prior erase invalidates iterators
286 // (including a cached end()) under backward-shift deletion.
287 if (I != Sub.OptionsMap.end() && I->second == O)
288 Sub.OptionsMap.erase(I);
289 }
290
291 if (O->getFormattingFlag() == cl::Positional)
292 for (auto *Opt = Sub.PositionalOpts.begin();
293 Opt != Sub.PositionalOpts.end(); ++Opt) {
294 if (*Opt == O) {
295 Sub.PositionalOpts.erase(CI: Opt);
296 break;
297 }
298 }
299 else if (O->getMiscFlags() & cl::Sink)
300 for (auto *Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
301 if (*Opt == O) {
302 Sub.SinkOpts.erase(CI: Opt);
303 break;
304 }
305 }
306 else if (O == Sub.ConsumeAfterOpt)
307 Sub.ConsumeAfterOpt = nullptr;
308 }
309
310 void removeOption(Option *O) {
311 forEachSubCommand(Opt&: *O, Action: [&](SubCommand &SC) { removeOption(O, SC: &SC); });
312 }
313
314 bool hasOptions(const SubCommand &Sub) const {
315 return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
316 nullptr != Sub.ConsumeAfterOpt);
317 }
318
319 bool hasOptions() const {
320 for (const auto *S : RegisteredSubCommands) {
321 if (hasOptions(Sub: *S))
322 return true;
323 }
324 return false;
325 }
326
327 bool hasNamedSubCommands() const {
328 for (const auto *S : RegisteredSubCommands)
329 if (!S->getName().empty())
330 return true;
331 return false;
332 }
333
334 SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
335
336 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
337 SubCommand &Sub = *SC;
338 if (!Sub.OptionsMap.insert(KV: std::make_pair(x&: NewName, y&: O)).second) {
339 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
340 << "' registered more than once!\n";
341 report_fatal_error(reason: "inconsistency in registered CommandLine options");
342 }
343 Sub.OptionsMap.erase(Val: O->ArgStr);
344 }
345
346 void updateArgStr(Option *O, StringRef NewName) {
347 forEachSubCommand(Opt&: *O,
348 Action: [&](SubCommand &SC) { updateArgStr(O, NewName, SC: &SC); });
349 }
350
351 void printOptionValues();
352
353 void registerCategory(OptionCategory *cat) {
354 assert(count_if(RegisteredOptionCategories,
355 [cat](const OptionCategory *Category) {
356 return cat->getName() == Category->getName();
357 }) == 0 &&
358 "Duplicate option categories");
359
360 RegisteredOptionCategories.insert(Ptr: cat);
361 }
362
363 void registerSubCommand(SubCommand *sub) {
364 assert(count_if(RegisteredSubCommands,
365 [sub](const SubCommand *Sub) {
366 return (!sub->getName().empty()) &&
367 (Sub->getName() == sub->getName());
368 }) == 0 &&
369 "Duplicate subcommands");
370 RegisteredSubCommands.insert(Ptr: sub);
371
372 // For all options that have been registered for all subcommands, add the
373 // option to this subcommand now.
374 assert(sub != &SubCommand::getAll() &&
375 "SubCommand::getAll() should not be registered");
376 for (auto &E : SubCommand::getAll().OptionsMap) {
377 Option *O = E.second;
378 if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
379 O->hasArgStr())
380 addOption(O, SC: sub);
381 else
382 addLiteralOption(Opt&: *O, SC: sub, Name: E.first);
383 }
384 }
385
386 void unregisterSubCommand(SubCommand *sub) {
387 RegisteredSubCommands.erase(Ptr: sub);
388 }
389
390 iterator_range<SmallPtrSet<SubCommand *, 4>::iterator>
391 getRegisteredSubcommands() {
392 return make_range(x: RegisteredSubCommands.begin(),
393 y: RegisteredSubCommands.end());
394 }
395
396 void reset() {
397 ActiveSubCommand = nullptr;
398 ProgramName.clear();
399 ProgramOverview = StringRef();
400
401 MoreHelp.clear();
402 RegisteredOptionCategories.clear();
403
404 ResetAllOptionOccurrences();
405 RegisteredSubCommands.clear();
406
407 SubCommand::getTopLevel().reset();
408 SubCommand::getAll().reset();
409 registerSubCommand(sub: &SubCommand::getTopLevel());
410
411 DefaultOptions.clear();
412 }
413
414private:
415 SubCommand *ActiveSubCommand = nullptr;
416
417 Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
418 Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
419 bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
420 Option *Opt = LookupOption(Sub, Arg, Value);
421 if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(O: Opt))
422 return nullptr;
423 return Opt;
424 }
425 SubCommand *LookupSubCommand(StringRef Name, std::string &NearestString);
426};
427
428} // namespace
429
430static ManagedStatic<CommandLineParser> GlobalParser;
431
432template <typename T, T TrueVal, T FalseVal>
433static bool parseBool(Option &O, StringRef ArgName, StringRef Arg, T &Value) {
434 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
435 Arg == "1") {
436 Value = TrueVal;
437 return false;
438 }
439
440 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
441 Value = FalseVal;
442 return false;
443 }
444 return O.error(Message: "'" + Arg +
445 "' is invalid value for boolean argument! Try 0 or 1");
446}
447
448void cl::AddLiteralOption(Option &O, StringRef Name) {
449 GlobalParser->addLiteralOption(Opt&: O, Name);
450}
451
452extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
453 GlobalParser->MoreHelp.push_back(x: Help);
454}
455
456Option::Option(NumOccurrencesFlag OccurrencesFlag, OptionHidden Hidden)
457 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
458 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0),
459 FullyInitialized(false), Position(0), AdditionalVals(0) {
460 Categories.push_back(Elt: &getGeneralCategory());
461}
462
463void Option::addArgument() {
464 GlobalParser->addOption(O: this);
465 FullyInitialized = true;
466}
467
468void Option::removeArgument() { GlobalParser->removeOption(O: this); }
469
470void Option::setArgStr(StringRef S) {
471 if (FullyInitialized)
472 GlobalParser->updateArgStr(O: this, NewName: S);
473 assert(!S.starts_with("-") && "Option can't start with '-");
474 ArgStr = S;
475 if (ArgStr.size() == 1)
476 setMiscFlag(Grouping);
477}
478
479void Option::addCategory(OptionCategory &C) {
480 assert(!Categories.empty() && "Categories cannot be empty.");
481 // Maintain backward compatibility by replacing the default GeneralCategory
482 // if it's still set. Otherwise, just add the new one. The GeneralCategory
483 // must be explicitly added if you want multiple categories that include it.
484 if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory())
485 Categories[0] = &C;
486 else if (!is_contained(Range&: Categories, Element: &C))
487 Categories.push_back(Elt: &C);
488}
489
490void Option::reset() {
491 NumOccurrences = 0;
492 setDefault();
493 if (isDefaultOption())
494 removeArgument();
495}
496
497void OptionCategory::registerCategory() {
498 GlobalParser->registerCategory(cat: this);
499}
500
501// A special subcommand representing no subcommand. It is particularly important
502// that this ManagedStatic uses constant initailization and not dynamic
503// initialization because it is referenced from cl::opt constructors, which run
504// dynamically in an arbitrary order.
505LLVM_REQUIRE_CONSTANT_INITIALIZATION
506static ManagedStatic<SubCommand> TopLevelSubCommand;
507
508// A special subcommand that can be used to put an option into all subcommands.
509static ManagedStatic<SubCommand> AllSubCommands;
510
511SubCommand &SubCommand::getTopLevel() { return *TopLevelSubCommand; }
512
513SubCommand &SubCommand::getAll() { return *AllSubCommands; }
514
515void SubCommand::registerSubCommand() {
516 GlobalParser->registerSubCommand(sub: this);
517}
518
519void SubCommand::unregisterSubCommand() {
520 GlobalParser->unregisterSubCommand(sub: this);
521}
522
523void SubCommand::reset() {
524 PositionalOpts.clear();
525 SinkOpts.clear();
526 OptionsMap.clear();
527
528 ConsumeAfterOpt = nullptr;
529}
530
531SubCommand::operator bool() const {
532 return (GlobalParser->getActiveSubCommand() == this);
533}
534
535//===----------------------------------------------------------------------===//
536// Basic, shared command line option processing machinery.
537//
538
539/// LookupOption - Lookup the option specified by the specified option on the
540/// command line. If there is a value specified (after an equal sign) return
541/// that as well. This assumes that leading dashes have already been stripped.
542Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
543 StringRef &Value) {
544 // Reject all dashes.
545 if (Arg.empty())
546 return nullptr;
547 assert(&Sub != &SubCommand::getAll());
548
549 size_t EqualPos = Arg.find(C: '=');
550
551 // If we have an equals sign, remember the value.
552 if (EqualPos == StringRef::npos) {
553 // Look up the option.
554 return Sub.OptionsMap.lookup(Val: Arg);
555 }
556
557 // If the argument before the = is a valid option name and the option allows
558 // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
559 // failure by returning nullptr.
560 auto I = Sub.OptionsMap.find(Val: Arg.substr(Start: 0, N: EqualPos));
561 if (I == Sub.OptionsMap.end())
562 return nullptr;
563
564 auto *O = I->second;
565 if (O->getFormattingFlag() == cl::AlwaysPrefix)
566 return nullptr;
567
568 Value = Arg.substr(Start: EqualPos + 1);
569 Arg = Arg.substr(Start: 0, N: EqualPos);
570 return I->second;
571}
572
573SubCommand *CommandLineParser::LookupSubCommand(StringRef Name,
574 std::string &NearestString) {
575 if (Name.empty())
576 return &SubCommand::getTopLevel();
577 // Find a subcommand with the edit distance == 1.
578 SubCommand *NearestMatch = nullptr;
579 for (auto *S : RegisteredSubCommands) {
580 assert(S != &SubCommand::getAll() &&
581 "SubCommand::getAll() is not expected in RegisteredSubCommands");
582 if (S->getName().empty())
583 continue;
584
585 if (S->getName() == Name)
586 return S;
587
588 if (!NearestMatch && S->getName().edit_distance(Other: Name) < 2)
589 NearestMatch = S;
590 }
591
592 if (NearestMatch)
593 NearestString = NearestMatch->getName();
594
595 return &SubCommand::getTopLevel();
596}
597
598/// LookupNearestOption - Lookup the closest match to the option specified by
599/// the specified option on the command line. If there is a value specified
600/// (after an equal sign) return that as well. This assumes that leading dashes
601/// have already been stripped.
602static Option *LookupNearestOption(StringRef Arg,
603 const OptionsMapTy &OptionsMap,
604 std::string &NearestString) {
605 // Reject all dashes.
606 if (Arg.empty())
607 return nullptr;
608
609 // Split on any equal sign.
610 std::pair<StringRef, StringRef> SplitArg = Arg.split(Separator: '=');
611 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
612 StringRef &RHS = SplitArg.second;
613
614 // Find the closest match.
615 Option *Best = nullptr;
616 unsigned BestDistance = 0;
617 for (const auto &[_, O] : OptionsMap) {
618 // Do not suggest really hidden options (not shown in any help).
619 if (O->getOptionHiddenFlag() == ReallyHidden)
620 continue;
621
622 SmallVector<StringRef, 16> OptionNames;
623 O->getExtraOptionNames(OptionNames);
624 if (O->hasArgStr())
625 OptionNames.push_back(Elt: O->ArgStr);
626
627 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
628 StringRef Flag = PermitValue ? LHS : Arg;
629 for (const auto &Name : OptionNames) {
630 unsigned Distance = StringRef(Name).edit_distance(
631 Other: Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
632 if (!Best || Distance < BestDistance) {
633 Best = O;
634 BestDistance = Distance;
635 if (RHS.empty() || !PermitValue)
636 NearestString = std::string(Name);
637 else
638 NearestString = (Twine(Name) + "=" + RHS).str();
639 }
640 }
641 }
642
643 return Best;
644}
645
646/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
647/// that does special handling of cl::CommaSeparated options.
648static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
649 StringRef ArgName, StringRef Value,
650 bool MultiArg = false) {
651 // Check to see if this option accepts a comma separated list of values. If
652 // it does, we have to split up the value into multiple values.
653 if (Handler->getMiscFlags() & CommaSeparated) {
654 StringRef Val(Value);
655 StringRef::size_type Pos = Val.find(C: ',');
656
657 while (Pos != StringRef::npos) {
658 // Process the portion before the comma.
659 if (Handler->addOccurrence(pos, ArgName, Value: Val.substr(Start: 0, N: Pos), MultiArg))
660 return true;
661 // Erase the portion before the comma, AND the comma.
662 Val = Val.substr(Start: Pos + 1);
663 // Check for another comma.
664 Pos = Val.find(C: ',');
665 }
666
667 Value = Val;
668 }
669
670 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
671}
672
673/// ProvideOption - For Value, this differentiates between an empty value ("")
674/// and a null value (StringRef()). The later is accepted for arguments that
675/// don't allow a value (-foo) the former is rejected (-foo=).
676static inline bool ProvideOption(Option *Handler, StringRef ArgName,
677 StringRef Value, int argc,
678 const char *const *argv, int &i) {
679 // Is this a multi-argument option?
680 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
681
682 // Enforce value requirements
683 switch (Handler->getValueExpectedFlag()) {
684 case ValueRequired:
685 if (!Value.data()) { // No value specified?
686 // If no other argument or the option only supports prefix form, we
687 // cannot look at the next argument.
688 if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
689 return Handler->error(Message: "requires a value!");
690 // Steal the next argument, like for '-o filename'
691 assert(argv && "null check");
692 Value = StringRef(argv[++i]);
693 }
694 break;
695 case ValueDisallowed:
696 if (NumAdditionalVals > 0)
697 return Handler->error(Message: "multi-valued option specified"
698 " with ValueDisallowed modifier!");
699
700 if (Value.data())
701 return Handler->error(Message: "does not allow a value! '" + Twine(Value) +
702 "' specified.");
703 break;
704 case ValueOptional:
705 break;
706 }
707
708 // If this isn't a multi-arg option, just run the handler.
709 if (NumAdditionalVals == 0)
710 return CommaSeparateAndAddOccurrence(Handler, pos: i, ArgName, Value);
711
712 // If it is, run the handle several times.
713 bool MultiArg = false;
714
715 if (Value.data()) {
716 if (CommaSeparateAndAddOccurrence(Handler, pos: i, ArgName, Value, MultiArg))
717 return true;
718 --NumAdditionalVals;
719 MultiArg = true;
720 }
721
722 while (NumAdditionalVals > 0) {
723 if (i + 1 >= argc)
724 return Handler->error(Message: "not enough values!");
725 assert(argv && "null check");
726 Value = StringRef(argv[++i]);
727
728 if (CommaSeparateAndAddOccurrence(Handler, pos: i, ArgName, Value, MultiArg))
729 return true;
730 MultiArg = true;
731 --NumAdditionalVals;
732 }
733 return false;
734}
735
736bool llvm::cl::ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
737 int Dummy = i;
738 return ProvideOption(Handler, ArgName: Handler->ArgStr, Value: Arg, argc: 0, argv: nullptr, i&: Dummy);
739}
740
741// getOptionPred - Check to see if there are any options that satisfy the
742// specified predicate with names that are the prefixes in Name. This is
743// checked by progressively stripping characters off of the name, checking to
744// see if there options that satisfy the predicate. If we find one, return it,
745// otherwise return null.
746//
747static Option *getOptionPred(StringRef Name, size_t &Length,
748 bool (*Pred)(const Option *),
749 const OptionsMapTy &OptionsMap) {
750 auto OMI = OptionsMap.find(Val: Name);
751 if (OMI != OptionsMap.end() && !Pred(OMI->second))
752 OMI = OptionsMap.end();
753
754 // Loop while we haven't found an option and Name still has at least two
755 // characters in it (so that the next iteration will not be the empty
756 // string.
757 while (OMI == OptionsMap.end() && Name.size() > 1) {
758 Name = Name.drop_back();
759 OMI = OptionsMap.find(Val: Name);
760 if (OMI != OptionsMap.end() && !Pred(OMI->second))
761 OMI = OptionsMap.end();
762 }
763
764 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
765 Length = Name.size();
766 return OMI->second; // Found one!
767 }
768 return nullptr; // No option found!
769}
770
771/// HandlePrefixedOrGroupedOption - The specified argument string (which started
772/// with at least one '-') does not fully match an available option. Check to
773/// see if this is a prefix or grouped option. If so, split arg into output an
774/// Arg/Value pair and return the Option to parse it with.
775static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
776 bool &ErrorParsing,
777 const OptionsMapTy &OptionsMap) {
778 if (Arg.size() == 1)
779 return nullptr;
780
781 // Do the lookup!
782 size_t Length = 0;
783 Option *PGOpt = getOptionPred(Name: Arg, Length, Pred: isPrefixedOrGrouping, OptionsMap);
784 if (!PGOpt)
785 return nullptr;
786
787 do {
788 StringRef MaybeValue =
789 (Length < Arg.size()) ? Arg.substr(Start: Length) : StringRef();
790 Arg = Arg.substr(Start: 0, N: Length);
791 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
792
793 // cl::Prefix options do not preserve '=' when used separately.
794 // The behavior for them with grouped options should be the same.
795 if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
796 (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
797 Value = MaybeValue;
798 return PGOpt;
799 }
800
801 if (MaybeValue[0] == '=') {
802 Value = MaybeValue.substr(Start: 1);
803 return PGOpt;
804 }
805
806 // This must be a grouped option.
807 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
808
809 // Grouping options inside a group can't have values.
810 if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
811 ErrorParsing |= PGOpt->error(Message: "may not occur within a group!");
812 return nullptr;
813 }
814
815 // Because the value for the option is not required, we don't need to pass
816 // argc/argv in.
817 int Dummy = 0;
818 ErrorParsing |= ProvideOption(Handler: PGOpt, ArgName: Arg, Value: StringRef(), argc: 0, argv: nullptr, i&: Dummy);
819
820 // Get the next grouping option.
821 Arg = MaybeValue;
822 PGOpt = getOptionPred(Name: Arg, Length, Pred: isGrouping, OptionsMap);
823 } while (PGOpt);
824
825 // We could not find a grouping option in the remainder of Arg.
826 return nullptr;
827}
828
829static bool RequiresValue(const Option *O) {
830 return O->getNumOccurrencesFlag() == cl::Required ||
831 O->getNumOccurrencesFlag() == cl::OneOrMore;
832}
833
834static bool EatsUnboundedNumberOfValues(const Option *O) {
835 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
836 O->getNumOccurrencesFlag() == cl::OneOrMore;
837}
838
839static bool isWhitespace(char C) {
840 return C == ' ' || C == '\t' || C == '\r' || C == '\n';
841}
842
843static bool isWhitespaceOrNull(char C) {
844 return isWhitespace(C) || C == '\0';
845}
846
847static bool isQuote(char C) { return C == '\"' || C == '\''; }
848
849void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
850 SmallVectorImpl<const char *> &NewArgv,
851 bool MarkEOLs) {
852 SmallString<128> Token;
853 bool InToken = false;
854 for (size_t I = 0, E = Src.size(); I != E; ++I) {
855 // Consume runs of whitespace.
856 if (!InToken) {
857 while (I != E && isWhitespace(C: Src[I])) {
858 // Mark the end of lines in response files.
859 if (MarkEOLs && Src[I] == '\n')
860 NewArgv.push_back(Elt: nullptr);
861 ++I;
862 }
863 if (I == E)
864 break;
865 InToken = true;
866 }
867
868 char C = Src[I];
869
870 // Backslash escapes the next character.
871 if (I + 1 < E && C == '\\') {
872 ++I; // Skip the escape.
873 Token.push_back(Elt: Src[I]);
874 continue;
875 }
876
877 // Consume a quoted string.
878 if (isQuote(C)) {
879 ++I;
880 while (I != E && Src[I] != C) {
881 // Backslash escapes the next character.
882 if (Src[I] == '\\' && I + 1 != E)
883 ++I;
884 Token.push_back(Elt: Src[I]);
885 ++I;
886 }
887 if (I == E)
888 break;
889 continue;
890 }
891
892 // End the token if this is whitespace.
893 if (isWhitespace(C)) {
894 NewArgv.push_back(Elt: Saver.save(S: Token.str()).data());
895 // Mark the end of lines in response files.
896 if (MarkEOLs && C == '\n')
897 NewArgv.push_back(Elt: nullptr);
898 Token.clear();
899 InToken = false;
900 continue;
901 }
902
903 // This is a normal character. Append it.
904 Token.push_back(Elt: C);
905 }
906
907 // Append the last token after hitting EOF with no whitespace.
908 if (InToken)
909 NewArgv.push_back(Elt: Saver.save(S: Token.str()).data());
910}
911
912/// Backslashes are interpreted in a rather complicated way in the Windows-style
913/// command line, because backslashes are used both to separate path and to
914/// escape double quote. This method consumes runs of backslashes as well as the
915/// following double quote if it's escaped.
916///
917/// * If an even number of backslashes is followed by a double quote, one
918/// backslash is output for every pair of backslashes, and the last double
919/// quote remains unconsumed. The double quote will later be interpreted as
920/// the start or end of a quoted string in the main loop outside of this
921/// function.
922///
923/// * If an odd number of backslashes is followed by a double quote, one
924/// backslash is output for every pair of backslashes, and a double quote is
925/// output for the last pair of backslash-double quote. The double quote is
926/// consumed in this case.
927///
928/// * Otherwise, backslashes are interpreted literally.
929static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
930 size_t E = Src.size();
931 int BackslashCount = 0;
932 // Skip the backslashes.
933 do {
934 ++I;
935 ++BackslashCount;
936 } while (I != E && Src[I] == '\\');
937
938 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
939 if (FollowedByDoubleQuote) {
940 Token.append(NumInputs: BackslashCount / 2, Elt: '\\');
941 if (BackslashCount % 2 == 0)
942 return I - 1;
943 Token.push_back(Elt: '"');
944 return I;
945 }
946 Token.append(NumInputs: BackslashCount, Elt: '\\');
947 return I - 1;
948}
949
950// Windows treats whitespace, double quotes, and backslashes specially, except
951// when parsing the first token of a full command line, in which case
952// backslashes are not special.
953static bool isWindowsSpecialChar(char C) {
954 return isWhitespaceOrNull(C) || C == '\\' || C == '\"';
955}
956static bool isWindowsSpecialCharInCommandName(char C) {
957 return isWhitespaceOrNull(C) || C == '\"';
958}
959
960// Windows tokenization implementation. The implementation is designed to be
961// inlined and specialized for the two user entry points.
962static inline void tokenizeWindowsCommandLineImpl(
963 StringRef Src, StringSaver &Saver, function_ref<void(StringRef)> AddToken,
964 bool AlwaysCopy, function_ref<void()> MarkEOL, bool InitialCommandName) {
965 SmallString<128> Token;
966
967 // Sometimes, this function will be handling a full command line including an
968 // executable pathname at the start. In that situation, the initial pathname
969 // needs different handling from the following arguments, because when
970 // CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as
971 // escaping the quote character, whereas when libc scans the rest of the
972 // command line, it does.
973 bool CommandName = InitialCommandName;
974
975 // Try to do as much work inside the state machine as possible.
976 enum { INIT, UNQUOTED, QUOTED } State = INIT;
977
978 for (size_t I = 0, E = Src.size(); I < E; ++I) {
979 switch (State) {
980 case INIT: {
981 assert(Token.empty() && "token should be empty in initial state");
982 // Eat whitespace before a token.
983 while (I < E && isWhitespaceOrNull(C: Src[I])) {
984 if (Src[I] == '\n')
985 MarkEOL();
986 ++I;
987 }
988 // Stop if this was trailing whitespace.
989 if (I >= E)
990 break;
991 size_t Start = I;
992 if (CommandName) {
993 while (I < E && !isWindowsSpecialCharInCommandName(C: Src[I]))
994 ++I;
995 } else {
996 while (I < E && !isWindowsSpecialChar(C: Src[I]))
997 ++I;
998 }
999 StringRef NormalChars = Src.slice(Start, End: I);
1000 if (I >= E || isWhitespaceOrNull(C: Src[I])) {
1001 // No special characters: slice out the substring and start the next
1002 // token. Copy the string if the caller asks us to.
1003 AddToken(AlwaysCopy ? Saver.save(S: NormalChars) : NormalChars);
1004 if (I < E && Src[I] == '\n') {
1005 MarkEOL();
1006 CommandName = InitialCommandName;
1007 } else {
1008 CommandName = false;
1009 }
1010 } else if (Src[I] == '\"') {
1011 Token += NormalChars;
1012 State = QUOTED;
1013 } else if (Src[I] == '\\') {
1014 assert(!CommandName && "or else we'd have treated it as a normal char");
1015 Token += NormalChars;
1016 I = parseBackslash(Src, I, Token);
1017 State = UNQUOTED;
1018 } else {
1019 llvm_unreachable("unexpected special character");
1020 }
1021 break;
1022 }
1023
1024 case UNQUOTED:
1025 if (isWhitespaceOrNull(C: Src[I])) {
1026 // Whitespace means the end of the token. If we are in this state, the
1027 // token must have contained a special character, so we must copy the
1028 // token.
1029 AddToken(Saver.save(S: Token.str()));
1030 Token.clear();
1031 if (Src[I] == '\n') {
1032 CommandName = InitialCommandName;
1033 MarkEOL();
1034 } else {
1035 CommandName = false;
1036 }
1037 State = INIT;
1038 } else if (Src[I] == '\"') {
1039 State = QUOTED;
1040 } else if (Src[I] == '\\' && !CommandName) {
1041 I = parseBackslash(Src, I, Token);
1042 } else {
1043 Token.push_back(Elt: Src[I]);
1044 }
1045 break;
1046
1047 case QUOTED:
1048 if (Src[I] == '\"') {
1049 if (I < (E - 1) && Src[I + 1] == '"') {
1050 // Consecutive double-quotes inside a quoted string implies one
1051 // double-quote.
1052 Token.push_back(Elt: '"');
1053 ++I;
1054 } else {
1055 // Otherwise, end the quoted portion and return to the unquoted state.
1056 State = UNQUOTED;
1057 }
1058 } else if (Src[I] == '\\' && !CommandName) {
1059 I = parseBackslash(Src, I, Token);
1060 } else {
1061 Token.push_back(Elt: Src[I]);
1062 }
1063 break;
1064 }
1065 }
1066
1067 if (State != INIT)
1068 AddToken(Saver.save(S: Token.str()));
1069}
1070
1071void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
1072 SmallVectorImpl<const char *> &NewArgv,
1073 bool MarkEOLs) {
1074 auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Elt: Tok.data()); };
1075 auto OnEOL = [&]() {
1076 if (MarkEOLs)
1077 NewArgv.push_back(Elt: nullptr);
1078 };
1079 tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1080 /*AlwaysCopy=*/true, MarkEOL: OnEOL, InitialCommandName: false);
1081}
1082
1083void cl::TokenizeWindowsCommandLineNoCopy(StringRef Src, StringSaver &Saver,
1084 SmallVectorImpl<StringRef> &NewArgv) {
1085 auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Elt: Tok); };
1086 auto OnEOL = []() {};
1087 tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false,
1088 MarkEOL: OnEOL, InitialCommandName: false);
1089}
1090
1091void cl::TokenizeWindowsCommandLineFull(StringRef Src, StringSaver &Saver,
1092 SmallVectorImpl<const char *> &NewArgv,
1093 bool MarkEOLs) {
1094 auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Elt: Tok.data()); };
1095 auto OnEOL = [&]() {
1096 if (MarkEOLs)
1097 NewArgv.push_back(Elt: nullptr);
1098 };
1099 tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1100 /*AlwaysCopy=*/true, MarkEOL: OnEOL, InitialCommandName: true);
1101}
1102
1103void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
1104 SmallVectorImpl<const char *> &NewArgv,
1105 bool MarkEOLs) {
1106 for (const char *Cur = Source.begin(); Cur != Source.end();) {
1107 SmallString<128> Line;
1108 // Check for comment line.
1109 if (isWhitespace(C: *Cur)) {
1110 while (Cur != Source.end() && isWhitespace(C: *Cur))
1111 ++Cur;
1112 continue;
1113 }
1114 if (*Cur == '#') {
1115 while (Cur != Source.end() && *Cur != '\n')
1116 ++Cur;
1117 continue;
1118 }
1119 // Find end of the current line.
1120 const char *Start = Cur;
1121 for (const char *End = Source.end(); Cur != End; ++Cur) {
1122 if (*Cur == '\\') {
1123 if (Cur + 1 != End) {
1124 ++Cur;
1125 if (*Cur == '\n' ||
1126 (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
1127 Line.append(in_start: Start, in_end: Cur - 1);
1128 if (*Cur == '\r')
1129 ++Cur;
1130 Start = Cur + 1;
1131 }
1132 }
1133 } else if (*Cur == '\n')
1134 break;
1135 }
1136 // Tokenize line.
1137 Line.append(in_start: Start, in_end: Cur);
1138 cl::TokenizeGNUCommandLine(Src: Line, Saver, NewArgv, MarkEOLs);
1139 }
1140}
1141
1142// It is called byte order marker but the UTF-8 BOM is actually not affected
1143// by the host system's endianness.
1144static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
1145 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
1146}
1147
1148// Substitute <CFGDIR> with the file's base path.
1149static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver,
1150 const char *&Arg) {
1151 assert(sys::path::is_absolute(BasePath));
1152 constexpr StringLiteral Token("<CFGDIR>");
1153 const StringRef ArgString(Arg);
1154
1155 SmallString<128> ResponseFile;
1156 StringRef::size_type StartPos = 0;
1157 for (StringRef::size_type TokenPos = ArgString.find(Str: Token);
1158 TokenPos != StringRef::npos;
1159 TokenPos = ArgString.find(Str: Token, From: StartPos)) {
1160 // Token may appear more than once per arg (e.g. comma-separated linker
1161 // args). Support by using path-append on any subsequent appearances.
1162 const StringRef LHS = ArgString.substr(Start: StartPos, N: TokenPos - StartPos);
1163 if (ResponseFile.empty())
1164 ResponseFile = LHS;
1165 else
1166 llvm::sys::path::append(path&: ResponseFile, a: LHS);
1167 ResponseFile.append(RHS: BasePath);
1168 StartPos = TokenPos + Token.size();
1169 }
1170
1171 if (!ResponseFile.empty()) {
1172 // Path-append the remaining arg substring if at least one token appeared.
1173 const StringRef Remaining = ArgString.substr(Start: StartPos);
1174 if (!Remaining.empty())
1175 llvm::sys::path::append(path&: ResponseFile, a: Remaining);
1176 Arg = Saver.save(S: ResponseFile.str()).data();
1177 }
1178}
1179
1180// FName must be an absolute path.
1181Error ExpansionContext::expandResponseFile(
1182 StringRef FName, SmallVectorImpl<const char *> &NewArgv) {
1183 assert(sys::path::is_absolute(FName));
1184 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1185 FS->getBufferForFile(Name: FName);
1186 if (!MemBufOrErr) {
1187 std::error_code EC = MemBufOrErr.getError();
1188 return llvm::createStringError(EC, S: Twine("cannot not open file '") + FName +
1189 "': " + EC.message());
1190 }
1191 MemoryBuffer &MemBuf = *MemBufOrErr.get();
1192 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
1193
1194 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
1195 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
1196 std::string UTF8Buf;
1197 if (hasUTF16ByteOrderMark(SrcBytes: BufRef)) {
1198 if (!convertUTF16ToUTF8String(SrcBytes: BufRef, Out&: UTF8Buf))
1199 return llvm::createStringError(EC: std::errc::illegal_byte_sequence,
1200 Fmt: "Could not convert UTF16 to UTF8");
1201 Str = StringRef(UTF8Buf);
1202 }
1203 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
1204 // these bytes before parsing.
1205 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
1206 else if (hasUTF8ByteOrderMark(S: BufRef))
1207 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1208
1209 // Tokenize the contents into NewArgv.
1210 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1211
1212 // Expanded file content may require additional transformations, like using
1213 // absolute paths instead of relative in '@file' constructs or expanding
1214 // macros.
1215 if (!RelativeNames && !InConfigFile)
1216 return Error::success();
1217
1218 StringRef BasePath = llvm::sys::path::parent_path(path: FName);
1219 for (const char *&Arg : NewArgv) {
1220 if (!Arg)
1221 continue;
1222
1223 // Substitute <CFGDIR> with the file's base path.
1224 if (InConfigFile)
1225 ExpandBasePaths(BasePath, Saver, Arg);
1226
1227 // Discover the case, when argument should be transformed into '@file' and
1228 // evaluate 'file' for it.
1229 StringRef ArgStr(Arg);
1230 StringRef FileName;
1231 bool ConfigInclusion = false;
1232 if (ArgStr.consume_front(Prefix: "@")) {
1233 FileName = ArgStr;
1234 if (!llvm::sys::path::is_relative(path: FileName))
1235 continue;
1236 } else if (ArgStr.consume_front(Prefix: "--config=")) {
1237 FileName = ArgStr;
1238 ConfigInclusion = true;
1239 } else {
1240 continue;
1241 }
1242
1243 // Update expansion construct.
1244 SmallString<128> ResponseFile;
1245 ResponseFile.push_back(Elt: '@');
1246 if (ConfigInclusion && !llvm::sys::path::has_parent_path(path: FileName)) {
1247 SmallString<128> FilePath;
1248 if (!findConfigFile(FileName, FilePath))
1249 return createStringError(
1250 EC: std::make_error_code(e: std::errc::no_such_file_or_directory),
1251 S: "cannot not find configuration file: " + FileName);
1252 ResponseFile.append(RHS: FilePath);
1253 } else {
1254 ResponseFile.append(RHS: BasePath);
1255 llvm::sys::path::append(path&: ResponseFile, a: FileName);
1256 }
1257 Arg = Saver.save(S: ResponseFile.str()).data();
1258 }
1259 return Error::success();
1260}
1261
1262/// Expand response files on a command line recursively using the given
1263/// StringSaver and tokenization strategy.
1264Error ExpansionContext::expandResponseFiles(
1265 SmallVectorImpl<const char *> &Argv) {
1266 struct ResponseFileRecord {
1267 std::string File;
1268 size_t End;
1269 };
1270
1271 // To detect recursive response files, we maintain a stack of files and the
1272 // position of the last argument in the file. This position is updated
1273 // dynamically as we recursively expand files.
1274 SmallVector<ResponseFileRecord, 3> FileStack;
1275
1276 // Push a dummy entry that represents the initial command line, removing
1277 // the need to check for an empty list.
1278 FileStack.push_back(Elt: {.File: "", .End: Argv.size()});
1279
1280 // Don't cache Argv.size() because it can change.
1281 for (unsigned I = 0; I != Argv.size();) {
1282 while (I == FileStack.back().End) {
1283 // Passing the end of a file's argument list, so we can remove it from the
1284 // stack.
1285 FileStack.pop_back();
1286 }
1287
1288 const char *Arg = Argv[I];
1289 // Check if it is an EOL marker
1290 if (Arg == nullptr) {
1291 ++I;
1292 continue;
1293 }
1294
1295 if (Arg[0] != '@') {
1296 ++I;
1297 continue;
1298 }
1299
1300 const char *FName = Arg + 1;
1301 // Note that CurrentDir is only used for top-level rsp files, the rest will
1302 // always have an absolute path deduced from the containing file.
1303 SmallString<128> CurrDir;
1304 if (llvm::sys::path::is_relative(path: FName)) {
1305 if (CurrentDir.empty()) {
1306 if (auto CWD = FS->getCurrentWorkingDirectory()) {
1307 CurrDir = *CWD;
1308 } else {
1309 return createStringError(
1310 EC: CWD.getError(), S: Twine("cannot get absolute path for: ") + FName);
1311 }
1312 } else {
1313 CurrDir = CurrentDir;
1314 }
1315 llvm::sys::path::append(path&: CurrDir, a: FName);
1316 FName = CurrDir.c_str();
1317 }
1318
1319 ErrorOr<llvm::vfs::Status> Res = FS->status(Path: FName);
1320 if (!Res || !Res->exists()) {
1321 std::error_code EC = Res.getError();
1322 if (!InConfigFile) {
1323 // If the specified file does not exist, leave '@file' unexpanded, as
1324 // libiberty does.
1325 if (!EC || EC == llvm::errc::no_such_file_or_directory) {
1326 ++I;
1327 continue;
1328 }
1329 }
1330 if (!EC)
1331 EC = llvm::errc::no_such_file_or_directory;
1332 return createStringError(EC, S: Twine("cannot not open file '") + FName +
1333 "': " + EC.message());
1334 }
1335 const llvm::vfs::Status &FileStatus = Res.get();
1336
1337 auto IsEquivalent =
1338 [FileStatus, this](const ResponseFileRecord &RFile) -> ErrorOr<bool> {
1339 ErrorOr<llvm::vfs::Status> RHS = FS->status(Path: RFile.File);
1340 if (!RHS)
1341 return RHS.getError();
1342 return FileStatus.equivalent(Other: *RHS);
1343 };
1344
1345 // Check for recursive response files.
1346 for (const auto &F : drop_begin(RangeOrContainer&: FileStack)) {
1347 if (ErrorOr<bool> R = IsEquivalent(F)) {
1348 if (R.get())
1349 return createStringError(
1350 EC: R.getError(), S: Twine("recursive expansion of: '") + F.File + "'");
1351 } else {
1352 return createStringError(EC: R.getError(),
1353 S: Twine("cannot open file: ") + F.File);
1354 }
1355 }
1356
1357 // Replace this response file argument with the tokenization of its
1358 // contents. Nested response files are expanded in subsequent iterations.
1359 SmallVector<const char *, 0> ExpandedArgv;
1360 if (Error Err = expandResponseFile(FName, NewArgv&: ExpandedArgv))
1361 return Err;
1362
1363 for (ResponseFileRecord &Record : FileStack) {
1364 // Increase the end of all active records by the number of newly expanded
1365 // arguments, minus the response file itself.
1366 Record.End += ExpandedArgv.size() - 1;
1367 }
1368
1369 FileStack.push_back(Elt: {.File: FName, .End: I + ExpandedArgv.size()});
1370 Argv.erase(CI: Argv.begin() + I);
1371 Argv.insert(I: Argv.begin() + I, From: ExpandedArgv.begin(), To: ExpandedArgv.end());
1372 }
1373
1374 // If successful, the top of the file stack will mark the end of the Argv
1375 // stream. A failure here indicates a bug in the stack popping logic above.
1376 // Note that FileStack may have more than one element at this point because we
1377 // don't have a chance to pop the stack when encountering recursive files at
1378 // the end of the stream, so seeing that doesn't indicate a bug.
1379 assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1380 return Error::success();
1381}
1382
1383bool cl::expandResponseFiles(int Argc, const char *const *Argv,
1384 const char *EnvVar, StringSaver &Saver,
1385 SmallVectorImpl<const char *> &NewArgv) {
1386#ifdef _WIN32
1387 auto Tokenize = cl::TokenizeWindowsCommandLine;
1388#else
1389 auto Tokenize = cl::TokenizeGNUCommandLine;
1390#endif
1391 // The environment variable specifies initial options.
1392 if (EnvVar)
1393 if (std::optional<std::string> EnvValue = sys::Process::GetEnv(name: EnvVar))
1394 Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
1395
1396 // Command line options can override the environment variable.
1397 NewArgv.append(in_start: Argv + 1, in_end: Argv + Argc);
1398 ExpansionContext ECtx(Saver.getAllocator(), Tokenize);
1399 if (Error Err = ECtx.expandResponseFiles(Argv&: NewArgv)) {
1400 errs() << toString(E: std::move(Err)) << '\n';
1401 return false;
1402 }
1403 return true;
1404}
1405
1406bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1407 SmallVectorImpl<const char *> &Argv) {
1408 ExpansionContext ECtx(Saver.getAllocator(), Tokenizer);
1409 if (Error Err = ECtx.expandResponseFiles(Argv)) {
1410 errs() << toString(E: std::move(Err)) << '\n';
1411 return false;
1412 }
1413 return true;
1414}
1415
1416ExpansionContext::ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T,
1417 vfs::FileSystem *FS)
1418 : Saver(A), Tokenizer(T), FS(FS ? FS : vfs::getRealFileSystem().get()) {}
1419
1420bool ExpansionContext::findConfigFile(StringRef FileName,
1421 SmallVectorImpl<char> &FilePath) {
1422 SmallString<128> CfgFilePath;
1423 const auto FileExists = [this](SmallString<128> Path) -> bool {
1424 auto Status = FS->status(Path);
1425 return Status &&
1426 Status->getType() == llvm::sys::fs::file_type::regular_file;
1427 };
1428
1429 // If file name contains directory separator, treat it as a path to
1430 // configuration file.
1431 if (llvm::sys::path::has_parent_path(path: FileName)) {
1432 CfgFilePath = FileName;
1433 if (llvm::sys::path::is_relative(path: FileName) && FS->makeAbsolute(Path&: CfgFilePath))
1434 return false;
1435 if (!FileExists(CfgFilePath))
1436 return false;
1437 FilePath.assign(in_start: CfgFilePath.begin(), in_end: CfgFilePath.end());
1438 return true;
1439 }
1440
1441 // Look for the file in search directories.
1442 for (const StringRef &Dir : SearchDirs) {
1443 if (Dir.empty())
1444 continue;
1445 CfgFilePath.assign(RHS: Dir);
1446 llvm::sys::path::append(path&: CfgFilePath, a: FileName);
1447 llvm::sys::path::native(path&: CfgFilePath);
1448 if (FileExists(CfgFilePath)) {
1449 FilePath.assign(in_start: CfgFilePath.begin(), in_end: CfgFilePath.end());
1450 return true;
1451 }
1452 }
1453
1454 return false;
1455}
1456
1457Error ExpansionContext::readConfigFile(StringRef CfgFile,
1458 SmallVectorImpl<const char *> &Argv) {
1459 SmallString<128> AbsPath;
1460 if (sys::path::is_relative(path: CfgFile)) {
1461 AbsPath.assign(RHS: CfgFile);
1462 if (std::error_code EC = FS->makeAbsolute(Path&: AbsPath))
1463 return make_error<StringError>(
1464 Args&: EC, Args: Twine("cannot get absolute path for " + CfgFile));
1465 CfgFile = AbsPath.str();
1466 }
1467 InConfigFile = true;
1468 RelativeNames = true;
1469 if (Error Err = expandResponseFile(FName: CfgFile, NewArgv&: Argv))
1470 return Err;
1471 return expandResponseFiles(Argv);
1472}
1473
1474static void initCommonOptions();
1475bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1476 StringRef Overview, raw_ostream *Errs,
1477 vfs::FileSystem *VFS, const char *EnvVar,
1478 bool LongOptionsUseDoubleDash) {
1479 initCommonOptions();
1480 SmallVector<const char *, 20> NewArgv;
1481 BumpPtrAllocator A;
1482 StringSaver Saver(A);
1483 NewArgv.push_back(Elt: argv[0]);
1484
1485 // Parse options from environment variable.
1486 if (EnvVar) {
1487 if (std::optional<std::string> EnvValue =
1488 sys::Process::GetEnv(name: StringRef(EnvVar)))
1489 TokenizeGNUCommandLine(Src: *EnvValue, Saver, NewArgv);
1490 }
1491
1492 // Append options from command line.
1493 for (int I = 1; I < argc; ++I)
1494 NewArgv.push_back(Elt: argv[I]);
1495 int NewArgc = static_cast<int>(NewArgv.size());
1496
1497 // Parse all options.
1498 return GlobalParser->ParseCommandLineOptions(
1499 argc: NewArgc, argv: &NewArgv[0], Overview, Errs, VFS, LongOptionsUseDoubleDash);
1500}
1501
1502/// Reset all options at least once, so that we can parse different options.
1503void CommandLineParser::ResetAllOptionOccurrences() {
1504 // Reset all option values to look like they have never been seen before.
1505 // Options might be reset twice (they can be reference in both OptionsMap
1506 // and one of the other members), but that does not harm.
1507 for (auto *SC : RegisteredSubCommands) {
1508 // reset() removes default options from OptionsMap (via removeArgument), so
1509 // collect the options first to avoid invalidating the map iterator.
1510 SmallVector<Option *, 0> Opts;
1511 Opts.reserve(N: SC->OptionsMap.size());
1512 for (auto &O : SC->OptionsMap)
1513 Opts.push_back(Elt: O.second);
1514 for (Option *O : Opts)
1515 O->reset();
1516 for (Option *O : SC->PositionalOpts)
1517 O->reset();
1518 for (Option *O : SC->SinkOpts)
1519 O->reset();
1520 if (SC->ConsumeAfterOpt)
1521 SC->ConsumeAfterOpt->reset();
1522 }
1523}
1524
1525bool CommandLineParser::ParseCommandLineOptions(
1526 int argc, const char *const *argv, StringRef Overview, raw_ostream *Errs,
1527 vfs::FileSystem *VFS, bool LongOptionsUseDoubleDash) {
1528 assert(hasOptions() && "No options specified!");
1529
1530 ProgramOverview = Overview;
1531 bool IgnoreErrors = Errs;
1532 if (!Errs)
1533 Errs = &errs();
1534 if (!VFS)
1535 VFS = vfs::getRealFileSystem().get();
1536 bool ErrorParsing = false;
1537
1538 // Expand response files.
1539 SmallVector<const char *, 20> newArgv(argv, argv + argc);
1540 BumpPtrAllocator A;
1541#ifdef _WIN32
1542 auto Tokenize = cl::TokenizeWindowsCommandLine;
1543#else
1544 auto Tokenize = cl::TokenizeGNUCommandLine;
1545#endif
1546 ExpansionContext ECtx(A, Tokenize, VFS);
1547 if (Error Err = ECtx.expandResponseFiles(Argv&: newArgv)) {
1548 *Errs << toString(E: std::move(Err)) << '\n';
1549 return false;
1550 }
1551 argv = &newArgv[0];
1552 argc = static_cast<int>(newArgv.size());
1553
1554 // Copy the program name into ProgName, making sure not to overflow it.
1555 ProgramName = std::string(sys::path::filename(path: StringRef(argv[0])));
1556
1557 // Check out the positional arguments to collect information about them.
1558 unsigned NumPositionalRequired = 0;
1559
1560 // Determine whether or not there are an unlimited number of positionals
1561 bool HasUnlimitedPositionals = false;
1562
1563 int FirstArg = 1;
1564 SubCommand *ChosenSubCommand = &SubCommand::getTopLevel();
1565 std::string NearestSubCommandString;
1566 bool MaybeNamedSubCommand =
1567 argc >= 2 && argv[FirstArg][0] != '-' && hasNamedSubCommands();
1568 if (MaybeNamedSubCommand) {
1569 // If the first argument specifies a valid subcommand, start processing
1570 // options from the second argument.
1571 ChosenSubCommand =
1572 LookupSubCommand(Name: StringRef(argv[FirstArg]), NearestString&: NearestSubCommandString);
1573 if (ChosenSubCommand != &SubCommand::getTopLevel())
1574 FirstArg = 2;
1575 }
1576 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1577
1578 assert(ChosenSubCommand);
1579 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1580 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1581 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1582 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1583
1584 for (auto *O: DefaultOptions) {
1585 addOption(O, ProcessDefaultOption: true);
1586 }
1587
1588 if (ConsumeAfterOpt) {
1589 assert(PositionalOpts.size() > 0 &&
1590 "Cannot specify cl::ConsumeAfter without a positional argument!");
1591 }
1592 if (!PositionalOpts.empty()) {
1593
1594 // Calculate how many positional values are _required_.
1595 bool UnboundedFound = false;
1596 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1597 Option *Opt = PositionalOpts[i];
1598 if (RequiresValue(O: Opt))
1599 ++NumPositionalRequired;
1600 else if (ConsumeAfterOpt) {
1601 // ConsumeAfter cannot be combined with "optional" positional options
1602 // unless there is only one positional argument...
1603 if (PositionalOpts.size() > 1) {
1604 if (!IgnoreErrors)
1605 Opt->error(Message: "error - this positional option will never be matched, "
1606 "because it does not Require a value, and a "
1607 "cl::ConsumeAfter option is active!");
1608 ErrorParsing = true;
1609 }
1610 } else if (UnboundedFound && !Opt->hasArgStr()) {
1611 // This option does not "require" a value... Make sure this option is
1612 // not specified after an option that eats all extra arguments, or this
1613 // one will never get any!
1614 //
1615 if (!IgnoreErrors)
1616 Opt->error(Message: "error - option can never match, because "
1617 "another positional argument will match an "
1618 "unbounded number of values, and this option"
1619 " does not require a value!");
1620 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1621 << "' is all messed up!\n";
1622 *Errs << PositionalOpts.size();
1623 ErrorParsing = true;
1624 }
1625 UnboundedFound |= EatsUnboundedNumberOfValues(O: Opt);
1626 }
1627 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1628 }
1629
1630 // PositionalVals - A vector of "positional" arguments we accumulate into
1631 // the process at the end.
1632 //
1633 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
1634
1635 // If the program has named positional arguments, and the name has been run
1636 // across, keep track of which positional argument was named. Otherwise put
1637 // the positional args into the PositionalVals list...
1638 Option *ActivePositionalArg = nullptr;
1639
1640 // Loop over all of the arguments... processing them.
1641 bool DashDashFound = false; // Have we read '--'?
1642 for (int i = FirstArg; i < argc; ++i) {
1643 Option *Handler = nullptr;
1644 std::string NearestHandlerString;
1645 StringRef Value;
1646 StringRef ArgName = "";
1647 bool HaveDoubleDash = false;
1648
1649 // Check to see if this is a positional argument. This argument is
1650 // considered to be positional if it doesn't start with '-', if it is "-"
1651 // itself, or if we have seen "--" already.
1652 //
1653 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1654 // Positional argument!
1655 if (ActivePositionalArg) {
1656 ProvidePositionalOption(Handler: ActivePositionalArg, Arg: StringRef(argv[i]), i);
1657 continue; // We are done!
1658 }
1659
1660 if (!PositionalOpts.empty()) {
1661 PositionalVals.push_back(Elt: std::make_pair(x: StringRef(argv[i]), y&: i));
1662
1663 // All of the positional arguments have been fulfulled, give the rest to
1664 // the consume after option... if it's specified...
1665 //
1666 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1667 for (++i; i < argc; ++i)
1668 PositionalVals.push_back(Elt: std::make_pair(x: StringRef(argv[i]), y&: i));
1669 break; // Handle outside of the argument processing loop...
1670 }
1671
1672 // Delay processing positional arguments until the end...
1673 continue;
1674 }
1675 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1676 !DashDashFound) {
1677 DashDashFound = true; // This is the mythical "--"?
1678 continue; // Don't try to process it as an argument itself.
1679 } else if (ActivePositionalArg &&
1680 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1681 // If there is a positional argument eating options, check to see if this
1682 // option is another positional argument. If so, treat it as an argument,
1683 // otherwise feed it to the eating positional.
1684 ArgName = StringRef(argv[i] + 1);
1685 // Eat second dash.
1686 if (ArgName.consume_front(Prefix: "-"))
1687 HaveDoubleDash = true;
1688
1689 Handler = LookupLongOption(Sub&: *ChosenSubCommand, Arg&: ArgName, Value,
1690 LongOptionsUseDoubleDash, HaveDoubleDash);
1691 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1692 ProvidePositionalOption(Handler: ActivePositionalArg, Arg: StringRef(argv[i]), i);
1693 continue; // We are done!
1694 }
1695 } else { // We start with a '-', must be an argument.
1696 ArgName = StringRef(argv[i] + 1);
1697 // Eat second dash.
1698 if (ArgName.consume_front(Prefix: "-"))
1699 HaveDoubleDash = true;
1700
1701 Handler = LookupLongOption(Sub&: *ChosenSubCommand, Arg&: ArgName, Value,
1702 LongOptionsUseDoubleDash, HaveDoubleDash);
1703
1704 // If Handler is not found in a specialized subcommand, look up handler
1705 // in the top-level subcommand.
1706 // cl::opt without cl::sub belongs to top-level subcommand.
1707 if (!Handler && ChosenSubCommand != &SubCommand::getTopLevel())
1708 Handler = LookupLongOption(Sub&: SubCommand::getTopLevel(), Arg&: ArgName, Value,
1709 LongOptionsUseDoubleDash, HaveDoubleDash);
1710
1711 // Check to see if this "option" is really a prefixed or grouped argument.
1712 if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1713 Handler = HandlePrefixedOrGroupedOption(Arg&: ArgName, Value, ErrorParsing,
1714 OptionsMap);
1715
1716 // Otherwise, look for the closest available option to report to the user
1717 // in the upcoming error.
1718 if (!Handler && SinkOpts.empty())
1719 LookupNearestOption(Arg: ArgName, OptionsMap, NearestString&: NearestHandlerString);
1720 }
1721
1722 if (!Handler) {
1723 if (!SinkOpts.empty()) {
1724 for (Option *SinkOpt : SinkOpts)
1725 SinkOpt->addOccurrence(pos: i, ArgName: "", Value: StringRef(argv[i]));
1726 continue;
1727 }
1728
1729 auto ReportUnknownArgument = [&](bool IsArg,
1730 StringRef NearestArgumentName) {
1731 *Errs << ProgramName << ": Unknown "
1732 << (IsArg ? "command line argument" : "subcommand") << " '"
1733 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
1734
1735 if (NearestArgumentName.empty())
1736 return;
1737
1738 *Errs << ProgramName << ": Did you mean '";
1739 if (IsArg)
1740 *Errs << PrintArg(NearestArgumentName, 0);
1741 else
1742 *Errs << NearestArgumentName;
1743 *Errs << "'?\n";
1744 };
1745
1746 if (i > 1 || !MaybeNamedSubCommand)
1747 ReportUnknownArgument(/*IsArg=*/true, NearestHandlerString);
1748 else
1749 ReportUnknownArgument(/*IsArg=*/false, NearestSubCommandString);
1750
1751 ErrorParsing = true;
1752 continue;
1753 }
1754
1755 // If this is a named positional argument, just remember that it is the
1756 // active one...
1757 if (Handler->getFormattingFlag() == cl::Positional) {
1758 if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1759 Handler->error(Message: "This argument does not take a value.\n"
1760 "\tInstead, it consumes any positional arguments until "
1761 "the next recognized option.", Errs&: *Errs);
1762 ErrorParsing = true;
1763 }
1764 ActivePositionalArg = Handler;
1765 }
1766 else
1767 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1768 }
1769
1770 // Check and handle positional arguments now...
1771 if (NumPositionalRequired > PositionalVals.size()) {
1772 *Errs << ProgramName
1773 << ": Not enough positional command line arguments specified!\n"
1774 << "Must specify at least " << NumPositionalRequired
1775 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1776 << ": See: " << argv[0] << " --help\n";
1777
1778 ErrorParsing = true;
1779 } else if (!HasUnlimitedPositionals &&
1780 PositionalVals.size() > PositionalOpts.size()) {
1781 *Errs << ProgramName << ": Too many positional arguments specified!\n"
1782 << "Can specify at most " << PositionalOpts.size()
1783 << " positional arguments: See: " << argv[0] << " --help\n";
1784 ErrorParsing = true;
1785
1786 } else if (!ConsumeAfterOpt) {
1787 // Positional args have already been handled if ConsumeAfter is specified.
1788 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1789 for (Option *Opt : PositionalOpts) {
1790 if (RequiresValue(O: Opt)) {
1791 ProvidePositionalOption(Handler: Opt, Arg: PositionalVals[ValNo].first,
1792 i: PositionalVals[ValNo].second);
1793 ValNo++;
1794 --NumPositionalRequired; // We fulfilled our duty...
1795 }
1796
1797 // If we _can_ give this option more arguments, do so now, as long as we
1798 // do not give it values that others need. 'Done' controls whether the
1799 // option even _WANTS_ any more.
1800 //
1801 bool Done = Opt->getNumOccurrencesFlag() == cl::Required;
1802 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1803 switch (Opt->getNumOccurrencesFlag()) {
1804 case cl::Optional:
1805 Done = true; // Optional arguments want _at most_ one value
1806 [[fallthrough]];
1807 case cl::ZeroOrMore: // Zero or more will take all they can get...
1808 case cl::OneOrMore: // One or more will take all they can get...
1809 ProvidePositionalOption(Handler: Opt, Arg: PositionalVals[ValNo].first,
1810 i: PositionalVals[ValNo].second);
1811 ValNo++;
1812 break;
1813 default:
1814 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1815 "positional argument processing!");
1816 }
1817 }
1818 }
1819 } else {
1820 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1821 unsigned ValNo = 0;
1822 for (Option *Opt : PositionalOpts)
1823 if (RequiresValue(O: Opt)) {
1824 ErrorParsing |= ProvidePositionalOption(
1825 Handler: Opt, Arg: PositionalVals[ValNo].first, i: PositionalVals[ValNo].second);
1826 ValNo++;
1827 }
1828
1829 // Handle the case where there is just one positional option, and it's
1830 // optional. In this case, we want to give JUST THE FIRST option to the
1831 // positional option and keep the rest for the consume after. The above
1832 // loop would have assigned no values to positional options in this case.
1833 //
1834 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1835 ErrorParsing |= ProvidePositionalOption(Handler: PositionalOpts[0],
1836 Arg: PositionalVals[ValNo].first,
1837 i: PositionalVals[ValNo].second);
1838 ValNo++;
1839 }
1840
1841 // Handle over all of the rest of the arguments to the
1842 // cl::ConsumeAfter command line option...
1843 for (; ValNo != PositionalVals.size(); ++ValNo)
1844 ErrorParsing |=
1845 ProvidePositionalOption(Handler: ConsumeAfterOpt, Arg: PositionalVals[ValNo].first,
1846 i: PositionalVals[ValNo].second);
1847 }
1848
1849 // Loop over args and make sure all required args are specified!
1850 for (const auto &Opt : OptionsMap) {
1851 switch (Opt.second->getNumOccurrencesFlag()) {
1852 case Required:
1853 case OneOrMore:
1854 if (Opt.second->getNumOccurrences() == 0) {
1855 Opt.second->error(Message: "must be specified at least once!");
1856 ErrorParsing = true;
1857 }
1858 [[fallthrough]];
1859 default:
1860 break;
1861 }
1862 }
1863
1864 // Now that we know if -debug is specified, we can use it.
1865 // Note that if ReadResponseFiles == true, this must be done before the
1866 // memory allocated for the expanded command line is free()d below.
1867 LLVM_DEBUG(dbgs() << "Args: ";
1868 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1869 dbgs() << '\n';);
1870
1871 // Free all of the memory allocated to the map. Command line options may only
1872 // be processed once!
1873 MoreHelp.clear();
1874
1875 // If we had an error processing our arguments, don't let the program execute
1876 if (ErrorParsing) {
1877 if (!IgnoreErrors)
1878 exit(status: 1);
1879 return false;
1880 }
1881 return true;
1882}
1883
1884//===----------------------------------------------------------------------===//
1885// Option Base class implementation
1886//
1887
1888bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1889 if (!ArgName.data())
1890 ArgName = ArgStr;
1891 if (ArgName.empty())
1892 Errs << HelpStr; // Be nice for positional arguments
1893 else
1894 Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
1895
1896 Errs << " option: " << Message << "\n";
1897 return true;
1898}
1899
1900bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1901 bool MultiArg) {
1902 if (!MultiArg)
1903 NumOccurrences++; // Increment the number of times we have been seen
1904
1905 return handleOccurrence(pos, ArgName, Arg: Value);
1906}
1907
1908// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1909// has been specified yet.
1910//
1911static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1912 if (O.ValueStr.empty())
1913 return DefaultMsg;
1914 return O.ValueStr;
1915}
1916
1917//===----------------------------------------------------------------------===//
1918// cl::alias class implementation
1919//
1920
1921// Return the width of the option tag for printing...
1922size_t alias::getOptionWidth() const {
1923 return argPlusPrefixesSize(ArgName: ArgStr);
1924}
1925
1926void Option::printHelpStr(StringRef HelpStr, size_t Indent,
1927 size_t FirstLineIndentedBy) {
1928 assert(Indent >= FirstLineIndentedBy);
1929 std::pair<StringRef, StringRef> Split = HelpStr.split(Separator: '\n');
1930 outs().indent(NumSpaces: Indent - FirstLineIndentedBy)
1931 << ArgHelpPrefix << Split.first << "\n";
1932 while (!Split.second.empty()) {
1933 Split = Split.second.split(Separator: '\n');
1934 outs().indent(NumSpaces: Indent) << Split.first << "\n";
1935 }
1936}
1937
1938void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent,
1939 size_t FirstLineIndentedBy) {
1940 const StringRef ValHelpPrefix = " ";
1941 assert(BaseIndent >= FirstLineIndentedBy);
1942 std::pair<StringRef, StringRef> Split = HelpStr.split(Separator: '\n');
1943 outs().indent(NumSpaces: BaseIndent - FirstLineIndentedBy)
1944 << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
1945 while (!Split.second.empty()) {
1946 Split = Split.second.split(Separator: '\n');
1947 outs().indent(NumSpaces: BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
1948 }
1949}
1950
1951// Print out the option for the alias.
1952void alias::printOptionInfo(size_t GlobalWidth) const {
1953 outs() << PrintArg(ArgStr);
1954 printHelpStr(HelpStr, Indent: GlobalWidth, FirstLineIndentedBy: argPlusPrefixesSize(ArgName: ArgStr));
1955}
1956
1957//===----------------------------------------------------------------------===//
1958// Parser Implementation code...
1959//
1960
1961// basic_parser implementation
1962//
1963
1964// Return the width of the option tag for printing...
1965size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1966 size_t Len = argPlusPrefixesSize(ArgName: O.ArgStr);
1967 auto ValName = getValueName();
1968 if (!ValName.empty()) {
1969 size_t FormattingLen = 3;
1970 if (O.getMiscFlags() & PositionalEatsArgs)
1971 FormattingLen = 6;
1972 Len += getValueStr(O, DefaultMsg: ValName).size() + FormattingLen;
1973 }
1974
1975 return Len;
1976}
1977
1978// printOptionInfo - Print out information about this option. The
1979// to-be-maintained width is specified.
1980//
1981void basic_parser_impl::printOptionInfo(const Option &O,
1982 size_t GlobalWidth) const {
1983 outs() << PrintArg(O.ArgStr);
1984
1985 auto ValName = getValueName();
1986 if (!ValName.empty()) {
1987 if (O.getMiscFlags() & PositionalEatsArgs) {
1988 outs() << " <" << getValueStr(O, DefaultMsg: ValName) << ">...";
1989 } else if (O.getValueExpectedFlag() == ValueOptional)
1990 outs() << "[=<" << getValueStr(O, DefaultMsg: ValName) << ">]";
1991 else {
1992 outs() << (O.ArgStr.size() == 1 ? " <" : "=<") << getValueStr(O, DefaultMsg: ValName)
1993 << '>';
1994 }
1995 }
1996
1997 Option::printHelpStr(HelpStr: O.HelpStr, Indent: GlobalWidth, FirstLineIndentedBy: getOptionWidth(O));
1998}
1999
2000void basic_parser_impl::printOptionName(const Option &O,
2001 size_t GlobalWidth) const {
2002 outs() << PrintArg(O.ArgStr);
2003 outs().indent(NumSpaces: GlobalWidth - O.ArgStr.size());
2004}
2005
2006// parser<bool> implementation
2007//
2008bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
2009 bool &Value) {
2010 return parseBool<bool, true, false>(O, ArgName, Arg, Value);
2011}
2012
2013// parser<boolOrDefault> implementation
2014//
2015bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
2016 boolOrDefault &Value) {
2017 return parseBool<boolOrDefault, boolOrDefault::BOU_TRUE,
2018 boolOrDefault::BOU_FALSE>(O, ArgName, Arg, Value);
2019}
2020
2021// parser<FixedOrScalableQuantity> implementation
2022//
2023template <typename FixedOrScalableQuantityT>
2024static bool parseFixedOrScalableQuantity(Option &O, StringRef Arg,
2025 StringRef ValueKind,
2026 FixedOrScalableQuantityT &Value) {
2027 using ScalarTy = typename FixedOrScalableQuantityT::ScalarTy;
2028
2029 Arg = Arg.trim();
2030
2031 ScalarTy MinValue;
2032 if (!Arg.getAsInteger(0, MinValue)) {
2033 Value = FixedOrScalableQuantityT::getFixed(MinValue);
2034 return false;
2035 }
2036
2037 StringRef Remainder = Arg;
2038 if (!Remainder.consume_front(Prefix: "vscale"))
2039 return O.error(Message: "'" + Arg + "' value invalid for " + ValueKind +
2040 " argument!");
2041
2042 Remainder = Remainder.ltrim();
2043 if (!Remainder.consume_front(Prefix: 'x'))
2044 return O.error(Message: "'" + Arg + "' value invalid for " + ValueKind +
2045 " argument!");
2046
2047 Remainder = Remainder.ltrim();
2048 if (Remainder.getAsInteger(0, MinValue))
2049 return O.error(Message: "'" + Arg + "' value invalid for " + ValueKind +
2050 " argument!");
2051
2052 Value = FixedOrScalableQuantityT::getScalable(MinValue);
2053 return false;
2054}
2055
2056// parser<int> implementation
2057//
2058bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
2059 int &Value) {
2060 if (Arg.getAsInteger(Radix: 0, Result&: Value))
2061 return O.error(Message: "'" + Arg + "' value invalid for integer argument!");
2062 return false;
2063}
2064
2065// parser<long> implementation
2066//
2067bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2068 long &Value) {
2069 if (Arg.getAsInteger(Radix: 0, Result&: Value))
2070 return O.error(Message: "'" + Arg + "' value invalid for long argument!");
2071 return false;
2072}
2073
2074// parser<long long> implementation
2075//
2076bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2077 long long &Value) {
2078 if (Arg.getAsInteger(Radix: 0, Result&: Value))
2079 return O.error(Message: "'" + Arg + "' value invalid for llong argument!");
2080 return false;
2081}
2082
2083// parser<unsigned> implementation
2084//
2085bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
2086 unsigned &Value) {
2087
2088 if (Arg.getAsInteger(Radix: 0, Result&: Value))
2089 return O.error(Message: "'" + Arg + "' value invalid for uint argument!");
2090 return false;
2091}
2092
2093// parser<unsigned long> implementation
2094//
2095bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2096 unsigned long &Value) {
2097
2098 if (Arg.getAsInteger(Radix: 0, Result&: Value))
2099 return O.error(Message: "'" + Arg + "' value invalid for ulong argument!");
2100 return false;
2101}
2102
2103// parser<unsigned long long> implementation
2104//
2105bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
2106 StringRef Arg,
2107 unsigned long long &Value) {
2108
2109 if (Arg.getAsInteger(Radix: 0, Result&: Value))
2110 return O.error(Message: "'" + Arg + "' value invalid for ullong argument!");
2111 return false;
2112}
2113
2114// parser<ElementCount> implementation
2115//
2116bool parser<ElementCount>::parse(Option &O, StringRef ArgName, StringRef Arg,
2117 ElementCount &Value) {
2118 return parseFixedOrScalableQuantity(O, Arg, ValueKind: getValueName(), Value);
2119}
2120
2121// parser<double>/parser<float> implementation
2122//
2123static bool parseDouble(Option &O, StringRef Arg, double &Value) {
2124 if (to_float(T: Arg, Num&: Value))
2125 return false;
2126 return O.error(Message: "'" + Arg + "' value invalid for floating point argument!");
2127}
2128
2129bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
2130 double &Val) {
2131 return parseDouble(O, Arg, Value&: Val);
2132}
2133
2134bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
2135 float &Val) {
2136 double dVal;
2137 if (parseDouble(O, Arg, Value&: dVal))
2138 return true;
2139 Val = (float)dVal;
2140 return false;
2141}
2142
2143// generic_parser_base implementation
2144//
2145
2146// findOption - Return the option number corresponding to the specified
2147// argument string. If the option is not found, getNumOptions() is returned.
2148//
2149unsigned generic_parser_base::findOption(StringRef Name) {
2150 unsigned e = getNumOptions();
2151
2152 for (unsigned i = 0; i != e; ++i) {
2153 if (getOption(N: i) == Name)
2154 return i;
2155 }
2156 return e;
2157}
2158
2159static StringRef EqValue = "=<value>";
2160static StringRef EmptyOption = "<empty>";
2161static StringRef OptionPrefix = " =";
2162static size_t getOptionPrefixesSize() {
2163 return OptionPrefix.size() + ArgHelpPrefix.size();
2164}
2165
2166static bool shouldPrintOption(StringRef Name, StringRef Description,
2167 const Option &O) {
2168 return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
2169 !Description.empty();
2170}
2171
2172// Return the width of the option tag for printing...
2173size_t generic_parser_base::getOptionWidth(const Option &O) const {
2174 if (O.hasArgStr()) {
2175 size_t Size =
2176 argPlusPrefixesSize(ArgName: O.ArgStr) + EqValue.size();
2177 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2178 StringRef Name = getOption(N: i);
2179 if (!shouldPrintOption(Name, Description: getDescription(N: i), O))
2180 continue;
2181 size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
2182 Size = std::max(a: Size, b: NameSize + getOptionPrefixesSize());
2183 }
2184 return Size;
2185 } else {
2186 size_t BaseSize = 0;
2187 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
2188 BaseSize = std::max(a: BaseSize, b: getOption(N: i).size() + 8);
2189 return BaseSize;
2190 }
2191}
2192
2193// printOptionInfo - Print out information about this option. The
2194// to-be-maintained width is specified.
2195//
2196void generic_parser_base::printOptionInfo(const Option &O,
2197 size_t GlobalWidth) const {
2198 if (O.hasArgStr()) {
2199 // When the value is optional, first print a line just describing the
2200 // option without values.
2201 if (O.getValueExpectedFlag() == ValueOptional) {
2202 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2203 if (getOption(N: i).empty()) {
2204 outs() << PrintArg(O.ArgStr);
2205 Option::printHelpStr(HelpStr: O.HelpStr, Indent: GlobalWidth,
2206 FirstLineIndentedBy: argPlusPrefixesSize(ArgName: O.ArgStr));
2207 break;
2208 }
2209 }
2210 }
2211
2212 outs() << PrintArg(O.ArgStr) << EqValue;
2213 Option::printHelpStr(HelpStr: O.HelpStr, Indent: GlobalWidth,
2214 FirstLineIndentedBy: EqValue.size() +
2215 argPlusPrefixesSize(ArgName: O.ArgStr));
2216 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2217 StringRef OptionName = getOption(N: i);
2218 StringRef Description = getDescription(N: i);
2219 if (!shouldPrintOption(Name: OptionName, Description, O))
2220 continue;
2221 size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
2222 outs() << OptionPrefix << OptionName;
2223 if (OptionName.empty()) {
2224 outs() << EmptyOption;
2225 assert(FirstLineIndent >= EmptyOption.size());
2226 FirstLineIndent += EmptyOption.size();
2227 }
2228 if (!Description.empty())
2229 Option::printEnumValHelpStr(HelpStr: Description, BaseIndent: GlobalWidth, FirstLineIndentedBy: FirstLineIndent);
2230 else
2231 outs() << '\n';
2232 }
2233 } else {
2234 if (!O.HelpStr.empty())
2235 outs() << " " << O.HelpStr << '\n';
2236 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2237 StringRef Option = getOption(N: i);
2238 outs() << " " << PrintArg(Option);
2239 Option::printHelpStr(HelpStr: getDescription(N: i), Indent: GlobalWidth, FirstLineIndentedBy: Option.size() + 8);
2240 }
2241 }
2242}
2243
2244static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
2245
2246// printGenericOptionDiff - Print the value of this option and it's default.
2247//
2248// "Generic" options have each value mapped to a name.
2249void generic_parser_base::printGenericOptionDiff(
2250 const Option &O, const GenericOptionValue &Value,
2251 const GenericOptionValue &Default, size_t GlobalWidth) const {
2252 outs() << " " << PrintArg(O.ArgStr);
2253 outs().indent(NumSpaces: GlobalWidth - O.ArgStr.size());
2254
2255 unsigned NumOpts = getNumOptions();
2256 for (unsigned i = 0; i != NumOpts; ++i) {
2257 if (!Value.compare(V: getOptionValue(N: i)))
2258 continue;
2259
2260 outs() << "= " << getOption(N: i);
2261 size_t L = getOption(N: i).size();
2262 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
2263 outs().indent(NumSpaces) << " (default: ";
2264 for (unsigned j = 0; j != NumOpts; ++j) {
2265 if (!Default.compare(V: getOptionValue(N: j)))
2266 continue;
2267 outs() << getOption(N: j);
2268 break;
2269 }
2270 outs() << ")\n";
2271 return;
2272 }
2273 outs() << "= *unknown option value*\n";
2274}
2275
2276// printOptionDiff - Specializations for printing basic value types.
2277//
2278namespace llvm {
2279namespace cl {
2280static raw_ostream &operator<<(raw_ostream &OS, boolOrDefault V) {
2281 return OS << static_cast<int>(V);
2282}
2283} // namespace cl
2284} // namespace llvm
2285
2286#define PRINT_OPT_DIFF(T) \
2287 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
2288 size_t GlobalWidth) const { \
2289 printOptionName(O, GlobalWidth); \
2290 std::string Str; \
2291 { \
2292 raw_string_ostream SS(Str); \
2293 SS << V; \
2294 } \
2295 outs() << "= " << Str; \
2296 size_t NumSpaces = \
2297 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2298 outs().indent(NumSpaces) << " (default: "; \
2299 if (D.hasValue()) \
2300 outs() << D.getValue(); \
2301 else \
2302 outs() << "*no default*"; \
2303 outs() << ")\n"; \
2304 }
2305
2306PRINT_OPT_DIFF(bool)
2307PRINT_OPT_DIFF(boolOrDefault)
2308PRINT_OPT_DIFF(int)
2309PRINT_OPT_DIFF(long)
2310PRINT_OPT_DIFF(long long)
2311PRINT_OPT_DIFF(unsigned)
2312PRINT_OPT_DIFF(unsigned long)
2313PRINT_OPT_DIFF(unsigned long long)
2314PRINT_OPT_DIFF(double)
2315PRINT_OPT_DIFF(float)
2316PRINT_OPT_DIFF(char)
2317PRINT_OPT_DIFF(ElementCount)
2318
2319void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
2320 const OptionValue<std::string> &D,
2321 size_t GlobalWidth) const {
2322 printOptionName(O, GlobalWidth);
2323 outs() << "= " << V;
2324 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
2325 outs().indent(NumSpaces) << " (default: ";
2326 if (D.hasValue())
2327 outs() << D.getValue();
2328 else
2329 outs() << "*no default*";
2330 outs() << ")\n";
2331}
2332
2333void parser<std::optional<std::string>>::printOptionDiff(
2334 const Option &O, std::optional<StringRef> V,
2335 const OptionValue<std::optional<std::string>> &D,
2336 size_t GlobalWidth) const {
2337 printOptionName(O, GlobalWidth);
2338 outs() << "= " << V;
2339 size_t VSize = V.has_value() ? V.value().size() : 0;
2340 size_t NumSpaces = MaxOptWidth > VSize ? MaxOptWidth - VSize : 0;
2341 outs().indent(NumSpaces) << " (default: ";
2342 if (D.hasValue() && D.getValue().has_value())
2343 outs() << D.getValue();
2344 else
2345 outs() << "*no value*";
2346 outs() << ")\n";
2347}
2348
2349// Print a placeholder for options that don't yet support printOptionDiff().
2350void basic_parser_impl::printOptionNoValue(const Option &O,
2351 size_t GlobalWidth) const {
2352 printOptionName(O, GlobalWidth);
2353 outs() << "= *cannot print option value*\n";
2354}
2355
2356//===----------------------------------------------------------------------===//
2357// -help and -help-hidden option implementation
2358//
2359
2360static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2361 const std::pair<const char *, Option *> *RHS) {
2362 return strcmp(s1: LHS->first, s2: RHS->first);
2363}
2364
2365static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2366 const std::pair<const char *, SubCommand *> *RHS) {
2367 return strcmp(s1: LHS->first, s2: RHS->first);
2368}
2369
2370// Copy Options into a vector so we can sort them as we like.
2371static void sortOpts(OptionsMapTy &OptMap,
2372 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2373 bool ShowHidden) {
2374 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2375
2376 for (auto I = OptMap.begin(), E = OptMap.end(); I != E; ++I) {
2377 // Ignore really-hidden options.
2378 if (I->second->getOptionHiddenFlag() == ReallyHidden)
2379 continue;
2380
2381 // Unless showhidden is set, ignore hidden flags.
2382 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2383 continue;
2384
2385 // If we've already seen this option, don't add it to the list again.
2386 if (!OptionSet.insert(Ptr: I->second).second)
2387 continue;
2388
2389 Opts.push_back(
2390 Elt: std::pair<const char *, Option *>(I->first.data(), I->second));
2391 }
2392
2393 // Sort the options list alphabetically.
2394 array_pod_sort(Start: Opts.begin(), End: Opts.end(), Compare: OptNameCompare);
2395}
2396
2397static void
2398sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
2399 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2400 for (auto *S : SubMap) {
2401 if (S->getName().empty())
2402 continue;
2403 Subs.push_back(Elt: std::make_pair(x: S->getName().data(), y&: S));
2404 }
2405 array_pod_sort(Start: Subs.begin(), End: Subs.end(), Compare: SubNameCompare);
2406}
2407
2408namespace {
2409
2410class HelpPrinter {
2411protected:
2412 const bool ShowHidden;
2413 using StrOptionPairVector =
2414 SmallVector<std::pair<const char *, Option *>, 128>;
2415 using StrSubCommandPairVector =
2416 SmallVector<std::pair<const char *, SubCommand *>, 128>;
2417 // Print the options. Opts is assumed to be alphabetically sorted.
2418 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2419 for (const auto &Opt : Opts)
2420 Opt.second->printOptionInfo(GlobalWidth: MaxArgLen);
2421 }
2422
2423 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2424 for (const auto &S : Subs) {
2425 outs() << " " << S.first;
2426 if (!S.second->getDescription().empty()) {
2427 outs().indent(NumSpaces: MaxSubLen - strlen(s: S.first));
2428 outs() << " - " << S.second->getDescription();
2429 }
2430 outs() << "\n";
2431 }
2432 }
2433
2434public:
2435 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2436 virtual ~HelpPrinter() = default;
2437
2438 // Invoke the printer.
2439 void operator=(bool Value) {
2440 if (!Value)
2441 return;
2442 printHelp();
2443
2444 // Halt the program since help information was printed
2445 exit(status: 0);
2446 }
2447
2448 void printHelp() {
2449 SubCommand *Sub = GlobalParser->getActiveSubCommand();
2450 auto &OptionsMap = Sub->OptionsMap;
2451 auto &PositionalOpts = Sub->PositionalOpts;
2452 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2453
2454 StrOptionPairVector Opts;
2455 sortOpts(OptMap&: OptionsMap, Opts, ShowHidden);
2456
2457 StrSubCommandPairVector Subs;
2458 sortSubCommands(SubMap: GlobalParser->RegisteredSubCommands, Subs);
2459
2460 if (!GlobalParser->ProgramOverview.empty())
2461 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2462
2463 if (Sub == &SubCommand::getTopLevel()) {
2464 outs() << "USAGE: " << GlobalParser->ProgramName;
2465 if (!Subs.empty())
2466 outs() << " [subcommand]";
2467 outs() << " [options]";
2468 } else {
2469 if (!Sub->getDescription().empty()) {
2470 outs() << "SUBCOMMAND '" << Sub->getName()
2471 << "': " << Sub->getDescription() << "\n\n";
2472 }
2473 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2474 << " [options]";
2475 }
2476
2477 for (auto *Opt : PositionalOpts) {
2478 if (Opt->hasArgStr())
2479 outs() << " --" << Opt->ArgStr;
2480 outs() << " " << Opt->HelpStr;
2481 }
2482
2483 // Print the consume after option info if it exists...
2484 if (ConsumeAfterOpt)
2485 outs() << " " << ConsumeAfterOpt->HelpStr;
2486
2487 if (Sub == &SubCommand::getTopLevel() && !Subs.empty()) {
2488 // Compute the maximum subcommand length...
2489 size_t MaxSubLen = 0;
2490 for (const auto &Sub : Subs)
2491 MaxSubLen = std::max(a: MaxSubLen, b: strlen(s: Sub.first));
2492
2493 outs() << "\n\n";
2494 outs() << "SUBCOMMANDS:\n\n";
2495 printSubCommands(Subs, MaxSubLen);
2496 outs() << "\n";
2497 outs() << " Type \"" << GlobalParser->ProgramName
2498 << " <subcommand> --help\" to get more help on a specific "
2499 "subcommand";
2500 }
2501
2502 outs() << "\n\n";
2503
2504 // Compute the maximum argument length...
2505 size_t MaxArgLen = 0;
2506 for (const auto &Opt : Opts)
2507 MaxArgLen = std::max(a: MaxArgLen, b: Opt.second->getOptionWidth());
2508
2509 outs() << "OPTIONS:\n";
2510 printOptions(Opts, MaxArgLen);
2511
2512 // Print any extra help the user has declared.
2513 for (const auto &I : GlobalParser->MoreHelp)
2514 outs() << I;
2515 GlobalParser->MoreHelp.clear();
2516 }
2517};
2518
2519class CategorizedHelpPrinter : public HelpPrinter {
2520public:
2521 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2522
2523 // Helper function for printOptions().
2524 // It shall return a negative value if A's name should be lexicographically
2525 // ordered before B's name. It returns a value greater than zero if B's name
2526 // should be ordered before A's name, and it returns 0 otherwise.
2527 static int OptionCategoryCompare(OptionCategory *const *A,
2528 OptionCategory *const *B) {
2529 return (*A)->getName().compare(RHS: (*B)->getName());
2530 }
2531
2532 // Make sure we inherit our base class's operator=()
2533 using HelpPrinter::operator=;
2534
2535protected:
2536 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2537 std::vector<OptionCategory *> SortedCategories;
2538 DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2539
2540 // Collect registered option categories into vector in preparation for
2541 // sorting.
2542 llvm::append_range(C&: SortedCategories,
2543 R&: GlobalParser->RegisteredOptionCategories);
2544
2545 // Sort the different option categories alphabetically.
2546 assert(SortedCategories.size() > 0 && "No option categories registered!");
2547 array_pod_sort(Start: SortedCategories.begin(), End: SortedCategories.end(),
2548 Compare: OptionCategoryCompare);
2549
2550 // Walk through pre-sorted options and assign into categories.
2551 // Because the options are already alphabetically sorted the
2552 // options within categories will also be alphabetically sorted.
2553 for (const auto &I : Opts) {
2554 Option *Opt = I.second;
2555 for (OptionCategory *Cat : Opt->Categories) {
2556 assert(llvm::is_contained(SortedCategories, Cat) &&
2557 "Option has an unregistered category");
2558 CategorizedOptions[Cat].push_back(x: Opt);
2559 }
2560 }
2561
2562 // Now do printing.
2563 for (OptionCategory *Category : SortedCategories) {
2564 // Hide empty categories for --help, but show for --help-hidden.
2565 const auto &CategoryOptions = CategorizedOptions[Category];
2566 if (CategoryOptions.empty())
2567 continue;
2568
2569 // Print category information.
2570 outs() << "\n";
2571 outs() << Category->getName() << ":\n";
2572
2573 // Check if description is set.
2574 if (!Category->getDescription().empty())
2575 outs() << Category->getDescription() << "\n\n";
2576 else
2577 outs() << "\n";
2578
2579 // Loop over the options in the category and print.
2580 for (const Option *Opt : CategoryOptions)
2581 Opt->printOptionInfo(GlobalWidth: MaxArgLen);
2582 }
2583 }
2584};
2585
2586// This wraps the Uncategorizing and Categorizing printers and decides
2587// at run time which should be invoked.
2588class HelpPrinterWrapper {
2589private:
2590 HelpPrinter &UncategorizedPrinter;
2591 CategorizedHelpPrinter &CategorizedPrinter;
2592
2593public:
2594 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2595 CategorizedHelpPrinter &CategorizedPrinter)
2596 : UncategorizedPrinter(UncategorizedPrinter),
2597 CategorizedPrinter(CategorizedPrinter) {}
2598
2599 // Invoke the printer.
2600 void operator=(bool Value);
2601};
2602
2603} // End anonymous namespace
2604
2605#if defined(__GNUC__)
2606// GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2607// enabled.
2608# if defined(__OPTIMIZE__)
2609# define LLVM_IS_DEBUG_BUILD 0
2610# else
2611# define LLVM_IS_DEBUG_BUILD 1
2612# endif
2613#elif defined(_MSC_VER)
2614// MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2615// Use _DEBUG instead. This macro actually corresponds to the choice between
2616// debug and release CRTs, but it is a reasonable proxy.
2617# if defined(_DEBUG)
2618# define LLVM_IS_DEBUG_BUILD 1
2619# else
2620# define LLVM_IS_DEBUG_BUILD 0
2621# endif
2622#else
2623// Otherwise, for an unknown compiler, assume this is an optimized build.
2624# define LLVM_IS_DEBUG_BUILD 0
2625#endif
2626
2627namespace {
2628class VersionPrinter {
2629public:
2630 void print(const std::vector<VersionPrinterTy> &ExtraPrinters) {
2631 raw_ostream &OS = outs();
2632#ifdef PACKAGE_VENDOR
2633 OS << PACKAGE_VENDOR << " ";
2634#else
2635 OS << "LLVM (http://llvm.org/):\n ";
2636#endif
2637 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION << "\n ";
2638#if LLVM_IS_DEBUG_BUILD
2639 OS << "DEBUG build";
2640#else
2641 OS << "Optimized build";
2642#endif
2643#ifndef NDEBUG
2644 OS << " with assertions";
2645#endif
2646 OS << ".\n";
2647
2648 // Iterate over any registered extra printers and call them to add further
2649 // information.
2650 if (!ExtraPrinters.empty()) {
2651 for (const auto &I : ExtraPrinters)
2652 I(outs());
2653 }
2654 }
2655 void operator=(bool OptionWasSpecified);
2656};
2657
2658struct CommandLineCommonOptions {
2659 // Declare the four HelpPrinter instances that are used to print out help, or
2660 // help-hidden as an uncategorized list or in categories.
2661 HelpPrinter UncategorizedNormalPrinter{false};
2662 HelpPrinter UncategorizedHiddenPrinter{true};
2663 CategorizedHelpPrinter CategorizedNormalPrinter{false};
2664 CategorizedHelpPrinter CategorizedHiddenPrinter{true};
2665 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2666 // a categorizing help printer
2667 HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2668 CategorizedNormalPrinter};
2669 HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2670 CategorizedHiddenPrinter};
2671 // Define a category for generic options that all tools should have.
2672 cl::OptionCategory GenericCategory{"Generic Options"};
2673
2674 // Define uncategorized help printers.
2675 // --help-list is hidden by default because if Option categories are being
2676 // used then --help behaves the same as --help-list.
2677 cl::opt<HelpPrinter, true, parser<bool>> HLOp{
2678 "help-list",
2679 cl::desc(
2680 "Display list of available options (--help-list-hidden for more)"),
2681 cl::location(L&: UncategorizedNormalPrinter),
2682 cl::Hidden,
2683 cl::ValueDisallowed,
2684 cl::cat(GenericCategory),
2685 cl::sub(SubCommand::getAll())};
2686
2687 cl::opt<HelpPrinter, true, parser<bool>> HLHOp{
2688 "help-list-hidden",
2689 cl::desc("Display list of all available options"),
2690 cl::location(L&: UncategorizedHiddenPrinter),
2691 cl::Hidden,
2692 cl::ValueDisallowed,
2693 cl::cat(GenericCategory),
2694 cl::sub(SubCommand::getAll())};
2695
2696 // Define uncategorized/categorized help printers. These printers change their
2697 // behaviour at runtime depending on whether one or more Option categories
2698 // have been declared.
2699 cl::opt<HelpPrinterWrapper, true, parser<bool>> HOp{
2700 "help",
2701 cl::desc("Display available options (--help-hidden for more)"),
2702 cl::location(L&: WrappedNormalPrinter),
2703 cl::ValueDisallowed,
2704 cl::cat(GenericCategory),
2705 cl::sub(SubCommand::getAll())};
2706
2707 cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2708 cl::DefaultOption};
2709
2710 cl::opt<HelpPrinterWrapper, true, parser<bool>> HHOp{
2711 "help-hidden",
2712 cl::desc("Display all available options"),
2713 cl::location(L&: WrappedHiddenPrinter),
2714 cl::Hidden,
2715 cl::ValueDisallowed,
2716 cl::cat(GenericCategory),
2717 cl::sub(SubCommand::getAll())};
2718
2719 cl::opt<bool> PrintOptions{
2720 "print-options",
2721 cl::desc("Print non-default options after command line parsing"),
2722 cl::Hidden,
2723 cl::init(Val: false),
2724 cl::cat(GenericCategory),
2725 cl::sub(SubCommand::getAll())};
2726
2727 cl::opt<bool> PrintAllOptions{
2728 "print-all-options",
2729 cl::desc("Print all option values after command line parsing"),
2730 cl::Hidden,
2731 cl::init(Val: false),
2732 cl::cat(GenericCategory),
2733 cl::sub(SubCommand::getAll())};
2734
2735 VersionPrinterTy OverrideVersionPrinter = nullptr;
2736
2737 std::vector<VersionPrinterTy> ExtraVersionPrinters;
2738
2739 // Define the --version option that prints out the LLVM version for the tool
2740 VersionPrinter VersionPrinterInstance;
2741
2742 cl::opt<VersionPrinter, true, parser<bool>> VersOp{
2743 "version", cl::desc("Display the version of this program"),
2744 cl::location(L&: VersionPrinterInstance), cl::ValueDisallowed,
2745 cl::cat(GenericCategory)};
2746};
2747} // End anonymous namespace
2748
2749// Lazy-initialized global instance of options controlling the command-line
2750// parser and general handling.
2751static ManagedStatic<CommandLineCommonOptions> CommonOptions;
2752
2753static void initCommonOptions() {
2754 *CommonOptions;
2755 initDebugCounterOptions();
2756 initGraphWriterOptions();
2757 initSignalsOptions();
2758 initStatisticOptions();
2759 initTimerOptions();
2760 initWithColorOptions();
2761 initDebugOptions();
2762 initRandomSeedOptions();
2763}
2764
2765OptionCategory &cl::getGeneralCategory() {
2766 // Initialise the general option category.
2767 static OptionCategory GeneralCategory{"General options"};
2768 return GeneralCategory;
2769}
2770
2771void VersionPrinter::operator=(bool OptionWasSpecified) {
2772 if (!OptionWasSpecified)
2773 return;
2774
2775 if (CommonOptions->OverrideVersionPrinter != nullptr) {
2776 CommonOptions->OverrideVersionPrinter(outs());
2777 exit(status: 0);
2778 }
2779 print(ExtraPrinters: CommonOptions->ExtraVersionPrinters);
2780
2781 exit(status: 0);
2782}
2783
2784void HelpPrinterWrapper::operator=(bool Value) {
2785 if (!Value)
2786 return;
2787
2788 // Decide which printer to invoke. If more than one option category is
2789 // registered then it is useful to show the categorized help instead of
2790 // uncategorized help.
2791 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2792 // unhide --help-list option so user can have uncategorized output if they
2793 // want it.
2794 CommonOptions->HLOp.setHiddenFlag(NotHidden);
2795
2796 CategorizedPrinter = true; // Invoke categorized printer
2797 } else {
2798 UncategorizedPrinter = true; // Invoke uncategorized printer
2799 }
2800}
2801
2802// Print the value of each option.
2803void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2804
2805void CommandLineParser::printOptionValues() {
2806 if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
2807 return;
2808
2809 SmallVector<std::pair<const char *, Option *>, 128> Opts;
2810 sortOpts(OptMap&: ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2811
2812 // Compute the maximum argument length...
2813 size_t MaxArgLen = 0;
2814 for (const auto &Opt : Opts)
2815 MaxArgLen = std::max(a: MaxArgLen, b: Opt.second->getOptionWidth());
2816
2817 for (const auto &Opt : Opts)
2818 Opt.second->printOptionValue(GlobalWidth: MaxArgLen, Force: CommonOptions->PrintAllOptions);
2819}
2820
2821// Utility function for printing the help message.
2822void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2823 if (!Hidden && !Categorized)
2824 CommonOptions->UncategorizedNormalPrinter.printHelp();
2825 else if (!Hidden && Categorized)
2826 CommonOptions->CategorizedNormalPrinter.printHelp();
2827 else if (Hidden && !Categorized)
2828 CommonOptions->UncategorizedHiddenPrinter.printHelp();
2829 else
2830 CommonOptions->CategorizedHiddenPrinter.printHelp();
2831}
2832
2833ArrayRef<StringRef> cl::getCompilerBuildConfig() {
2834 static const StringRef Config[] = {
2835 // Placeholder to ensure the array always has elements, since it's an
2836 // error to have a zero-sized array. Slice this off before returning.
2837 "",
2838 // Actual compiler build config feature list:
2839#if LLVM_IS_DEBUG_BUILD
2840 "+unoptimized",
2841#endif
2842#ifndef NDEBUG
2843 "+assertions",
2844#endif
2845#ifdef EXPENSIVE_CHECKS
2846 "+expensive-checks",
2847#endif
2848#if __has_feature(address_sanitizer)
2849 "+asan",
2850#endif
2851#if __has_feature(dataflow_sanitizer)
2852 "+dfsan",
2853#endif
2854#if __has_feature(hwaddress_sanitizer)
2855 "+hwasan",
2856#endif
2857#if __has_feature(memory_sanitizer)
2858 "+msan",
2859#endif
2860#if __has_feature(thread_sanitizer)
2861 "+tsan",
2862#endif
2863#if __has_feature(undefined_behavior_sanitizer)
2864 "+ubsan",
2865#endif
2866#ifdef LLVM_INTEGRATED_CRT_ALLOC
2867 "+alloc:" LLVM_INTEGRATED_CRT_ALLOC,
2868#endif
2869 };
2870 return ArrayRef(Config).drop_front(N: 1);
2871}
2872
2873// Utility function for printing the build config.
2874void cl::printBuildConfig(raw_ostream &OS) {
2875#if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG
2876 OS << "Build config: ";
2877 llvm::interleaveComma(c: cl::getCompilerBuildConfig(), os&: OS);
2878 OS << '\n';
2879#endif
2880}
2881
2882/// Utility function for printing version number.
2883void cl::PrintVersionMessage() {
2884 CommonOptions->VersionPrinterInstance.print(ExtraPrinters: CommonOptions->ExtraVersionPrinters);
2885}
2886
2887void cl::SetVersionPrinter(VersionPrinterTy func) {
2888 CommonOptions->OverrideVersionPrinter = func;
2889}
2890
2891void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2892 CommonOptions->ExtraVersionPrinters.push_back(x: func);
2893}
2894
2895OptionsMapTy &cl::getRegisteredOptions(SubCommand &Sub) {
2896 initCommonOptions();
2897 auto &Subs = GlobalParser->RegisteredSubCommands;
2898 (void)Subs;
2899 assert(Subs.contains(&Sub));
2900 return Sub.OptionsMap;
2901}
2902
2903iterator_range<SmallPtrSet<SubCommand *, 4>::iterator>
2904cl::getRegisteredSubcommands() {
2905 return GlobalParser->getRegisteredSubcommands();
2906}
2907
2908void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2909 initCommonOptions();
2910 for (auto &I : Sub.OptionsMap) {
2911 bool Unrelated = true;
2912 for (auto &Cat : I.second->Categories) {
2913 if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
2914 Unrelated = false;
2915 }
2916 if (Unrelated)
2917 I.second->setHiddenFlag(cl::ReallyHidden);
2918 }
2919}
2920
2921void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
2922 SubCommand &Sub) {
2923 initCommonOptions();
2924 for (auto &I : Sub.OptionsMap) {
2925 bool Unrelated = true;
2926 for (auto &Cat : I.second->Categories) {
2927 if (is_contained(Range&: Categories, Element: Cat) ||
2928 Cat == &CommonOptions->GenericCategory)
2929 Unrelated = false;
2930 }
2931 if (Unrelated)
2932 I.second->setHiddenFlag(cl::ReallyHidden);
2933 }
2934}
2935
2936void cl::ResetCommandLineParser() { GlobalParser->reset(); }
2937void cl::ResetAllOptionOccurrences() {
2938 GlobalParser->ResetAllOptionOccurrences();
2939}
2940
2941void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2942 const char *Overview) {
2943 llvm::cl::ParseCommandLineOptions(argc, argv, Overview: StringRef(Overview),
2944 Errs: &llvm::nulls());
2945}
2946