112c1cd33SDouglas Gregor //===- StringMatcher.cpp - Generate a matcher for input strings -----------===//
212c1cd33SDouglas Gregor //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
612c1cd33SDouglas Gregor //
712c1cd33SDouglas Gregor //===----------------------------------------------------------------------===//
812c1cd33SDouglas Gregor //
912c1cd33SDouglas Gregor // This file implements the StringMatcher class.
1012c1cd33SDouglas Gregor //
1112c1cd33SDouglas Gregor //===----------------------------------------------------------------------===//
1212c1cd33SDouglas Gregor 
136bda14b3SChandler Carruth #include "llvm/TableGen/StringMatcher.h"
14b2ca1b3fSEugene Zelenko #include "llvm/ADT/StringRef.h"
1512c1cd33SDouglas Gregor #include "llvm/Support/raw_ostream.h"
16b2ca1b3fSEugene Zelenko #include <cassert>
1712c1cd33SDouglas Gregor #include <map>
18b2ca1b3fSEugene Zelenko #include <string>
19b2ca1b3fSEugene Zelenko #include <utility>
20b2ca1b3fSEugene Zelenko #include <vector>
21b2ca1b3fSEugene Zelenko 
2212c1cd33SDouglas Gregor using namespace llvm;
2312c1cd33SDouglas Gregor 
2412c1cd33SDouglas Gregor /// FindFirstNonCommonLetter - Find the first character in the keys of the
2512c1cd33SDouglas Gregor /// string pairs that is not shared across the whole set of strings.  All
2612c1cd33SDouglas Gregor /// strings are assumed to have the same length.
2712c1cd33SDouglas Gregor static unsigned
FindFirstNonCommonLetter(const std::vector<const StringMatcher::StringPair * > & Matches)2812c1cd33SDouglas Gregor FindFirstNonCommonLetter(const std::vector<const
2912c1cd33SDouglas Gregor                               StringMatcher::StringPair*> &Matches) {
3012c1cd33SDouglas Gregor   assert(!Matches.empty());
3112c1cd33SDouglas Gregor   for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
3212c1cd33SDouglas Gregor     // Check to see if letter i is the same across the set.
3312c1cd33SDouglas Gregor     char Letter = Matches[0]->first[i];
3412c1cd33SDouglas Gregor 
35*d395befaSKazu Hirata     for (const StringMatcher::StringPair *Match : Matches)
36*d395befaSKazu Hirata       if (Match->first[i] != Letter)
3712c1cd33SDouglas Gregor         return i;
3812c1cd33SDouglas Gregor   }
3912c1cd33SDouglas Gregor 
4012c1cd33SDouglas Gregor   return Matches[0]->first.size();
4112c1cd33SDouglas Gregor }
4212c1cd33SDouglas Gregor 
4312c1cd33SDouglas Gregor /// EmitStringMatcherForChar - Given a set of strings that are known to be the
4412c1cd33SDouglas Gregor /// same length and whose characters leading up to CharNo are the same, emit
4512c1cd33SDouglas Gregor /// code to verify that CharNo and later are the same.
4612c1cd33SDouglas Gregor ///
4712c1cd33SDouglas Gregor /// \return - True if control can leave the emitted code fragment.
EmitStringMatcherForChar(const std::vector<const StringPair * > & Matches,unsigned CharNo,unsigned IndentCount,bool IgnoreDuplicates) const48d590c857SAlex Bradbury bool StringMatcher::EmitStringMatcherForChar(
49d590c857SAlex Bradbury     const std::vector<const StringPair *> &Matches, unsigned CharNo,
50d590c857SAlex Bradbury     unsigned IndentCount, bool IgnoreDuplicates) const {
5112c1cd33SDouglas Gregor   assert(!Matches.empty() && "Must have at least one string to match!");
5212c1cd33SDouglas Gregor   std::string Indent(IndentCount * 2 + 4, ' ');
5312c1cd33SDouglas Gregor 
5412c1cd33SDouglas Gregor   // If we have verified that the entire string matches, we're done: output the
5512c1cd33SDouglas Gregor   // matching code.
5612c1cd33SDouglas Gregor   if (CharNo == Matches[0]->first.size()) {
57d590c857SAlex Bradbury     if (Matches.size() > 1 && !IgnoreDuplicates)
58d590c857SAlex Bradbury       report_fatal_error("Had duplicate keys to match on");
5912c1cd33SDouglas Gregor 
6012c1cd33SDouglas Gregor     // If the to-execute code has \n's in it, indent each subsequent line.
6112c1cd33SDouglas Gregor     StringRef Code = Matches[0]->second;
6212c1cd33SDouglas Gregor 
6312c1cd33SDouglas Gregor     std::pair<StringRef, StringRef> Split = Code.split('\n');
6412c1cd33SDouglas Gregor     OS << Indent << Split.first << "\t // \"" << Matches[0]->first << "\"\n";
6512c1cd33SDouglas Gregor 
6612c1cd33SDouglas Gregor     Code = Split.second;
6712c1cd33SDouglas Gregor     while (!Code.empty()) {
6812c1cd33SDouglas Gregor       Split = Code.split('\n');
6912c1cd33SDouglas Gregor       OS << Indent << Split.first << "\n";
7012c1cd33SDouglas Gregor       Code = Split.second;
7112c1cd33SDouglas Gregor     }
7212c1cd33SDouglas Gregor     return false;
7312c1cd33SDouglas Gregor   }
7412c1cd33SDouglas Gregor 
7512c1cd33SDouglas Gregor   // Bucket the matches by the character we are comparing.
7612c1cd33SDouglas Gregor   std::map<char, std::vector<const StringPair*>> MatchesByLetter;
7712c1cd33SDouglas Gregor 
78*d395befaSKazu Hirata   for (const StringPair *Match : Matches)
79*d395befaSKazu Hirata     MatchesByLetter[Match->first[CharNo]].push_back(Match);
8012c1cd33SDouglas Gregor 
8112c1cd33SDouglas Gregor   // If we have exactly one bucket to match, see how many characters are common
8212c1cd33SDouglas Gregor   // across the whole set and match all of them at once.
8312c1cd33SDouglas Gregor   if (MatchesByLetter.size() == 1) {
8412c1cd33SDouglas Gregor     unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
8512c1cd33SDouglas Gregor     unsigned NumChars = FirstNonCommonLetter-CharNo;
8612c1cd33SDouglas Gregor 
8712c1cd33SDouglas Gregor     // Emit code to break out if the prefix doesn't match.
8812c1cd33SDouglas Gregor     if (NumChars == 1) {
8912c1cd33SDouglas Gregor       // Do the comparison with if (Str[1] != 'f')
9012c1cd33SDouglas Gregor       // FIXME: Need to escape general characters.
9112c1cd33SDouglas Gregor       OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
9212c1cd33SDouglas Gregor       << Matches[0]->first[CharNo] << "')\n";
9312c1cd33SDouglas Gregor       OS << Indent << "  break;\n";
9412c1cd33SDouglas Gregor     } else {
95a4055582SBenjamin Kramer       // Do the comparison with if memcmp(Str.data()+1, "foo", 3).
9612c1cd33SDouglas Gregor       // FIXME: Need to escape general strings.
97a4055582SBenjamin Kramer       OS << Indent << "if (memcmp(" << StrVariableName << ".data()+" << CharNo
98a4055582SBenjamin Kramer          << ", \"" << Matches[0]->first.substr(CharNo, NumChars) << "\", "
99b2ca1b3fSEugene Zelenko          << NumChars << ") != 0)\n";
10012c1cd33SDouglas Gregor       OS << Indent << "  break;\n";
10112c1cd33SDouglas Gregor     }
10212c1cd33SDouglas Gregor 
103d590c857SAlex Bradbury     return EmitStringMatcherForChar(Matches, FirstNonCommonLetter, IndentCount,
104d590c857SAlex Bradbury                                     IgnoreDuplicates);
10512c1cd33SDouglas Gregor   }
10612c1cd33SDouglas Gregor 
10712c1cd33SDouglas Gregor   // Otherwise, we have multiple possible things, emit a switch on the
10812c1cd33SDouglas Gregor   // character.
10912c1cd33SDouglas Gregor   OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
11012c1cd33SDouglas Gregor   OS << Indent << "default: break;\n";
11112c1cd33SDouglas Gregor 
112dd9a6411SKazu Hirata   for (const auto &LI : MatchesByLetter) {
11312c1cd33SDouglas Gregor     // TODO: escape hard stuff (like \n) if we ever care about it.
114dd9a6411SKazu Hirata     OS << Indent << "case '" << LI.first << "':\t // " << LI.second.size()
115dd9a6411SKazu Hirata        << " string";
116dd9a6411SKazu Hirata     if (LI.second.size() != 1)
117dd9a6411SKazu Hirata       OS << 's';
11812c1cd33SDouglas Gregor     OS << " to match.\n";
119dd9a6411SKazu Hirata     if (EmitStringMatcherForChar(LI.second, CharNo + 1, IndentCount + 1,
120d590c857SAlex Bradbury                                  IgnoreDuplicates))
12112c1cd33SDouglas Gregor       OS << Indent << "  break;\n";
12212c1cd33SDouglas Gregor   }
12312c1cd33SDouglas Gregor 
12412c1cd33SDouglas Gregor   OS << Indent << "}\n";
12512c1cd33SDouglas Gregor   return true;
12612c1cd33SDouglas Gregor }
12712c1cd33SDouglas Gregor 
12812c1cd33SDouglas Gregor /// Emit - Top level entry point.
12912c1cd33SDouglas Gregor ///
Emit(unsigned Indent,bool IgnoreDuplicates) const130d590c857SAlex Bradbury void StringMatcher::Emit(unsigned Indent, bool IgnoreDuplicates) const {
13112c1cd33SDouglas Gregor   // If nothing to match, just fall through.
13212c1cd33SDouglas Gregor   if (Matches.empty()) return;
13312c1cd33SDouglas Gregor 
13412c1cd33SDouglas Gregor   // First level categorization: group strings by length.
13512c1cd33SDouglas Gregor   std::map<unsigned, std::vector<const StringPair*>> MatchesByLength;
13612c1cd33SDouglas Gregor 
137*d395befaSKazu Hirata   for (const StringPair &Match : Matches)
138*d395befaSKazu Hirata     MatchesByLength[Match.first.size()].push_back(&Match);
13912c1cd33SDouglas Gregor 
14012c1cd33SDouglas Gregor   // Output a switch statement on length and categorize the elements within each
14112c1cd33SDouglas Gregor   // bin.
14212c1cd33SDouglas Gregor   OS.indent(Indent*2+2) << "switch (" << StrVariableName << ".size()) {\n";
14312c1cd33SDouglas Gregor   OS.indent(Indent*2+2) << "default: break;\n";
14412c1cd33SDouglas Gregor 
145dd9a6411SKazu Hirata   for (const auto &LI : MatchesByLength) {
146dd9a6411SKazu Hirata     OS.indent(Indent * 2 + 2)
147dd9a6411SKazu Hirata         << "case " << LI.first << ":\t // " << LI.second.size() << " string"
148dd9a6411SKazu Hirata         << (LI.second.size() == 1 ? "" : "s") << " to match.\n";
149dd9a6411SKazu Hirata     if (EmitStringMatcherForChar(LI.second, 0, Indent, IgnoreDuplicates))
15012c1cd33SDouglas Gregor       OS.indent(Indent*2+4) << "break;\n";
15112c1cd33SDouglas Gregor   }
15212c1cd33SDouglas Gregor 
15312c1cd33SDouglas Gregor   OS.indent(Indent*2+2) << "}\n";
15412c1cd33SDouglas Gregor }
155