LCOV - code coverage report
Current view: top level - lib/Option - OptTable.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 201 205 98.0 %
Date: 2017-09-14 15:23:50 Functions: 17 17 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- OptTable.cpp - Option Table Implementation -------------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : 
      10             : #include "llvm/ADT/STLExtras.h"
      11             : #include "llvm/ADT/StringRef.h"
      12             : #include "llvm/ADT/StringSet.h"
      13             : #include "llvm/Option/Arg.h"
      14             : #include "llvm/Option/ArgList.h"
      15             : #include "llvm/Option/Option.h"
      16             : #include "llvm/Option/OptSpecifier.h"
      17             : #include "llvm/Option/OptTable.h"
      18             : #include "llvm/Support/Compiler.h"
      19             : #include "llvm/Support/ErrorHandling.h"
      20             : #include "llvm/Support/raw_ostream.h"
      21             : #include <algorithm>
      22             : #include <cassert>
      23             : #include <cctype>
      24             : #include <cstring>
      25             : #include <map>
      26             : #include <string>
      27             : #include <utility>
      28             : #include <vector>
      29             : 
      30             : using namespace llvm;
      31             : using namespace llvm::opt;
      32             : 
      33             : namespace llvm {
      34             : namespace opt {
      35             : 
      36             : // Ordering on Info. The ordering is *almost* case-insensitive lexicographic,
      37             : // with an exception. '\0' comes at the end of the alphabet instead of the
      38             : // beginning (thus options precede any other options which prefix them).
      39    14368699 : static int StrCmpOptionNameIgnoreCase(const char *A, const char *B) {
      40    14368699 :   const char *X = A, *Y = B;
      41    14368699 :   char a = tolower(*A), b = tolower(*B);
      42    46740655 :   while (a == b) {
      43    16838188 :     if (a == '\0')
      44             :       return 0;
      45             : 
      46    16185978 :     a = tolower(*++X);
      47    16185978 :     b = tolower(*++Y);
      48             :   }
      49             : 
      50    13716489 :   if (a == '\0') // A is a prefix of B.
      51             :     return 1;
      52    13588767 :   if (b == '\0') // B is a prefix of A.
      53             :     return -1;
      54             : 
      55             :   // Otherwise lexicographic.
      56    12189594 :   return (a < b) ? -1 : 1;
      57             : }
      58             : 
      59             : #ifndef NDEBUG
      60             : static int StrCmpOptionName(const char *A, const char *B) {
      61             :   if (int N = StrCmpOptionNameIgnoreCase(A, B))
      62             :     return N;
      63             :   return strcmp(A, B);
      64             : }
      65             : 
      66             : static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) {
      67             :   if (&A == &B)
      68             :     return false;
      69             : 
      70             :   if (int N = StrCmpOptionName(A.Name, B.Name))
      71             :     return N < 0;
      72             : 
      73             :   for (const char * const *APre = A.Prefixes,
      74             :                   * const *BPre = B.Prefixes;
      75             :                           *APre != nullptr && *BPre != nullptr; ++APre, ++BPre){
      76             :     if (int N = StrCmpOptionName(*APre, *BPre))
      77             :       return N < 0;
      78             :   }
      79             : 
      80             :   // Names are the same, check that classes are in order; exactly one
      81             :   // should be joined, and it should succeed the other.
      82             :   assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) &&
      83             :          "Unexpected classes for options with same name.");
      84             :   return B.Kind == Option::JoinedClass;
      85             : }
      86             : #endif
      87             : 
      88             : // Support lower_bound between info and an option name.
      89             : static inline bool operator<(const OptTable::Info &I, const char *Name) {
      90    14368699 :   return StrCmpOptionNameIgnoreCase(I.Name, Name) < 0;
      91             : }
      92             : 
      93             : } // end namespace opt
      94             : } // end namespace llvm
      95             : 
      96         390 : OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {}
      97             : 
      98       42467 : OptTable::OptTable(ArrayRef<Info> OptionInfos, bool IgnoreCase)
      99      127401 :     : OptionInfos(OptionInfos), IgnoreCase(IgnoreCase) {
     100             :   // Explicitly zero initialize the error to work around a bug in array
     101             :   // value-initialization on MinGW with gcc 4.3.5.
     102             : 
     103             :   // Find start of normal options.
     104       84934 :   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
     105     4421194 :     unsigned Kind = getInfo(i + 1).Kind;
     106     2210597 :     if (Kind == Option::InputClass) {
     107             :       assert(!TheInputOptionID && "Cannot have multiple input options!");
     108       84934 :       TheInputOptionID = getInfo(i + 1).ID;
     109     2168130 :     } else if (Kind == Option::UnknownClass) {
     110             :       assert(!TheUnknownOptionID && "Cannot have multiple unknown options!");
     111       84934 :       TheUnknownOptionID = getInfo(i + 1).ID;
     112     2125663 :     } else if (Kind != Option::GroupClass) {
     113       42467 :       FirstSearchableIndex = i;
     114       42467 :       break;
     115             :     }
     116             :   }
     117             :   assert(FirstSearchableIndex != 0 && "No searchable options?");
     118             : 
     119             : #ifndef NDEBUG
     120             :   // Check that everything after the first searchable option is a
     121             :   // regular option class.
     122             :   for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) {
     123             :     Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind;
     124             :     assert((Kind != Option::InputClass && Kind != Option::UnknownClass &&
     125             :             Kind != Option::GroupClass) &&
     126             :            "Special options should be defined first!");
     127             :   }
     128             : 
     129             :   // Check that options are in order.
     130             :   for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions(); i != e; ++i){
     131             :     if (!(getInfo(i) < getInfo(i + 1))) {
     132             :       getOption(i).dump();
     133             :       getOption(i + 1).dump();
     134             :       llvm_unreachable("Options are not in order!");
     135             :     }
     136             :   }
     137             : #endif
     138             : 
     139             :   // Build prefixes.
     140    85029514 :   for (unsigned i = FirstSearchableIndex + 1, e = getNumOptions() + 1;
     141    84987047 :                 i != e; ++i) {
     142   169889160 :     if (const char *const *P = getInfo(i).Prefixes) {
     143   274194332 :       for (; *P != nullptr; ++P) {
     144   283874628 :         PrefixesUnion.insert(*P);
     145             :       }
     146             :     }
     147             :   }
     148             : 
     149             :   // Build prefix chars.
     150      127401 :   for (StringSet<>::const_iterator I = PrefixesUnion.begin(),
     151      295670 :                                    E = PrefixesUnion.end(); I != E; ++I) {
     152      251604 :     StringRef Prefix = I->getKey();
     153      420300 :     for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end();
     154      294498 :                                    C != CE; ++C)
     155      337392 :       if (!is_contained(PrefixChars, *C))
     156       83277 :         PrefixChars.push_back(*C);
     157             :   }
     158       42467 : }
     159             : 
     160             : OptTable::~OptTable() = default;
     161             : 
     162    98558161 : const Option OptTable::getOption(OptSpecifier Opt) const {
     163    98558161 :   unsigned id = Opt.getID();
     164    98558161 :   if (id == 0)
     165    67560642 :     return Option(nullptr, nullptr);
     166             :   assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID.");
     167    61995038 :   return Option(&getInfo(id), this);
     168             : }
     169             : 
     170     1322853 : static bool isInput(const StringSet<> &Prefixes, StringRef Arg) {
     171     1322853 :   if (Arg == "-")
     172             :     return true;
     173     2645572 :   for (StringSet<>::const_iterator I = Prefixes.begin(),
     174     5341533 :                                    E = Prefixes.end(); I != E; ++I)
     175     5363936 :     if (Arg.startswith(I->getKey()))
     176             :       return false;
     177             :   return true;
     178             : }
     179             : 
     180             : /// \returns Matched size. 0 means no match.
     181    18301344 : static unsigned matchOption(const OptTable::Info *I, StringRef Str,
     182             :                             bool IgnoreCase) {
     183    37641086 :   for (const char * const *Pre = I->Prefixes; *Pre != nullptr; ++Pre) {
     184    41237800 :     StringRef Prefix(*Pre);
     185             :     if (Str.startswith(Prefix)) {
     186    28086546 :       StringRef Rest = Str.substr(Prefix.size());
     187             :       bool Matched = IgnoreCase
     188    30468808 :           ? Rest.startswith_lower(I->Name)
     189    42113263 :           : Rest.startswith(I->Name);
     190        8278 :       if (Matched)
     191     2558316 :         return Prefix.size() + StringRef(I->Name).size();
     192             :     }
     193             :   }
     194             :   return 0;
     195             : }
     196             : 
     197             : // Returns true if one of the Prefixes + In.Names matches Option
     198   154712370 : static bool optionMatches(const OptTable::Info &In, StringRef Option) {
     199   154712370 :   if (In.Prefixes)
     200   489035124 :     for (size_t I = 0; In.Prefixes[I]; I++)
     201  1170970374 :       if (Option == std::string(In.Prefixes[I]) + In.Name)
     202             :         return true;
     203             :   return false;
     204             : }
     205             : 
     206             : // This function is for flag value completion.
     207             : // Eg. When "-stdlib=" and "l" was passed to this function, it will return
     208             : // appropiriate values for stdlib, which starts with l.
     209             : std::vector<std::string>
     210          20 : OptTable::suggestValueCompletions(StringRef Option, StringRef Arg) const {
     211             :   // Search all options and return possible values.
     212       23573 :   for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
     213       47102 :     const Info &In = OptionInfos[I];
     214       23551 :     if (!In.Values || !optionMatches(In, Option))
     215       23533 :       continue;
     216             : 
     217          36 :     SmallVector<StringRef, 8> Candidates;
     218          54 :     StringRef(In.Values).split(Candidates, ",", -1, false);
     219             : 
     220          36 :     std::vector<std::string> Result;
     221         344 :     for (StringRef Val : Candidates)
     222             :       if (Val.startswith(Arg))
     223         801 :         Result.push_back(Val);
     224          18 :     return Result;
     225             :   }
     226             :   return {};
     227             : }
     228             : 
     229             : std::vector<std::string>
     230          11 : OptTable::findByPrefix(StringRef Cur, unsigned short DisableFlags) const {
     231          11 :   std::vector<std::string> Ret;
     232       23243 :   for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
     233       46442 :     const Info &In = OptionInfos[I];
     234       23221 :     if (!In.Prefixes || (!In.HelpText && !In.GroupID))
     235        3355 :       continue;
     236       19866 :     if (In.Flags & DisableFlags)
     237        4706 :       continue;
     238             : 
     239       50280 :     for (int I = 0; In.Prefixes[I]; I++) {
     240      140480 :       std::string S = std::string(In.Prefixes[I]) + std::string(In.Name) + "\t";
     241       17560 :       if (In.HelpText)
     242        8628 :         S += In.HelpText;
     243       17560 :       if (StringRef(S).startswith(Cur))
     244        4729 :         Ret.push_back(S);
     245             :     }
     246             :   }
     247          11 :   return Ret;
     248             : }
     249             : 
     250      120087 : bool OptTable::addValues(const char *Option, const char *Values) {
     251   154832172 :   for (size_t I = FirstSearchableIndex, E = OptionInfos.size(); I < E; I++) {
     252   309424170 :     Info &In = OptionInfos[I];
     253   154712085 :     if (optionMatches(In, Option)) {
     254      120087 :       In.Values = Values;
     255      120087 :       return true;
     256             :     }
     257             :   }
     258             :   return false;
     259             : }
     260             : 
     261     1322853 : Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index,
     262             :                            unsigned FlagsToInclude,
     263             :                            unsigned FlagsToExclude) const {
     264     1322853 :   unsigned Prev = Index;
     265     1322853 :   const char *Str = Args.getArgString(Index);
     266             : 
     267             :   // Anything that doesn't start with PrefixesUnion is an input, as is '-'
     268             :   // itself.
     269     1322853 :   if (isInput(PrefixesUnion, Str))
     270       42180 :     return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
     271             : 
     272     2617586 :   const Info *Start = OptionInfos.data() + FirstSearchableIndex;
     273     2617586 :   const Info *End = OptionInfos.data() + OptionInfos.size();
     274     2617586 :   StringRef Name = StringRef(Str).ltrim(PrefixChars);
     275             : 
     276             :   // Search for the first next option which could be a prefix.
     277     2617586 :   Start = std::lower_bound(Start, End, Name.data());
     278             : 
     279             :   // Options are stored in sorted order, with '\0' at the end of the
     280             :   // alphabet. Since the only options which can accept a string must
     281             :   // prefix it, we iteratively search for the next option which could
     282             :   // be a prefix.
     283             :   //
     284             :   // FIXME: This is searching much more than necessary, but I am
     285             :   // blanking on the simplest way to make it fast. We can solve this
     286             :   // problem when we move to TableGen.
     287     1311415 :   for (; Start != End; ++Start) {
     288             :     unsigned ArgSize = 0;
     289             :     // Scan for first option which is a proper prefix.
     290    35354464 :     for (; Start != End; ++Start)
     291    36602688 :       if ((ArgSize = matchOption(Start, Str, IgnoreCase)))
     292             :         break;
     293     1310092 :     if (Start == End)
     294             :       break;
     295             : 
     296     1279158 :     Option Opt(Start, this);
     297             : 
     298     1853961 :     if (FlagsToInclude && !Opt.hasFlag(FlagsToInclude))
     299         253 :       continue;
     300     2558108 :     if (Opt.hasFlag(FlagsToExclude))
     301          45 :       continue;
     302             : 
     303             :     // See if this option matches.
     304     1279009 :     if (Arg *A = Opt.accept(Args, Index, ArgSize))
     305     1277847 :       return A;
     306             : 
     307             :     // Otherwise, see if this argument was missing values.
     308        1172 :     if (Prev != Index)
     309             :       return nullptr;
     310             :   }
     311             : 
     312             :   // If we failed to find an option and this arg started with /, then it's
     313             :   // probably an input path.
     314       30946 :   if (Str[0] == '/')
     315       92505 :     return new Arg(getOption(TheInputOptionID), Str, Index++, Str);
     316             : 
     317         333 :   return new Arg(getOption(TheUnknownOptionID), Str, Index++, Str);
     318             : }
     319             : 
     320       44540 : InputArgList OptTable::ParseArgs(ArrayRef<const char *> ArgArr,
     321             :                                  unsigned &MissingArgIndex,
     322             :                                  unsigned &MissingArgCount,
     323             :                                  unsigned FlagsToInclude,
     324             :                                  unsigned FlagsToExclude) const {
     325       44540 :   InputArgList Args(ArgArr.begin(), ArgArr.end());
     326             : 
     327             :   // FIXME: Handle '@' args (or at least error on them).
     328             : 
     329       44540 :   MissingArgIndex = MissingArgCount = 0;
     330       44540 :   unsigned Index = 0, End = ArgArr.size();
     331     1367440 :   while (Index < End) {
     332             :     // Ingore nullptrs, they are response file's EOL markers
     333     2645862 :     if (Args.getArgString(Index) == nullptr) {
     334          46 :       ++Index;
     335          46 :       continue;
     336             :     }
     337             :     // Ignore empty arguments (other things may still take them as arguments).
     338     3968586 :     StringRef Str = Args.getArgString(Index);
     339     2645742 :     if (Str == "") {
     340          18 :       ++Index;
     341          18 :       continue;
     342             :     }
     343             : 
     344     1322844 :     unsigned Prev = Index;
     345     1322844 :     Arg *A = ParseOneArg(Args, Index, FlagsToInclude, FlagsToExclude);
     346             :     assert(Index > Prev && "Parser failed to consume argument.");
     347             : 
     348             :     // Check for missing argument error.
     349     1322844 :     if (!A) {
     350             :       assert(Index >= End && "Unexpected parser error.");
     351             :       assert(Index - Prev - 1 && "No missing arguments!");
     352           8 :       MissingArgIndex = Prev;
     353           8 :       MissingArgCount = Index - Prev - 1;
     354           8 :       break;
     355             :     }
     356             : 
     357     1322836 :     Args.append(A);
     358             :   }
     359             : 
     360       44540 :   return Args;
     361             : }
     362             : 
     363        3154 : static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) {
     364        3154 :   const Option O = Opts.getOption(Id);
     365        3154 :   std::string Name = O.getPrefixedName();
     366             : 
     367             :   // Add metavar, if used.
     368        6308 :   switch (O.getKind()) {
     369           0 :   case Option::GroupClass: case Option::InputClass: case Option::UnknownClass:
     370           0 :     llvm_unreachable("Invalid option with help text.");
     371             : 
     372           2 :   case Option::MultiArgClass:
     373           2 :     if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) {
     374             :       // For MultiArgs, metavar is full list of all argument names.
     375           2 :       Name += ' ';
     376             :       Name += MetaVarName;
     377             :     }
     378             :     else {
     379             :       // For MultiArgs<N>, if metavar not supplied, print <value> N times.
     380           0 :       for (unsigned i=0, e=O.getNumArgs(); i< e; ++i) {
     381           0 :         Name += " <value>";
     382             :       }
     383             :     }
     384             :     break;
     385             : 
     386             :   case Option::FlagClass:
     387             :     break;
     388             : 
     389             :   case Option::ValuesClass:
     390             :     break;
     391             : 
     392         484 :   case Option::SeparateClass: case Option::JoinedOrSeparateClass:
     393             :   case Option::RemainingArgsClass: case Option::RemainingArgsJoinedClass:
     394             :     Name += ' ';
     395             :     LLVM_FALLTHROUGH;
     396        1142 :   case Option::JoinedClass: case Option::CommaJoinedClass:
     397             :   case Option::JoinedAndSeparateClass:
     398        1142 :     if (const char *MetaVarName = Opts.getOptionMetaVar(Id))
     399             :       Name += MetaVarName;
     400             :     else
     401             :       Name += "<value>";
     402             :     break;
     403             :   }
     404             : 
     405        3154 :   return Name;
     406             : }
     407             : 
     408             : namespace {
     409       34984 : struct OptionInfo {
     410             :   std::string Name;
     411             :   StringRef HelpText;
     412             : };
     413             : } // namespace
     414             : 
     415          30 : static void PrintHelpOptionList(raw_ostream &OS, StringRef Title,
     416             :                                 std::vector<OptionInfo> &OptionHelp) {
     417          30 :   OS << Title << ":\n";
     418             : 
     419             :   // Find the maximum option length.
     420          30 :   unsigned OptionFieldWidth = 0;
     421        3214 :   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
     422             :     // Limit the amount of padding we are willing to give up for alignment.
     423        6308 :     unsigned Length = OptionHelp[i].Name.size();
     424        3154 :     if (Length <= 23)
     425        2348 :       OptionFieldWidth = std::max(OptionFieldWidth, Length);
     426             :   }
     427             : 
     428             :   const unsigned InitialPad = 2;
     429        6338 :   for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) {
     430        6308 :     const std::string &Option = OptionHelp[i].Name;
     431        3154 :     int Pad = OptionFieldWidth - int(Option.size());
     432        6308 :     OS.indent(InitialPad) << Option;
     433             : 
     434             :     // Break on long option names.
     435        3154 :     if (Pad < 0) {
     436         806 :       OS << "\n";
     437         806 :       Pad = OptionFieldWidth + InitialPad;
     438             :     }
     439        9462 :     OS.indent(Pad + 1) << OptionHelp[i].HelpText << '\n';
     440             :   }
     441          30 : }
     442             : 
     443        6823 : static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) {
     444        6823 :   unsigned GroupID = Opts.getOptionGroupID(Id);
     445             : 
     446             :   // If not in a group, return the default help group.
     447        6823 :   if (!GroupID)
     448             :     return "OPTIONS";
     449             : 
     450             :   // Abuse the help text of the option groups to store the "help group"
     451             :   // name.
     452             :   //
     453             :   // FIXME: Split out option groups.
     454        8132 :   if (const char *GroupHelp = Opts.getOptionHelpText(GroupID))
     455             :     return GroupHelp;
     456             : 
     457             :   // Otherwise keep looking.
     458        3669 :   return getOptionHelpGroup(Opts, GroupID);
     459             : }
     460             : 
     461          11 : void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
     462             :                          bool ShowHidden, bool ShowAllAliases) const {
     463          11 :   PrintHelp(OS, Name, Title, /*Include*/ 0, /*Exclude*/
     464             :             (ShowHidden ? 0 : HelpHidden), ShowAllAliases);
     465          11 : }
     466             : 
     467          18 : void OptTable::PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
     468             :                          unsigned FlagsToInclude, unsigned FlagsToExclude,
     469             :                          bool ShowAllAliases) const {
     470          18 :   OS << "OVERVIEW: " << Title << "\n";
     471          18 :   OS << '\n';
     472          18 :   OS << "USAGE: " << Name << " [options] <inputs>\n";
     473          18 :   OS << '\n';
     474             : 
     475             :   // Render help text into a map of group-name to a list of (option, help)
     476             :   // pairs.
     477             :   using helpmap_ty = std::map<std::string, std::vector<OptionInfo>>;
     478          36 :   helpmap_ty GroupedOptionHelp;
     479             : 
     480          36 :   for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
     481       16107 :     unsigned Id = i + 1;
     482             : 
     483             :     // FIXME: Split out option groups.
     484       32214 :     if (getOptionKind(Id) == Option::GroupClass)
     485         373 :       continue;
     486             : 
     487       31468 :     unsigned Flags = getInfo(Id).Flags;
     488       15734 :     if (FlagsToInclude && !(Flags & FlagsToInclude))
     489        6539 :       continue;
     490        9195 :     if (Flags & FlagsToExclude)
     491        1647 :       continue;
     492             : 
     493             :     // If an alias doesn't have a help text, show a help text for the aliased
     494             :     // option instead.
     495       15096 :     const char *HelpText = getOptionHelpText(Id);
     496        7548 :     if (!HelpText && ShowAllAliases) {
     497         288 :       const Option Alias = getOption(Id).getAlias();
     498         144 :       if (Alias.isValid())
     499         216 :         HelpText = getOptionHelpText(Alias.getID());
     500             :     }
     501             : 
     502        7548 :     if (HelpText) {
     503        3154 :       const char *HelpGroup = getOptionHelpGroup(*this, Id);
     504        3154 :       const std::string &OptName = getOptionHelpName(*this, Id);
     505       25232 :       GroupedOptionHelp[HelpGroup].push_back({OptName, HelpText});
     506             :     }
     507             :   }
     508             : 
     509          18 :   for (helpmap_ty::iterator it = GroupedOptionHelp .begin(),
     510          18 :          ie = GroupedOptionHelp.end(); it != ie; ++it) {
     511          30 :     if (it != GroupedOptionHelp .begin())
     512          12 :       OS << "\n";
     513          90 :     PrintHelpOptionList(OS, it->first, it->second);
     514             :   }
     515             : 
     516          18 :   OS.flush();
     517          18 : }

Generated by: LCOV version 1.13