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