Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see compiler reformulation of C++ code with optimizations

I'm wondering if/how it's possible to see how the compiler reformulates a piece of code with clang++/g++ when optimizations are turned on. I know that the Intel compiler has a flag to produce relevant output, but I can't seem to find the equivalent in the other compilers.

like image 580
Nikos Kazazakis Avatar asked Mar 07 '17 21:03

Nikos Kazazakis


People also ask

How do I find optimized code?

you can get an idea of optimization using the option -fdump-tree-optimized with gcc . and you'll get an optimised file. you cannot run the code but using that you can get an idea of optimization . dont forget to include -O2 or -O3 or some other level.

How does compiler optimize code?

Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.

Is compiler code Optimised?

The code optimization in the synthesis phase is a program transformation technique, which tries to improve the intermediate code by making it consume fewer resources (i.e. CPU, Memory) so that faster-running machine code will result.

Can compiler optimization break code?

Once in a while C++ code will not work when compiled with some level of optimization. It may be compiler doing optimization that breaks the code or it may be code containing undefined behavior which allows the compiler to do whatever it feels.


1 Answers

So, thanks to your directions I was able to discover something really cool, so I thought I'd share:

With Clang++-4.0, one can compile the executable as follows:

clang++-4.0 -std=c++14 -O3  -fsave-optimization-record -foptimization-record-file=myOptfile.yaml sourceFile.cpp

This saves a record of successful and unsuccessful optimizations in myOptfile.yaml. This can be viewed using llvm-opt-report-4.0, but its true power is if viewed using llvm/utils/opt-viewer.py.

In order to do that, clone the llvm repository, navigate to your source directory, and run the following after you generate myOptFile.yaml:

python ~/myInstallDir/llvm/utils/opt-viewer/opt-viewer.py myOptFile.yaml reportsDirectory/

This will create a lot of html files that you can navigate using index.html (in the reportsDirectory folder).

The result is awesome, and looks like this:

enter image description here

Most things are clickable, so you can navigate using the html hyperlinks to other parts of the source code, including c++ libraries and see what happened!

like image 142
Nikos Kazazakis Avatar answered Oct 14 '22 22:10

Nikos Kazazakis