[clang] Warning for incorrect useof 'pure' attribute (PR #78200)

Aaron Ballman via cfe-commits cfe-commits at lists.llvm.org
Wed Jan 17 08:51:03 PST 2024


================
@@ -11792,6 +11792,26 @@ static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
                                          OldDecl, Previous);
 }
 
+static void CheckFunctionDeclarationAttributesUsage(Sema &S,
+                                                    FunctionDecl *NewFD) {
+  bool IsPure = NewFD->hasAttr<PureAttr>();
+  bool IsConst = NewFD->hasAttr<ConstAttr>();
+
+  if (IsPure && IsConst) {
+    S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
+    NewFD->dropAttr<PureAttr>();
+  }
+  if (IsPure || IsConst) {
+    // constructors and destructors also functions which returns void
+    if (NewFD->getReturnType()->isVoidType()) {
+      S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
+          << IsConst;
+      NewFD->dropAttr<PureAttr>();
+      NewFD->dropAttr<ConstAttr>();
----------------
AaronBallman wrote:

I see the following cases where we'd use that:

https://github.com/llvm/llvm-project/blob/a96b4671b97b167230986bd2811676064c608596/clang/lib/Sema/SemaDecl.cpp#L7071
https://github.com/llvm/llvm-project/blob/a96b4671b97b167230986bd2811676064c608596/clang/lib/Sema/SemaDecl.cpp#L7264
https://github.com/llvm/llvm-project/blob/a96b4671b97b167230986bd2811676064c608596/clang/lib/Sema/SemaDecl.cpp#L7270
https://github.com/llvm/llvm-project/blob/5b65f6f5864ff23e4d87ab1d954a77be343b4c4b/clang/lib/Sema/SemaDeclCXX.cpp#L6548
https://github.com/llvm/llvm-project/blob/5b65f6f5864ff23e4d87ab1d954a77be343b4c4b/clang/lib/Sema/SemaTemplate.cpp#L9233

so it's not the most common pattern in the world but it would simplify some code. I would name it `dropAttrs()` though so it's clear that it drops all of the attributes, not just one of them. I wouldn't insist on introducing the API for this patch, but it would be a reasonable follow-up.

(FWIW, `hasAttr` would be a bigger win in terms of variadic template support.)

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


More information about the cfe-commits mailing list