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