GCC optimization/ru

Это руководство предлагает введение в оптимизацию компилируемого кода используя безопасные, разумные флаги CFLAGS и CXXFLAGS. Оно также описывает теорию оптимизации в общих чертах.

Что такое CFLAGS и CXXFLAGS?
CFLAGS and CXXFLAGS are environment variables that are used to tell the GNU Compiler Collection (GCC) what kinds of switches to use when compiling source code. The CFLAGS variable is used for compiling code written in C, while the CXXFLAGS variable is for code written in C++.

Они могут быть использованы для уменьшения количества отладочных сообщений программы, увеличения уровня сообщений об ошибках, и, конечно же, оптимизации производимого кода. GCC manual поддерживает полный список доступных параметров и их предназначений.

Как их использовать?
CFLAGS and CXXFLAGS can be used in two ways. First, they can be used per-program with Makefiles generated by the program.

However, this should not be done when installing packages found in the Portage tree. Instead, for Gentoo-based machines, set the CFLAGS and CXXFLAGS variables in This way all packages will be compiled using the options specified in

As seen in the example above the CXXFLAGS variable is set to use all the options present in CFLAGS. Most every system should be configured in this manner; additional options for CXXFLAGS are extremely rare in common use cases.

Заблуждения
While CFLAGS and CXXFLAGS can be very effective means of getting source code to produce smaller and/or faster binaries, they can also impair the function of the code, bloat its size, slow down its execution time. Setting them incorrectly can even cause compilation failures!

CFLAGS are not a magic bullet; they will not automatically make the system run faster or reduce the size of binaries on the disk. Adding too many flags in an attempt to optimize (or "rice") the system is a sure recipe for failure. The point of diminishing returns is reached rather quickly when dealing with CFLAGS.

Despite the boasts and brags found on the internet, aggressive CFLAGS and CXXFLAGS are far more likely to harm binaries than to do any good. Keep in mind the flags are designed to be used at specific places for specific purposes. Few flags work as intended globally.

Готовы?
Being aware of the risks involved, take a look at some sane, safe optimizations. These will hold in good stead and will be endearing to developers the next time a problem is reported on Bugzilla. (Developers will usually request the user to recompile a package with minimal CFLAGS to see if the problem persists. Remember: aggressive flags can ruin code!)

Основы
The goal behind CFLAGS and CXXFLAGS is to create code tailor-made to your system; it should function perfectly while being lean and fast, if possible. Sometimes these conditions are mutually exclusive, so this guide will stick to combinations known to work well. Ideally, they are the best available for any CPU architecture. For informational purposes, aggressive flag use will be covered later. Not every option listed on the GCC manual (there are hundreds) will be discussed, but basic, most common flags will be reviewed.

-march
The first and most important option is. This tells the compiler what code it should produce for the system's processor architecture (or arch); it tells GCC that it should produce code for a certain kind of CPU. Different CPUs have different capabilities, support different instruction sets, and have different ways of executing code. The  flag will instruct the compiler to produce specific code for the system's CPU, with all its capabilities, features, instruction sets, quirks, and so on.

Even though the  variable in  specifies the general architecture used,   should still be used so that programs can be optimized for the system specific processor. x86 and x86-64 CPUs (among others) should make use of the  flag.

What kind of CPU does the system have? To find out, run the following command:

Более детальную информацию, включая значения  и , можно получить с помощью следующей команды:

Now lets see  in action. This example is for an older Pentium III chip:

А это другой пример для 64-разрядного AMD CPU:

If the type of CPU is undetermined, or if the user does not know what setting to choose, it is possible use the  setting. When this flag is used, GCC will attempt to detect the processor and automatically set appropriate flags for it. However, this should not be used when intending to compile packages for different CPUs!

If compiling packages on one computer in order 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, GCC'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 its available instruction sets and the correct ABI; it will have no backwards compatibility for older/different CPUs. Consider using  when generating code for older CPUs such as i386 and i486. produces more generic code than ; though it will tune code for a certain CPU, it does not take into account available instruction sets and ABI. Do not 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, GCC's behavior and flag naming is not consistent across architectures, so be sure to check the GCC manual to determine which one should be used.

-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

