[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

Fangrui Song via cfe-commits cfe-commits at lists.llvm.org
Mon Apr 1 23:23:59 PDT 2024


================
@@ -1980,6 +1981,23 @@ static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
 }
 
+// Mark alias/ifunc target as used. For C++, we look up the demangled name
+// ignoring parameters. This should handle the majority of use cases while
+// leaveing false positives for namespace scope names and false negatives in
+// the presence of overloads.
+static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
+                                    StringRef Str) {
+  char *Demangled = llvm::itaniumDemangle(Str, /*ParseParams=*/false);
+  if (Demangled)
+    Str = Demangled;
+  const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
+  LookupResult LR(S, target, Sema::LookupOrdinaryName);
+  if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
+    for (NamedDecl *ND : LR)
+      ND->markUsed(S.Context);
----------------
MaskRay wrote:

"alias" can target variables. "ifunc" has an existing diagnostic to reject non-function targets.
```
% cat a.c
static int x;
extern void y() __attribute__((ifunc("x")));
% clang -c a.c
a.c:2:32: error: ifunc must point to a defined function
    2 | extern void y() __attribute__((ifunc("x")));
      |                                ^
1 error generated.
```

I am adding a template test:
```cpp
template <class T>
static void *f3(T) { return nullptr; }
static void *f3() { return nullptr; } // expected-warning{{unused function 'f3'}}
extern void g3() __attribute__((ifunc("_ZL2f3IiEPvT_")));
void *use3 = f3(0);
```

I think the current code does the right thing for templates.

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


More information about the cfe-commits mailing list