Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ compilers automatically eliminate duplicate code?

Code duplication is usually bad and often quite easy to spot. I suppose that compilers could detect it automatically in easiest cases - they already parse the text and get the intermediate representation that they analyze in various ways - detect suspicious patterns like uninitialized variables, optimize emitted code, etc. I guess they could often detect functionally duplicate code this way as well and account for it while emitting machine code.

Are there C++ compilers that can detect duplicate code and only emit corresponding machine code once instead of for each duplicate in the source text?

like image 978
sharptooth Avatar asked Oct 04 '10 13:10

sharptooth


2 Answers

Some do, some don't.

From the LLVM optimization's page: -mergefunc (MergeFunctions pass, how it works)

The functions are separated in small blocks in the LLVM Intermediate Representation, this optimization pass tries to merge similar blocks. It's not guaranteed to succeed though.

You'll find plenty of other optimizations on this page, even though some of them may appear cryptic at first glance.

I would add a note though, that duplicate code isn't so bad for the compiler / executable, it's bad from a maintenance point of view, and there is nothing a compiler can do about it.

like image 91
Matthieu M. Avatar answered Sep 22 '22 16:09

Matthieu M.


I think the question makes the false assumption that compilers would always want to eliminate code duplication. code duplication is bad for readability/maintainability of source code not necesarily performance of compiled code, indeed one could consider loop unrolling as a compiler adding duplicate code to increase speed. compiled code does not need to follow the same principles as source code and generally doesn't as it is for the machine not for humans to read.

generally compilers are busy compiling not transforming source code, of course IDEs may allow both.

like image 33
jk. Avatar answered Sep 21 '22 16:09

jk.