За исключением, каждая из настроек с префиксом   активирует несколько дополнительных флагов, поэтому удостоверьтесь, что Вы прочитали главу руководства GCC по параметрам оптимизации для изучения того, какие флаги активируются на каждом уровне с приставкой  , также как и некоторые из объяснений того, что они делают.

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.


 * : 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.


 * : 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.


 * : В GCC 4.8 был введен новый общий уровень оптимизации -Og. Он удовлетворяет потребность в быстрой компиляции и имеет превосходные возможности для отладки, обеспечивая при этом приемлемый уровень производительности во время выполнения. Общий опыт разработки должен быть лучше, чем с уровнем оптимизации по умолчанию -O0. Обратите внимание, что -Og не означает -g, он просто отключает оптимизацию кода, которая может помешать отладке.


 * : Новое в GCC 4.7, состоит из  плюс ,  , и  . Этот параметр нарушает строгое соответствие стандарту, и не рекомендуется для использования.

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 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 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 Extentions (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.

Но я получаю лучшую производительность с -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 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.

Истина в том, что это чрезвычайно агрессивные флаги. Посмотрите по форумам Gentoo и Bugzilla, чтобы увидеть, что эти флаги могут сделать: ничего хорошего!

You do not 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 the code and get your bugs marked INVALID or WONTFIX.

Вам не требуются такие опасные флаги, как эти. Не используйте их. Придерживайтесь основ: ,   , и.

Что по поводу уровней оптимизации -O больших чем 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.

Нужно больше доказательств? Исследуйте исходный код:

Как видите, любое значение, большее тройки, рассматривается как.

Что насчет компиляции не на целевой машине?
Некоторые читатели могут спросить, не приведет ли компиляция не на целевой машине, сильно отличающейся архитектурой процессора или структурой GCC, к плохому качеству оптимизации (по сравнению с нативной компиляцией). Ответ прост: Нет. Независимо от используемого оборудования, на котором проводится компиляция, и от значения переменной CHOST, с использованием которой был собран GCC, если используются те же аргументы (кроме ) и та же версия GCC (хотя небольшие оптимизации могут отличаться), результирующий уровень оптимизации останется строго тем же.

Например, если Gentoo установлен на компьютере, на котором переменная CHOST для GCC равна i686-pc-linux-gnu, а сервер Distcc настроен на другом компьютере, на котором CHOST для GCC равна i486-linux-gnu, то не нужно бояться, что результаты будут менее оптимальны из-за отличающейся архитектуры удаленного компилятора и/или оборудования. Результат будет оптимизирован в той же степени, как и при сборке на целевом компьютере, если, конечно, обоим компиляторам передаются одинаковые параметры (и параметр  не включает значение  ). В данном конкретном случае целевую архитектуру нужно явно определять, как указано в статье Distcc и -march=native.

Единственная разница в поведении между двумя версиями GCC, построенными с использованием разных архитектур в значении параметра  по умолчанию. Он берется из переменной CHOST для GCC, если он не указан явно в командной строке.

А что об избыточных флагах?
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.

Руководство разработчика Gentoo описывает в общих чертах, где и как работает фильтрация/замещение флагов.

Возможно обойти фильтрацию уровней, избыточно перечисляя флаги для определенного уровня, например   , делая такие вещи как:

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.

Скорее всего, вы продолжите испытывать проблемы, когда Вы собираете пакет с недопустимыми флагами. При сообщении о проблемах на Bugzilla, флаги, которые Вы используете в будут легко видны, и Вам скажут, чтобы Вы перекомпилировали пакет без этих флагов. Сохраните себя от проблем с перекомпиляцией не используя избыточные флаги с самого начала! Не предполагайте автоматически, что Вы знаете больше, чем разработчики.

Что по поводу LDFLAGS?
The Gentoo developers have already set basic, safe LDFLAGS in the base profiles, so they do not need to be changed.

Могу ли я использовать флаги для отдельных пакетов?
Information on how to use per-package environment variables (including CFLAGS ) is described in the Gentoo Handbook, "Per-Package Environment Variables".

Источники
Следующие источники могут быть полезными в дальнейшем изучении оптимизации:


 * Онлайн-документация GCC


 * Глава 5 настольной книги по установке Gentoo


 * man make.conf


 * Wikipedia


 * форумы Gentoo