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