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