Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get optimized source code from GCC

I have a task to create optimized C++ source code and give it to friend for compilation. It means, that I do not control the final compilation, I just write the source code of C++ program.

I know, that a can make optimization during compilation with -O1 (and -O2 and others) options of GCC. But how can I get this optimized source code instead of compiled program? I am not able to configure parameters of my friend's compiler, that is why I need to make a good source on my side.

like image 501
maxpestun Avatar asked Jan 19 '23 00:01

maxpestun


2 Answers

The optimizations performed by GCC are low level, that means you won't get C++ code again but assembly code in best case. But you won't be able to convert it or something.

In sum: Optimize the source code on code level, not on object level.

like image 107
Sebastian Dressler Avatar answered Jan 20 '23 16:01

Sebastian Dressler


You could ask GCC to dump its internal (Gimple, ...) representations, at various "stages". The middle-end of GCC is made of hundreds of passes, and you could ask GCC to dump them, with arguments like -fdump-tree-all or -fdump-gimple-all; beware that you can get hundreds of dump files for a single compilation!

However, GCC internal representations are quite low level, and you should not expect to understand them without reading a lot of material.

The dump options I am mentionning are mostly useful to those working inside GCC, or extending it thru plugins coded in C or extensions coded in MELT (a high-level domain specific language to extend GCC). I am not sure they will be very useful to your friend. However, they can be useful to make you understand that optimization passes do a lot of complex processing.

And don't forget that premature optimization is evil : you should first make your program run correctly, then benchmark and profile it, at last optimize the few parts worth of your efforts. You probably won't be able to write correct & efficient programs without testing and running them yourself, before giving them to your friend.

like image 22
Basile Starynkevitch Avatar answered Jan 20 '23 14:01

Basile Starynkevitch