llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
29.11k stars 12.01k forks source link

Identify dead code in preprocessor blocks #27437

Open LegalizeAdulthood opened 8 years ago

LegalizeAdulthood commented 8 years ago
Bugzilla Link 27063
Version unspecified
OS All

Extended Description

Suppose we have code like the following:

#ifdef USE_FOO
// a bunch of code
#else
// a bunch of code that doesn't define USE_FOO
#ifdef USE_FOO
// dead code
#endif
// a bunch of code
#endif

A symbol can't be both defined and undefined at the same time and therefore this chunk of code has dead code that can never be reached by the compiler.

Write a check that looks for dead preprocessor blocks like this that can't possibly reach the compiler and removes those blocks.

The general problem is detecting mutually exclusive preprocessor conditions such that nested preprocessor conditional directives result in code that can never reach the compiler.

This can be further generalized to conditional expressions at the top level that can never be true. The canonical form of such dead code is:

#if 0
// dead code
#else
// live code
#endif

#if 1
// live code
#else
// dead code
#endif

A good first pass of such a check would be simply identifying such blocks of code.

A second pass would remove the dead code blocks, adjusting surrounding preprocessor conditions as necessary.

PiotrZSL commented 1 year ago

Second case is implemented in https://reviews.llvm.org/D145617