GCC optimization/fr

Ce guide est une introduction à l'optimisation de code compilé en recourant à des variables CFLAGS et CXXFLAGS saines. Il présente aussi la théorie sousjacente à l'optimisation en général.

Introduction
Que sont les variables CFLAGS et CXXFLAGS ?

CFLAGS et CXXFLAGS sont des variables d'environnement utilisées pour dire aux compilateurs de la collection GNU,, quels types de commutateurs utiliser lors de la compilation du code source. CFLAGS concerne le code écrit en C, tandis que CXXFLAGS concerne le code écrite en C++.

Elles peuvent être utilisées pour diminuer le nombre de message de débogage pour un programme, augmenter le niveau d'alerte, et bien-sûr, optimiser le code produit. Le manuel de GNU gcc (en anglais) tient à jour une liste exhaustive des options disponibles et de leurs objectifs.

Comment sont-elles utilisées ?
Les variables CFLAGS et CXXFLAGS peuvent être utilisées de deux façons. Premièrement, elles peuvent être utilisées par programme dans des Makefiles générés par automake.

Cependant, ceci ne devrait pas être fait lors de l'installation de paquets provenant de l'arbre de Portage. Au lieu de cela, définissez vos variables CFLAGS et CXXFLAGS dans le fichier. De cette manière, tous les paquets seront compilés en utilisant les options que vous y aurez définies.

CFLAGS in /etc/portage/make.conf

Comme vous pouvez le voir, CXXFLAGS est définie pour utiliser toutes les options présentes dans CFLAGS. C'est ce que vous devriez faire sans risque la plupart du temps. Vous ne devriez jamais spécifier des options additionnelles dans CXXFLAGS.

Erreurs de conception
ALors que CFLAGS et CXXFLAGS peuvent être un moyen efficace de produire des binaires plus compacts et/ou plus rapides, elles peuvent aussi empêcher votre code de fonctionner, augmenter sa taille, ralentir son exécution et même causer des erreurs de compilation.

Les options de CFLAGS ne sont pas une baguette magique ; elles ne feront pas tourner votre système plus vite ou ne réduiront pas la taille de vos binaires automatiquement. Ajouter de plus en plus d'options dans l'espoir d'optimiser votre système est une recette garantie d'échec. Il y a un point à partir duquel les retours seront négatifs.

Malgré toute la vantardise que vous trouverez sur Internet, des CFLAGS et CXXFLAGS agressifs créeront du tort à vos programmes plus qu'elles ne leur feront de bien. Souvenez-vous que ces options ont été conçues pour être employées à des endroits précis pour des  objectifs précis. La simple raison qu'une option particulière de CFLAGS est profitable à un morceau de code, ne signifie pas qu'elle convient à n'importe quelle programme  que vous installerez sur votre machine !

Prêt ?
Maintenant que vous avez pris conscience des risques potentiels, jetons un coup d'œil à quelques optimisations saines et sûres pour votre ordinateur. Elles vous maintiendront en bons termes avec les développeurs la prochaine fois que vous rapporterez un problème sur Bugzilla. (Les développeurs vous demanderont généralement de recompiler un paquet avec des options de la variable CFLAGS minimales, pour voir si le problème subsiste. Souvenez-vous que des options agressives peuvent causer du tort à votre code.)

Les bases
L'objectif derrière l'utilisation des options des variables CFLAGS et CXXFLAGS est de créer un code parfaitement adapté à votre système ; il devrait fonctionner parfaitement tout en étant aussi compact et rapide que possible. Parfois, ces conditions sont incompatibles entre elles, c'est pourquoi nous nous en tiendrons à des combinaisons réputées pour bien fonctionner. Idéalement, elles sont les meilleurs disponibles pour toute architecture de processeur. Nous parlerons des options agressives plus tard, ainsi vous saurez à quoi vous en tenir. Nous ne discuterons pas chacune des options listées dans le manuel de   (elles sont des centaines), mais nous couvrirons les options les plus basiques et courantes.

-march
La première, et la plus importante, option est. Elle dit au compilateur quel code il devrait produire pour votre architecture de processeur (ou arch) ; elle dit qu'il devrait produire du code pour un certain type de processeur. Des processeurs différents ont des aptitudes différents, prennent en charge différents jeux d'instructions, et ont des manières différentes d'exécuter le code. L'option  renseigne le compilateur pour qu'il produise le code spécifique à votre processeur, en tenant compte de toutes les aptitudes, fonctionnalités, jeux d'instructions, comportements, etc. de ce processeur.

