StringMatcher.cpp 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. //===- StringMatcher.cpp - Generate a matcher for input strings -----------===//
  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 file implements the StringMatcher class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/TableGen/StringMatcher.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/Support/ErrorHandling.h"
  15. #include "llvm/Support/raw_ostream.h"
  16. #include <cassert>
  17. #include <map>
  18. #include <string>
  19. #include <utility>
  20. #include <vector>
  21. using namespace llvm;
  22. /// FindFirstNonCommonLetter - Find the first character in the keys of the
  23. /// string pairs that is not shared across the whole set of strings. All
  24. /// strings are assumed to have the same length.
  25. static unsigned
  26. FindFirstNonCommonLetter(const std::vector<const
  27. StringMatcher::StringPair*> &Matches) {
  28. assert(!Matches.empty());
  29. for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
  30. // Check to see if letter i is the same across the set.
  31. char Letter = Matches[0]->first[i];
  32. for (const StringMatcher::StringPair *Match : Matches)
  33. if (Match->first[i] != Letter)
  34. return i;
  35. }
  36. return Matches[0]->first.size();
  37. }
  38. /// EmitStringMatcherForChar - Given a set of strings that are known to be the
  39. /// same length and whose characters leading up to CharNo are the same, emit
  40. /// code to verify that CharNo and later are the same.
  41. ///
  42. /// \return - True if control can leave the emitted code fragment.
  43. bool StringMatcher::EmitStringMatcherForChar(
  44. const std::vector<const StringPair *> &Matches, unsigned CharNo,
  45. unsigned IndentCount, bool IgnoreDuplicates) const {
  46. assert(!Matches.empty() && "Must have at least one string to match!");
  47. std::string Indent(IndentCount * 2 + 4, ' ');
  48. // If we have verified that the entire string matches, we're done: output the
  49. // matching code.
  50. if (CharNo == Matches[0]->first.size()) {
  51. if (Matches.size() > 1 && !IgnoreDuplicates)
  52. report_fatal_error("Had duplicate keys to match on");
  53. // If the to-execute code has \n's in it, indent each subsequent line.
  54. StringRef Code = Matches[0]->second;
  55. std::pair<StringRef, StringRef> Split = Code.split('\n');
  56. OS << Indent << Split.first << "\t // \"" << Matches[0]->first << "\"\n";
  57. Code = Split.second;
  58. while (!Code.empty()) {
  59. Split = Code.split('\n');
  60. OS << Indent << Split.first << "\n";
  61. Code = Split.second;
  62. }
  63. return false;
  64. }
  65. // Bucket the matches by the character we are comparing.
  66. std::map<char, std::vector<const StringPair*>> MatchesByLetter;
  67. for (const StringPair *Match : Matches)
  68. MatchesByLetter[Match->first[CharNo]].push_back(Match);
  69. // If we have exactly one bucket to match, see how many characters are common
  70. // across the whole set and match all of them at once.
  71. if (MatchesByLetter.size() == 1) {
  72. unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
  73. unsigned NumChars = FirstNonCommonLetter-CharNo;
  74. // Emit code to break out if the prefix doesn't match.
  75. if (NumChars == 1) {
  76. // Do the comparison with if (Str[1] != 'f')
  77. // FIXME: Need to escape general characters.
  78. OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
  79. << Matches[0]->first[CharNo] << "')\n";
  80. OS << Indent << " break;\n";
  81. } else {
  82. // Do the comparison with if memcmp(Str.data()+1, "foo", 3).
  83. // FIXME: Need to escape general strings.
  84. OS << Indent << "if (memcmp(" << StrVariableName << ".data()+" << CharNo
  85. << ", \"" << Matches[0]->first.substr(CharNo, NumChars) << "\", "
  86. << NumChars << ") != 0)\n";
  87. OS << Indent << " break;\n";
  88. }
  89. return EmitStringMatcherForChar(Matches, FirstNonCommonLetter, IndentCount,
  90. IgnoreDuplicates);
  91. }
  92. // Otherwise, we have multiple possible things, emit a switch on the
  93. // character.
  94. OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
  95. OS << Indent << "default: break;\n";
  96. for (const auto &LI : MatchesByLetter) {
  97. // TODO: escape hard stuff (like \n) if we ever care about it.
  98. OS << Indent << "case '" << LI.first << "':\t // " << LI.second.size()
  99. << " string";
  100. if (LI.second.size() != 1)
  101. OS << 's';
  102. OS << " to match.\n";
  103. if (EmitStringMatcherForChar(LI.second, CharNo + 1, IndentCount + 1,
  104. IgnoreDuplicates))
  105. OS << Indent << " break;\n";
  106. }
  107. OS << Indent << "}\n";
  108. return true;
  109. }
  110. /// Emit - Top level entry point.
  111. ///
  112. void StringMatcher::Emit(unsigned Indent, bool IgnoreDuplicates) const {
  113. // If nothing to match, just fall through.
  114. if (Matches.empty()) return;
  115. // First level categorization: group strings by length.
  116. std::map<unsigned, std::vector<const StringPair*>> MatchesByLength;
  117. for (const StringPair &Match : Matches)
  118. MatchesByLength[Match.first.size()].push_back(&Match);
  119. // Output a switch statement on length and categorize the elements within each
  120. // bin.
  121. OS.indent(Indent*2+2) << "switch (" << StrVariableName << ".size()) {\n";
  122. OS.indent(Indent*2+2) << "default: break;\n";
  123. for (const auto &LI : MatchesByLength) {
  124. OS.indent(Indent * 2 + 2)
  125. << "case " << LI.first << ":\t // " << LI.second.size() << " string"
  126. << (LI.second.size() == 1 ? "" : "s") << " to match.\n";
  127. if (EmitStringMatcherForChar(LI.second, 0, Indent, IgnoreDuplicates))
  128. OS.indent(Indent*2+4) << "break;\n";
  129. }
  130. OS.indent(Indent*2+2) << "}\n";
  131. }