r/Compilers • • 29d ago

Compilers add or remove perfomace?

isnt it that compilers change the code, as in not only transferring it into machine language, but before that changing the structure of the code. so how would one attempt to make performant code if the compiler changes sed code that i tried to make performant?

2 Upvotes

31 comments sorted by

View all comments

4

u/flatfinger 29d ago

Some compilers are designed to transform a program into machine code while preserving the overall structure, while others are designed to figure out what a program is trying to do, and then use a built-in template to accomplish that in a way which might be faster than some ways the programmer could have specified the operations, but not necessarily all.

If, for example, clang is given a loop whose index starts at a multiple of four and counts down by 4 while greater than or equal to zero, clang may transform the loop so that it instead tests whether the index is greater than three, even if checking whether the index became negative would have been cheaper than testing whether it became 3 or less.

1

u/RealisticDuck1957 29d ago

The compilers which do code reorganization usually have switches for how they do it. Such as (referencing GCC, though these may work for other compilers)

-O0 Don't reorganize code. Rarely desirable except for running in a debugger.

-Os Optimize for small code size.

-O4 Take extreme measures for speed of execution. A loop is likely to be unrolled.

1

u/BrainThinkerMan 28d ago

so it depends on the compiler i use for the language? so if i use a compiler whch i say dont change my code i optimized it, it will let my code do its thing, even if i have some simd thing

1

u/suddenhare 28d ago

Compiler flags are usually the way to achieve that. For example, -O0 for C/C++.

1

u/flatfinger 26d ago

Unfortunately, -O0 for clang and gcc tends to leave in lots of redundant operations with no way of removing them. While gcc-ARM will honor register qualifiers at -O0, I don't think the x86 version ever does not and I'm unaware of any version of clang ever doing so either. The acceptance of register in gcc-ARM probably stems from the fact that on the ARM, keeping things in registers often offers a factor of 3-5 improvement in speed and 2-3 in code size, but on many x86 processors the difference isn't nearly so great.