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