Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASM-optimizations lost after compilation?

Not that I'm in that situation currently, but I'm just interested in the answer...

Assuming you have some code written in C/C++ and you want to manually optimize it by modifying it in ASM.

What happens if you alter the code in C/C++ and recompile from source. Sure, the optimization on the just compiled file is lost. How do you avoid that these optimizations need to be redone each time the project is compiled? Do you create separate source files for the parts that need to be optimized to make it less complex? Or is there some kind of automatic tool to do this...? Guess you cannot use diff/patch for this...

Please share your experiences, thanks

like image 338
Atmocreations Avatar asked Feb 25 '26 00:02

Atmocreations


2 Answers

You write some functions in a separate ASM file and call those functions from your C/C++ code. Or you write inline assembly directly in your C/C++ code.

In other words, you could start with some C/C++ code to get some basic ASM code, but after you start tweaking it, you delete the original C/C++ code and replace it with your ASM code, using one of these 2 methods.

like image 81
Tarydon Avatar answered Feb 27 '26 13:02

Tarydon


Instead of modifying the output, why don't you rewrite the critical sections of code in inlined assembler? The method how to do that varies between compilers -- check your compilers documentation.

In MSVC:

// asm_overview.cpp
// processor: x86
void __declspec(naked) main()
{
    // Naked functions must provide their own prolog...
    __asm {
        push ebp
        mov ebp, esp
        sub esp, __LOCAL_SIZE
    }

    // ... and epilog
    __asm {
        pop ebp
        ret
    }
}

In GCC:

 __asm__ ("movl %eax, %ebx\n\t"
          "movl $56, %esi\n\t"
          "movl %ecx, $label(%edx,%ebx,$4)\n\t"
          "movb %ah, (%ebx)");

Note also, that doing ASM changes AFTER compilation and optimization is something only for those that know EXACTLY what they are doing. Not only does the compiler optimize the structure in a way a human couldn't (at least not one without lighting calculator abilities), it also performs a much more complex analisys of the code that we could ever do.

Trust in your compiler. It's the greatest tool you'll ever work with ;).

like image 41
Kornel Kisielewicz Avatar answered Feb 27 '26 13:02

Kornel Kisielewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!