[llvm] [NFC][LowerTypeTests] Move CfiFunctionLinkage and cfi.functions creation to LowerTypeTests (PR #223581)

via llvm-commits llvm-commits at lists.llvm.org
Mon Sep 14 19:24:04 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-analysis

Author: Vitaly Buka (vitalybuka)

<details>
<summary>Changes</summary>

Move enum CfiFunctionLinkage from llvm/Analysis/TypeMetadataUtils.h into
llvm/Transforms/IPO/LowerTypeTests.h (in namespace lowertypetests).

Move hasTypeMetadata and findCfiFunctions into LowerTypeTests.

Encapsulate cfi.functions, aliases, and symvers metadata creation into
lowertypetests::createCfiMetadata, moving the generation logic from
ThinLTOBitcodeWriter into LowerTypeTests.cpp.

Metadata is accessed with:
- cfi.functions: LowerTypeTests, CrossDSOCFI, LTO (Unified LTO mode)
- aliases: LowerTypeTests, LTO (Unified LTO mode)
- symvers: LowerTypeTests


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


4 Files Affected:

- (modified) llvm/include/llvm/Analysis/TypeMetadataUtils.h (-7) 
- (modified) llvm/include/llvm/Transforms/IPO/LowerTypeTests.h (+31-5) 
- (modified) llvm/lib/Transforms/IPO/LowerTypeTests.cpp (+107) 
- (modified) llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp (+5-94) 


``````````diff
diff --git a/llvm/include/llvm/Analysis/TypeMetadataUtils.h b/llvm/include/llvm/Analysis/TypeMetadataUtils.h
index d6f4c8c0e8b54..9e0776e60a038 100644
--- a/llvm/include/llvm/Analysis/TypeMetadataUtils.h
+++ b/llvm/include/llvm/Analysis/TypeMetadataUtils.h
@@ -30,13 +30,6 @@ class GlobalVariable;
 class Instruction;
 class Module;
 
-/// The type of CFI jumptable needed for a function.
-enum CfiFunctionLinkage {
-  CFL_Definition = 0,
-  CFL_Declaration = 1,
-  CFL_WeakDeclaration = 2
-};
-
 /// A call site that could be devirtualized.
 struct DevirtCallSite {
   /// The offset from the address point to the virtual function.
diff --git a/llvm/include/llvm/Transforms/IPO/LowerTypeTests.h b/llvm/include/llvm/Transforms/IPO/LowerTypeTests.h
index b3c275001a9a7..0ea74ff361f4c 100644
--- a/llvm/include/llvm/Transforms/IPO/LowerTypeTests.h
+++ b/llvm/include/llvm/Transforms/IPO/LowerTypeTests.h
@@ -14,19 +14,25 @@
 #ifndef LLVM_TRANSFORMS_IPO_LOWERTYPETESTS_H
 #define LLVM_TRANSFORMS_IPO_LOWERTYPETESTS_H
 
-#include "llvm/ADT/FunctionExtras.h"
-#include "llvm/ADT/STLFunctionalExtras.h"
-#include "llvm/ADT/SmallVector.h"
-#include "llvm/IR/PassManager.h"
-#include "llvm/Support/Compiler.h"
 #include <cstdint>
 #include <cstring>
 #include <limits>
 #include <set>
 #include <vector>
 
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/FunctionExtras.h"
+#include "llvm/ADT/STLFunctionalExtras.h"
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/PassManager.h"
+#include "llvm/Support/Compiler.h"
+
 namespace llvm {
 
+class Function;
+class GlobalObject;
+class GlobalValue;
 class Module;
 class ModuleSummaryIndex;
 class raw_ostream;
@@ -204,8 +210,28 @@ struct ByteArrayBuilder {
                          uint64_t &AllocByteOffset, uint8_t &AllocMask);
 };
 
+/// The type of CFI jumptable needed for a function.
+enum CfiFunctionLinkage {
+  CFL_Definition = 0,
+  CFL_Declaration = 1,
+  CFL_WeakDeclaration = 2
+};
+
 LLVM_ABI bool isJumpTableCanonical(Function *F);
 
+/// Returns whether a global or its associated global has attached type
+/// metadata.
+LLVM_ABI bool hasTypeMetadata(const GlobalObject *GO);
+
+/// Finds all functions and aliases in \p M that may need CFI jump table
+/// entries.
+LLVM_ABI SetVector<GlobalValue *> findCfiFunctions(Module &M);
+
+/// Creates cfi.functions, aliases, and symvers named metadata in \p DestM
+/// for CFI functions in \p CfiFunctions from source module \p SrcM.
+LLVM_ABI void createCfiMetadata(Module &DestM, const Module &SrcM,
+                                ArrayRef<GlobalValue *> CfiFunctions);
+
 /// Specifies how to drop type tests.
 enum class DropTestKind {
   Assume, /// Drop only llvm.assumes using type test value.
diff --git a/llvm/lib/Transforms/IPO/LowerTypeTests.cpp b/llvm/lib/Transforms/IPO/LowerTypeTests.cpp
index 35ec5d795495f..3697972a87f79 100644
--- a/llvm/lib/Transforms/IPO/LowerTypeTests.cpp
+++ b/llvm/lib/Transforms/IPO/LowerTypeTests.cpp
@@ -18,6 +18,7 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/EquivalenceClasses.h"
+#include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SetVector.h"
@@ -64,6 +65,7 @@
 #include "llvm/IR/Use.h"
 #include "llvm/IR/User.h"
 #include "llvm/IR/Value.h"
+#include "llvm/Object/ModuleSymbolTable.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CommandLine.h"
@@ -293,6 +295,111 @@ bool lowertypetests::isJumpTableCanonical(Function *F) {
   return F->hasFnAttribute("cfi-canonical-jump-table");
 }
 
+bool lowertypetests::hasTypeMetadata(const GlobalObject *GO) {
+  if (MDNode *MD = GO->getMetadata(LLVMContext::MD_associated))
+    if (auto *AssocVM = dyn_cast_or_null<ValueAsMetadata>(MD->getOperand(0)))
+      if (auto *AssocGO = dyn_cast<GlobalObject>(AssocVM->getValue()))
+        if (AssocGO->hasMetadata(LLVMContext::MD_type))
+          return true;
+  return GO->hasMetadata(LLVMContext::MD_type);
+}
+
+SetVector<GlobalValue *> lowertypetests::findCfiFunctions(Module &M) {
+  SetVector<GlobalValue *> CfiFunctions;
+  for (auto &F : M)
+    if ((!F.hasLocalLinkage() || F.hasAddressTaken()) && hasTypeMetadata(&F))
+      CfiFunctions.insert(&F);
+  for (auto &A : M.aliases())
+    if (auto *F = dyn_cast<Function>(A.getAliasee()))
+      if (hasTypeMetadata(F))
+        CfiFunctions.insert(&A);
+  return CfiFunctions;
+}
+
+static void createCfiFunctionsMetadata(Module &DestM,
+                                       ArrayRef<GlobalValue *> CfiFunctions) {
+  auto &Ctx = DestM.getContext();
+  SmallVector<MDNode *, 8> CfiFunctionMDs;
+  for (auto *V : CfiFunctions) {
+    Function &F = *cast<Function>(V->getAliaseeObject());
+    SmallVector<MDNode *, 2> Types;
+    F.getMetadata(LLVMContext::MD_type, Types);
+
+    SmallVector<Metadata *, 4> Elts;
+    Elts.push_back(MDString::get(Ctx, V->getName()));
+    CfiFunctionLinkage Linkage;
+    if (lowertypetests::isJumpTableCanonical(&F))
+      Linkage = CFL_Definition;
+    else if (F.hasExternalWeakLinkage())
+      Linkage = CFL_WeakDeclaration;
+    else
+      Linkage = CFL_Declaration;
+    Elts.push_back(ConstantAsMetadata::get(
+        llvm::ConstantInt::get(Type::getInt8Ty(Ctx), Linkage)));
+    GlobalValue::GUID GUID = V->getGUID();
+    Elts.push_back(ConstantAsMetadata::get(
+        llvm::ConstantInt::get(Type::getInt64Ty(Ctx), GUID)));
+    append_range(Elts, Types);
+    CfiFunctionMDs.push_back(MDTuple::get(Ctx, Elts));
+  }
+
+  if (!CfiFunctionMDs.empty()) {
+    NamedMDNode *NMD = DestM.getOrInsertNamedMetadata("cfi.functions");
+    for (auto *MD : CfiFunctionMDs)
+      NMD->addOperand(MD);
+  }
+}
+
+static void createCfiAliasesMetadata(Module &DestM, const Module &SrcM) {
+  auto &Ctx = DestM.getContext();
+  MapVector<const Function *, std::vector<const GlobalAlias *>> FunctionAliases;
+  for (const auto &A : SrcM.aliases()) {
+    if (!isa<Function>(A.getAliasee()))
+      continue;
+
+    const auto *F = cast<Function>(A.getAliasee());
+    FunctionAliases[F].push_back(&A);
+  }
+
+  if (!FunctionAliases.empty()) {
+    NamedMDNode *NMD = DestM.getOrInsertNamedMetadata("aliases");
+    for (auto &Alias : FunctionAliases) {
+      SmallVector<Metadata *> Elts;
+      Elts.push_back(MDString::get(Ctx, Alias.first->getName()));
+      for (auto *A : Alias.second)
+        Elts.push_back(MDString::get(Ctx, A->getName()));
+      NMD->addOperand(MDTuple::get(Ctx, Elts));
+    }
+  }
+}
+
+static void createCfiSymversMetadata(Module &DestM, const Module &SrcM) {
+  auto &Ctx = DestM.getContext();
+  SmallVector<MDNode *, 8> Symvers;
+  ModuleSymbolTable::CollectAsmSymvers(
+      SrcM, [&](StringRef Name, StringRef Alias) {
+        const Function *F = SrcM.getFunction(Name);
+        if (!F || F->use_empty())
+          return;
+
+        Symvers.push_back(MDTuple::get(
+            Ctx, {MDString::get(Ctx, Name), MDString::get(Ctx, Alias)}));
+      });
+
+  if (!Symvers.empty()) {
+    NamedMDNode *NMD = DestM.getOrInsertNamedMetadata("symvers");
+    for (auto *MD : Symvers)
+      NMD->addOperand(MD);
+  }
+}
+
+void lowertypetests::createCfiMetadata(Module &DestM, const Module &SrcM,
+                                       ArrayRef<GlobalValue *> CfiFunctions) {
+  createCfiFunctionsMetadata(DestM, CfiFunctions);
+  createCfiAliasesMetadata(DestM, SrcM);
+  createCfiSymversMetadata(DestM, SrcM);
+}
+
 namespace {
 
 struct ByteArrayInfo {
diff --git a/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp b/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
index cccc49384f921..399f7f3186b8c 100644
--- a/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
+++ b/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
@@ -10,7 +10,6 @@
 #include "llvm/Analysis/BasicAliasAnalysis.h"
 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
 #include "llvm/Analysis/ProfileSummaryInfo.h"
-#include "llvm/Analysis/TypeMetadataUtils.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DebugInfo.h"
@@ -18,7 +17,6 @@
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/PassManager.h"
-#include "llvm/Object/ModuleSymbolTable.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Transforms/IPO.h"
 #include "llvm/Transforms/IPO/FunctionAttrs.h"
@@ -322,21 +320,6 @@ void splitAndWriteThinLTOBitcode(
 
   promoteTypeIds(M, ModuleId);
 
-  // Returns whether a global or its associated global has attached type
-  // metadata. The former may participate in CFI or whole-program
-  // devirtualization, so they need to appear in the merged module instead of
-  // the thin LTO module. Similarly, globals that are associated with globals
-  // with type metadata need to appear in the merged module because they will
-  // reference the global's section directly.
-  auto HasTypeMetadata = [](const GlobalObject *GO) {
-    if (MDNode *MD = GO->getMetadata(LLVMContext::MD_associated))
-      if (auto *AssocVM = dyn_cast_or_null<ValueAsMetadata>(MD->getOperand(0)))
-        if (auto *AssocGO = dyn_cast<GlobalObject>(AssocVM->getValue()))
-          if (AssocGO->hasMetadata(LLVMContext::MD_type))
-            return true;
-    return GO->hasMetadata(LLVMContext::MD_type);
-  };
-
   // Collect the set of virtual functions that are eligible for virtual constant
   // propagation. Each eligible function must not access memory, must return
   // an integer of width <=64 bits, must take at least one argument, must not
@@ -354,7 +337,7 @@ void splitAndWriteThinLTOBitcode(
   // comdat in MergedM to keep the comdat together.
   DenseSet<const Comdat *> MergedMComdats;
   for (GlobalVariable &GV : M.globals())
-    if (!GV.isDeclaration() && HasTypeMetadata(&GV)) {
+    if (!GV.isDeclaration() && lowertypetests::hasTypeMetadata(&GV)) {
       if (const auto *C = GV.getComdat())
         MergedMComdats.insert(C);
       forEachVirtualFunction(GV.getInitializer(), [&](Function *F) {
@@ -386,7 +369,7 @@ void splitAndWriteThinLTOBitcode(
           return EligibleVirtualFns.count(F);
         if (auto *GVar =
                 dyn_cast_or_null<GlobalVariable>(GV->getAliaseeObject()))
-          return HasTypeMetadata(GVar);
+          return lowertypetests::hasTypeMetadata(GVar);
         return false;
       }));
   StripDebugInfo(*MergedM);
@@ -406,20 +389,13 @@ void splitAndWriteThinLTOBitcode(
       F.setComdat(nullptr);
     }
 
-  SetVector<GlobalValue *> CfiFunctions;
-  for (auto &F : M)
-    if ((!F.hasLocalLinkage() || F.hasAddressTaken()) && HasTypeMetadata(&F))
-      CfiFunctions.insert(&F);
-  for (auto &A : M.aliases())
-    if (auto *F = dyn_cast<Function>(A.getAliasee()))
-      if (HasTypeMetadata(F))
-        CfiFunctions.insert(&A);
+  SetVector<GlobalValue *> CfiFunctions = lowertypetests::findCfiFunctions(M);
 
   // Remove all globals with type metadata, globals with comdats that live in
   // MergedM, and aliases pointing to such globals from the thin LTO module.
   filterModule(&M, [&](const GlobalValue *GV) {
     if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getAliaseeObject()))
-      if (HasTypeMetadata(GVar))
+      if (lowertypetests::hasTypeMetadata(GVar))
         return false;
     if (const auto *C = GV->getComdat())
       if (MergedMComdats.count(C))
@@ -436,72 +412,7 @@ void splitAndWriteThinLTOBitcode(
   promoteInternals(*MergedM, M, ModuleId, {});
   promoteInternals(M, *MergedM, ModuleId, CfiFunctions);
 
-  auto &Ctx = MergedM->getContext();
-  SmallVector<MDNode *, 8> CfiFunctionMDs;
-  for (auto *V : CfiFunctions) {
-    Function &F = *cast<Function>(V->getAliaseeObject());
-    SmallVector<MDNode *, 2> Types;
-    F.getMetadata(LLVMContext::MD_type, Types);
-
-    SmallVector<Metadata *, 4> Elts;
-    Elts.push_back(MDString::get(Ctx, V->getName()));
-    CfiFunctionLinkage Linkage;
-    if (lowertypetests::isJumpTableCanonical(&F))
-      Linkage = CFL_Definition;
-    else if (F.hasExternalWeakLinkage())
-      Linkage = CFL_WeakDeclaration;
-    else
-      Linkage = CFL_Declaration;
-    Elts.push_back(ConstantAsMetadata::get(
-        llvm::ConstantInt::get(Type::getInt8Ty(Ctx), Linkage)));
-    GlobalValue::GUID GUID = V->getGUID();
-    Elts.push_back(ConstantAsMetadata::get(
-        llvm::ConstantInt::get(Type::getInt64Ty(Ctx), GUID)));
-    append_range(Elts, Types);
-    CfiFunctionMDs.push_back(MDTuple::get(Ctx, Elts));
-  }
-
-  if(!CfiFunctionMDs.empty()) {
-    NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("cfi.functions");
-    for (auto *MD : CfiFunctionMDs)
-      NMD->addOperand(MD);
-  }
-
-  MapVector<Function *, std::vector<GlobalAlias *>> FunctionAliases;
-  for (auto &A : M.aliases()) {
-    if (!isa<Function>(A.getAliasee()))
-      continue;
-
-    auto *F = cast<Function>(A.getAliasee());
-    FunctionAliases[F].push_back(&A);
-  }
-
-  if (!FunctionAliases.empty()) {
-    NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("aliases");
-    for (auto &Alias : FunctionAliases) {
-      SmallVector<Metadata *> Elts;
-      Elts.push_back(MDString::get(Ctx, Alias.first->getName()));
-      for (auto *A : Alias.second)
-        Elts.push_back(MDString::get(Ctx, A->getName()));
-      NMD->addOperand(MDTuple::get(Ctx, Elts));
-    }
-  }
-
-  SmallVector<MDNode *, 8> Symvers;
-  ModuleSymbolTable::CollectAsmSymvers(M, [&](StringRef Name, StringRef Alias) {
-    Function *F = M.getFunction(Name);
-    if (!F || F->use_empty())
-      return;
-
-    Symvers.push_back(MDTuple::get(
-        Ctx, {MDString::get(Ctx, Name), MDString::get(Ctx, Alias)}));
-  });
-
-  if (!Symvers.empty()) {
-    NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("symvers");
-    for (auto *MD : Symvers)
-      NMD->addOperand(MD);
-  }
+  lowertypetests::createCfiMetadata(*MergedM, M, CfiFunctions.getArrayRef());
 
   simplifyExternals(*MergedM);
 

``````````

</details>


https://github.com/llvm/llvm-project/pull/223581


More information about the llvm-commits mailing list