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