Skip to content Skip to sidebar Skip to footer

How To Set Optimization Level For A Specific File In Android Ndk?

I have a native library for Android that has some files that include NEON assembly code. I've inherited this code from some other coder, and given my knowledge regarding NEON assem

Solution 1:

GCC >= 4.4 seems to support #pragma GCC optimize to change the optimization level mid-file, and also attribute optimize to set it per function.

See http://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Function-Specific-Option-Pragmas.html#Function-Specific-Option-Pragmas and http://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Function-Attributes.html#Function-Attributes.

According to those links, putting #pragma GCC optimize ("O0") at the top of the file causing the problem should do the trick.

Solution 2:

I don't know how to change the optimization level per-file, but doing so may harm your application's performance, so i wouldn't recommend it anway. I assume that the assembly code is in the form of inline assembly block, i.e. blocks of assembly coder interleaves with normal C or C++ code. It looks the following

asm {
  .. assembly goes here, usually each line in double-quotes, often ending in \n\t
  : ... input operands. Might not be present ...
  : ... output operands. Might not be present ...
  : ... clobber operands. Might not be present ...
}

The most likely reason why the compiler would remove an inline assembly block is if it contains no output operands, or if the output operands are all unused. You can avoid try by marking the inline assembly block as volatile which tells the compiler not to mess with it. To do that, simply write volatile after the asm keyword.

Another thing that discourages the compiler from messing with inline assembly blocks is adding "memory" to their clobber list. This tells the compiler that the assembly is reading from or writing to arbitrary memory locations. And while you're at it, also add "cc" for good measure. This tells the compiler that the inline assembly messes with the condition-code register, i.e. that it executes test instructions which influence the behaviour of later conditional branch instructions.

In conclusion, try making all inline assembly blocks look like this

asmvolatile {
  .. whatever ...
  : ... whatever ...
  : ... whatever ...
  : ... whatever ..., "cc", "memory"
}

Note that asm may also be spelled __asm__, and that volatile may also be spelled __volatile__.

Post a Comment for "How To Set Optimization Level For A Specific File In Android Ndk?"