GCC optimization/pt-br

Este guia fornece uma introdução à otimização de códigos usando CFLAGS e CXXFLAGS seguras e sensatas. Também descreve a teoria por trás da otimização em geral.

O que são CFLAGS e CXXFLAGS?
CFLAGS e CXXFLAGS estão entre as variáveis de ambiente convencionalmente usadas para especificar opções do compilador para um sistema de compilação ao compilar códigos C e C++. Enquanto estas variáveis não são padronizadas, o seu uso é essencialmente onipresente e qualquer construção escrita corretamente deve compreender estas para passar opções extras ou opções personalizadas quando se invoca o compilador. Veja a página de informação do GNU make para uma lista de algumas das variáveis comumente usadas nesta categoria.

Como uma grande proporção dos pacotes que compõem o sistema do Gentoo são escritos em C e C++, estas são duas variáveis que certamente os administradores irão querer definir corretamente como elas vão influenciar significativamente a forma como grande parte do sistema é construída.

Elas podem ser usadas para diminuir a quantidade de mensagens de debug para um programa, aumentar os níveis de alertas de erro e, é claro, otimizar o código produzido. O Manual do GCC mantém uma lista completa das opções disponíveis e seus propósitos.

Como elas são usadas?
Normalmente, CFLAGS e CXXFLAGS seria definida no ambiente ao chamar um script de configuração ou com makefiles gerados pelo programa. Em sistemas baseados no Gentoo, defina as variáveis CFLAGS e CXXFLAGS no. As variáveis definidas neste arquivo serão exportadas para o ambiente de programas chamados pelo Portage de tal forma que todos os pacotes serão compilados usando estas opções como base.

Como vimos no exemplo anterior, a variável CXXFLAGS é definida para usar todas as opções presentes na CFLAGS. A maioria dos sistemas devem ser configurados desta maneira. Opções adicionais para as CXXFLAGS são menos comuns e usualmente não são aplicáveis de forma geral o suficiente para merecer colocá-los globalmente.

Equívocos
Enquanto CFLAGS e CXXFLAGS podem ser muito eficazes de obter o código fonte e produzer binários menores e/ou rápidos, elas podem também prejudicar o funcionamento do código, inchar seu tamanho, desacelerar o tempo de execução. Definindo-as incorretamente pode até mesmo causar falhas na compilação!

Remember, the global CFLAGS configured in will be applied to every package on the system so administrators typically only set general, widely-applicable options. Individual packages further modify these options either in the ebuild or the build system itself to generate the final set of flags used when invoking the compiler.

Pronto?
Estando ciente dos riscos envolvidos, dê uma olhada em algumas otimizações seguras e sensatas. Estas serão mantidas em um bom lugar e serão agradáveis para os desenvolvedores da próxima vez que um problema for relatado no Bugzilla. (Os desenvolvedores irão, normalmente, solicitar aos usuários para recompilar um pacote com o mínimo de CFLAGS para ver se o problema persiste. Lembre-se: flags agressivas podem arruinar o código!)

O básico
O objetivo por trás da CFLAGS e CXXFLAGS é a criação de código feito sob medida para o seu sistema; deve funcionar perfeitamente ao ser enxuto e rápido, se possível. Às vezes estas condições são mutuamente exclusivas, assim este guia irá manter combinações conhecidas por funcionarem bem. Idealmente, elas são as melhores disponíveis para qualquer arquitetura de CPU. Para fins informativos, flags agressivas serão cobertas posteriormente. Nem toda opção listada no manual do GCC (há centenas) serão discutidas, mas basicamente, a maioria das flags serão revistas.

-march
A primeira e mais importante opção é. Isto informa ao compilador que código deve produzir para a arquitetura do processador (ou "arch"); ele informa ao GCC que deverá produzir código para um determinado tipo de CPU. Diferentes CPUs tem diferentes capacidades, suporta diferentes conjuntos de instruções e tem maneiras diferentes de execução de código. A flag  irá instruir o compilador para produzir um código específico para a CPU do sistema, com todas as suas capacidades, recursos, conjunto de instruções, particularidades e assim por diante.

is an ISA selection option; it tells the compiler that it may use the instructions from the ISA. On an Intel/AMD64 platform with  or lower optimization level, the code will likely end up with AVX instructions used but using shorter SSE XMM registers. To take full advantage of AVX YMM registers, the,   or   options should be used as well.

is an optimization option (default at  and  ), which attempts to vectorize loops using the selected ISA if possible. The reason it isn't enabled at  is that it doesn't always improve code, it can make code slower as well, and usually makes the code larger; it really depends on the loop etc.

Mesmo que a variável  no  especifique a arquitetura geral usada,   ainda deve ser usado de modo que os programas possam ser otimizados para o processador específico do sistema. CPUs x86 e x86-64 (entre outras) devem utilizar a flag.

Que tipo de CPU o sistema tem? Para encontrar, execute o seguinte comando:

or even install and add the available CPU-specific options to the  file, which the tool does through e.g. the CPU_FLAGS_X86 variable:

Para obter maiores detalhes, incluindo os valores  e , dois comandos podem ser usados.


 * O primeiro comando informa ao compilador não fazer nenhuma ligação e, ao invés de interpretar a opção   para esclarecer as opções da linha de comando,  ele agora irá mostrar se certas opções estão habilitadas ou desabilitadas . Neste caso, as opções mostradas são aquelas habilitadas para o alvo selecionado:


 * O segundo comando irá mostrar as diretivas do compilador para construir o arquivo cabeçalho, mas sem realmente executar os passos e ao invés disto mostrá-los na tela . A saída final é o comando que contém todas as opções de otimização e seleção de arquitetura:


 * The glibc-hwcaps feature (>=sys-libs/glibc-2.33) can be used to define  for a more general processor architecture (for >=sys-devel/gcc-11):

In this example cpu supports x86-64-v3 psABI x86_64 and you can use it for

Agora vamos ver  em ação. Este exemplo é para um antigo chip Pentium III:

Aqui está outro para uma CPU AMD 64-bit:

Se o tipo da CPU é indeterminado, ou se o usuário não sabe qual configuração escolher, é possível usar a configuração. Quando esta flag é usada, o GCC tentará detectar o processador e automaticamente definir as flags apropriadas para ele. Entretanto, isto não deve ser usado quando se pretende compilar pacotes para diferentes CPUs!

Se compilar pacotes em um computador a fim de executá-los em um computador diferente (tal como quando se utiliza um computador rápido para construir para uma máquina antiga, lenta), então "não" use. "Native" significa que o código produzido executará "apenas" naquele tipo de CPU. As aplicações construídas com  em um AMD Athlon 64 CPU não serão capazes de executar em uma antiga CPU VIA C3.

Também estão disponíveis as flags  e. Estas flags são normalmente usadas apenas quando não há a opção  disponível; certas arquiteturas de processadores podem exigir   ou até mesmo. Infelizmente o comportamento do GCC não é muito consistente com a forma como cada flag se comporta de uma arquitetura para outra.

Em CPUs x86 e x86-64,  irá gerar um código especificamente para esta CPU usando seu conjunto de instruções disponíveis e a correta ABI; ele não terá compatibilidade com versões anteriores para antigas/diferentes CPUs. Considere usar  quando gerar códigos para antigas CPUs tais como i386 e i486. produz um código mais genérico do que ; mas isto vai ajustar o código para uma determinada CPU, ele não leva em conta os conjuntos de instruções disponíveis e ABI. Não use  em sistemas x86 e x86-64, de forma que ele é obsoleto para estas arquiteturas.

Apenas em CPUs não x86/x86-64 (como Sparc, Alpha e PowerPC) pode exigir  ou   ao invés de. Nestas arquiteturas,  /   às vezes se comportam como   (em x86/x86-64), com um nome de flag diferente. Mais uma vez, o comportamento do GCC e nomeação de flag não é consistente em todas as arquiteturas, por isso não deixe de verificar o manual do GCC para determinar qual deve ser usado.

-O
Next up is the  variable. This variable controls the overall level of optimization. Changing this value will make the code compilation take more time and will use much more memory, especially as the level of optimization is increased.

There are seven  settings: ,  ,  ,  ,  ,  , and. Only use 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 us examine each optimization level:


 * : This level (that is the letter "O" followed by a zero) turns off optimization entirely and is the default if no  level is specified in CFLAGS or CXXFLAGS . This reduces compilation time and can improve debugging info, but some applications will not work properly without optimization enabled. This option is not recommended except for debugging purposes.


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


 * : A step up from . The recommended level of optimization unless the system has 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. SSE or AVX may be utilized at this level but no YMM registers will be used unless   is also enabled.


 * : the highest level of optimization possible. It enables optimizations that are expensive in terms of compile time and memory usage. Compiling with   is not a guaranteed way to improve performance, and in fact, in many cases, can slow down a system due to larger binaries and increased memory usage.   is also known to break several packages. Using   is not recommended. However, it also enables   so that loops in the code get vectorized and will use AVX YMM registers.


 * : optimizes code for size. It activates all  options that do not increase the size of the generated code. It can be useful for machines that have extremely limited disk storage space and/or CPUs with small cache sizes.


 * : In GCC 4.8, a new general optimization level,, has been introduced. It addresses the need for fast compilation and a superior debugging experience while providing a reasonable level of runtime performance. Overall experience for development should be better than the default optimization level  .  Note that   does not imply  , it simply disables optimizations that may interfere with debugging.


 * : New in GCC 4.7, consists of  plus ,  , and  . This option breaks strict standards compliance, and is not recommended for use.

