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