Même si la variable CHOST dans le fichier spécifie l'architecture générale utilisée,   devrait quand même être utilisée pour que les programmes soient optimisés pour votre processeur spécifique. Les processeur x86 et x86-64 (parmi d'autres) devrait utiliser l'option.

What kind of CPU do you have? To find out, run the following command:

Now let's see  in action. This example is for an older Pentium III chip:

/etc/portage/make.conf: Pentium III

Here's another one for a 64-bit AMD CPU:

/etc/portage/make.conf: AMD64

If you still aren't sure what kind of CPU you have, you may just want to use. When this flag is used, GCC will detect your processor and automatically set appropriate flags for it.However, this should not be used if you intend to compile packages for a different CPU!

So if you're compiling packages on one computer, but intend to run them on a different computer (such as when using a fast computer to build for an older, slower machine), then do not use. "Native" means that the code produced will run only on that type of CPU. The applications built with  on an AMD Athlon 64 CPU will not be able to run on an old VIA C3 CPU.

Also available are the  and   flags. These flags are normally only used when there is no available  option; certain processor architectures may require   or even. Unfortunately,  's behavior isn't very consistent with how each flag behaves from one architecture to the next.

On x86 and x86-64 CPUs,  will generate code specifically for that CPU using all its available instruction sets and the correct ABI; it will have no backwards compatibility for older/different CPUs. If you don't need to execute code on anything other than the system you're running Gentoo on, continue to use. You should only consider using  when you need to generate code for older CPUs such as i386 and i486. produces more generic code than  ; though it will tune code for a certain CPU, it doesn't take into account available instruction sets and ABI. Don't use  on x86 or x86-64 systems, as it is deprecated for those arches.

Only non-x86/x86-64 CPUs (such as Sparc, Alpha, and PowerPC) may require  or   instead of. On these architectures, /   will sometimes behave just like   (on x86/x86-64). . . but with a different flag name. Again,  's behavior and flag naming just isn't consistent across architectures, so be sure to check the   manual to determine which one you should use for your system.

-O
Next up is the  variable. This controls the overall level of optimization. This makes the code compilation take somewhat more time, and can take up much more memory, especially as you increase the level of optimization.

There are five  settings:  ,   ,   ,   , and. You should use only one of them in.

With the exception of , the   settings each activate several additional flags, so be sure to read the gcc manual's chapter on optimization options to learn which flags are activated at each   level, as well as some explanations as to what they do.