As previously mentioned,  is the recommended optimization level. If package compilation fails and while not using, try rebuilding with that option. As a fallback option, try setting the CFLAGS and CXXFLAGS to a lower optimization level, such as  or even   (for error reporting and checking for possible problems).

-pipe
A common flag is. This flag 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 those cases 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 it may need to be activated. In that case add it to the flags. Though the GCC manual does not specify all architectures, it is turned on by using the  option. It's still necessary to explicitly enable the  option, to activate it on x86-32 with GCC up to version 4.6, or when using   on x86-32 with any version of GCC. However, using  will make debugging hard or impossible.

In particular, it makes troubleshooting applications written in Java and compiled by gcj 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. When not doing software debugging and no other debugging-related CFLAGS such as  have been used, then try using.

-msse, -msse2, -msse3, -mmmx, -m3dnow
These flags enable the Streaming SIMD Extensions (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.

Normally none of these flags need to be added to, as long as the system is 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 additional flags will need to be enabled where appropriate after checking.

Hardening optimizations
Hardening an otherwise unhardened system, like when using a desktop profile, can be considered a GCC optimization as well, especially in the light of security vulnerabilities such as Meltdown and Spectre.

Some packages feature an individual  USE flag, enabling tested security enhancements (like CFLAGs/CXXFLAGs). It may be a good idea to set this system-wide in.

Overflow protection
Optimizing CFLAGS/CXXFLAGS for overflow protection can be a good idea if security concerns outweigh speed optimization. This may be the case on a daily-use desktop system, while e.g. on an optimized gaming PC it will be considered counterproductive.

ASLR
Address Space Layout Randomization (ASLR) is a state-of-the-art measure to increase security by randomly placing each function and buffer in memory. This makes it harder for attack vectors to succeed.

For full ASLR it is recommended to switch to a hardened profile, as ASLR is only fully applied in combination with PaX and PIE/PIC. See Hardened/Introduction to Hardened Gentoo for further details.

But I get better performance with -funroll-loops -fomg-optimize!
No, people only think they do because someone has convinced them that more flags are better. Aggressive flags will only hurt applications when used system-wide. Even the GCC manual says that using  and   will make 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!

These flags are not needed globally in CFLAGS or CXXFLAGS. They will only hurt performance. They might bring on the idea of having a high-performance system running on the bleeding edge, but they don't do anything but bloat the code and get bugs marked INVALID or WONTFIX.

Dangerous flags like these are not needed. 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:

As can be seen, any value higher than 3 is treated as just.

What about compiling outside the target machine?
Some readers might wonder if compiling outside the target machine with a strictly inferior CPU or GCC sub-architecture will result in inferior optimization results (compared to a native compilation). The answer is simple: No. Regardless of the actual hardware on which the compilation takes place and the CHOST for which GCC was built, as long as the same arguments are used (except for ) and the same version of GCC is used (although minor version might be different), the resulting optimizations are strictly the same.

To exemplify, if Gentoo is installed on a machine whose GCC's CHOST is i686-pc-linux-gnu, and a Distcc server is setup on another computer whose GCC's CHOST is i486-linux-gnu, then there is no need to be afraid that the results would be less optimal because of the strictly inferior sub-architecture of the remote compiler and/or hardware. The result would be as optimized as a native build, as long as the same options are passed to both compilers (and the  parameter doesn't get a   argument). In this particular case the target architecture needs to be specified explicitly as explained in Distcc and -march=native.

The only difference in behavior between two GCC versions built targeting different sub-architectures is the implicit default argument for the  parameter, which is derived from the GCC's CHOST when not explicitly provided in the command line.

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:

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 the whole system with  if some of the flags turned on by that level will cause problems with certain packages. Therefore, don't try to "outsmart" the developers who maintain those packages. Trust the developers. Flag filtering and replacing is done to ensure stability of the system and application! If an ebuild specifies alternative flags, then don't try to get around it.

Building packages with unacceptable flags will most likely lead to problems. When reporting problems on Bugzilla, the flags that are used in will be readily visible and developers will ask to recompile without those flags. Save the trouble of recompiling by not using redundant flags in the first place! Don't just automatically assume to be more knowledgeable than the developers.

What about LDFLAGS?
The Gentoo developers have already set basic, safe LDFLAGS in the base profiles, so they do not need to be changed.

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".

Profile Guided Optimization (PGO)
Profile guided optimization (PGO) consists of compiling and profiling a program to assess hot paths in the code. Optimizations are then applied based on this analysis.

performance may improve via PGO, although it may as much as double the compile times. To enable for :

Firefox also supports PGO although sometimes it may break the build.

Link Time Optimization (LTO)
LTO is still experimental. LTO may need to be disabled before reporting bugs because it is a common source of problems.

To enable for building itself with LTO:

There is a guide available on the Clang page but there is also a popular overlay (gentooLTO) which lists workarounds needed to make LTO build for the whole system and not break binaries during compilation or execution.

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


 * GCC online documentation