Kevin Meier
Kevin Meier

Reputation: 2582

Clang: Do not optimize a specific function

For a long time i used gcc to compile C code. Sometimes i had to use the optimize("O0") attribute to disable optimizations for a specific function. Now i like to do this with clang.

Assume the following code:

#include <stdio.h>

void __attribute__((optimize("O0"))) blabla(void) {
}

int main(void) {
    blabla();
    return 0;
}

If i compile it with clang i get this error:

test2.c:3:21: warning: unknown attribute 'optimize' ignored [-Wattributes]
void __attribute__((optimize("O0"))) blabla(void) {
                    ^
1 warning generated.

Then i used google (and also) stackoverflow to find out what attribute is required for clang, because many of them are not in the standard (as soon as i know).

I found this thread: In clang, how do you use per-function optimization attributes?

If i try the attribute optimize("0") i get this error:

test2.c:3:21: warning: unknown attribute 'optimize' ignored [-Wattributes]
void __attribute__((optimize("0"))) blabla(void) {
                    ^
1 warning generated.

And if i try the attribute optnone i get this error:

test2.c:3:21: warning: unknown attribute 'optnone' ignored [-Wattributes]
void __attribute__((optnone)) blabla(void) {
                    ^
1 warning generated.

I also tried to move the attribute after the function name, but it doesn't work (for some reason there is a warning about GCC?!):

test2.c:3:34: warning: GCC does not allow optnone attribute in this position on a function definition [-Wgcc-compat]
void blabla(void) __attribute__((optnone)) {
                                 ^
test2.c:3:34: warning: unknown attribute 'optnone' ignored [-Wattributes]
2 warnings generated.

Another test with the following code:

#include <stdio.h>

[[clang::optnone]]
void blabla(void) {
}

int main(void) {
    blabla();
    return 0;
}

It produces:

user@ubuntu:/tmp/optxx$ clang test2.c
test2.c:3:1: error: expected identifier or '('
[[clang::optnone]]
^
test2.c:3:2: error: expected expression
[[clang::optnone]]
 ^
test2.c:8:5: warning: implicit declaration of function 'blabla' is invalid in C99 [-Wimplicit-function-declaration]
    blabla();
    ^
1 warning and 2 errors generated.

Probably i do something wrong, but i cannot see what.

-edit-

clang version:

user@ubuntu:/tmp/optxx$ clang -v
Ubuntu clang version 3.3-16ubuntu1 (branches/release_33) (based on LLVM 3.3)
Target: x86_64-pc-linux-gnu
Thread model: posix

Upvotes: 15

Views: 20985

Answers (1)

Marcus M&#252;ller
Marcus M&#252;ller

Reputation: 36482

Try the following, clang-style attribute specification:

[[clang::optnone]]
void blabla(void);

EDIT: Clang 3.3 is pretty outdated. Use a more recent version, and your original ((optnone)) code will work.

Upvotes: 10

Related Questions