LLVM 24.0.0git
CommandLine.cpp
Go to the documentation of this file.
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
19
20#include "DebugOptions.h"
21
22#include "llvm-c/Support.h"
23#include "llvm/ADT/ArrayRef.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"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/Error.h"
41#include "llvm/Support/Path.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 {
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.
80#endif
81
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() {}
98void parser<int>::anchor() {}
105void parser<float>::anchor() {}
107void parser<std::optional<std::string>>::anchor() {}
108void parser<char>::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 = "-";
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) {
137 for (size_t I = 0; I < Pad; ++I) {
138 Prefix.push_back(' ');
139 }
140 Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
141 return Prefix;
142}
143
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(Arg.ArgName, 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.
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.
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(&SubCommand::getTopLevel()); }
192
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,
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(std::make_pair(Name, &Opt)).second) {
223 errs() << ProgramName << ": CommandLine Error: Option '" << Name
224 << "' registered more than once!\n";
225 report_fatal_error("inconsistency in registered CommandLine options");
226 }
227 }
228
229 void addLiteralOption(Option &Opt, StringRef Name) {
230 forEachSubCommand(
231 Opt, [&](SubCommand &SC) { addLiteralOption(Opt, &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(std::make_pair(O->ArgStr, O)).second ||
241 (RegisteredSubCommands.contains(SC) &&
242 (LibraryIndex.contains(O->ArgStr) ||
243 ToolIndex.contains(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(O);
253 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
254 if (SC->ConsumeAfterOpt) {
255 O->error("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("inconsistency in registered CommandLine options");
267 }
268
269 void addOption(Option *O) {
270 forEachSubCommand(*O, [&](SubCommand &SC) { addOption(O, &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(O->ArgStr);
278
279 SubCommand &Sub = *SC;
280 for (auto Name : OptionNames) {
281 auto I = Sub.OptionsMap.find(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(Opt);
293 break;
294 }
295 }
296 else if (O == Sub.ConsumeAfterOpt)
297 Sub.ConsumeAfterOpt = nullptr;
298 }
299
300 void removeOption(Option *O) {
301 forEachSubCommand(*O, [&](SubCommand &SC) { removeOption(O, &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(*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(std::make_pair(NewName, O)).second) {
329 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
330 << "' registered more than once!\n";
331 report_fatal_error("inconsistency in registered CommandLine options");
332 }
333 Sub.OptionsMap.erase(O->ArgStr);
334 }
335
336 void updateArgStr(Option *O, StringRef NewName) {
337 forEachSubCommand(*O,
338 [&](SubCommand &SC) { updateArgStr(O, NewName, &SC); });
339 }
340
341 void printOptionValues();
342
343 void
344 indexLibraries(ArrayRef<const LibraryOptions *> Libs,
347 bool HadErrors = false;
348 for (const LibraryOptions *L : Libs) {
349 L->forEachOption([&](StringRef Spelling, StringRef, StringRef) {
350 StringRef Name = Spelling.rtrim('=');
351 auto [It, Inserted] = Index.try_emplace(Name, L);
352 if (Inserted ? !Other.contains(Name) &&
353 none_of(RegisteredSubCommands,
354 [&](SubCommand *SC) {
355 return SC->OptionsMap.contains(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("inconsistency in registered CommandLine options");
366 }
367
368 void indexLibraryOptions() {
369 indexLibraries(ArrayRef(Libraries).drop_front(NumIndexedLibraries),
370 LibraryIndex, ToolIndex);
371 NumIndexedLibraries = Libraries.size();
372 }
373
374 void setToolOptions(ArrayRef<const LibraryOptions *> Libs) {
375 if (ArrayRef(ToolOptions) == Libs)
376 return;
377 ToolOptions.assign(Libs);
378 ToolIndex.clear();
379 indexLibraries(ToolOptions, ToolIndex, 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(Name))
386 return L;
387 return ToolIndex.lookup(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(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(sub);
408
409 // For all options that have been registered for all subcommands, add the
410 // option to this subcommand now.
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, sub);
417 else
418 addLiteralOption(*O, sub, E.first);
419 }
420 }
421
422 void unregisterSubCommand(SubCommand *sub) {
423 RegisteredSubCommands.erase(sub);
424 }
425
428 return make_range(RegisteredSubCommands.begin(),
429 RegisteredSubCommands.end());
430 }
431
432 void reset() {
433 ActiveSubCommand = nullptr;
434 ProgramName.clear();
435 ProgramOverview = StringRef();
436
437 MoreHelp.clear();
438 RegisteredOptionCategories.clear();
439
441 RegisteredSubCommands.clear();
442 Libraries.clear();
443 LibraryIndex.clear();
444 NumIndexedLibraries = 0;
445 ToolOptions.clear();
446 ToolIndex.clear();
447
450 registerSubCommand(&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("'" + Arg +
486 "' is invalid value for boolean argument! Try 0 or 1");
487}
488
490 globalParser().addLiteralOption(O, Name);
491}
492
494 globalParser().MoreHelp.push_back(Help);
495}
496
498 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
499 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0),
500 FullyInitialized(false), Position(0) {
501 Categories.push_back(&getGeneralCategory());
502}
503
505 globalParser().addOption(this);
506 FullyInitialized = true;
507}
508
509void Option::removeArgument() { globalParser().removeOption(this); }
510
512 if (FullyInitialized)
513 globalParser().updateArgStr(this, S);
514 assert(!S.starts_with("-") && "Option can't start with '-");
515 ArgStr = S;
516}
517
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(Categories, &C))
526 Categories.push_back(&C);
527}
528
530 NumOccurrences = 0;
531 setDefault();
532}
533
534void OptionCategory::registerCategory() {
535 globalParser().registerCategory(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.
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.
550 static ManagedStatic<SubCommand> AllSubCommands;
551 return *AllSubCommands;
552}
553
555 globalParser().registerSubCommand(this);
556}
557
559 globalParser().unregisterSubCommand(this);
560}
561
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;
586
587 size_t EqualPos = Arg.find('=');
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(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(Arg.substr(0, 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(EqualPos + 1);
607 Arg = Arg.substr(0, 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(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.
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('=');
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(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 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(',');
693
694 while (Pos != StringRef::npos) {
695 // Process the portion before the comma.
696 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos)))
697 return true;
698 // Erase the portion before the comma, AND the comma.
699 Val = Val.substr(Pos + 1);
700 // Check for another comma.
701 Pos = Val.find(',');
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("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("does not allow a value! '" + Twine(Value) +
732 "' specified.");
733 break;
734 case ValueOptional:
735 break;
736 }
737
738 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
739}
740
742 int Dummy = i;
743 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
744}
745
746// Find the cl::Prefix or cl::AlwaysPrefix option whose name is the longest
747// prefix of Name.
749 const OptionsMapTy &OptionsMap) {
750 for (; !Name.empty(); Name = Name.drop_back()) {
751 Option *O = OptionsMap.lookup(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.
766 const OptionsMapTy &OptionsMap) {
767 if (Arg.size() == 1)
768 return nullptr;
769
770 size_t Length = 0;
771 Option *POpt = findPrefixOption(Arg, Length, OptionsMap);
772 if (!POpt)
773 return nullptr;
774
775 StringRef MaybeValue =
776 (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
777 Arg = Arg.substr(0, Length);
778
779 // cl::Prefix options do not preserve '=' when used separately.
780 if (POpt->getFormattingFlag() == cl::Prefix && MaybeValue.starts_with("="))
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
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(Src[I])) {
815 // Mark the end of lines in response files.
816 if (MarkEOLs && Src[I] == '\n')
817 NewArgv.push_back(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(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(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(Saver.save(Token.str()).data());
852 // Mark the end of lines in response files.
853 if (MarkEOLs && C == '\n')
854 NewArgv.push_back(nullptr);
855 Token.clear();
856 InToken = false;
857 continue;
858 }
859
860 // This is a normal character. Append it.
861 Token.push_back(C);
862 }
863
864 // Append the last token after hitting EOF with no whitespace.
865 if (InToken)
866 NewArgv.push_back(Saver.save(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(BackslashCount / 2, '\\');
898 if (BackslashCount % 2 == 0)
899 return I - 1;
900 Token.push_back('"');
901 return I;
902 }
903 Token.append(BackslashCount, '\\');
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}
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.
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(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(Src[I]))
951 ++I;
952 } else {
953 while (I < E && !isWindowsSpecialChar(Src[I]))
954 ++I;
955 }
956 StringRef NormalChars = Src.slice(Start, I);
957 if (I >= E || isWhitespaceOrNull(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(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(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(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(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('"');
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(Src[I]);
1019 }
1020 break;
1021 }
1022 }
1023
1024 if (State != INIT)
1025 AddToken(Saver.save(Token.str()));
1026}
1027
1030 bool MarkEOLs) {
1031 auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1032 auto OnEOL = [&]() {
1033 if (MarkEOLs)
1034 NewArgv.push_back(nullptr);
1035 };
1036 tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1037 /*AlwaysCopy=*/true, OnEOL, false);
1038}
1039
1041 SmallVectorImpl<StringRef> &NewArgv) {
1042 auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok); };
1043 auto OnEOL = []() {};
1044 tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false,
1045 OnEOL, false);
1046}
1047
1050 bool MarkEOLs) {
1051 auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1052 auto OnEOL = [&]() {
1053 if (MarkEOLs)
1054 NewArgv.push_back(nullptr);
1055 };
1056 tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1057 /*AlwaysCopy=*/true, OnEOL, true);
1058}
1059
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(*Cur)) {
1067 while (Cur != Source.end() && isWhitespace(*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(Start, 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(Start, LineEnd ? LineEnd : Cur);
1119 cl::TokenizeGNUCommandLine(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.
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(Token);
1139 TokenPos != StringRef::npos;
1140 TokenPos = ArgString.find(Token, 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(StartPos, TokenPos - StartPos);
1144 if (ResponseFile.empty())
1145 ResponseFile = LHS;
1146 else
1147 llvm::sys::path::append(ResponseFile, LHS);
1148 ResponseFile.append(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(StartPos);
1155 if (!Remaining.empty())
1156 llvm::sys::path::append(ResponseFile, Remaining);
1157 Arg = Saver.save(ResponseFile.str()).data();
1158 }
1159}
1160
1161// FName must be an absolute path.
1162Error ExpansionContext::expandResponseFile(
1163 StringRef FName, SmallVectorImpl<const char *> &NewArgv) {
1165 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1166 FS->getBufferForFile(FName);
1167 if (!MemBufOrErr) {
1168 std::error_code EC = MemBufOrErr.getError();
1169 return llvm::createStringError(EC, 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(BufRef)) {
1179 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
1180 return llvm::createStringError(std::errc::illegal_byte_sequence,
1181 "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(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(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("@")) {
1214 FileName = ArgStr;
1215 if (!llvm::sys::path::is_relative(FileName))
1216 continue;
1217 } else if (ArgStr.consume_front("--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('@');
1227 if (ConfigInclusion && !llvm::sys::path::has_parent_path(FileName)) {
1228 SmallString<128> FilePath;
1229 if (!findConfigFile(FileName, FilePath))
1230 return createStringError(
1231 std::make_error_code(std::errc::no_such_file_or_directory),
1232 "cannot not find configuration file: " + FileName);
1233 ResponseFile.append(FilePath);
1234 } else {
1235 ResponseFile.append(BasePath);
1236 llvm::sys::path::append(ResponseFile, FileName);
1237 }
1238 Arg = Saver.save(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.
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.
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({"", 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(FName)) {
1286 if (CurrentDir.empty()) {
1287 if (auto CWD = FS->getCurrentWorkingDirectory()) {
1288 CurrDir = *CWD;
1289 } else {
1290 return createStringError(
1291 CWD.getError(), Twine("cannot get absolute path for: ") + FName);
1292 }
1293 } else {
1294 CurrDir = CurrentDir;
1295 }
1296 llvm::sys::path::append(CurrDir, FName);
1297 FName = CurrDir.c_str();
1298 }
1299
1300 ErrorOr<llvm::vfs::Status> Res = FS->status(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)
1313 return createStringError(EC, 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(RFile.File);
1321 if (!RHS)
1322 return RHS.getError();
1323 return FileStatus.equivalent(*RHS);
1324 };
1325
1326 // Check for recursive response files.
1327 for (const auto &F : drop_begin(FileStack)) {
1328 if (ErrorOr<bool> R = IsEquivalent(F)) {
1329 if (R.get())
1330 return createStringError(
1331 R.getError(), Twine("recursive expansion of: '") + F.File + "'");
1332 } else {
1333 return createStringError(R.getError(),
1334 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, 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({FName, I + ExpandedArgv.size()});
1351 Argv.erase(Argv.begin() + I);
1352 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), 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,
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(EnvVar))
1375 Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
1376
1377 // Command line options can override the environment variable.
1378 NewArgv.append(Argv + 1, Argv + Argc);
1379 ExpansionContext ECtx(Saver.getAllocator(), Tokenize);
1380 if (Error Err = ECtx.expandResponseFiles(NewArgv)) {
1381 errs() << toString(std::move(Err)) << '\n';
1382 return false;
1383 }
1384 return true;
1385}
1386
1389 ExpansionContext ECtx(Saver.getAllocator(), Tokenizer);
1390 if (Error Err = ECtx.expandResponseFiles(Argv)) {
1391 errs() << toString(std::move(Err)) << '\n';
1392 return false;
1393 }
1394 return true;
1395}
1396
1398 vfs::FileSystem *FS)
1399 : Saver(A), Tokenizer(T), FS(FS ? FS : vfs::getRealFileSystem().get()) {}
1400
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 &&
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(FileName)) {
1413 CfgFilePath = FileName;
1414 if (llvm::sys::path::is_relative(FileName) && FS->makeAbsolute(CfgFilePath))
1415 return false;
1416 if (!FileExists(CfgFilePath))
1417 return false;
1418 FilePath.assign(CfgFilePath.begin(), 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(Dir);
1427 llvm::sys::path::append(CfgFilePath, FileName);
1428 llvm::sys::path::native(CfgFilePath);
1429 if (FileExists(CfgFilePath)) {
1430 FilePath.assign(CfgFilePath.begin(), CfgFilePath.end());
1431 return true;
1432 }
1433 }
1434
1435 return false;
1436}
1437
1440 SmallString<128> AbsPath;
1441 if (sys::path::is_relative(CfgFile)) {
1442 AbsPath.assign(CfgFile);
1443 if (std::error_code EC = FS->makeAbsolute(AbsPath))
1445 EC, Twine("cannot get absolute path for " + CfgFile));
1446 CfgFile = AbsPath.str();
1447 }
1448 InConfigFile = true;
1449 RelativeNames = true;
1450 if (Error Err = expandResponseFile(CfgFile, Argv))
1451 return Err;
1452 return expandResponseFiles(Argv);
1453}
1454
1455static void initCommonOptions();
1458 StringRef Overview, raw_ostream *Errs, vfs::FileSystem *VFS,
1459 const char *EnvVar, ArrayRef<const LibraryOptions *> ToolOptions = {}) {
1463 StringSaver Saver(A);
1464 NewArgv.push_back(Args[0]);
1465
1466 // Parse options from environment variable.
1467 if (EnvVar) {
1468 if (std::optional<std::string> EnvValue =
1469 sys::Process::GetEnv(StringRef(EnvVar)))
1470 TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1471 }
1472
1473 // Append options from command line.
1474 append_range(NewArgv, Args.drop_front());
1475 int NewArgc = static_cast<int>(NewArgv.size());
1476
1477 // Parse all options.
1478 return globalParser().ParseCommandLineOptions(
1479 NewArgc, &NewArgv[0], Overview, Errs, VFS, Context, 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(nullptr, ArrayRef(argv, argc), Overview,
1486 Errs, VFS, EnvVar);
1487}
1488
1491 StringRef Overview, raw_ostream *Errs,
1492 vfs::FileSystem *VFS, const char *EnvVar) {
1493 return parseCommandLineOptionsImpl(&Context, Args, Overview, Errs, VFS,
1494 EnvVar);
1495}
1496
1500 StringRef Overview, raw_ostream *Errs,
1501 vfs::FileSystem *VFS, const char *EnvVar) {
1502 return parseCommandLineOptionsImpl(&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.
1515 Opts.reserve(SC->OptionsMap.size());
1516 for (auto &O : SC->OptionsMap)
1517 Opts.push_back(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,
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);
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(newArgv)) {
1552 *Errs << toString(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(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(StringRef(argv[FirstArg]), 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(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("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("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(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 //
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(ActivePositionalArg, StringRef(argv[i]), i);
1657 continue; // We are done!
1658 }
1659
1660 if (!PositionalOpts.empty()) {
1661 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), 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(std::make_pair(StringRef(argv[i]), 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("-");
1687
1688 Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
1689 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1690 ProvidePositionalOption(ActivePositionalArg, 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("-");
1697
1698 Handler = LookupOption(*ChosenSubCommand, 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(SubCommand::getTopLevel(), ArgName, Value);
1705
1706 if (!Handler && Context) {
1707 if (const LibraryOptions *L =
1708 lookupLibraryOption(ArgName.split('=').first)) {
1709 ArrayRef<const char *> Rest(argv + i, argc - i);
1710 unsigned N;
1711 if (Error E = Context->parse(*L, Rest, N)) {
1712 *Errs << ProgramName << ": " << toString(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(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(ArgName, OptionsMap, 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("This argument does not take a value.\n"
1762 "\tInstead, it consumes any positional arguments until "
1763 "the next recognized option.", *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(Opt)) {
1793 ProvidePositionalOption(Opt, PositionalVals[ValNo].first,
1794 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(Opt, PositionalVals[ValNo].first,
1812 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(Opt)) {
1826 ErrorParsing |= ProvidePositionalOption(
1827 Opt, PositionalVals[ValNo].first, 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(PositionalOpts[0],
1838 PositionalVals[ValNo].first,
1839 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(ConsumeAfterOpt, PositionalVals[ValNo].first,
1848 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("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(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, 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 {
1923}
1924
1926 size_t FirstLineIndentedBy) {
1927 assert(Indent >= FirstLineIndentedBy);
1928 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1929 outs().indent(Indent - FirstLineIndentedBy)
1930 << ArgHelpPrefix << Split.first << "\n";
1931 while (!Split.second.empty()) {
1932 Split = Split.second.split('\n');
1933 outs().indent(Indent) << Split.first << "\n";
1934 }
1935}
1936
1938 size_t FirstLineIndentedBy) {
1939 const StringRef ValHelpPrefix = " ";
1940 assert(BaseIndent >= FirstLineIndentedBy);
1941 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1942 outs().indent(BaseIndent - FirstLineIndentedBy)
1943 << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
1944 while (!Split.second.empty()) {
1945 Split = Split.second.split('\n');
1946 outs().indent(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);
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...
1965 size_t Len = argPlusPrefixesSize(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, 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//
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, ValName) << ">...";
1988 } else if (O.getValueExpectedFlag() == ValueOptional)
1989 outs() << "[=<" << getValueStr(O, ValName) << ">]";
1990 else {
1991 outs() << (O.ArgStr.size() == 1 ? " <" : "=<") << getValueStr(O, ValName)
1992 << '>';
1993 }
1994 }
1995
1996 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1997}
1998
2000 size_t GlobalWidth) const {
2001 outs() << PrintArg(O.ArgStr);
2002 outs().indent(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//
2017 boolOrDefault::BOU_FALSE>(O, ArgName, Arg, Value);
2018}
2019
2020// parser<FixedOrScalableQuantity> implementation
2021//
2022template <typename FixedOrScalableQuantityT>
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("vscale"))
2038 return O.error("'" + Arg + "' value invalid for " + ValueKind +
2039 " argument!");
2040
2041 Remainder = Remainder.ltrim();
2042 if (!Remainder.consume_front('x'))
2043 return O.error("'" + Arg + "' value invalid for " + ValueKind +
2044 " argument!");
2045
2046 Remainder = Remainder.ltrim();
2047 if (Remainder.getAsInteger(0, MinValue))
2048 return O.error("'" + 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(0, Value))
2060 return O.error("'" + 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(0, Value))
2069 return O.error("'" + 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(0, Value))
2078 return O.error("'" + 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(0, Value))
2088 return O.error("'" + 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(0, Value))
2098 return O.error("'" + 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(0, Value))
2109 return O.error("'" + 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, getValueName(), Value);
2118}
2119
2120// parser<double>/parser<float> implementation
2121//
2122static bool parseDouble(Option &O, StringRef Arg, double &Value) {
2123 if (to_float(Arg, Value))
2124 return false;
2125 return O.error("'" + 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, Val);
2131}
2132
2133bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
2134 float &Val) {
2135 double dVal;
2136 if (parseDouble(O, Arg, 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//
2149 unsigned e = getNumOptions();
2150
2151 for (unsigned i = 0; i != e; ++i) {
2152 if (getOption(i) == Name)
2153 return i;
2154 }
2155 return e;
2156}
2157
2158static StringRef EqValue = "=<value>";
2159static StringRef EmptyOption = "<empty>";
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...
2173 if (O.hasArgStr()) {
2174 size_t Size =
2175 argPlusPrefixesSize(O.ArgStr) + EqValue.size();
2176 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2177 StringRef Name = getOption(i);
2178 if (!shouldPrintOption(Name, getDescription(i), O))
2179 continue;
2180 size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
2181 Size = std::max(Size, 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(BaseSize, getOption(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//
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(i).empty()) {
2203 outs() << PrintArg(O.ArgStr);
2204 Option::printHelpStr(O.HelpStr, GlobalWidth,
2205 argPlusPrefixesSize(O.ArgStr));
2206 break;
2207 }
2208 }
2209 }
2210
2211 outs() << PrintArg(O.ArgStr) << EqValue;
2212 Option::printHelpStr(O.HelpStr, GlobalWidth,
2213 EqValue.size() +
2214 argPlusPrefixesSize(O.ArgStr));
2215 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2216 StringRef OptionName = getOption(i);
2217 StringRef Description = getDescription(i);
2218 if (!shouldPrintOption(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(Description, GlobalWidth, 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) {
2237 outs() << " " << PrintArg(Option);
2238 Option::printHelpStr(getDescription(i), GlobalWidth, 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.
2249 const Option &O, const GenericOptionValue &Value,
2250 const GenericOptionValue &Default, size_t GlobalWidth) const {
2251 outs() << " " << PrintArg(O.ArgStr);
2252 outs().indent(GlobalWidth - O.ArgStr.size());
2253
2254 unsigned NumOpts = getNumOptions();
2255 for (unsigned i = 0; i != NumOpts; ++i) {
2256 if (!Value.compare(getOptionValue(i)))
2257 continue;
2258
2259 outs() << "= " << getOption(i);
2260 size_t L = getOption(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(getOptionValue(j)))
2265 continue;
2266 outs() << getOption(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 {
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)
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)
2317
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().
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(LHS->first, 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(LHS->first, 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(I->second).second)
2386 continue;
2387
2388 Opts.push_back(
2389 std::pair<const char *, Option *>(I->first.data(), I->second));
2390 }
2391
2392 // Sort the options list alphabetically.
2393 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2394}
2395
2396static void
2398 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2399 for (auto *S : SubMap) {
2400 if (S->getName().empty())
2401 continue;
2402 Subs.push_back(std::make_pair(S->getName().data(), S));
2403 }
2404 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2405}
2406
2407namespace {
2408
2409class HelpPrinter {
2410protected:
2411 const bool ShowHidden;
2412 using StrOptionPairVector =
2414 using StrSubCommandPairVector =
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(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(MaxSubLen - strlen(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(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(OptionsMap, Opts, ShowHidden);
2455
2456 StrSubCommandPairVector Subs;
2457 sortSubCommands(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(MaxSubLen, strlen(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(MaxArgLen, Opt.second->getOptionWidth());
2507
2509 if (ShowHidden && globalParser().RecognizeLibraryOptions)
2510 for (const LibraryOptions *L : concat<const LibraryOptions *const>(
2511 globalParser().Libraries, globalParser().ToolOptions))
2512 L->forEachOption(
2513 [&](StringRef Spelling, StringRef MetaVar, StringRef Help) {
2514 if (!Help.empty())
2515 LibraryOpts.emplace_back((Spelling + MetaVar).str(), Help);
2516 });
2517 llvm::sort(LibraryOpts);
2518 for (const auto &[Name, Help] : LibraryOpts)
2519 MaxArgLen = std::max(MaxArgLen, argPlusPrefixesSize(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);
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((*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(SortedCategories,
2562 globalParser().RegisteredOptionCategories);
2563
2564 // Sort the different option categories alphabetically.
2565 assert(SortedCategories.size() > 0 && "No option categories registered!");
2566 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2567 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(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(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.
2697 "help-list",
2698 cl::desc(
2699 "Display list of available options (--help-list-hidden for more)"),
2700 cl::location(UncategorizedNormalPrinter),
2701 cl::Hidden,
2703 cl::cat(GenericCategory),
2705
2707 "help-list-hidden",
2708 cl::desc("Display list of all available options"),
2709 cl::location(UncategorizedHiddenPrinter),
2710 cl::Hidden,
2712 cl::cat(GenericCategory),
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.
2719 "help",
2720 cl::desc("Display available options (--help-hidden for more)"),
2721 cl::location(WrappedNormalPrinter),
2723 cl::cat(GenericCategory),
2725
2726 cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp)};
2727
2729 "help-hidden",
2730 cl::desc("Display all available options"),
2731 cl::location(WrappedHiddenPrinter),
2732 cl::Hidden,
2734 cl::cat(GenericCategory),
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(false),
2742 cl::cat(GenericCategory),
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(false),
2750 cl::cat(GenericCategory),
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
2761 "version", cl::desc("Display the version of this program"),
2762 cl::location(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.
2770
2782
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(0);
2796 }
2797 print(CommonOptions->ExtraVersionPrinters);
2798
2799 exit(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
2828 sortOpts(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(MaxArgLen, Opt.second->getOptionWidth());
2834
2835 for (const auto &Opt : Opts)
2836 Opt.second->printOptionValue(MaxArgLen, 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
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(1);
2889}
2890
2891// Utility function for printing the build config.
2893#if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG
2894 OS << "Build config: ";
2896 OS << '\n';
2897#endif
2898}
2899
2900/// Utility function for printing version number.
2902 CommonOptions->VersionPrinterInstance.print(CommonOptions->ExtraVersionPrinters);
2903}
2904
2906 CommonOptions->OverrideVersionPrinter = func;
2907}
2908
2910 CommonOptions->ExtraVersionPrinters.push_back(func);
2911}
2912
2915 auto &Subs = globalParser().RegisteredSubCommands;
2916 (void)Subs;
2917 assert(Subs.contains(&Sub));
2918 return Sub.OptionsMap;
2919}
2920
2923 return globalParser().getRegisteredSubcommands();
2924}
2925
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
2940 SubCommand &Sub) {
2942 for (auto &I : Sub.OptionsMap) {
2943 bool Unrelated = true;
2944 for (auto &Cat : I.second->Categories) {
2945 if (is_contained(Categories, Cat) ||
2946 Cat == &CommonOptions->GenericCategory)
2947 Unrelated = false;
2948 }
2949 if (Unrelated)
2950 I.second->setHiddenFlag(cl::ReallyHidden);
2951 }
2952}
2953
2955
2957 globalParser().Libraries.push_back(&L);
2958}
2959
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(parse(*Other.SavedLibraries[I], Args.drop_front(I), N));
2970 I += N;
2971 }
2972}
2973
2976 unsigned &Consumed) {
2977 auto [It, Inserted] = Values.try_emplace(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>(Args.size(), 2);
2985 for (unsigned J = 0; J != NumArgs; ++J)
2986 Saved[J] = Saver.save(Args[J]).data();
2987 Consumed = 1;
2988 if (Error E = L.parse(It->second, ArrayRef(Saved, NumArgs), Consumed, Alloc))
2989 return E;
2990 SavedArgs.append(Saved, Saved + Consumed);
2991 SavedLibraries.resize(SavedArgs.size(), &L);
2992 return Error::success();
2993}
2994
2996 globalParser().ResetAllOptionOccurrences();
2997}
2998
3003
3004void LLVMParseCommandLineOptions(int argc, const char *const *argv,
3005 const char *Overview) {
3007 Overview, &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);
3017 Overview, &Stream)) {
3018 *ErrorMessage = strdup(Err.c_str());
3019 return 1;
3020 }
3021 return 0;
3022}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void opt_bool_anchor()
static StringRef OptionPrefix
static bool RequiresValue(const Option *O)
static int SubNameCompare(const std::pair< const char *, SubCommand * > *LHS, const std::pair< const char *, SubCommand * > *RHS)
static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad=DefaultPad)
static bool shouldPrintOption(StringRef Name, StringRef Description, const Option &O)
static bool parseDouble(Option &O, StringRef Arg, double &Value)
static CommandLineParser & globalParser()
static bool parseBool(Option &O, StringRef ArgName, StringRef Arg, T &Value)
static const size_t DefaultPad
static StringRef EmptyOption
static bool parseCommandLineOptionsImpl(LibraryOptionsContext *Context, ArrayRef< const char * > Args, StringRef Overview, raw_ostream *Errs, vfs::FileSystem *VFS, const char *EnvVar, ArrayRef< const LibraryOptions * > ToolOptions={})
static bool hasUTF8ByteOrderMark(ArrayRef< char > S)
static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver, const char *&Arg)
static SmallString< 8 > argPrefix(StringRef ArgName, size_t Pad=DefaultPad)
static StringRef ArgHelpPrefix
void opt_unsigned_anchor()
static bool isWindowsSpecialCharInCommandName(char C)
static StringRef getValueStr(const Option &O, StringRef DefaultMsg)
static Option * HandlePrefixedOption(StringRef &Arg, StringRef &Value, const OptionsMapTy &OptionsMap)
The specified argument string (which started with at least one '-') does not fully match an available...
static size_t getOptionPrefixesSize()
static bool ProvideOption(Option *Handler, StringRef ArgName, StringRef Value, int argc, const char *const *argv, int &i)
ProvideOption - For Value, this differentiates between an empty value ("") and a null value (StringRe...
static bool isQuote(char C)
static ManagedStatic< CommandLineCommonOptions > CommonOptions
static void initCommonOptions()
void opt_char_anchor()
static void sortOpts(OptionsMapTy &OptMap, SmallVectorImpl< std::pair< const char *, Option * > > &Opts, bool ShowHidden)
DenseMap< StringRef, Option * > OptionsMapTy
static void tokenizeWindowsCommandLineImpl(StringRef Src, StringSaver &Saver, function_ref< void(StringRef)> AddToken, bool AlwaysCopy, function_ref< void()> MarkEOL, bool InitialCommandName)
static Option * findPrefixOption(StringRef Name, size_t &Length, const OptionsMapTy &OptionsMap)
static bool isWhitespace(char C)
static bool parseFixedOrScalableQuantity(Option &O, StringRef Arg, StringRef ValueKind, FixedOrScalableQuantityT &Value)
static size_t parseBackslash(StringRef Src, size_t I, SmallString< 128 > &Token)
Backslashes are interpreted in a rather complicated way in the Windows-style command line,...
static StringRef ArgPrefixLong
static void sortSubCommands(const SmallPtrSetImpl< SubCommand * > &SubMap, SmallVectorImpl< std::pair< const char *, SubCommand * > > &Subs)
#define PRINT_OPT_DIFF(T)
static bool isWhitespaceOrNull(char C)
static StringRef EqValue
static const size_t MaxOptWidth
static bool EatsUnboundedNumberOfValues(const Option *O)
static int OptNameCompare(const std::pair< const char *, Option * > *LHS, const std::pair< const char *, Option * > *RHS)
static Option * LookupNearestOption(StringRef Arg, const OptionsMapTy &OptionsMap, std::string &NearestString)
LookupNearestOption - Lookup the closest match to the option specified by the specified option on the...
void opt_int_anchor()
static StringRef ArgPrefix
static bool isWindowsSpecialChar(char C)
static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, StringRef ArgName, StringRef Value)
CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() that does special handling ...
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:213
Fixup Statepoint Caller Saved
#define _
static llvm::Error parse(GsymDataExtractor &Data, uint64_t BaseAddr, LineEntryCallback const &Callback)
Definition LineTable.cpp:54
static void Help(StringTable CPUNames, ArrayRef< SubtargetFeatureKV > FeatTable)
Display help for feature and mcpu choices.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
Provides a library for accessing information about this process and other processes on the operating ...
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
iterator begin()
Definition DenseMap.h:682
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Represents either an error or a value T.
Definition ErrorOr.h:56
reference get()
Definition ErrorOr.h:149
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
size_t getBufferSize() const
const char * getBufferEnd() const
const char * getBufferStart() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
iterator end() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void assign(StringRef RHS)
Assign from a StringRef.
Definition SmallString.h:53
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
const char * c_str()
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:880
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:482
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:627
LLVM_ABI unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
Definition StringRef.cpp:88
size_t size_type
Definition StringRef.h:62
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:712
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
StringRef ltrim(char Char) const
Return string with consecutive Char characters starting from the the left removed.
Definition StringRef.h:818
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
StringRef trim(char Char) const
Return string with consecutive Char characters starting from the left and right removed.
Definition StringRef.h:842
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:653
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:22
BumpPtrAllocator & getAllocator() const
Definition StringSaver.h:28
StringRef save(const char *S)
Definition StringSaver.h:31
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
Contains options that control response file expansion.
LLVM_ABI ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T, vfs::FileSystem *FS=nullptr)
LLVM_ABI bool findConfigFile(StringRef FileName, SmallVectorImpl< char > &FilePath)
Looks for the specified configuration file.
LLVM_ABI Error expandResponseFiles(SmallVectorImpl< const char * > &Argv)
Expands constructs "@file" in the provided array of arguments recursively.
LLVM_ABI Error readConfigFile(StringRef CfgFile, SmallVectorImpl< const char * > &Argv)
Reads command line options from the given configuration file.
Error parse(const LibraryOptions &L, ArrayRef< const char * > Args, unsigned &Consumed)
void assign(const LibraryOptionsContext &Other)
The options of a library that declares them in TableGen rather than as cl::opt (see llvm/Option/Libra...
SmallPtrSet< SubCommand *, 1 > Subs
int getNumOccurrences() const
enum ValueExpected getValueExpectedFlag() const
void addCategory(OptionCategory &C)
enum FormattingFlags getFormattingFlag() const
virtual void printOptionInfo(size_t GlobalWidth) const =0
enum NumOccurrencesFlag getNumOccurrencesFlag() const
virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value)
SmallVector< OptionCategory *, 1 > Categories
bool error(const Twine &Message, StringRef ArgName=StringRef(), raw_ostream &Errs=llvm::errs())
void setArgStr(StringRef S)
bool hasArgStr() const
unsigned getMiscFlags() const
virtual void setDefault()=0
virtual void printOptionValue(size_t GlobalWidth, bool Force) const =0
static void printEnumValHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
void removeArgument()
Unregisters this option from the CommandLine system.
static void printHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
virtual size_t getOptionWidth() const =0
StringRef HelpStr
Option(enum NumOccurrencesFlag OccurrencesFlag, enum OptionHidden Hidden)
StringRef getName() const
SubCommand(StringRef Name, StringRef Description="")
static LLVM_ABI SubCommand & getTopLevel()
LLVM_ABI void unregisterSubCommand()
static LLVM_ABI SubCommand & getAll()
LLVM_ABI void reset()
DenseMap< StringRef, Option * > OptionsMap
LLVM_ABI void registerSubCommand()
SmallVector< Option *, 4 > PositionalOpts
void printOptionInfo(const Option &O, size_t GlobalWidth) const
virtual StringRef getValueName() const
void printOptionNoValue(const Option &O, size_t GlobalWidth) const
size_t getOptionWidth(const Option &O) const
void printOptionName(const Option &O, size_t GlobalWidth) const
virtual size_t getOptionWidth(const Option &O) const
virtual StringRef getDescription(unsigned N) const =0
virtual const GenericOptionValue & getOptionValue(unsigned N) const =0
virtual unsigned getNumOptions() const =0
virtual StringRef getOption(unsigned N) const =0
void printGenericOptionDiff(const Option &O, const GenericOptionValue &V, const GenericOptionValue &Default, size_t GlobalWidth) const
virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const
unsigned findOption(StringRef Name)
bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V)
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an SmallVector or SmallString.
static LLVM_ABI std::optional< std::string > GetEnv(StringRef name)
The virtual file system interface.
The result of a status operation.
LLVM_ABI bool equivalent(const Status &Other) const
LLVM_C_ABI LLVMBool LLVMParseCommandLineOptionsWithError(int argc, const char *const *argv, const char *Overview, char **ErrorMessage)
Like LLVMParseCommandLineOptions() but returns non-zero and sets *ErrorMessage on error.
LLVM_C_ABI void LLVMParseCommandLineOptions(int argc, const char *const *argv, const char *Overview)
This function parses the given arguments using the LLVM command line parser.
int LLVMBool
Definition Types.h:28
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr size_t NameSize
Definition XCOFF.h:30
This namespace contains all of the command line option processing machinery.
LLVM_ABI iterator_range< SmallPtrSet< SubCommand *, 4 >::iterator > getRegisteredSubcommands()
Use this to get all registered SubCommands from the provided parser.
LLVM_ABI void PrintVersionMessage()
Utility function for printing version number.
LLVM_ABI bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl< const char * > &Argv)
A convenience helper which supports the typical use case of expansion function call.
LLVM_ABI LibraryOptionsContext & getCAPILibraryOptions()
LLVM_ABI void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a string of Windows command line arguments, which may contain quotes and escaped quotes.
LLVM_ABI OptionCategory & getGeneralCategory()
LLVM_ABI void addLibraryOptions(const LibraryOptions &L)
Makes ParseCommandLineOptions recognize L's options.
@ ValueDisallowed
LLVM_ABI void ResetAllOptionOccurrences()
Reset all command line options to a state that looks as if they have never appeared on the command li...
LLVM_ABI void SetVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Override the default (LLV...
LLVM_ABI void tokenizeConfigFile(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes content of configuration file.
LLVM_ABI DenseMap< StringRef, Option * > & getRegisteredOptions(SubCommand &Sub=SubCommand::getTopLevel())
Use this to get a map of all registered named options (e.g.
LLVM_ABI bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv)
A convenience helper which concatenates the options specified by the environment variable EnvVar and ...
LLVM_ABI void ResetCommandLineParser()
Reset the command line parser back to its initial state.
LLVM_ABI void PrintOptionValues()
LLVM_ABI void AddLiteralOption(Option &O, StringRef Name)
Adds a new option for parsing and provides the option it refers to.
void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V, const OptionValue< DT > &Default, size_t GlobalWidth)
LLVM_ABI void TokenizeWindowsCommandLineNoCopy(StringRef Source, StringSaver &Saver, SmallVectorImpl< StringRef > &NewArgv)
Tokenizes a Windows command line while attempting to avoid copies.
LLVM_ABI void printBuildConfig(raw_ostream &OS)
Prints the compiler build configuration.
void(*)(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs) TokenizerCallback
String tokenization function type.
LLVM_ABI bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i)
Parses Arg into the option handler Handler.
static raw_ostream & operator<<(raw_ostream &OS, boolOrDefault V)
initializer< Ty > init(const Ty &Val)
std::function< void(raw_ostream &)> VersionPrinterTy
@ PositionalEatsArgs
LLVM_ABI bool parseCommandLineOptions(LibraryOptionsContext &Context, ArrayRef< const char * > Args, StringRef Overview="", raw_ostream *Errs=nullptr, vfs::FileSystem *VFS=nullptr, const char *EnvVar=nullptr)
LLVM_ABI ArrayRef< StringRef > getCompilerBuildConfig()
An array of optional enabled settings in the LLVM build configuration, which may be of interest to co...
LocationClass< Ty > location(Ty &L)
LLVM_ABI bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, vfs::FileSystem *VFS=nullptr, const char *EnvVar=nullptr)
LLVM_ABI void HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub=SubCommand::getTopLevel())
Mark all options not part of this category as cl::ReallyHidden.
LLVM_ABI void AddExtraVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Add an extra printer to u...
LLVM_ABI void PrintHelpMessage(bool Hidden=false, bool Categorized=false)
This function just prints the help message, exactly the same way as if the -help or -help-hidden opti...
LLVM_ABI void TokenizeWindowsCommandLineFull(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a Windows full command line, including command name at the start.
@ NormalFormatting
LLVM_ABI void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a command line that can contain escapes and quotes.
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
Definition Path.cpp:478
LLVM_ABI bool has_parent_path(const Twine &path, Style style=Style::native)
Has parent path?
Definition Path.cpp:667
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
Definition Path.cpp:716
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:688
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Length
Definition DWP.cpp:577
void initWithColorOptions()
Definition WithColor.cpp:34
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
@ Done
Definition Threading.h:60
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void initDebugOptions()
Definition Debug.cpp:189
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2334
LLVM_ABI bool hasUTF16ByteOrderMark(ArrayRef< char > SrcBytes)
Returns true if a blob of text starts with a UTF-16 big or little endian byte order mark.
void initDebugCounterOptions()
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1167
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
bool to_float(const Twine &T, float &Num)
@ no_such_file_or_directory
Definition Errc.h:65
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI bool convertUTF16ToUTF8String(ArrayRef< char > SrcBytes, std::string &Out)
Converts a stream of raw bytes assumed to be UTF16 into a UTF8 std::string.
void initSignalsOptions()
Definition Signals.cpp:64
void initStatisticOptions()
Definition Statistic.cpp:49
LLVM_ABI raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
void initTimerOptions()
Definition Timer.cpp:569
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Other
Any other memory.
Definition ModRef.h:68
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
void initRandomSeedOptions()
@ Sub
Subtraction of integers.
void initGraphWriterOptions()
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1612
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
#define N
#define INIT(o, n)
Definition regexec.c:71
LLVM_ABI extrahelp(StringRef help)