teak-llvm/clang/test/Preprocessor/expr_define_expansion.c
Nico Weber b2348f4ced Add -Wexpansion-to-undefined: warn when using defined in a macro definition.
[cpp.cond]p4:
  Prior to evaluation, macro invocations in the list of preprocessing
  tokens that will become the controlling constant expression are replaced
  (except for those macro names modified by the 'defined' unary operator),
  just as in normal text. If the token 'defined' is generated as a result
  of this replacement process or use of the 'defined' unary operator does
  not match one of the two specified forms prior to macro replacement, the
  behavior is undefined.

This isn't an idle threat, consider this program:
  #define FOO
  #define BAR defined(FOO)
  #if BAR
  ...
  #else
  ...
  #endif
clang and gcc will pick the #if branch while Visual Studio will take the
#else branch.  Emit a warning about this undefined behavior.

One problem is that this also applies to function-like macros. While the
example above can be written like

    #if defined(FOO) && defined(BAR)
    #defined HAVE_FOO 1
    #else
    #define HAVE_FOO 0
    #endif

there is no easy way to rewrite a function-like macro like `#define FOO(x)
(defined __foo_##x && __foo_##x)`.  Function-like macros like this are used in
practice, and compilers seem to not have differing behavior in that case. So
this a default-on warning only for object-like macros. For function-like
macros, it is an extension warning that only shows up with `-pedantic`.
(But it's undefined behavior in both cases.)

llvm-svn: 258128
2016-01-19 15:15:31 +00:00

29 lines
636 B
C

// RUN: %clang_cc1 %s -E -CC -verify
// RUN: %clang_cc1 %s -E -CC -DPEDANTIC -pedantic -verify
#define FOO && 1
#if defined FOO FOO
#endif
#define A
#define B defined(A)
#if B // expected-warning{{macro expansion producing 'defined' has undefined behavior}}
#endif
#define m_foo
#define TEST(a) (defined(m_##a) && a)
#if defined(PEDANTIC)
// expected-warning@+4{{macro expansion producing 'defined' has undefined behavior}}
#endif
// This shouldn't warn by default, only with pedantic:
#if TEST(foo)
#endif
// Only one diagnostic for this case:
#define INVALID defined(
#if INVALID // expected-error{{macro name missing}}
#endif