[cfe-dev] Implementing -Wunused-variables

Douglas Gregor dgregor at apple.com
Mon Oct 5 07:54:06 PDT 2009


Hello Oscar,

On Oct 4, 2009, at 6:04 PM, Oscar Bonilla wrote:
> So I'm trying to get my feet wet with clang, and I noticed that right
> now clang doesn't notice when you declare a variable but don't use it.

Correct, Clang is missing this warning. It would make a great addition!

> I wrote this simple testcase and put it in
>
> llvm/tools/clang/test/Sema/warning-unused-variables.c
>
> ---
> // RUN: clang -fsyntax-only -Wunused-variables -verify %s
>
> void f0(void) {
> 	int	a, b; // expected-warning{{unused-variable}}
> 	a = 10;
> 	return;
> }
> ---
>
> And sure enough:
>
> $ clang-cc -Wunused-variables -fsyntax-only -verify warn-unused-
> variables.c
> Warnings expected but not seen:
>   Line 4: unused-variable
> Warnings seen but not expected:
>   Line 0: unknown warning option '-Wunused-variables'
>
> Obviously there is no -Wunused-variables flag or unused variables
> warning yet because that's what I need to implement. So my question
> is, what's the best way start hacking on this? Is there a document
> that describes the AST and where the warnings are generated? What
> files should I start reading?

Generally, the best way to figure out how to add a new warning like  
this is to find a similar warning. Clang has -Wunused-parameter  
already implemented, so that's a great start. There are a few places  
you'll need to look at and (in some cases) modify to implement - 
Wunused-variables:

	include/clang/Basic/DiagnosticSemaKinds.td: define a new  
warn_unused_variable warning here
	lib/Sema/Sema.h: DiagnoseUnusedParameters shows how to emit a similar  
warning
	lib/Sema/SemaDecl.cpp: Sema::ActOnPopScope is where you probably want  
to look for unused variables (when they are being popped out of scope)
    	lib/Sema/SemaExpr.cpp: Sema::MarkDeclarationReferenced is called  
whenever any declaration (variable, function, method, etc.) is used by  
the source code.

Most of the documentation for the ASTs is within the AST headers,  
which is also accessible via Doxygen:

	http://clang.llvm.org/doxygen/

	- Doug



More information about the cfe-dev mailing list