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