Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Clang][TableGen] Use StringRef::str() instead of std::string() cast #113645

Merged
merged 1 commit into from
Oct 28, 2024

Conversation

jurahul
Copy link
Contributor

@jurahul jurahul commented Oct 25, 2024

Use StringRef::str() instead of std::string(StringRef) to cast from StringRef to std::string.

@jurahul jurahul marked this pull request as ready for review October 25, 2024 17:20
@llvmbot llvmbot added the clang Clang issues not falling into any other category label Oct 25, 2024
@llvmbot
Copy link
Member

llvmbot commented Oct 25, 2024

@llvm/pr-subscribers-clang

Author: Rahul Joshi (jurahul)

Changes

Use StringRef::str() instead of std::string(StringRef) to cast from StringRef to std::string.


Full diff: https://github.com/llvm/llvm-project/pull/113645.diff

4 Files Affected:

  • (modified) clang/utils/TableGen/ClangAttrEmitter.cpp (+41-49)
  • (modified) clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp (+1-1)
  • (modified) clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp (+1-1)
  • (modified) clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp (+2-2)
diff --git a/clang/utils/TableGen/ClangAttrEmitter.cpp b/clang/utils/TableGen/ClangAttrEmitter.cpp
index 4890d249c6d8f7..d33545b86a5aac 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -54,19 +54,18 @@ class FlattenedSpelling {
   const Record &OriginalSpelling;
 
 public:
-  FlattenedSpelling(const std::string &Variety, const std::string &Name,
+  FlattenedSpelling(const std::string &Variety, StringRef Name,
                     const std::string &Namespace, bool KnownToGCC,
                     const Record &OriginalSpelling)
-      : V(Variety), N(Name), NS(Namespace), K(KnownToGCC),
+      : V(Variety), N(Name.str()), NS(Namespace), K(KnownToGCC),
         OriginalSpelling(OriginalSpelling) {}
   explicit FlattenedSpelling(const Record &Spelling)
-      : V(std::string(Spelling.getValueAsString("Variety"))),
-        N(std::string(Spelling.getValueAsString("Name"))),
-        OriginalSpelling(Spelling) {
+      : V(Spelling.getValueAsString("Variety").str()),
+        N(Spelling.getValueAsString("Name").str()), OriginalSpelling(Spelling) {
     assert(V != "GCC" && V != "Clang" &&
            "Given a GCC spelling, which means this hasn't been flattened!");
     if (V == "CXX11" || V == "C23" || V == "Pragma")
-      NS = std::string(Spelling.getValueAsString("Namespace"));
+      NS = Spelling.getValueAsString("Namespace").str();
   }
 
   const std::string &variety() const { return V; }
@@ -105,15 +104,15 @@ GetFlattenedSpellings(const Record &Attr) {
     StringRef Variety = Spelling->getValueAsString("Variety");
     StringRef Name = Spelling->getValueAsString("Name");
     if (Variety == "GCC") {
-      Ret.emplace_back("GNU", std::string(Name), "", true, *Spelling);
-      Ret.emplace_back("CXX11", std::string(Name), "gnu", true, *Spelling);
+      Ret.emplace_back("GNU", Name, "", true, *Spelling);
+      Ret.emplace_back("CXX11", Name, "gnu", true, *Spelling);
       if (Spelling->getValueAsBit("AllowInC"))
-        Ret.emplace_back("C23", std::string(Name), "gnu", true, *Spelling);
+        Ret.emplace_back("C23", Name, "gnu", true, *Spelling);
     } else if (Variety == "Clang") {
-      Ret.emplace_back("GNU", std::string(Name), "", false, *Spelling);
-      Ret.emplace_back("CXX11", std::string(Name), "clang", false, *Spelling);
+      Ret.emplace_back("GNU", Name, "", false, *Spelling);
+      Ret.emplace_back("CXX11", Name, "clang", false, *Spelling);
       if (Spelling->getValueAsBit("AllowInC"))
-        Ret.emplace_back("C23", std::string(Name), "clang", false, *Spelling);
+        Ret.emplace_back("C23", Name, "clang", false, *Spelling);
     } else
       Ret.push_back(FlattenedSpelling(*Spelling));
   }
@@ -123,9 +122,7 @@ GetFlattenedSpellings(const Record &Attr) {
 
 static std::string ReadPCHRecord(StringRef type) {
   return StringSwitch<std::string>(type)
-      .EndsWith("Decl *", "Record.readDeclAs<" +
-                              std::string(type.data(), 0, type.size() - 1) +
-                              ">()")
+      .EndsWith("Decl *", "Record.readDeclAs<" + type.drop_back().str() + ">()")
       .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
       .Case("Expr *", "Record.readExpr()")
       .Case("IdentifierInfo *", "Record.readIdentifier()")
@@ -146,18 +143,16 @@ static StringRef getStorageType(StringRef type) {
 static std::string WritePCHRecord(StringRef type, StringRef name) {
   return "Record." +
          StringSwitch<std::string>(type)
-             .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
+             .EndsWith("Decl *", "AddDeclRef(" + name.str() + ");\n")
              .Case("TypeSourceInfo *",
-                   "AddTypeSourceInfo(" + std::string(name) + ");\n")
-             .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
+                   "AddTypeSourceInfo(" + name.str() + ");\n")
+             .Case("Expr *", "AddStmt(" + name.str() + ");\n")
              .Case("IdentifierInfo *",
-                   "AddIdentifierRef(" + std::string(name) + ");\n")
-             .Case("StringRef", "AddString(" + std::string(name) + ");\n")
-             .Case("ParamIdx",
-                   "push_back(" + std::string(name) + ".serialize());\n")
-             .Case("OMPTraitInfo *",
-                   "writeOMPTraitInfo(" + std::string(name) + ");\n")
-             .Default("push_back(" + std::string(name) + ");\n");
+                   "AddIdentifierRef(" + name.str() + ");\n")
+             .Case("StringRef", "AddString(" + name.str() + ");\n")
+             .Case("ParamIdx", "push_back(" + name.str() + ".serialize());\n")
+             .Case("OMPTraitInfo *", "writeOMPTraitInfo(" + name.str() + ");\n")
+             .Default("push_back(" + name.str() + ");\n");
 }
 
 // Normalize attribute name by removing leading and trailing
@@ -198,7 +193,7 @@ static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
       std::string AN;
       if (Attr->isSubClassOf("TargetSpecificAttr") &&
           !Attr->isValueUnset("ParseKind")) {
-        AN = std::string(Attr->getValueAsString("ParseKind"));
+        AN = Attr->getValueAsString("ParseKind").str();
 
         // If this attribute has already been handled, it does not need to be
         // handled again.
@@ -226,7 +221,7 @@ namespace {
 
   public:
     Argument(StringRef Arg, StringRef Attr)
-        : lowerName(std::string(Arg)), upperName(lowerName), attrName(Attr),
+        : lowerName(Arg.str()), upperName(lowerName), attrName(Attr),
           isOpt(false), Fake(false) {
       if (!lowerName.empty()) {
         lowerName[0] = std::tolower(lowerName[0]);
@@ -332,8 +327,7 @@ namespace {
 
     void writePCHWrite(raw_ostream &OS) const override {
       OS << "    "
-         << WritePCHRecord(type,
-                           "SA->get" + std::string(getUpperName()) + "()");
+         << WritePCHRecord(type, "SA->get" + getUpperName().str() + "()");
     }
 
     std::string getIsOmitted() const override {
@@ -699,12 +693,12 @@ namespace {
     VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
         : Argument(Arg, Attr), Type(std::move(T)),
           ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
-          RangeName(std::string(getLowerName())) {}
+          RangeName(getLowerName().str()) {}
 
     VariadicArgument(StringRef Arg, StringRef Attr, std::string T)
         : Argument(Arg, Attr), Type(std::move(T)),
           ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
-          RangeName(std::string(getLowerName())) {}
+          RangeName(getLowerName().str()) {}
 
     const std::string &getType() const { return Type; }
     const std::string &getArgName() const { return ArgName; }
@@ -793,8 +787,8 @@ namespace {
       // If we can't store the values in the current type (if it's something
       // like StringRef), store them in a different type and convert the
       // container afterwards.
-      std::string StorageType = std::string(getStorageType(getType()));
-      std::string StorageName = std::string(getLowerName());
+      std::string StorageType = getStorageType(getType()).str();
+      std::string StorageName = getLowerName().str();
       if (StorageType != getType()) {
         StorageName += "Storage";
         OS << "    SmallVector<" << StorageType << ", 4> "
@@ -1082,8 +1076,7 @@ namespace {
 
   public:
     VariadicEnumArgument(const Record &Arg, StringRef Attr)
-        : VariadicArgument(Arg, Attr,
-                           std::string(Arg.getValueAsString("Type"))),
+        : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type").str()),
           values(Arg.getValueAsListOfStrings("Values")),
           enums(Arg.getValueAsListOfStrings("Enums")),
           uniques(uniqueEnumsInOrder(enums)),
@@ -1438,7 +1431,7 @@ namespace {
     void writePCHWrite(raw_ostream &OS) const override {
       OS << "    "
          << WritePCHRecord(getType(),
-                           "SA->get" + std::string(getUpperName()) + "Loc()");
+                           "SA->get" + getUpperName().str() + "Loc()");
     }
   };
 
@@ -1771,11 +1764,10 @@ static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
 static bool
 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
   assert(!Spellings.empty() && "An empty list of spellings was provided");
-  std::string FirstName =
-      std::string(NormalizeNameForSpellingComparison(Spellings.front().name()));
+  StringRef FirstName =
+      NormalizeNameForSpellingComparison(Spellings.front().name());
   for (const auto &Spelling : drop_begin(Spellings)) {
-    std::string Name =
-        std::string(NormalizeNameForSpellingComparison(Spelling.name()));
+    StringRef Name = NormalizeNameForSpellingComparison(Spelling.name());
     if (Name != FirstName)
       return false;
   }
@@ -1990,7 +1982,7 @@ struct AttributeSubjectMatchRule {
   }
 
   std::string getSpelling() const {
-    std::string Result = std::string(MetaSubject->getValueAsString("Name"));
+    std::string Result = MetaSubject->getValueAsString("Name").str();
     if (isSubRule()) {
       Result += '(';
       if (isNegatedSubRule())
@@ -2750,7 +2742,7 @@ static void emitAttributes(const RecordKeeper &Records, raw_ostream &OS,
     for (const auto &[R, _] : reverse(Supers)) {
       if (R->getName() != "TargetSpecificAttr" &&
           R->getName() != "DeclOrTypeAttr" && SuperName.empty())
-        SuperName = std::string(R->getName());
+        SuperName = R->getName().str();
       if (R->getName() == "InheritableAttr")
         Inheritable = true;
     }
@@ -4086,9 +4078,9 @@ static void emitArgInfo(const Record &R, raw_ostream &OS) {
 }
 
 static std::string GetDiagnosticSpelling(const Record &R) {
-  std::string Ret = std::string(R.getValueAsString("DiagSpelling"));
+  StringRef Ret = R.getValueAsString("DiagSpelling");
   if (!Ret.empty())
-    return Ret;
+    return Ret.str();
 
   // If we couldn't find the DiagSpelling in this object, we can check to see
   // if the object is one that has a base, and if it is, loop up to the Base
@@ -4121,7 +4113,7 @@ static std::string CalculateDiagnostic(const Record &S) {
       SmallVector<StringRef, 2> Frags;
       SplitString(V, Frags, ",");
       for (auto Str : Frags) {
-        DiagList.push_back(std::string(Str.trim()));
+        DiagList.push_back(Str.trim().str());
       }
     }
   }
@@ -4152,7 +4144,7 @@ static std::string CalculateDiagnostic(const Record &S) {
 }
 
 static std::string GetSubjectWithSuffix(const Record *R) {
-  const std::string &B = std::string(R->getName());
+  const std::string B = R->getName().str();
   if (B == "DeclBase")
     return "Decl";
   return B + "Decl";
@@ -4861,7 +4853,7 @@ void EmitClangAttrParsedAttrKinds(const RecordKeeper &Records,
       std::string AttrName;
       if (Attr.isSubClassOf("TargetSpecificAttr") &&
           !Attr.isValueUnset("ParseKind")) {
-        AttrName = std::string(Attr.getValueAsString("ParseKind"));
+        AttrName = Attr.getValueAsString("ParseKind").str();
         if (!Seen.insert(AttrName).second)
           continue;
       } else
@@ -5134,7 +5126,7 @@ GetAttributeHeadingAndSpellings(const Record &Documentation,
                     "documented");
 
   // Determine the heading to be used for this attribute.
-  std::string Heading = std::string(Documentation.getValueAsString("Heading"));
+  std::string Heading = Documentation.getValueAsString("Heading").str();
   if (Heading.empty()) {
     // If there's only one spelling, we can simply use that.
     if (Spellings.size() == 1)
@@ -5144,7 +5136,7 @@ GetAttributeHeadingAndSpellings(const Record &Documentation,
       for (auto I = Spellings.begin(), E = Spellings.end();
            I != E; ++I) {
         std::string Spelling =
-            std::string(NormalizeNameForSpellingComparison(I->name()));
+            NormalizeNameForSpellingComparison(I->name()).str();
         Uniques.insert(Spelling);
       }
       // If the semantic map has only one spelling, that is sufficient for our
diff --git a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
index 1a2503dcf660cf..45a97425ef920a 100644
--- a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
@@ -63,7 +63,7 @@ void clang::EmitClangCommentCommandInfo(const RecordKeeper &Records,
   std::vector<StringMatcher::StringPair> Matches;
   for (size_t i = 0, e = Tags.size(); i != e; ++i) {
     const Record &Tag = *Tags[i];
-    std::string Name = std::string(Tag.getValueAsString("Name"));
+    std::string Name = Tag.getValueAsString("Name").str();
     std::string Return;
     raw_string_ostream(Return) << "return &Commands[" << i << "];";
     Matches.emplace_back(std::move(Name), std::move(Return));
diff --git a/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp b/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
index bd75b3f6b652a1..2d615760814e01 100644
--- a/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
@@ -51,7 +51,7 @@ void clang::EmitClangCommentHTMLNamedCharacterReferences(
   std::vector<StringMatcher::StringPair> NameToUTF8;
   SmallString<32> CLiteral;
   for (const Record *Tag : Records.getAllDerivedDefinitions("NCR")) {
-    std::string Spelling = std::string(Tag->getValueAsString("Spelling"));
+    std::string Spelling = Tag->getValueAsString("Spelling").str();
     uint64_t CodePoint = Tag->getValueAsInt("CodePoint");
     CLiteral.clear();
     CLiteral.append("return ");
diff --git a/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp b/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
index a457315bc62c5c..7d65cfe0d3f529 100644
--- a/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
@@ -24,7 +24,7 @@ void clang::EmitClangCommentHTMLTags(const RecordKeeper &Records,
   ArrayRef<const Record *> Tags = Records.getAllDerivedDefinitions("Tag");
   std::vector<StringMatcher::StringPair> Matches;
   for (const Record *Tag : Tags) {
-    Matches.emplace_back(std::string(Tag->getValueAsString("Spelling")),
+    Matches.emplace_back(Tag->getValueAsString("Spelling").str(),
                          "return true;");
   }
 
@@ -42,7 +42,7 @@ void clang::EmitClangCommentHTMLTagsProperties(const RecordKeeper &Records,
   std::vector<StringMatcher::StringPair> MatchesEndTagOptional;
   std::vector<StringMatcher::StringPair> MatchesEndTagForbidden;
   for (const Record *Tag : Tags) {
-    std::string Spelling = std::string(Tag->getValueAsString("Spelling"));
+    std::string Spelling = Tag->getValueAsString("Spelling").str();
     StringMatcher::StringPair Match(Spelling, "return true;");
     if (Tag->getValueAsBit("EndTagOptional"))
       MatchesEndTagOptional.push_back(Match);

Copy link
Collaborator

@AaronBallman AaronBallman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@jurahul
Copy link
Contributor Author

jurahul commented Oct 28, 2024

Thanks. I'll queue this behind #113809.

Use `StringRef::str()` instead of std::string(StringRef) to cast from
StringRef to std::string.
@jurahul jurahul force-pushed the clang_tablegen_std_string branch from c160176 to 9192413 Compare October 28, 2024 18:50
@jurahul jurahul merged commit 8e6856e into llvm:main Oct 28, 2024
8 checks passed
@jurahul jurahul deleted the clang_tablegen_std_string branch October 28, 2024 23:15
NoumanAmir657 pushed a commit to NoumanAmir657/llvm-project that referenced this pull request Nov 4, 2024
…lvm#113645)

Use `StringRef::str()` instead of std::string(StringRef) to cast from
StringRef to std::string.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
clang Clang issues not falling into any other category
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants