Skip to content

[attributes][analyzer] Generalize [[clang::suppress]] to declarations. #80371

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions clang/include/clang/Basic/Attr.td
Original file line number Diff line number Diff line change
Expand Up @@ -2891,6 +2891,13 @@ def Suppress : DeclOrStmtAttr {
let Spellings = [CXX11<"gsl", "suppress">, Clang<"suppress">];
let Args = [VariadicStringArgument<"DiagnosticIdentifiers">];
let Accessors = [Accessor<"isGSL", [CXX11<"gsl", "suppress">]>];
// There's no fundamental reason why we can't simply accept all Decls
// but let's make a short list so that to avoid supporting something weird
// by accident. We can always expand the list later.
let Subjects = SubjectList<[
Stmt, Var, Field, ObjCProperty, Function, ObjCMethod, Record, ObjCInterface,
ObjCImplementation, Namespace, Empty
], ErrorDiag, "variables, functions, structs, interfaces, and namespaces">;
let Documentation = [SuppressDocs];
}

Expand Down
23 changes: 23 additions & 0 deletions clang/include/clang/Basic/AttrDocs.td
Original file line number Diff line number Diff line change
Expand Up @@ -5313,6 +5313,29 @@ Putting the attribute on a compound statement suppresses all warnings in scope:
}
}

The attribute can also be placed on entire declarations of functions, classes,
variables, member variables, and so on, to suppress warnings related
to the declarations themselves. When used this way, the attribute additionally
suppresses all warnings in the lexical scope of the declaration:

.. code-block:: c++

class [[clang::suppress]] C {
int foo() {
int *x = nullptr;
...
return *x; // warnings suppressed in the entire class scope
}

int bar();
};

int C::bar() {
int *x = nullptr;
...
return *x; // warning NOT suppressed! - not lexically nested in 'class C{}'
}

Some static analysis warnings are accompanied by one or more notes, and the
line of code against which the warning is emitted isn't necessarily the best
for suppression purposes. In such cases the tools are allowed to implement
Expand Down
3 changes: 3 additions & 0 deletions clang/lib/Sema/SemaDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2960,6 +2960,9 @@ static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
else if (const auto *SupA = dyn_cast<SuppressAttr>(Attr))
// Do nothing. Each redeclaration should be suppressed separately.
NewAttr = nullptr;
else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));

Expand Down
5 changes: 0 additions & 5 deletions clang/lib/Sema/SemaDeclAttr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5245,11 +5245,6 @@ static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
// Suppression attribute with GSL spelling requires at least 1 argument.
if (!AL.checkAtLeastNumArgs(S, 1))
return;
} else if (!isa<VarDecl>(D)) {
// Analyzer suppression applies only to variables and statements.
S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type_str)
<< AL << 0 << "variables and statements";
return;
}

std::vector<StringRef> DiagnosticIdentifiers;
Expand Down
4 changes: 2 additions & 2 deletions clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,8 @@ static void checkObjCUnusedIvar(const ObjCImplementationDecl *D,

PathDiagnosticLocation L =
PathDiagnosticLocation::create(Ivar, BR.getSourceManager());
BR.EmitBasicReport(D, Checker, "Unused instance variable", "Optimization",
os.str(), L);
BR.EmitBasicReport(ID, Checker, "Unused instance variable",
"Optimization", os.str(), L);
}
}

Expand Down
18 changes: 16 additions & 2 deletions clang/lib/StaticAnalyzer/Core/BugSuppression.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,12 @@ class CacheInitializer : public RecursiveASTVisitor<CacheInitializer> {
CacheInitializer(ToInit).TraverseDecl(const_cast<Decl *>(D));
}

bool VisitVarDecl(VarDecl *VD) {
bool VisitDecl(Decl *D) {
// Bug location could be somewhere in the init value of
// a freshly declared variable. Even though it looks like the
// user applied attribute to a statement, it will apply to a
// variable declaration, and this is where we check for it.
return VisitAttributedNode(VD);
return VisitAttributedNode(D);
}

bool VisitAttributedStmt(AttributedStmt *AS) {
Expand Down Expand Up @@ -147,6 +147,20 @@ bool BugSuppression::isSuppressed(const PathDiagnosticLocation &Location,
// done as well as perform a lot of work we'll never need.
// Gladly, none of our on-by-default checkers currently need it.
DeclWithIssue = ACtx.getTranslationUnitDecl();
} else {
// This is the fast path. However, we should still consider the topmost
// declaration that isn't TranslationUnitDecl, because we should respect
// attributes on the entire declaration chain.
while (true) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

What is going on here? How does this differ from just getTranslationUnitDecl?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This is, uh, a somewhat premature performance optimization. I think I want to get rid of it, as discussed in #79398 (it's incorrect as well), but it probably requires a separate discussion.

The static analyzer normally always takes the fast path as every single "supported" checker fills in the data correctly.

This isn't just about scanning the TU here for discovering suppressed ranges, it's more about the fact that the static analyzer is so careful about not analyzing non-user code that normally it doesn't even deserialize PCHs if they aren't directly required for analysis. This is demonstrated by the lovely test case in clang/test/Analysis/check-deserialization.cpp. A full TU scan here will cause these PCHs to be deserialized even though the rest of the analysis never needed to look at them.

I have some data that this can have significant performance impact. However, other tools such as clang-tidy never had such optimization (they always scan the entire TU indiscriminately) and this never stopped them from satisfying the usual performance expectations of static analysis tools. We've also abandoned this optimization in a downstream fork for a while and it seems perfectly livable.

So I want to either abandon this non-deserialization guarantee (simply always scan the entire TU), or find a different way to satisfy it (eg., collect those ranges eagerly during AST construction so that to avoid the after-the-fact scan; then if PCHs/modules are used, suppression ranges will make it into PCHs and get deserialized together with them as-needed). I'll probably try to do some of that in the coming weeks but I wanted this patch to be independent from that so that to get the attribute's behavior to reasonable shape without breaking anything else.

// Use the "lexical" parent. Eg., if the attribute is on a class, suppress
// warnings in inline methods but not in out-of-line methods.
const Decl *Parent =
dyn_cast_or_null<Decl>(DeclWithIssue->getLexicalDeclContext());
if (Parent == nullptr || isa<TranslationUnitDecl>(Parent))
break;

DeclWithIssue = Parent;
}
}

// While some warnings are attached to AST nodes (mostly path-sensitive
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,17 @@ struct DerivedWithVirtualDtor : RefCntblBase {
virtual ~DerivedWithVirtualDtor() {}
};

// Confirm that the checker respects [[clang::suppress]]
struct [[clang::suppress]] SuppressedDerived : RefCntblBase { };
struct [[clang::suppress]] SuppressedDerivedWithVirtualDtor : RefCntblBase {
virtual ~SuppressedDerivedWithVirtualDtor() {}
};

// FIXME: Support attributes on base specifiers? Currently clang
// doesn't support such attributes at all, even though it knows
// how to parse them.
//
// struct SuppressedBaseSpecDerived : [[clang::suppress]] RefCntblBase { };

template<class T>
struct DerivedClassTmpl : T { };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ void raw_ptr() {
// CHECK-NEXT:{{^ | }} ^
auto foo4 = [=](){ (void) ref_countable; };
// CHECK: warning: Implicitly captured raw-pointer 'ref_countable' to uncounted type is unsafe [webkit.UncountedLambdaCapturesChecker]

// Confirm that the checker respects [[clang::suppress]].
RefCountable* suppressed_ref_countable = nullptr;
[[clang::suppress]] auto foo5 = [suppressed_ref_countable](){};
// CHECK-NOT: warning: Captured raw-pointer 'suppressed_ref_countable' to uncounted type is unsafe [webkit.UncountedLambdaCapturesChecker]
}

void references() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ class Foo {
// expected-warning@-1{{Local variable 'baz' is uncounted and unsafe [alpha.webkit.UncountedLocalVarsChecker]}}
auto *baz2 = this->provide_ref_ctnbl();
// expected-warning@-1{{Local variable 'baz2' is uncounted and unsafe [alpha.webkit.UncountedLocalVarsChecker]}}
[[clang::suppress]] auto *baz_suppressed = provide_ref_ctnbl(); // no-warning
}
};
} // namespace auto_keyword
Expand Down
9 changes: 9 additions & 0 deletions clang/test/Analysis/Checkers/WebKit/uncounted-members.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ namespace members {
RefCountable* a = nullptr;
// expected-warning@-1{{Member variable 'a' in 'members::Foo' is a raw pointer to ref-countable type 'RefCountable'}}

[[clang::suppress]]
RefCountable* a_suppressed = nullptr;

protected:
RefPtr<RefCountable> b;

Expand All @@ -25,8 +28,14 @@ namespace members {
};

void forceTmplToInstantiate(FooTmpl<RefCountable>) {}

struct [[clang::suppress]] FooSuppressed {
private:
RefCountable* a = nullptr;
};
}


namespace ignore_unions {
union Foo {
RefCountable* a;
Expand Down
10 changes: 10 additions & 0 deletions clang/test/Analysis/ObjCRetSigs.m
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,32 @@

@interface MyBase
-(long long)length;
-(long long)suppressedLength;
@end

@interface MySub : MyBase{}
-(double)length;
-(double)suppressedLength;
@end

@implementation MyBase
-(long long)length{
printf("Called MyBase -length;\n");
return 3;
}
-(long long)suppressedLength{
printf("Called MyBase -length;\n");
return 3;
}
@end

@implementation MySub
-(double)length{ // expected-warning{{types are incompatible}}
printf("Called MySub -length;\n");
return 3.3;
}
-(double)suppressedLength [[clang::suppress]]{ // no-warning
printf("Called MySub -length;\n");
return 3.3;
}
@end
17 changes: 15 additions & 2 deletions clang/test/Analysis/objc_invalidation.m
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,17 @@ @interface MissingInvalidationMethod : Foo <FooBar_Protocol>
@implementation MissingInvalidationMethod
@end

@interface SuppressedMissingInvalidationMethod : Foo <FooBar_Protocol>
@property (assign) [[clang::suppress]] SuppressedMissingInvalidationMethod *foobar16_warn;
// FIXME: Suppression should have worked but decl-with-issue is the ivar, not the property.
#if RUN_IVAR_INVALIDATION
// expected-warning@-3 {{Property foobar16_warn needs to be invalidated; no invalidation method is defined in the @implementation for SuppressedMissingInvalidationMethod}}
#endif

@end
@implementation SuppressedMissingInvalidationMethod
@end

@interface MissingInvalidationMethod2 : Foo <FooBar_Protocol> {
Foo *Ivar1;
#if RUN_IVAR_INVALIDATION
Expand Down Expand Up @@ -290,8 +301,10 @@ @implementation MissingInvalidationMethodDecl2
@end

@interface InvalidatedInPartial : SomeInvalidationImplementingObject {
SomeInvalidationImplementingObject *Ivar1;
SomeInvalidationImplementingObject *Ivar2;
SomeInvalidationImplementingObject *Ivar1;
SomeInvalidationImplementingObject *Ivar2;
[[clang::suppress]]
SomeInvalidationImplementingObject *Ivar3; // no-warning
}
-(void)partialInvalidator __attribute__((annotate("objc_instance_variable_invalidator_partial")));
@end
Expand Down
14 changes: 14 additions & 0 deletions clang/test/Analysis/suppression-attr-doc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,17 @@ int bar2(bool coin_flip) {
__attribute__((suppress))
return *result; // leak warning is suppressed only on this path
}

class [[clang::suppress]] C {
int foo() {
int *x = nullptr;
return *x; // warnings suppressed in the entire class
}

int bar();
};

int C::bar() {
int *x = nullptr;
return *x; // expected-warning{{Dereference of null pointer (loaded from variable 'x')}}
}
68 changes: 68 additions & 0 deletions clang/test/Analysis/suppression-attr.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s

namespace [[clang::suppress]]
suppressed_namespace {
int foo() {
int *x = 0;
return *x;
}

int foo_forward();
}

int suppressed_namespace::foo_forward() {
int *x = 0;
return *x; // expected-warning{{Dereference of null pointer (loaded from variable 'x')}}
}

// Another instance of the same namespace.
namespace suppressed_namespace {
int bar() {
int *x = 0;
return *x; // expected-warning{{Dereference of null pointer (loaded from variable 'x')}}
}
}

void lambda() {
[[clang::suppress]] {
auto lam = []() {
int *x = 0;
return *x;
};
}
}

class [[clang::suppress]] SuppressedClass {
int foo() {
int *x = 0;
return *x;
}

int bar();
};

int SuppressedClass::bar() {
int *x = 0;
return *x; // expected-warning{{Dereference of null pointer (loaded from variable 'x')}}
}

class SuppressedMethodClass {
[[clang::suppress]] int foo() {
int *x = 0;
return *x;
}

[[clang::suppress]] int bar1();
int bar2();
};

int SuppressedMethodClass::bar1() {
int *x = 0;
return *x; // expected-warning{{Dereference of null pointer (loaded from variable 'x')}}
}

[[clang::suppress]]
int SuppressedMethodClass::bar2() {
int *x = 0;
return *x; // no-warning
}
Loading