Let's examine each optimization level:


 * : This level (that's the letter "O" followed by a zero) turns off optimization entirely and is the default if no  level is specified in CFLAGS or CXXFLAGS. Your code will not be optimized; it's not normally desired.


 * : This is the most basic optimization level. The compiler will try to produce faster, smaller code without taking much compilation time. It's pretty basic, but it should get the job done all the time.


 * : A step up from  . This is the recommended level of optimization unless you have special needs.   will activate a few more flags in addition to the ones activated by   . With  , the compiler will attempt to increase code performance without compromising on size, and without taking too much compilation time.


 * : This is the highest level of optimization possible, and also the riskiest. It will take a longer time to compile your code with this option, and in fact it should not be used system-wide with  4.x . The behavior of   has changed significantly since version 3.x. In 3.x,   has been shown to lead to marginally faster execution times over  , but this is no longer the case with   4.x. Compiling all your packages with   will result in larger binaries that require more memory, and will significantly increase the odds of compilation failure or unexpected program behavior (including errors). The downsides outweigh the benefits; remember the principle of diminishing returns. Using   is not recommended for   4.x.


 * : This level will optimize your code for size. It activates all  options that don't increase the size of the generated code. It can be useful for machines that have extremely limited disk storage space and/or have CPUs with small cache sizes. However, it can cause quite a few problems, which is why it is filtered out by many of the ebuilds in the tree. Using   is not recommended.

As previously mentioned,  is the recommended optimization level. If package compilations error out, check to make sure that you aren't using. As a fallback option, try setting your CFLAGS and CXXFLAGS to a lower optimization level, such as  or even   (for error reporting and checking for possible problems) and recompile the package.

-pipe
A common flag is. This flag actually has no effect on the generated code, but it makes the compilation process faster. It tells the compiler to use pipes instead of temporary files during the different stages of compilation, which uses more memory. On systems with low memory, gcc might get killed. In that case, do not use this flag.

-fomit-frame-pointer
This is a very common flag designed to reduce generated code size. It is turned on at all levels of  (except   ) on architectures where doing so does not interfere with debugging (such as x86-64), but you may need to activate it yourself by adding it to your flags. Though the GNU  manual does not specify all architectures it is turned on by using  , you will need to explicitly activate it on x86. However, using this flag will make debugging hard to impossible.

In particular, it makes troubleshooting applications written in Java much harder, though Java is not the only code affected by using this flag. So while the flag can help, it also makes debugging harder; backtraces in particular will be useless. However, if you don't plan to do much software debugging and haven't added any other debugging-related CFLAGS such as , then you can try using.

-msse, -msse2, -msse3, -mmmx, -m3dnow
These flags enable the SSE, SSE2 , SSE3 , MMX , and 3DNow! instruction sets for x86 and x86-64 architectures. These are useful primarily in multimedia, gaming, and other floating point-intensive computing tasks, though they also contain several other mathematical enhancements. These instruction sets are found in more modern CPUs.

You normally don't need to add any of these flags to as long as you are using the correct   (for example,   implies   ). Some notable exceptions are newer VIA and AMD64 CPUs that support instructions not implied by  (such as SSE3). For CPUs like these you'll need to enable additional flags where appropriate after checking the output of.

But I get better performance with -funroll-loops -fomg-optimize!
No, you only think you do because someone has convinced you that more flags are better. Aggressive flags will only hurt your applications when used system-wide. Even the  manual says that using   and   makes code larger and run more slowly. Yet for some reason, these two flags, along with ,   ,   , and similar flags, continue to be very popular among ricers who want the biggest bragging rights.

The truth of the matter is that they are dangerously aggressive flags. Take a good look around the Gentoo Forums and Bugzilla to see what those flags do: nothing good!

You don't need to use those flags globally in CFLAGS or CXXFLAGS. They will only hurt performance. They may make you sound like you have a high-performance system running on the bleeding edge, but they don't do anything but bloat your code and get your bugs marked INVALID or WONTFIX.

You don't need dangerous flags like these. Don't use them. Stick to the basics: ,   , and.

What about -O levels higher than 3?
Some users boast about even better performance obtained by using ,   , and so on, but the reality is that   levels higher than 3 have no effect. The compiler may accept CFLAGS like , but it actually doesn't do anything with them. It only performs the optimizations for , nothing more.

Need more proof? Examine the  source code :

-O source code

As you can see, any value higher than 3 is treated as just.

What about redundant flags?
Oftentimes CFLAGS and CXXFLAGS that are turned on at various  levels are specified redundantly in. Sometimes this is done out of ignorance, but it is also done to avoid flag filtering or flag replacing.

Flag filtering/replacing is done in many of the ebuilds in the Portage tree. It is usually done because packages fail to compile at certain  levels, or when the source code is too sensitive for any additional flags to be used. The ebuild will either filter out some or all CFLAGS and CXXFLAGS, or it may replace  with a different level.

The Gentoo Developer Manual outlines where and how flag filtering/replacing works.

It's possible to circumvent  filtering by redundantly listing the flags for a certain level, such as  , by doing things like:

Specifying redundant CFLAGS

However,this is not a smart thing to do. CFLAGS are filtered for a reason! When flags are filtered, it means that it is unsafe to build a package with those flags. Clearly, it is not safe to compile your whole system with  if some of the flags turned on by that level will cause problems with certain packages. Therefore, you shouldn't try to "outsmart" the developers who maintain those packages. Trust the developers. Flag filtering and replacing is done for your benefit! If an ebuild specifies alternative flags, then don't try to get around it.

You will most likely continue to run into problems when you build a package with unacceptable flags. When you report your troubles on Bugzilla, the flags you use in will be readily visible and you will be told to recompile without those flags. Save yourself the trouble of recompiling by not using redundant flags in the first place! Don't just automatically assume that you know better than the developers.

What about LDFLAGS?
The Gentoo developers have already set basic, safe LDFLAGS in the base profiles, so you don't need to change them.

Can I use per-package flags?
Information on how to use per-package environment variables (including CFLAGS) is described in the Gentoo Handbook, "Per-Package Environment Variables".

Resources
The following resources are of some help in further understanding optimization:


 * The GNU gcc manual


 * Chapter 5 of the Gentoo Installation Handbooks




 * Wikipedia


 * The Gentoo Forums

Acknowledgements
We would like to thank the following authors and editors for their contributions to this guide:


 * nightmorph